Les cookies nous permettent de vous proposer nos services plus facilement. En utilisant nos services, vous nous donnez expressément votre accord pour exploiter ces cookies.En savoir plus OK

Microchip-ATWINC15x0 ATWINC15x0 Wi-Fi® Network Controller Software Design Guide-Manuel

Microchip- ATWINC15x0 ATWINC15x0 Wi-Fi® Network Controller Software Design Guide - Manuel

Voir également :
[TXT] Microchip-AN1476-Com..> 2018-11-13 18:55  499K  
[TXT] Microchip-Atmel-ATUC64L4U-32-bit-Atmel-AVR-Microcontroller-Manuel 2018-11-20 16:26  1.9M  
[TXT] Microchip-CAP1188-8-Channel-Capacitive-Touch-Sensor-with-8-LED-Drivers-Manuel 2018-11-13 19:07  1.4M  
[TXT] Microchip-CAP1203-3-..> 2018-11-13 19:06  1.2M  
[TXT] Microchip-CAP1206-6-..> 2018-11-13 18:58  736K  
[TXT] Microchip-CAP1208-8-..> 2018-11-13 19:01  1.0M  
[TXT] Microchip-CAP1293-3-..> 2018-11-13 18:57  620K  
[TXT] Microchip-CAP1296-6-..> 2018-11-13 19:00  883K  
[TXT] Microchip-CAP1298-8-..> 2018-11-13 19:03  1.1M  
[TXT] Microchip-SEC1110-Sm..> 2018-11-13 18:48  479K  
[TXT] Microchip-SEC1210-Sm..> 2018-11-13 18:52  479K 

Au format texte :

ATWINC15x0 ATWINC15x0 Wi-Fi® Network Controller Software Design Guide Introduction Microchip’s SmartConnect ATWINC15x0 is an IEEE® 802.11 b/g/n network controller SoC for Internet of Things (IoT) applications. It is an ideal add-on to the existing microcontroller (MCU) solutions bringing WiFi and network capabilities through an SPI-to-Wi-Fi interface. The ATWINC15x0 connects to any Microchip AVR® or Microchip SMART™ MCU with minimal resource requirements. Features • Wi-Fi IEEE 802.11 b/g/n STA, and AP modes • Wi-Fi Protected Setup (WPS) • Support of WEP, WPA/WPA2 Personal, and WPA/WPA2 Enterprise Security – EAP-TLS – EAP-PEAPv0/1 with TLS – EAP-TTLSv0 with MSCHAPv2 – EAP-PEAPv0/1 with MSCHAPv2 • Embedded network stack protocols to offload work from the MCU (minimize the host CPU requirements). This allows the Wi-Fi Network Controller (WINC) to operate with a wide range of MCUs including low-end MCUs. • Embedded uIP TCP/IP stack with BSD-Style socket API • Embedded network protocols – DHCP client/server – DNS resolver client – SNTP client for UTC time synchronization • Embedded TLS security abstracted behind BSD-style socket API • HTTP server for provisioning over AP mode • Ultra-low C IEEE 802.11 b/g/n RF/PH/MAC SoC • Fast boot from On-Chip boot ROM • 8 Mb (WINC1510) and 4 Mb (WINC1500) internal Flash memory with Over-the-Air (OTA) firmware upgrade • WINC1510 support Host File Download feature which can be used for host MCU over the air firmware update • Low-power consumption with different Power Save modes • Low footprint host driver with the following capabilities: – Can run on 8-, 16-, and 32-bit MCU using SPI interface – Little- and big-endian support © 2018 Microchip Technology Inc. User Guide DS00002389B-page 1 Table of Contents Introduction......................................................................................................................1 Features.......................................................................................................................... 1 1. Host Driver Architecture............................................................................................ 5 1.1. WLAN API.................................................................................................................................... 5 1.2. Socket API....................................................................................................................................5 1.3. Host Interface (HIF)......................................................................................................................6 1.4. Board Support Package (BSP).....................................................................................................6 1.5. Serial Bus Interface......................................................................................................................6 2. ATWINC15x0 System Architecture............................................................................7 2.1. Bus Interface................................................................................................................................ 7 2.2. Nonvolatile Storage......................................................................................................................8 2.3. CPU..............................................................................................................................................8 2.4. IEEE 802.11 MAC Hardware........................................................................................................8 2.5. Program Memory..........................................................................................................................8 2.6. Data Memory................................................................................................................................8 2.7. Shared Packet Memory................................................................................................................8 2.8. IEEE 802.11 MAC Firmware........................................................................................................ 8 2.9. Memory Manager......................................................................................................................... 8 2.10. Power Management..................................................................................................................... 9 2.11. WINC RTOS.................................................................................................................................9 2.12. WINC IoT Library..........................................................................................................................9 3. WINC Initialization and Simple Application..............................................................11 3.1. BSP Initialization.........................................................................................................................11 3.2. WINC Host Driver Initialization................................................................................................... 11 3.3. Socket Layer Initialization...........................................................................................................11 3.4. WINC Event Handling................................................................................................................ 12 3.5. Example Code............................................................................................................................13 4. ATWINC15x0 Configuration.....................................................................................14 4.1. Device Parameters.....................................................................................................................14 4.2. WINC Modes of Operation......................................................................................................... 14 4.3. Network Parameters...................................................................................................................16 4.4. Power Save Modes.................................................................................................................... 17 4.5. Configuring Listen Interval and DTIM Monitoring.......................................................................18 5. Wi-Fi Station Mode.................................................................................................. 20 5.1. Scan Configuration Parameters................................................................................................. 20 5.2. Wi-Fi Scan..................................................................................................................................20 5.3. Wi-Fi Security.............................................................................................................................21 5.4. On Demand Wi-Fi Connection................................................................................................... 22 ATWINC15x0 © 2018 Microchip Technology Inc. User Guide DS00002389B-page 2 5.5. Default Connection.....................................................................................................................25 5.6. Encrypted Credential Storage.................................................................................................... 26 5.7. Simple Roaming.........................................................................................................................27 5.8. Multiple Gain Table.....................................................................................................................29 5.9. Host File Download.................................................................................................................... 30 6. Socket Programming............................................................................................... 39 6.1. Overview.................................................................................................................................... 39 6.2. Sockets API................................................................................................................................39 6.3. Socket Connection Flow.............................................................................................................47 6.4. Example Code............................................................................................................................51 7. Transport Layer Security (TLS)............................................................................... 56 7.1. TLS Overview.............................................................................................................................56 7.2. TLS Connection Establishment..................................................................................................56 7.3. Server Certificate Installation..................................................................................................... 58 7.4. WINC TLS Limitations................................................................................................................59 7.5. SSL Client Code Example..........................................................................................................60 8. Wi-Fi AP Mode........................................................................................................ 62 8.1. Overview.................................................................................................................................... 62 8.2. Setting the WINC AP Mode........................................................................................................62 8.3. Limitations.................................................................................................................................. 62 8.4. Sequence Diagram.....................................................................................................................62 8.5. AP Mode Code Example............................................................................................................63 9. Provisioning............................................................................................................. 65 9.1. HTTP Provisioning..................................................................................................................... 65 9.2. Limitations.................................................................................................................................. 68 9.3. Wi-Fi Protected Setup (WPS).....................................................................................................68 10. Over-The-Air Upgrade.............................................................................................71 10.1. Overview.................................................................................................................................... 71 10.2. OTA Image Architecture............................................................................................................. 71 10.3. OTA Download Sequence Diagram........................................................................................... 72 10.4. OTA Firmware Rollback............................................................................................................. 72 10.5. OTA Limitations..........................................................................................................................73 10.6. OTA Code Example....................................................................................................................73 11. Multicast Sockets.....................................................................................................74 11.1. Overview.................................................................................................................................... 74 11.2. How to Use Filters......................................................................................................................74 11.3. Multicast Socket Code Example.................................................................................................74 12. WINC Serial Flash Memory.....................................................................................78 12.1. Overview and Features.............................................................................................................. 78 12.2. Accessing to Serial Flash...........................................................................................................78 12.3. Read/Write/Erase Operations.................................................................................................... 78 ATWINC15x0 © 2018 Microchip Technology Inc. User Guide DS00002389B-page 3 13. Host Interface (HIF) Protocol...................................................................................81 13.1. Transfer Sequence Between the HIF Layer and the WINC Firmware........................................82 13.2. HIF Message Header Structure..................................................................................................84 13.3. HIF Layer APIs...........................................................................................................................84 13.4. Scan Code Example...................................................................................................................85 14. WINC SPI Protocol..................................................................................................90 14.1. Introduction.................................................................................................................................90 14.2. Message Flow for Basic Transactions......................................................................................101 14.3. SPI Level Protocol Example.....................................................................................................105 15. Appendix A. How to Generate Certificates............................................................128 15.1. Introduction...............................................................................................................................128 15.2. Steps........................................................................................................................................ 128 15.3. Limitations................................................................................................................................ 128 16. Appendix B. X.509 Certificate Format and Conversion.........................................129 16.1. Introduction...............................................................................................................................129 16.2. Conversion Between Different Formats................................................................................... 129 17. References............................................................................................................ 131 18. Document Revision History................................................................................... 132 The Microchip Web Site.............................................................................................. 133 Customer Change Notification Service........................................................................133 Customer Support....................................................................................................... 133 Microchip Devices Code Protection Feature............................................................... 133 Legal Notice.................................................................................................................134 Trademarks................................................................................................................. 134 Quality Management System Certified by DNV...........................................................135 Worldwide Sales and Service......................................................................................136 ATWINC15x0 © 2018 Microchip Technology Inc. User Guide DS00002389B-page 4 1. Host Driver Architecture The following figure shows the architecture of the WINC host driver software, which runs on the host MCU. Figure 1-1. Host Driver Software Architecture The ATWINC15x0 host driver software is a C library, which provides the host MCU application with necessary APIs to perform necessary WLAN and socket operations. The components of the host driver are described in the following sub-sections. 1.1 WLAN API This module provides an interface to the application for all Wi-Fi operations and any non-IP related operations. This includes the following services: • Wi-Fi STA management operations – Wi-Fi scan – Wi-Fi connection management (connect, disconnect, connection status, and so on) – WPS activation/deactivation • Wi-Fi AP enable/disable • Wi-Fi power save control API This interface is defined in the m2m_wifi.h file. 1.2 Socket API This module provides the socket communication APIs that are mostly compliant with the well-known BSD sockets to enable rapid application development. To comply with the nature of the MCU application environment, there are differences in API prototypes and in usage of some APIs between the WINC sockets and BSD sockets. This interface is defined in the socket.h file. ATWINC15x0 Host Driver Architecture © 2018 Microchip Technology Inc. User Guide DS00002389B-page 5 The detailed description of the socket operations is provided in Socket Programming. 1.3 Host Interface (HIF) The HIF is responsible for handling the communication between the host driver and the WINC firmware. This includes interrupt handling, DMA and HIF command/response management. The host driver communicates with the firmware in the form of commands and responses formatted by the HIF layer. The interface is defined in the m2m_hif.h file. The detailed description of the HIF design is provided in Host Interface Protocol. 1.4 Board Support Package (BSP) The Board Support Package abstracts the functionality of a specific host MCU platform. This allows the driver to be portable to a wide range of hardware and hosts. Abstraction includes: pin assignment, power on/off sequence, reset sequence and peripheral definitions (Push buttons, LEDs, and so on). The minimum required BSP functionality is defined in the nm_bsp.h file. 1.5 Serial Bus Interface The Serial Bus Interface module abstracts the hardware associated with implementing the bus between the Host and the WINC. The serial bus interface abstracts I2C, SPI, or UART bus (Currently, host driver supports only SPI bus interface). The basic bus access operations (Read and Write) are implemented in this module as appropriate for the interface type and the specific hardware. The bus interface APIs are defined in the nm_bus_wrapper.h file. ATWINC15x0 Host Driver Architecture © 2018 Microchip Technology Inc. User Guide DS00002389B-page 6 2. ATWINC15x0 System Architecture The following figure shows the ATWINC15x0 system architecture. In addition to its built-in Wi-Fi IEEE-802.11 physical layer and RF front end, the WINC ASIC contains an embedded APS3S-Cortus 32- bit CPU to run the WINC firmware. The firmware comprises the Wi-Fi IEEE-802.11 MAC layer and embedded protocol stacks which offload the host MCU. The components of the system are described in the following sub-sections. Figure 2-1. ATWINC15x0 System Architecture 2.1 Bus Interface Hardware logic for the supported bus types for the ATWINC15x0 communications. Note:  SPI is currently the bus interface supported by the Host Driver. ATWINC15x0 ATWINC15x0 System Architecture © 2018 Microchip Technology Inc. User Guide DS00002389B-page 7 2.2 Nonvolatile Storage The ATWINC1510 has an integrated 8 Mb and the ATWINC1500 has an integrated 4 Mb serial Flash inside the WINC package (SIP). This stores the WINC firmware image and can store a second image to support OTA. It also stores information used by the WINC firmware in the run-time. The detailed description of the serial Flash is provided in WINC Serial Flash Memory. 2.3 CPU The SoC contains an APS3S-Cortus 32-bit CPU running at 40 MHz clock speed which executes the embedded WINC firmware. 2.4 IEEE 802.11 MAC Hardware The SoC contains a hardware accelerator to ensure fast and compliant implementation of the IEEE 802.11 MAC layer and associated timing. It offloads IEEE 802.11 MAC functionality from firmware to improve performance and boost the MAC throughput. The accelerator includes hardware encryption/ decryption of Wi-Fi traffic and traffic filtering mechanisms to avoid unnecessary processing in software. 2.5 Program Memory 128 KB Instruction RAM is provided for execution of the ATWINC15x0 firmware code. 2.6 Data Memory 64 KB RAM is provided for the ATWINC15x0 firmware data storage. 2.7 Shared Packet Memory 128 KB memory is provided for TX/RX packet management. It is shared between the MAC hardware and the CPU. This memory is managed by the Memory Manager SW component. 2.8 IEEE 802.11 MAC Firmware The system supports IEEE 802.11 b/g/n Wi-Fi MAC including WEP and WPA/WPA2 security supplicant. Between the MAC hardware and the firmware, a full range of IEEE 802.11 features are implemented and supported including beacon generation and reception, control packet generation and reception, and packet aggregation and de-aggregation. 2.9 Memory Manager The memory manager is responsible for the allocation and de-allocation of memory chunks in both shared packet memory and data memory. ATWINC15x0 ATWINC15x0 System Architecture © 2018 Microchip Technology Inc. User Guide DS00002389B-page 8 2.10 Power Management The Power Management module is responsible for handling different Power Save modes supported by the WINC and coordinating these modes with the Wi-Fi transceiver. 2.11 WINC RTOS The firmware includes a low-footprint real-time scheduler which allows concurrent multi-tasking on the ATWINC15x0 CPU. The ATWINC15x0 RTOS provides semaphores and timer functionality. 2.12 WINC IoT Library The WINC IoT library provides a set of networking protocols in the WINC firmware. It offloads the host MCU from networking and transport layer protocols. The following sections describe the components of the WINC IoT library. 2.12.1 WINC TCP/IP STACK The WINC TCP/IP is an IPv4.0 stack based on the uIP (pronounced micro IP) TCP/IP stack. uIP is a low footprint TCP/IP stack which has the ability to run on a memory-constrained microcontroller platform. It was originally developed by Adam Dunkels, licensed under a BSD style license, and further developed by a wide group of developers. The WINC TCP/IP stack is a customized version of the original uIP implementation which has several enhancements to boost TCP and UDP throughput. 2.12.2 DHCP CLIENT/SERVER A DHCP client is embedded in the WINC firmware that can automatically obtain an IP configuration after connecting to a Wi-Fi network. The WINC firmware provides an instance of a DHCP server that automatically starts when the WINC AP mode is enabled. When the host MCU application activates the AP mode, it is allowed to configure the DHCP Server IP address pool range within the AP configuration parameters. 2.12.3 DNS RESOLVER The WINC firmware contains an instance of an embedded DNS resolver. This module can return an IP address by resolving the host domain names supplied with the socket API call gethostbyname. 2.12.4 SNTP The SNTP (Simple Network Time Protocol) module implements an SNTP client used to synchronize the WINC internal clock to the UTC clock. 2.12.5 Enterprise Security The Enterprise Security module implements the following authentication protocols for establishing a Wi-Fi connection with an AP by WPA/WPA2-Enterprise Security. • EAP with TLS • EAP-PEAPv0/v1 with MSCHAPV2 • EAP-TTLSv0 with MSCHAPv2 • EAP-PEAPv0/v1 with MSCHAPv2 2.12.6 TRANSPORT LAYER SECURITY For TLS implementation, refer to Section 7 “Transport Layer Security (TLS)” for details. ATWINC15x0 ATWINC15x0 System Architecture © 2018 Microchip Technology Inc. User Guide DS00002389B-page 9 2.12.7 WI-FI PROTECTED SETUP For WPS protocol implementation, refer to Section 10.3 “Wi-Fi Protected Setup (WPS)” for details. 2.12.8 CRYPTO LIBRARY The Crypto Library contains a set of cryptographic algorithms used by the common security protocols. This library has an implementation of the following algorithms: • MD4 Hash algorithm (used only for MsChapv2.0 digest calculation) • MD5 Hash algorithm • SHA-1 Hash algorithm • SHA-256 Hash algorithm • DES Encryption (used only for MsChapv2.0 digest calculation) • MS-CHAPv2.0 (used as the EAP-TTLS inner authentication algorithm) • MS-CHAPv2.0 (used as the EAP-PEAP and EAP-TTLS inner authentication algorithm) • AES-128, AES-256 Encryption (used for securing WPS and TLS traffic) • BigInt module for large integer arithmetic (for Public Key Cryptographic computations) • RSA Public Key cryptography algorithms (includes RSA Signature and RSA Encryption algorithms) ATWINC15x0 ATWINC15x0 System Architecture © 2018 Microchip Technology Inc. User Guide DS00002389B-page 10 3. WINC Initialization and Simple Application After powering-up the WINC device, a set of synchronous initialization sequences must be executed, for the correct operation of the Wi-Fi functions. This chapter aims to explain the different steps required during the initialization phase of the system. After initialization, the host MCU application is required to call the WINC driver entry point to handle events from the WINC firmware. • BSP Initialization • WINC Host Driver Initialization • Socket Layer Initialization • Call WINC Driver Entry Point Note:  The initialization sequence must be completed to successfully operate the WINC start-up procedure. 3.1 BSP Initialization The BSP is initialized by calling the nm_bsp_init API. The BSP initialization routine performs the following steps: • Resets the WINC1 using the corresponding host MCU control GPIOs. • Initializes the host MCU GPIO which connects to the WINC interrupt line. It configures the GPIO as an interrupt source to the host MCU. During runtime, the WINC interrupts the host to notify the application of events and data pending inside the WINC firmware. • Initializes the host MCU delay function used within nm_bsp_sleep implementation. 3.2 WINC Host Driver Initialization The WINC host driver is initialized by calling the m2m_wifi_init API. The host driver initialization routine performs the following steps: • Initializes the bus wrapper and SPI peripheral. The compilation flag CONF_WINC_USE_SPI must be enabled in conf_winc.h (bus interfaces CONF_WINC_USE_UART and CONF_WINC_USE_I2C are currently not supported). • Registers an application-defined Wi-Fi event handler. • Initializes the driver and ensures compatibility between the WINC firmware version and the driver version. • Initializes the host interface and the Wi-Fi layer and registers the BSP Interrupt. Note:  A Wi-Fi event handler is required for the correct operation of any WINC application. 3.3 Socket Layer Initialization Socket layer initialization is carried out by calling the socketInit API. It must be called prior to any socket activity. For more information about socket initialization and programming, refer to WINC Sockets API. 1 Refer to the ATWINC15x0-MR210xB Data Sheet (DS70005304) for more information about the hardware power-up/down sequence. ATWINC15x0 WINC Initialization and Simple Application © 2018 Microchip Technology Inc. User Guide DS00002389B-page 11 3.4 WINC Event Handling The WINC host driver API allows the host MCU application to interact with the WINC firmware. To facilitate interaction, the WINC driver implements the Host Interface (HIF) Protocol as described in Section 15 “Host Interface (HIF) Protocol”. The HIF protocol defines how to serialize and de-serialize API requests and response callbacks over the serial bus interface SPI (I2C and UART are currently not supported). Figure 3-1. WINC System Architecture The WINC host driver API provides services to the host MCU applications that are mainly divided in two major categories: Wi-Fi control services and Socket services. The Wi-Fi control services allow actions such as channel scanning, network identification, connection and disconnection. The Socket control services allow application data transfer once a Wi-Fi connection is established. 3.4.1 Asynchronous Events Some APIs in the ATWINC15x0 host driver are synchronous function calls, where the result is ready by the return of the function. However, most API functions in the ATWINC15x0 host driver are asynchronous. This means that when the application calls an API to request a service, the call is non-blocking and returns immediately, before the requested action is completed. When completed, a notification is provided in the form of a HIF protocol message from the WINC firmware to the host which, in turn, is delivered to the application via a callback2 function. Asynchronous operation is essential when the requested service such as Wi-Fi connection may take significant time to complete. In general, the ATWINC15x0 firmware uses asynchronous events to signal the host driver about status change or pending data. The HIF uses push architecture where the data and events are pushed from the ATWINC15x0 firmware to the host MCU in a First-Come First-Served (FCFS) manner. For instance, the host MCU application has two open sockets: socket 1 and socket 2. If the ATWINC15x0 receives socket 1 data followed by socket 2 data, then HIF delivers socket data in two HIF protocol messages in the order in which it is received. HIF does not allow reading socket 2 data before socket 1 data. 3.4.2 Interrupt Handling The HIF interrupts the host MCU when one or more events are pending in the ATWINC15x0 firmware. The host MCU application is a big state machine which processes received data and events when the 2 The callback is C function which contains an application-defined logic. The callback is registered using the ATWINC15x0 host driver registration API to handle the result of the requested service. ATWINC15x0 WINC Initialization and Simple Application © 2018 Microchip Technology Inc. User Guide DS00002389B-page 12 ATWINC15x0 driver calls the event callback function(s). To receive event callbacks, the host MCU application is required to call the m2m_wifi_handle_events API to let the host driver retrieve and process the pending events from the ATWINC15x0 firmware. It is recommended to call this function if any of the following events occur: • The host MCU application polls the API in main loop or a dedicated task • When the host MCU receives an interrupt from the ATWINC15x0 firmware Note:  All the application-defined event callback functions registered with the ATWINC15x0 driver run in the context m2m_wifi_handle_events API. The above HIF architecture allows the ATWINC15x0 host driver to be flexible to run in the following configurations: • Host MCU with no operating system configuration – the MCU main loop is responsible to handle deferred work from the interrupt handler • Host MCU with operating system configuration – a dedicated task or thread is required to call m2m_wifi_handle_events to handle deferred work from the interrupt handler Note:  1. Host driver entry point m2m_wifi_handle_events is non-reentrant. In the operating system configuration, it is required to protect the host driver from reentrance by a synchronization object. 2. When the host MCU is polling m2m_wifi_handle_events, the API checks for pending unhandled interrupt from the ATWINC15x0. If no interrupt is pending, it returns immediately. If an interrupt is pending, m2m_wifi_handle_events sequentially reads all the pending HIF messages and dispatches the HIF message content to the respective registered callback. If a callback is not registered to handle the type of message, the HIF message content is discarded. 3.5 Example Code The following example code shows the initialization flow, as described in the previous sections. static void wifi_cb(uint8_t u8MsgType, void *pvMsg) { } int main (void) { tstrWifiInitParam param; nm_bsp_init(); m2m_memset((uint8*)¶m, 0, sizeof(param)); param.pfAppWifiCb = wifi_cb; /*intilize the WINC Driver*/ ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret){ M2M_ERR("Driver Init Failed <%d>\n",ret); while(1); } while(1){ /* Handle the app state machine plus the WINC event handler */ while(m2m_wifi_handle_events(NULL) != M2M_SUCCESS) { } } } ATWINC15x0 WINC Initialization and Simple Application © 2018 Microchip Technology Inc. User Guide DS00002389B-page 13 4. ATWINC15x0 Configuration The ATWINC15x0 firmware offers a set of configurable parameters that control its behavior. There is a set of APIs provided to the host MCU application to configure these parameters. The configuration APIs are categorized according to their functionality, into device, network and power saving parameters. Any parameters left unset by the host MCU application use their default values assigned during the initialization of the ATWINC15x0 firmware. A host MCU application needs to configure its parameters when coming out of cold boot or when a specific configuration change is required. 4.1 Device Parameters 4.1.1 System Time It is important to set the WINC system to UTC time to ensure a proper validity check of the X509 certificate expiration date. Since the WINC does not contain a built-in Real-Time Clock (RTC), there are two ways to obtain UTC time: • Using the internal SNTP client – this is enabled by default in the WINC firmware at start-up. The SNTP client synchronizes the WINC system clock to the UTC time from the time servers. The NTP server that SNTP client uses can be configured using the API m2m_wifi_configure_sntp. The default NTP server used by the WINC is time-c.nist.gov. The SNTP client uses a default update cycle of one day. • From the host MCU RTC – if the host MCU has a RTC, the application may disable the SNTP client by calling m2m_wifi_enable_sntp(0) (by passing zero as the argument) after the WINC initialization. The application provisions the WINC system time by calling m2m_wifi_set_system_time API. 4.1.2 Firmware and Driver Version During initialization (m2m_wifi_init), the host driver checks the compatibility between the driver and the WINC firmware. The relevant parameters are: • M2M_HIF_MAJOR_VALUE • M2M_HIF_MINOR_VALUE Note:  These parameters are stated in release note version information as “Host Interface Level: X.Y”. If the driver and the WINC firmware have the same values of M2M_HIF_MAJOR_VALUE, then they are deemed compatible and m2m_wifi_init returns with M2M_SUCCESS. If the driver and the WINC firmware have different values of M2M_HIF_MAJOR_VALUE, then they are deemed incompatible and m2m_wifi_init returns with M2M_ERR_FW_VER_MISMATCH. In this case, communication is limited; the only permitted communication is for the driver to request the WINC firmware to switch to the WINC firmware image in the inactive partition of WINC flash, via m2m_wifi_check_ota_rb and m2m_ota_switch_firmware. Example code to handle this situation is available in the driver file m2m_ota.h. 4.2 WINC Modes of Operation The WINC firmware supports the following modes of operation: ATWINC15x0 ATWINC15x0 Configuration © 2018 Microchip Technology Inc. User Guide DS00002389B-page 14 • Idle mode • Wi-Fi STA mode • Wi-Fi Hotspot (AP) Figure 4-1. WINC Modes of Operation IDLE AP STA m2_wifi_connect m2m_wifi_default_connect M2M_WIFI_RESP_CON_STATE_CHANGED m2m_wifi_disconnect m2m_wifi_disable_ap m2m_wifi_enable_ap 4.2.1 Idle Mode After the host MCU application calls the ATWINC15x0 driver initialization m2m_wifi_init API, the ATWINC15x0 remains in Idle mode waiting for any command to change the mode or to update the configuration parameters. In this mode, the ATWINC15x0 enters into Power Save mode which disables the IEEE 802.11 radio and all unneeded peripherals and suspends the ATWINC15x0 CPU. If the ATWINC15x0 receives any configuration commands from the host MCU, it updates the configuration, sends back the response to the host MCU, and then returns to the Power Save mode. 4.2.2 Wi-Fi Station Mode The ATWINC15x0 enters Station (STA) mode when the host MCU requests connection to an AP using the m2m_wifi_connect or m2m_wifi_default_connect APIs. Note:  m2m_wifi_connect is deprecated from v19.6.1 and above. For more details, see 5.3 Wi-Fi Security. The ATWINC15x0 exits STA mode when it receives a disconnect request from the Wi-Fi AP conveyed to the host MCU application via the event callback M2M_WIFI_RESP_CON_STATE_CHANGED or when the host MCU application decides to terminate the connection via m2m_wifi_disconnect API. Note:  The supported API functions in this mode use the HIF command types: tenuM2mConfigCmd and tenuM2mStaCmd. See the full list of commands in the m2m_types.h header file. For more information about STA mode, refer to Wi-Fi Station Mode. 4.2.3 Wi-Fi Hotspot (AP) Mode In AP mode, the WINC allows Wi-Fi stations to connect and obtain the IP address from the WINC DHCP server. To enter AP mode, the host MCU application calls m2m_wifi_enable_ap API. To exit AP mode, the application calls m2m_wifi_disable_ap API. The supported API functions in this mode use the HIF command types: tenuM2mApCmd and tenuM2mConfigCmd. See the full list of commands in the m2m_types.h header file. For more information about this mode, refer to Wi-Fi AP Mode. ATWINC15x0 ATWINC15x0 Configuration © 2018 Microchip Technology Inc. User Guide DS00002389B-page 15 4.3 Network Parameters 4.3.1 Wi-Fi MAC Address The WINC firmware provides two methods to assign the WINC MAC address: • Assignment from the host MCU – this method occurs when the host MCU application calls the m2m_wifi_set_mac_address API after initialization using m2m_wifi_init API. • Assignment from the WINC OTP (One-Time-Programmable) memory – the WINC supports an internal MAC address assignment method through a built-in OTP memory. If MAC address is programmed in the WINC OTP memory, the WINC working MAC address defaults to the OTP MAC address unless the host MCU application programmatically sets a different MAC address after initialization using the API m2m_wifi_set_mac_address. Note:  • OTP MAC address is programmed in the WINC OTP memory at the time of manufacturing. • Use m2m_wifi_get_otp_mac_address API to check if there is a valid programmed MAC address in the WINC OTP memory. The host MCU application can also use the same API to read the OTP MAC address octets. m2m_wifi_get_otp_mac_address API not to be confused with the m2m_wifi_get_mac_address API which reads the working WINC MAC address in the WINC firmware regardless from whether it is assigned from the host MCU or from the WINC OTP. • For more details on API, refer to the Atmel Software Framework for ATWINC1500 (Wi-Fi). 4.3.2 IP Address The ATWINC15x0 firmware uses the embedded DHCP client to automatically obtain an IP configuration after a successful Wi-Fi connection. DHCP is the preferred method and therefore it is used as a default method. After the IP configuration is obtained, the host MCU application is notified by the asynchronous event M2M_WIFI_REQ_DHCP_CONF. Alternatively, the host MCU application can set a static IP configuration by calling the m2m_wifi_set_static_ip API. Before setting a static IP address, it is recommended to disable DHCP using the API m2m_wifi_enable_dhcp(0) and then set the static IP as shown below. In Main(), disable dhcp after m2m_wifi_init as shown below /* Initialize Wi-Fi driver with data and status callbacks. */ param.pfAppWifiCb = wifi_cb; ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret) { printf("main: m2m_wifi_init call error!(%d)\r\n", ret); while (1) {} } m2m_wifi_enable_dhcp(0); Set Static IP when WINC is connected to AP as shown below. static void wifi_cb(uint8_t u8MsgType, void *pvMsg) { switch (u8MsgType) { case M2M_WIFI_RESP_CON_STATE_CHANGED: { tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged *)pvMsg; if (pstrWifiState->u8CurrState == M2M_WIFI_CONNECTED){ printf("Wi-Fi connected\r\n"); tstrM2MIPConfig ip_client; ip_client.u32StaticIP = _htonl(0xc0a80167); // Provide the required Static IP ATWINC15x0 ATWINC15x0 Configuration © 2018 Microchip Technology Inc. User Guide DS00002389B-page 16 ip_client.u32DNS = _htonl(0xc0a80101); // Provide DNS server details ip_client.u32SubnetMask = _htonl(0xFFFFFF00); // Provide the SubnetMask for the currently connected AP ip_client.u32Gateway = _htonl(0xc0a80101); // Provide the GAteway IP for the AP printf("Wi-Fi setting static ip\r\n"); m2m_wifi_set_static_ip(&ip_client); } } } 4.4 Power Save Modes The WINC firmware supports multiple Power Save modes which provide flexibility to the host MCU application to tweak the system power consumption. The host MCU can configure the WINC Power Saving policy using the m2m_wifi_set_sleep_mode and m2m_wifi_set_lsn_int APIs. The WINC supports the following Power Save modes: • M2M_PS_MANUAL • M2M_PS_DEEP_AUTOMATIC • M2M_PS_AUTOMATIC (deprecated, not be used in new implementations) • M2M_PS_H_AUTOMATIC (deprecated, not be used in new implementations) Note:  M2M_PS_DEEP_AUTOMATIC mode recommended for most applications. 4.4.1 M2M_PS_MANUAL This is a fully host-driven Power Save mode. • The WINC sleeps when the host uses the m2m_wifi_request_sleep API. During this period, the host MCU can also sleep for extended durations. • The WINC wakes up when the host MCU application requests services from the WINC by calling any host driver API function, for example, Wi-Fi or socket operation. Note:  In M2M_PS_MANUAL mode, when the WINC sleeps due to m2m_wifi_request_sleep API, the WINC does not wake up to receive and monitor AP beacon. Beacon monitoring is resumed when the host MCU application wakes up the WINC. For an active Wi-Fi connection, the AP may exit the connection if the WINC is unavailable due to long sleep time. If connection is dropped, the WINC detects the disconnection on the next wake-up cycle and notifies the host to reconnect to the AP again. To maintain an active Wi-Fi connection for extended durations, the host MCU application must periodically wake up the WINC in order to send a keep-alive Wi-Fi frame to the AP. The host must carefully choose the sleep period to satisfy the tradeoff between keeping the Wi-Fi connection uninterrupted and minimizing the system power consumption. This mode is useful for applications which send notifications very rarely due to a certain trigger. It also fits applications which periodically send notifications with a very long spacing between notifications. Careful power planning is required when using this mode. If the host MCU decides to sleep for a longer period, it may use M2M_PS_MANUAL or may power off the WINC3 . The advantage of this mode compared to powering off the WINC is that M2M_PS_MANUAL saves the time required for the WINC firmware to boot since the firmware is always loaded in the WINC memory. The real advantage and disadvantage depend on the nature of the application. In some applications, the sleep duration can be long enough to be a 3 Refer to the ATWINC15x0-MR210xB Data Sheet (DS70005304) for more information about the hardware power-up/down sequence. ATWINC15x0 ATWINC15x0 Configuration © 2018 Microchip Technology Inc. User Guide DS00002389B-page 17 power-efficient decision to power off the WINC and then power it on again and reconnect to the AP when the host MCU wakes up. In other situations, a latency-sensitive application may choose to use M2M_PS_MANUAL to avoid the WINC firmware boot latency on the expense of slightly increased power consumption. During the WINC Sleep mode, the WINC in M2M_PS_MANUAL mode saves more power than M2M_PS_DEEP_AUTOMATIC mode. In M2M_PS_MANUAL mode, the WINC skips beacon monitoring whereas in M2M_PS_DEEP_AUTOMATIC mode, it wakes up to receive beacons. The comparison also includes the effect of the host MCU sleep duration: if the host MCU sleeps for a longer period, the Wi-Fi connection may frequently drop and the power advantage of the M2M_PS_MANUAL mode is lost due to the power consumed in the Wi-Fi reconnection. In contrast, the M2M_PS_DEEP_AUTOMATIC mode can keep the Wi-Fi connection for long durations at the expense of waking up the WINC to monitor the AP beacon. 4.4.2 M2M_PS_AUTOMATIC This mode is deprecated and kept for backward compatibility and development reasons. It is not recommended to use in new implementations. 4.4.3 M2M_PS_H_AUTOMATIC This mode is deprecated and kept for backward compatibility and development reasons. It is not recommended to use in new implementations. 4.4.4 M2M_PS_DEEP_AUTOMATIC This mode implements the Wi-Fi standard power-saving method in the WINC module. The WINC sleeps and periodically wakes up to monitor AP beacons. The AP is required to buffer data while stations are in Power Save mode and transmit data when stations wake-up. The AP periodically transmits a beacon frame to synchronize with a network for every beacon period. A station, which is in Power Save mode, periodically wakes up to receive the beacon. The beacon conveys information to the station about pending unicast data, which are buffered inside the AP while the station was in Sleep mode. The beacon also provides information about the broadcast/multicast data. In this mode, the WINC module enters into Sleep state by turning off the IEEE 802.11 radio, MAC, and system clock. Prior to entering the Sleep mode, the ATWINC15x0 programs a hardware timer (running on an internal low-power oscillator) with a sleep period determined by the WINC firmware power management module. Any of the following events can wake-up the WINC module from Sleep state: • Expiry of the hardware sleep timer. The WINC wakes up to receive the upcoming beacon from AP. • The WINC wakes up4 when the host MCU application requests services from the WINC by calling any host driver API function, for example, Wi-Fi or socket operation. 4.5 Configuring Listen Interval and DTIM Monitoring The WINC allows the host MCU application to tweak system power consumption by configuring beacon monitoring parameters. The AP periodically send beacons for every DTIM period (for example, 100 ms). The beacon contains a TIM element which informs the station about the unicast data for the station that are buffered in the AP. The station negotiates with the AP for a listen interval. The listen interval tells the AP for how many beacon periods the station will sleep before it wakes up to receive data buffered in the 4 The wake-up sequence is internally handled in the WINC host driver by the hif_chip_wake API. Refer to Section 15 “Host Interface Protocol” for more information. ATWINC15x0 ATWINC15x0 Configuration © 2018 Microchip Technology Inc. User Guide DS00002389B-page 18 AP. Some APs might drop buffered data after Listen Interval elapses if the data is not retrieved by the station. The WINC driver allows the host MCU application to configure beacon monitoring parameters as follows: • Configure DTIM monitoring – that is to enable or disable reception of broadcast/multicast data using the following API: – m2m_wifi_set_sleep_mode(desired_mode, 1) to receive broadcast data – m2m_wifi_set_sleep_mode(desired_mode, 0) to ignore broadcast data • Configure the listen interval – using the m2m_wifi_set_lsn_int API Note:  Listen interval value provided to the m2m_wifi_set_lsn_int API is expressed in the unit of beacon period. ATWINC15x0 ATWINC15x0 Configuration © 2018 Microchip Technology Inc. User Guide DS00002389B-page 19 5. Wi-Fi Station Mode This chapter provides information about the WINC Wi-Fi Station (STA) mode as described in Wi-Fi Station Mode. The STA mode involves a scan operation; association to an AP using parameters (SSID and credentials) provided by the host MCU or using AP parameters stored in the WINC nonvolatile storage (default connection). The chapter also provides information about supported security modes along with code examples. 5.1 Scan Configuration Parameters 5.1.1 Scan Region The number of RF channels supported varies by geographical region. For example, 13 channels are supported in Asia while 11 channels are supported in North America. By default, the WINC initial region configuration is equal to 14 channels, but this can be changed by setting the scan region using the m2m_wifi_set_scan_region API. The scan region can be selected from the enum tenuM2mScanRegion. 5.1.2 Scan Options During Wi-Fi scan operation, the WINC sends probe request Wi-Fi frames and waits for the scan wait time to receive probe response frames in the current Wi-Fi channel. After the scan wait time, the WINC switches to the next channel. Increasing the scan wait time increases the possibility to detect more number of access points during scan operation but this leads to more power consumption and overall scan duration. The WINC firmware default scan wait time is optimized to provide the tradeoff between the power consumption and scan accuracy. The WINC firmware provides flexible configuration options to allow the host MCU application to set the scan time. For more details, refer to the m2m_wifi_set_scan_options API. 5.2 Wi-Fi Scan A Wi-Fi scan operation can be initiated by calling the m2m_wifi_request_scan API. The scan can be performed on all 2.4GHz Wi-Fi channels or on a specific requested channel. The scan response time depends on the scan options which can be set by calling m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption). For instance, if the host MCU application requests to scan all channels, the scan time is equal to NoOfChannels (13) * ptstrM2MScanOption->u8NumOfSlot * ptstrM2MScanOption->u8SlotTime. The scan operation is illustrated in the following figure. ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 20 Figure 5-1. Wi-Fi Scan Operation 5.3 Wi-Fi Security The following types of security are supported in the WINC Wi-Fi STA mode. • OPEN • WEP (Wired Equivalent Protocol) • WPA/WPA2 (Wi-Fi Protected Access - Personal Security mode that is Passphrase) • 802.1X (WPA/WPA2-Enterprise security) For 802.1X Enterprise Security, the following authentication methods are supported from ATWINC1500 firmware version 19.6.1. • EAP-TLS • EAP-PEAPv0/TLS • EAP-PEAPv1/TLS • EAP-TTLSv0/MSCHAPv2 • EAP-PEAPv0/MSCHAPv2 ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 21 • EAP-PEAPv1/MSCHAPv2 The m2m_wifi_connect is deprecated from v19.6.1 and above firmware. The legacy APIs m2m_wifi_connect and m2m_wifi_connect_sc are available as wrappers for the new APIs. Functionally its behavior is unchanged from previously released drivers. The recommended API for various security type such as OPEN, WEP, WPA/WPA2, 802.1X are summarized in the Table 5-1. All new connect APIs, enable connection to a particular access point by specifying its BSSID and the SSID. To restrict connection to a specific access point, the application can specify the BSSID (in addition to SSID) in the argument tstrNetworkId -> pu8Bssid. The application can instruct the WINC whether to store the credentials or not to store in Flash and also whether the saved credentials must be encrypted or not. This is done by configuring the enum tenuCredStoreOption. For enterprise security, the application can configure WINC to send actual identity or use anonymous identity during phase 1 authentication. This can be done by setting or clearing bUnencryptedUserName in argument tstrAuth1xTls or tstrAuth1xMschap2. For more details on usage of API m2m_wifi_connect_1x_tls, refer ASF (v3.42 or above) example "WINC1500 Connecting a EAP-TLS / PEAPv0 with TLS / PEAPv1 with TLS Secured AP Example". For more details on usage of API m2m_wifi_connect_1x_mschap2, refer ASF (v3.42 or above) example "WINC1500 Connecting a EAP-TTLSv0 with MSCHAPv2 / EAP-PEAPv0 with MSCHAPv2 / EAP-PEAPv1 with MSCHAPv2 Secured AP Example". 5.4 On Demand Wi-Fi Connection The host MCU application may establish a Wi-Fi connection on demand when all the required connection parameters (SSID, security credentials, and so on.) are known to the application. To start a Wi-Fi connection on demand, the application calls the following APIs based on the security type. Table 5-1. List of APIs based on Security Type Security Type API Open m2m_wifi_connect_open WEP m2m_wifi_connect_wep WPA/WPA2 m2m_wifi_connect_psk 802.1x with MSCHAPv2 m2m_wifi_connect_1x_mschap2 802.1x with TLS m2m_wifi_connect_1x_tls Alternatively, the application can call the API m2m_wifi_connect to connect with an access point which supports Open, WEP, WPA/WPA2 and 802.1x with MSCHAPv2. m2m_wifi_connect is deprecated in v19.6.1 and is kept for legacy purpose. Note:  Using the API in the Table 5-1 implies that the host MCU application has prior knowledge of the connection parameters. For instance, connection parameters can be stored on nonvolatile storage attached to the host MCU. The Wi-Fi on demand connection operation is described in the following figure. ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 22 Figure 5-2. On-demand Wi-Fi Connection 5.4.1 Example Code 5.4.1.1 Example Code for Connecting to Enterprise Network (PEAP and TTLSv0) with MSCHAPv2 as Phase2 Authentication #define MAIN_WLAN_SSID "WINC1500_ENTERPRISE" /**< Destination SSID */ #define MAIN_WLAN_802_1X_USR_NAME "DEMO_USER" /**< RADIUS user account name */ #define MAIN_WLAN_802_1X_PWD "DemoPassword" /**< RADIUS user account password */ int main(void) { int8_t ret; tstrWifiInitParam param; tstrNetworkId networkId; tstrAuth1xMschap2 mschapv2_credential; /* Initialize the board. */ system_init(); /* Initialize the UART console. */ configure_console(); printf(STRING_HEADER); /* Initialize the BSP. */ nm_bsp_init(); /* Initialize Wi-Fi parameters structure. */ memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); /* Initialize Wi-Fi driver with data and status callbacks. */ param.pfAppWifiCb = wifi_cb; ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret) { printf("main: m2m_wifi_init call error!(%d)\r\n", ret); while (1) { } } ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 23 networkId.pu8Bssid = NULL; networkId.pu8Ssid = (uint8 *)MAIN_WLAN_SSID; networkId.u8SsidLen = strlen(MAIN_WLAN_SSID); networkId.enuChannel = M2M_WIFI_CH_ALL; mschapv2_credential.pu8Domain = NULL; //mschapv2_credential.u16DomainLen = strlen(mschapv2_credential.pu8Domain); mschapv2_credential.pu8UserName = (uint8 *)MAIN_WLAN_802_1X_USR_NAME; mschapv2_credential.pu8Password = (uint8 *)MAIN_WLAN_802_1X_PWD; mschapv2_credential.u16UserNameLen = strlen(MAIN_WLAN_802_1X_USR_NAME); mschapv2_credential.u16PasswordLen = strlen(MAIN_WLAN_802_1X_PWD); mschapv2_credential.bUnencryptedUserName = false; mschapv2_credential.bPrependDomain = true; printf("Connecting to %s\r\n\tUsername:%s\r\n", MAIN_WLAN_SSID, MAIN_WLAN_802_1X_USR_NAME); m2m_wifi_connect_1x_mschap2( WIFI_CRED_SAVE_ENCRYPTED, &networkId, &mschapv2_credential); /* Infinite loop to handle a event from the WINC1500. */ while (1) { while (m2m_wifi_handle_events(NULL) != M2M_SUCCESS) { } } return 0; } 5.4.1.2 Example Code for Connecting to PEAP Enterprise Network with TLS as Phase2 Authentication and EAP- TLS /** security information for Wi-Fi connection */ #define MAIN_WLAN_SSID "WINC1500_ENTERPRISE" /**< Destination SSID */ #define MAIN_WLAN_802_1X_USR_NAME "DEMO_USER" /**< RADIUS user account name */ const uint8_t modulus[] = { /** private key modulus extracted from key file */ }; const uint8_t exponent[] = { /** private key exponent coefficient extracted from key file */ }; const uint8_t certificate[] = { /** certificate coefficient corresponding to Private Key */ }; int main(void) { int8_t ret; tstrWifiInitParam param; tstrNetworkId networkId; tstrAuth1xTls tls_credential; /* Initialize the board. */ system_init(); /* Initialize the UART console. */ configure_console(); printf(STRING_HEADER); /* Initialize the BSP. */ nm_bsp_init(); /* Initialize Wi-Fi parameters structure. */ memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); /* Initialize Wi-Fi driver with data and status callbacks. */ param.pfAppWifiCb = wifi_cb; ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret) { printf("main: m2m_wifi_init call error!(%d)\r\n", ret); while (1) { } } printf("Username:%s\r\n",MAIN_WLAN_802_1X_USR_NAME); /* Connect to the enterprise network. */ networkId.pu8Bssid = NULL; networkId.pu8Ssid = (uint8 *)MAIN_WLAN_SSID; networkId.u8SsidLen = strlen(MAIN_WLAN_SSID); networkId.enuChannel = M2M_WIFI_CH_ALL; ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 24 tls_credential.pu8Domain = NULL; tls_credential.pu8UserName = (uint8 *)MAIN_WLAN_802_1X_USR_NAME; tls_credential.pu8PrivateKey_Mod = (uint8 *)modulus; tls_credential.pu8PrivateKey_Exp = (uint8 *)exponent; tls_credential.pu8Certificate = (uint8 *)certificate; tls_credential.u16UserNameLen = strlen(MAIN_WLAN_802_1X_USR_NAME); tls_credential.u16PrivateKeyLen = sizeof(modulus); tls_credential.u16CertificateLen = sizeof(certificate); tls_credential.bUnencryptedUserName = true; tls_credential.bPrependDomain = true; printf("Connecting to %s...\r\n\t\tUsername:%s\r \n",networkId.pu8Ssid,tls_credential.pu8UserName); m2m_wifi_connect_1x_tls(WIFI_CRED_SAVE_ENCRYPTED, &networkId, &tls_credential); /* Infinite loop to handle a event from the WINC1500. */ while (1) { while (m2m_wifi_handle_events(NULL) != M2M_SUCCESS) { } } return 0; } 5.5 Default Connection The host MCU application establishes the default connection based on the connection profile stored in the WINC serial Flash using the m2m_wifi_default_connect API. This API does not require AP information to establish the connection. Note:  The connection profile information is automatically stored in the WINC Flash when on-demand WiFi connection API is called (see Table 5-1). Saving of this connection profile is dependent on the enum tenuCredStoreOption. The credentials such as passphrase of the AP or Enterprise certificate and other parameters like SSID, IP address, BSSID are encrypted using AES128-CBC before they are written into the serial Flash. This makes it difficult for an attacker to retrieve the sensitive information even if an attacker has physical access to the device. If there is no cached profile or if a connection cannot be established with any of the cached profile, an event of type M2M_WIFI_RESP_DEFAULT_CONNECT is delivered to the host driver indicating failure. Upon successful default connection, the host application can read the current Wi-Fi connection status by calling m2m_wifi_get_connection_info API. The m2m_wifi_get_connection_info is an asynchronous API. The actual connection information is provided in the asynchronous event M2M_WIFI_RESP_CONN_INFO in Wi-Fi callback. The callback parameter of type tstrM2MConnInfo provides information about AP SSID, RSSI (AP received power level), security type, IP address obtained by DHCP. Note:  A connection profile is cached in the serial Flash if and only if the connection is successfully established with the target AP. The Wi-Fi default connection operation is shown in the following figure. ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 25 Figure 5-3. Wi-Fi Default Connection 5.6 Encrypted Credential Storage In ATWINC15x0 firmware v19.6.1 and above, the credentials such as passphrase of the AP or Enterprise certificate and other parameters like SSID, IP address, BSSID are encrypted using AES128-CBC before they are written into the serial Flash. This makes it difficult for an attacker to retrieve the sensitive information inspite of having physical access to the device. The encryption provided by this feature must not be considered secure. The encryption is only intended to prevent credentials being revealed in plain text by an opportunistic read of ATWINC15x0 Flash. Therefore, other security practices must be followed where possible, such as changing passwords regularly and deleting credentials when they are no longer required. When requesting for a connection to a network, the application can specify how the connection credentials must be stored in ATWINC15x0 Flash. The options are as follows: • Do not store credentials • Store credentials unencrypted • Store credentials encrypted The credentials consist of: • SSID • BSSID (if provided) • WEP key (for WEP connection) • Passphrase and PSK (for WPA/WPA2 PSK connection) • Domain, User name and Password (for WPA/WPA2 1x MSCHAPv2 connection) • Domain, User name, Certificate and Private Key (for WPA/WPA2 1x TLS connection) ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 26 The credentials are stored in ATWINC15x0 Flash when connection succeeds, and only one set of credentials is stored at a time; if new credentials need to be stored then the old credentials are removed (overwritten with 0’s). If credentials are stored in ATWINC15x0 Flash, then the application can request subsequent connections without providing the credentials again, using m2m_wifi_default_connect. If roaming is enabled, roaming can take place regardless of whether the credentials are stored in ATWINC15x0 Flash. (They are stored in data memory for the duration of a connection.) The application can delete credentials from ATWINC15x0 Flash using m2m_wifi_delete_sc. Note:  Version 19.6.1 firmware implements a new format for the ATWINC15x0 Flash store for connection parameters. The effects of this are: • During a firmware upgrade to v19.6.1, previously stored credentials are reformatted. After the first successful connection to an access point, these stored credentials are encrypted. • During a firmware upgrade to v19.6.1, previously stored IP address and Wi-Fi channel are deleted. • After a firmware downgrade from v19.6.1 to previous firmware, credentials stored by v19.6.1 firmware are not readable by the previous firmware. The operation of the previous firmware is otherwise unaffected. 5.7 Simple Roaming Simple Roaming is a custom feature which is supported by WINC firmware version 19.6.1 and above. With Simple Roaming feature enabled, the ATWINC1500 configured as station can move around in an ESS area with multiple access point. The WINC automatically switches to another AP which has the same SSID, authentication procedure and credentials with better signal strength. Roaming enables a station to change its AP while remaining connected to the network. The following figure explains the simple roaming feature. ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 27 Figure 5-4. Simple Roaming STA AP in Range New AP Old AP (1) Probe Request (Ch 1) (2) Probe Response (Ch 1) (1) Probe Request (Ch n) (2) Probe Response (Ch n) (5) Authentication Request (6) Authentication Reply (7) Reassociation Request (12) Reassociation Reply (8) Send Security Block (9) Ack Security Block (10) Move Notify (11) Move Response In v19.6.1, the WINC roam occurs on link-loss detection with the existing AP, which is determined by tracking beacons and sending NULL frame keep-alive packets. ISO/OSI Layer 2 roaming occurs when the WINC roams from one AP to another AP, both of which are inside the same IP subnet. Layer 3 roaming occurs when the WINC roams from one AP to another AP which are in different subnets, whereby the WINC attempts to obtain a new IP address within the new subnet via DHCP. As a result of layer 3 roaming, any existing network connections is broken, and the upper layer protocols handle this IP address change if a continuous connection is required in layers 4 and above. Roaming algorithm is internal to WINC firmware. The Host MCU can enable or disable the roaming functionality using the API's m2m_wifi_enable_roaming and m2m_wifi_disable_roaming. The roaming must be called after the WINC initialization. When roaming is enabled, if the WINC successfully roamed to a new AP, then the M2M_WIFI_RESP_CON_STATE_CHANGED message with state as M2M_WIFI_ROAMED is sent to host MCU. If the WINC is not able to find a new AP, then M2M_WIFI_RESP_CON_STATE_CHANGED message with state as M2M_WIFI_DISCONNECTED is sent to the host MCU. The API call m2m_wifi_enable_roaming() sets the ATWINC15x0 to detect link-loss, and when link loss is detected with the existing access point, the following roaming steps are performed. • A precautionary de-authentication frame is sent to the old AP. • Scanning is performed to determine if there is an AP within the same ESS as the previous AP in the vicinity. • If an AP is found, authentication and re-association messages are exchanged with the new AP, followed by a normal 4-way security handshake in the case of WPA/WPA2, or an EAPOL exchange in the case of 802.1x Enterprise security. ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 28 • A DHCP request is sent to the new AP to attempt to retain the same IP address. A notification event is sent to the host MCU of type M2M_WIFI_RESP_CON_STATE_CHANGE with the state of M2M_WIFI_ROAMED. Additionally, an M2M_WIFI_REQ_DHCP_CONF event conveying either the same or a new IP address is sent to the host MCU. • If there is any problem with the connection, or DHCP fails, then a de-authentication message is sent to the AP, and an M2M_WIFI_RESP_CON_STATE_CHANGED event is sent to the host MCU with the state set as M2M_WIFI_DISCONNECTED. The bEnableDhcp parameter enables control of whether or not a DHCP request is sent after roaming to a new AP. The API call m2m_wifi_disable_roaming is used to disable roaming. 5.8 Multiple Gain Table There are restrictions regarding the maximum transmit power of a wireless device according to the regulatory agencies of the region. For Wi-Fi devices, the maximum transmit power is limited according the regulation of the region in which the Wi-Fi device is used. The gain table can be used to configure the transmission power in WINC. The digital gain (DG) that are used for different channels and different data rates are stored in ATWINC15x0 Flash as a table called Gain table. In ATWINC15x0, the Power Amplifier (PA) and Pre-power Amplifier (PPA) values are configured in the firmware directly. The following figure shows the format of the gain table. Figure 5-5. Gain Table 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 -10 -9 -9 -9 -9 -9 -9 -9 -9 -9 -10 -9 -9 -9 2 -10 -9 -9 -9 -9 -9 -9 -9 -9 -9 -10 -9 -9 -9 5.5 -10 -9 -9 -9 -9 -9 -9 -9 -9 -9 -10 -9 -9 -9 11 -10 -9 -9 -9 -9 -9 -9 -9 -9 -9 -10 -9 -9 -9 6 -11 -7 -7 -7 -7 -7 -7 -7 -7 -7 -9 -7 -7 -7 9 -11 -7 -7 -7 -7 -7 -7 -7 -7 -7 -9 -7 -7 -7 12 -11 -7 -7 -7 -7 -7 -7 -7 -7 -7 -9 -7 -7 -7 18 -11 -7 -7 -7 -7 -7 -7 -7 -7 -7 -9 -7 -7 -7 24 -11 -7 -7 -7 -7 -7 -7 -7 -7 -7 -9 -7 -7 -7 36 -11 -7 -7 -7 -7 -7 -7 -7 -7 -7 -9 -7 -7 -7 48 -11 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 54 -11 -9 -9 -9 -8 -8 -8 -8 -8 -8 -9 -8 -8 -8 mcs0 -12 -7 -7 -7 -7 -7 -7 -7 -7 -7 -10 -7 -7 -7 mcs1 -12 -7 -7 -7 -7 -7 -7 -7 -7 -7 -10 -7 -7 -7 mcs2 -12 -7 -7 -7 -7 -7 -7 -7 -7 -7 -10 -7 -7 -7 mcs3 -12 -7 -7 -7 -7 -7 -7 -7 -7 -7 -10 -7 -7 -7 mcs4 -12 -7 -7 -7 -7 -7 -7 -7 -7 -7 -10 -7 -7 -7 mcs5 -12 -8 -8 -7 -7 -7 -7 -7 -7 -7 -10 -7 -7 -7 mcs6 -12 -9 -8 -8 -8 -8 -8 -8 -8 -8 -10 -8 -8 -8 mcs7 -12 -10 -9 -9 -9 -9 -9 -9 -9 -9 -10 -9 -9 -9 1e9c 0 1edc 0 Data Rates Channels Digital Gain Specific Configuration The Gain tables are provided as part of firmware update package in form of .csv file available at src/ firmware/Tools/gain_builder/gain_sheets folder. The gain values are downloaded as part of complete download process. For more details, see "WINC Devices – Integrated Serial Flash Memory Download Procedure" document. Prior to v19.6.1 only one gain table was supported in ATWINC15x0, with which the WINC can only operate in one regulatory region without requiring different Flash content. The ATWINC15x0 firmware version 19.6.1 or above supports multiple gain table and the Flash can store up to four gain tables. The table can be selected by the Host MCU using the API m2m_wifi_set_gain_table_idx. If the ATWINC15x0 has to operate in multiple region with maximum ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 29 transmit power allowed in that region, multiple gain table feature can be used to select gain table (by Host MCU) based on the region in which the ATWINC15x0 is operated. 5.8.1 Writing the Gain Table to ATWINC15x0 The gain builder application uses multiple .csv files (up to a maximum of 4) and perform the necessary maths operations on the gain table to calculate the gain values and write them to the Flash: gain_builder [-table ] [-index ][-no_wait] [-port] Note:  The img_path* parameters specify the separate tables, and the index parameter specifies the default table to use on power up. 5.8.2 Selecting a Specific Gain Table Setting the specific gain table index is achieved using API m2m_wifi_set_gain_table_idx. The m2m_wifi_set_gain_table_idx must be called after the initialization and before any connection request. The corresponding gain tables must be available in the Flash. Note:  The ATWINC15x0 firmware release v19.6.1 contains only one gain table that can be used in all the region. 5.9 Host File Download The Host File Download is a feature supported in the ATWINC15x0 firmware version 19.6.1 and above. This feature is supported only in the ATWINC1510 device which has 8 Mb Flash. The ATWINC1500 only has 4 Mbit of Flash memory and therefore this feature is not supported for the ATWINC1500. With Host file download feature, the Host MCU can instruct the ATWINC1510 to download a file and save it in the ATWINC1510 Flash. The ATWINC1510 can download the file from a HTTP or a HTTPS web server only. The maximum size of file that can be stored in the ATWINC1510 is 508 KB. This feature is ideal for updating the firmware of host MCU. However, the feature is not limited to MCU OTA only. When performing MCU OTA updates, there is no enforced file format, so the Application Developer can choose a strategy to perform integrity check validation on the received file. The WINC does not perform any integrity check on the downloaded file and therefore, it is recommended that the Application do it instead. The feature is designed for single file support and allows for a maximum size of 508 KB. The driver protects against invalid access to the file stored in the WINC’s Flash by using file handlers to identify each file. If a new download starts or if the file is erased, access to the file partition is denied. Also, the application can request an explicit erase to delete the file from the ATWINC’s Flash, destroying any potentially confidential data. The API m2m_ota_host_file_get is used to download file from remote location and store it in ATWINC1500 Flash. The m2m_ota_host_file_get can be used to download only one file at a time. When the get file API is called again, the previously stored file is erased and new file download is initiated. To retrieve the downloaded file from the ATWINC1510 Flash, m2m_ota_host_file_read_spi or m2m_ota_host_file_read_hif API can be used by the host MCU. The completion of file download is notified through the callback registered in m2m_ota_host_file_get API. The user can use the m2m_ota_host_file_read_spi or m2m_ota_host_file_read_hif API by passing required arguments to initiate the file read from the WINC Flash. ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 30 5.9.1 Overview Whenever an application needs information which is stored in a file somewhere in a remote location, the application can use the Host File Download feature to retrieve the file from the remote location and temporarily store it in the WINC’s Flash. When a download is successfully completed, a file handler is generated and stored in NVM in the WINC, therefore it is valid even after a WINC reset. After a handler is generated, access to the file is possible via the provided APIs and reading of a file is possible via two mechanisms, HIF and SPI. In either case, the read operation requires the file handler of the file which the application is trying to access, if the handler being requested and the handler internally stored match, then the access is granted. The same procedure is valid for erasing the file. The use of a file handler avoids access to invalid data, for example when trying to concurrently access the file. The following figure depicts the steps which the WINC follows when performing a Host File Download. Figure 5-6. Host File Download Operation within the WINC OTA File Get Check Available Space Start Download OTA Get Successful OTA Get Failed Notify Host of the Result OK Failed Completed Failed The download starts only if the space available in Flash is enough to store the file which is requested to be downloaded. If Host File Download is requested in the ATWINC1500 (4 Mb Flash), the download fails since there is no Host File partition in Flash and therefore no space to store the file. The “Start Download” step causes any previously available valid file handler to be invalidated. When “OTA Get Successful” message is received, a new file handler is generated along with the status and the total size of the downloaded file, they are included in the Download completion notification sent to the host. 5.9.2 OTA Initialization To use the Host File Download feature, the WINC and the OTA driver must be initialized. The following is the procedure for OTA initialization: 1. m2m_wifi_init or m2m_wifi_reinit – this API is required to initialize the WINC and to set up the callback for the HIF communication. After this step, the WINC can be configured to connect to a network and download a file. For more details to understand when to use each of these two options, see the API documentation. ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 31 2. m2m_ota_init – this API registers the OTA callback, which is required to execute any callbacks configured through the Host File Download APIs and to notify the Application of file download status. 5.9.3 Using Host File Download for MCU OTA Host File Download allows an application to download a file from a remote location. The link to the file can be through a secure connection and once the file is downloaded, it is stored in the WINC's Flash and the Application is notified about it. The files to download can be of any kind and are not limited to MCU binaries, making this feature both flexible and powerful. One example would be the download of text files, which can hold, for instance, a file checksum, which can later be used by the Application to verify the integrity of the downloaded binary. An Host MCU OTA requires the following steps: • Provide an http/https link to the file to tell WINC to download the file from a specific remote location, which can be done using API m2m_ota_host_file_get. • Read the image from the WINC using spi_flash_read. Since there is a limitation currently in which the bootloader would also need to perform m2m_wifi_init, m2m_ota_init and only then it should do m2m_ota_host_file_read_spi to read the image from WINC. m2m_ota_host_file_read_hif and m2m_ota_host_file_read_spi are not used in the ASF Example for MCU OTA to keep the driver footprint small while working around the limitation described above. However, this limitation is only present when the Application needs to be reset, or in this case switch to a bootloader, the WINC driver will lose track of the file handler and will have to load it again through the initialization process. If no reset or shutdown need to be performed and if no different Application needs to be loaded after downloading the file, these two APIs can be used. Figure 5-7. Example Host File Download for MCU OTA File Get CB Application WINC Bootloader WINC File Integrity Check Switch to Bootloader Switch to Application File Handler inval File Handler gen MCU & WINC Reset m2m_wifi_init() m2m_ota_init() **Connect to Wi-Fi network** m2m_ota_host_file_get() HIF Msg M2M_OTA_RESP_HOST_FILE_DOWNLOAD m2m_wifi_download_mode() spi_flash_read() ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 32 Other steps that must be considered by the Application Developer are: • It is recommended to verify the integrity of the image using a checksum calculation and match it against a previously known checksum. The user can design the validation mechanism since no predefined file format is enforced for MCU OTA. • There is an option to erase the file from Flash. Although this is not mandatory before requesting a new download, it can be useful for security purposes, ensuring that sensitive data is unavailable after its use. Note:  The WINC does not perform any integrity check of any of the downloaded files via Host File Download and that must be checked by the application. 5.9.4 API Description For a more detailed description of the APIs, refer to WINC1500_SW_API.chm. 5.9.4.1 OTA File Get NMI_API sint8 m2m_ota_host_file_get ( unsigned char *pcDownloadUrl, tpfFileGetCb pfHFDGetCb ); This API is used to get a file which links to the file stored remotely. The link is passed to the WINC to establish a TCP connection to retrieve the file from that location. It is also possible to use a server configured for TLS. A callback must also be provided so that it is executed when the File Get operation completes. The status of the File Get is passed onto this callback and if the status is successful, the file handler generated by the WINC and the total size of the downloaded file is passed correctly to the callback. 5.9.4.2 File Get Callback typedef void (*tpfFileGetCb) ( uint8 u8Status, uint8 u8Handler, uint32 u32Size ); The callback for the File Get receives three arguments; status of the File Get request, file handler ID and the total size of the file. If the status is OTA_STATUS_SUCCESS, then the file handler and size can be used, otherwise its values are not populated. From the Application’s point of view, they must not be considered valid. The file handler is auto-generated in the WINC and it identifies the file. Only when a download finishes successfully, the corresponding file handler is generated. The handler is required to both read from the file or erase the file. Similarly, if the download is aborted or interrupted, then the handler is not generated, instead the handler will have the value of HFD_INVALID_HANDLER, which blocks any further operation on the Flash through the APIs. When the file download completes successfully, the total size of the download file is passed to the callback to notify the application. Using which the application tracks the total size of the downloaded data and the amount of data read. 5.9.4.3 OTA File Read HIF NMI_API sint8 m2m_ota_host_file_read_hif ( uint8 u8Handler, uint32 u32Offset, uint32 u32Size, ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 33 tpfFileReadCb pfHFDReadCb ); When the download completes, the file is stored in the WINC’s Flash. This API can be used to read the file from the WINC using HIF messages. It is mandatory to have a valid handler, not having one could mean that the file has been invalidated and therefore it must be unavailable for any operation. This protects read against invalid or corrupted data. The offset marks the position in bytes of Flash to read from, counting from the beginning of the file. Therefore, an offset of zero is translated as reading from the beginning of the file. Size specifies the amount of bytes to read, starting at the offset defined. The last argument is the callback to be executed when the read is complete. Advantages (vs SPI read) • While reading a file using HIF messages, the host can continue operation, being notified by an interrupt from the WINC when data read is complete. • Does not require the WINC to be reset after the read is complete. Disadvantages (vs SPI read) • File reads via HIF are slightly slower than reads via SPI. 5.9.4.4 File Read HIF Callback typedef void (*tpfFileReadCb) ( uint8 u8Status, void *pBuff, uint32 u32Size ); The callback is only executed after a file read via HIF messages and it receives three arguments. • The first argument is the status of the read, if the read is unsuccessful, then the other arguments will have irrelevant values. • The second argument is a pointer to the buffer of data read. • The third argument is size, which indicates the amount of data read and therefore contained in the buffer (maximum 128 bytes). Specifying large amounts of data to be read via the HIF may exceed the buffer maximum size (128 bytes), therefore it is recommended to use u32Size to offset a second read from within this callback. This requires the application to track the total size of the file and the amount of bytes read, requesting the reading of each section at a time until the end of the file is reached. 5.9.4.5 OTA File Read SPI NMI_API sint8 m2m_ota_host_file_read_spi ( uint8 u8Handler, uint8 *pu8Buff, uint32 u32Offset, uint32 u32Size ); The file read via SPI is similar to the read via HIF. The use of a callback is not considered, because to access the WINC’s Flash via SPI, the WINC must be set into a certain mode to allow for safe read/write of its Flash. Therefore, it is typical to use a loop to read all the data necessary while the WINC is in that state and then restart the WINC. To use this API, the application must call m2m_wifi_download_mode to make the WINC safe for read/ write Flash access and once the read is completed, the WINC must be reinitialized (m2m_wifi_reinit, ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 34 m2m_ota_init) and to connect to the network again if the Application based on the request. pu8Buff is a pointer to a buffer provided by the Application and to where the data will be read to. Advantages (vs HIF read) • SPI read is faster than HIF Read. Disadvantages (vs HIF read) • Requires the WINC to set into a special mode and restart later. • Generally blocks as the read are done within a loop to minimize WINC reset. 5.9.4.6 OTA File Erase API NMI_API sint8 m2m_ota_host_file_erase ( uint8 u8Handler, tpfFileEraseCb pfHFDEraseCb ); The File Erase API requires the following two arguments: • The first argument is a handler of the file to erase, to ensure that it is valid to perform a Flash erase. • The second argument is a callback which executes when the erase is complete. Having a callback to tell the Application when the erase has been completed is useful to act as a trigger for a subsequent operation (example, download a second file). Note:  The file erase performs an erase of the entire host file partition and any file handler is destroyed regardless of the end result of the erase operation in the WINC. Since the data in the Flash is partially or completely destroyed, the handlers are invalidated when the process starts for safety. 5.9.4.7 File Erase Callback typedef void (*tpfFileEraseCb) ( uint8 u8Status ); The callback for a File Erase receives the erase status of the operation. A status of OTA_STATUS_SUCCESS ensures that the data has been completely erased, any other result does not ensure that the data is still valid, but also do not ensure that the data has been completely erased. 5.9.4.8 OTA Abort API NMI_API sint8 m2m_ota_abort ( void ); If a Host File Download has been started and the Application decides to cancel the download, it can issue a call to this API to do so. This does not require any input parameter. Note:  This API is shared with the WINC OTA and if issued when a WINC OTA is in progress, the WINC OTA is canceled. 5.9.5 Limitations • Out of 512 KB of Flash in the ATWINC1510, the first sector (of size 4 KB) is used by the WINC for storing the file information for host file download feature. Which means that a total of 508 KB size of Flash can be used by application to store the host file. • The feature is only supported in ATWINC1510 since the ATWINC1500 only has 4 Mbit of Flash memory, which means there is no space to store a file. ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 35 • There is no file system and only one file is stored at a time. When the get file is called again, the previously stored file is erased and a new file download is initiated. • The WINC OTA firmware download and the Host OTA file download cannot run concurrently. • The WINC interprets 404 Not Found error when application attempts to download a broken or dead link and provides the OTA_STATUS_SERVER_ERROR error status. The WINC does not interpret any other message for broken link. The WINC downloads the error message into SPI Flash and indicates Host as file download. It is the application’s responsibility to check if the file is valid. 5.9.6 Built in Automated Test Equipment (ATE) Mechanism A factory flashed ATWINC15x0 module running the v19.6.1 firmware has a special ATE firmware in the Flash space reserved for OTA transfers (which is overwritten by the first OTA update). A host API can be called during WINC initialization that causes the device to boot into this special firmware (m2m_ate_init). The API to control the ATE functions provided by this firmware is detailed in \ASF\common\components\wifi\winc1500\driver\include\m2m_ate_mode.h. The following is the sample code. int main(void) { /* Initialize the board. */ system_init(); /* Initialize the UART console. */ configure_console(); printf(STRING_HEADER); /* Initialize the BSP. */ nm_bsp_init(); /*Check if initialization of ATE firmware is succeeded or not*/ if(M2M_SUCCESS == m2m_ate_init()) { /*Run TX test case if defined*/ #if (M2M_ATE_RUN_TX_TEST_CASE == ENABLE) start_tx_test(M2M_ATE_TX_RATE_1_Mbps_INDEX); #endif /*Run RX test case if defined*/ #if (M2M_ATE_RUN_RX_TEST_CASE == ENABLE) start_rx_test(); #endif /*De-Initialization of ATE firmware test mode*/ m2m_ate_deinit(); } else { M2M_ERR("Failed to initialize ATE firmware.\r\n"); while(1); } #if ((M2M_ATE_RUN_RX_TEST_CASE == ENABLE) && (M2M_ATE_RUN_TX_TEST_CASE == ENABLE)) M2M_INFO("Test cases have been finished.\r\n"); #else M2M_INFO("Test case has been finished.\r\n"); #endif while(1); } #if (M2M_ATE_RUN_TX_TEST_CASE == ENABLE) static void start_tx_test(uint8_t tx_rate) { tstrM2mAteTx tx_struct; ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 36 /*Initialize parameter structure*/ m2m_memset((uint8 *)&tx_struct, 0 , sizeof(tx_struct)); /*Set TX Configuration parameters, *refer to tstrM2mAteTx for more information about parameters*/ tx_struct.channel_num = M2M_ATE_CHANNEL_11; tx_struct.data_rate = m2m_ate_get_tx_rate(tx_rate); tx_struct.dpd_ctrl = M2M_ATE_TX_DPD_DYNAMIC; tx_struct.duty_cycle = M2M_ATE_TX_DUTY_1; tx_struct.frame_len = 1024; tx_struct.num_frames = 0; tx_struct.phy_burst_tx = M2M_ATE_TX_SRC_MAC; tx_struct.tx_gain_sel = M2M_ATE_TX_GAIN_DYNAMIC; tx_struct.use_pmu = M2M_ATE_PMU_DISBLE; tx_struct.cw_tx = M2M_ATE_TX_MODE_CW; tx_struct.xo_offset_x1000 = 0; /*Start TX Case*/ if(M2M_ATE_SUCCESS == m2m_ate_start_tx(&tx_struct)) { uint32 u32TxTimeout = M2M_ATE_TEST_DURATION_IN_SEC; M2M_INFO(">>Running TX Test case on CH<%02u>.\r\n", tx_struct.channel_num); do { nm_bsp_sleep(1000); printf("%02u\r", (unsigned int)u32TxTimeout); }while(--u32TxTimeout); if(M2M_ATE_SUCCESS == m2m_ate_stop_tx()) { M2M_INFO("Completed TX Test successfully.\r\n"); } } else { M2M_INFO("Failed to start TX Test case.\r\n"); } } #endif #if (M2M_ATE_RUN_RX_TEST_CASE == ENABLE) static void start_rx_test(void) { tstrM2mAteRx rx_struct; /*Initialize parameter structure*/ m2m_memset((uint8 *)&rx_struct, 0, sizeof(rx_struct)); /*Set RX Configuration parameters*/ rx_struct.channel_num = M2M_ATE_CHANNEL_6; rx_struct.use_pmu = M2M_ATE_PMU_DISBLE; rx_struct.xo_offset_x1000 = 0; /*Start RX Case*/ if(M2M_ATE_SUCCESS == m2m_ate_start_rx(&rx_struct)) { tstrM2mAteRxStatus rx_data; uint32 u32RxTimeout = M2M_ATE_TEST_DURATION_IN_SEC; M2M_INFO(">>Running RX Test case on CH<%02u>.\r\n", rx_struct.channel_num); do { m2m_ate_read_rx_status(&rx_data); M2M_INFO("Num Rx PKTs: %d, Num ERR PKTs: %d, PER: %1.3f", (int)rx_data.num_rx_pkts, (int)rx_data.num_err_pkts, (rx_data.num_rx_pkts>0)?((double)rx_data.num_err_pkts/ (double)rx_data.num_rx_pkts):(0)); nm_bsp_sleep(1000); }while(--u32RxTimeout); printf("\r\n"); if(M2M_ATE_SUCCESS == m2m_ate_stop_rx()) { M2M_INFO("Compeleted RX Test successfully.\r\n"); } } ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 37 else { M2M_INFO("Failed to start RX Test case.\r\n"); } } #endif ATWINC15x0 Wi-Fi Station Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 38 6. Socket Programming 6.1 Overview The ATWINC15x0 socket Application Programming Interface (API) allows the host MCU application to interact with intranet and remote internet hosts. The ATWINC15x0 socket API is based on the BSD (Berkeley) sockets. This chapter explains the ATWINC15x0 socket programming and how it differs from regular BSD sockets. Note:  The reader must have a basic understanding of the following topics before reading this chapter: • BSD sockets • TCP • UDP • Internet protocols 6.1.1 Socket Types The ATWINC15x0 socket API provides two types of sockets: • Datagram sockets (connectionless sockets) – uses the UDP protocol • Stream sockets (connection-oriented sockets) – uses the TCP protocol 6.1.2 Socket Properties Each ATWINC15x0 socket is identified by a unique combination of the following: • Socket ID – a unique identifier for each socket. This is the return value of the socket API. • Local socket address – a combination of the ATWINC15x0 IP address and port number assigned by the ATWINC15x0 firmware for the socket. • Protocol – transport layer protocol, either TCP or UDP. • Remote socket address – applicable only for TCP stream sockets. This is necessary since TCP is connection oriented. Each connection made to a specific IP address and port number requires a separate socket. The remote socket address can be obtained in the socket event callback which is described in the succeeding section. Note:  TCP port 53 and UDP port 53 represent two different sockets. 6.1.3 Limitations • The ATWINC15x0 sockets API support up to 7 TCP sockets and 4 UDP sockets. • The ATWINC15x0 sockets API support only IPv4. It does not support IPv6. 6.2 Sockets API 6.2.1 API Prerequisites • C header file socket.h – this includes all the necessary socket API function declarations. When using any ATWINC15x0 socket API as described in the following sections, the host MCU application must include the socket.h header file. • Initialization – the ATWINC15x0 socket API initializes once before calling any socket API function. This is done using the socketInit API described in Socket API Functions. ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 39 6.2.2 Non-blocking Asynchronous Socket APIs Most ATWINC15x0 socket APIs are asynchronous function calls that do not block the host MCU application. The behavior of the ATWINC15x0 asynchronous APIs are described in Asynchronous Events. For example, the host MCU application can register an application-defined socket event callback function using the ATWINC15x0 socket API registerSocketCallback. When the host MCU application calls the socket API connect, the API returns a zero value (SUCCESS) immediately indicating that the request is accepted. The host MCU application must then wait for the ATWINC15x0 socket API to call the registered socket callback when the connection is established or if a connection time-out occurred. The socket callback function provides the necessary information to determine the connection status. 6.2.3 Socket API Functions The ATWINC15x0 socket API provides the following functions. 6.2.3.1 socketInit The host MCU application must call the API socketInit once during initialization. The API is a synchronous API. 6.2.3.2 registerSocketCallback The registerSocketCallback function allows the host MCU application to provide the ATWINC15x0 sockets with application-defined event callbacks for socket operations. The API is a synchronous API. The API registers the following callbacks: • The socket event callback • The DNS resolve callback The socket event callback is an application-defined function that is called by the ATWINC15x0 socket API whenever a socket event occurs. Within this handler, the host MCU application must provide an application-defined logic that handles the events of interest. The DNS resolve event handler is the application-defined function that is called by the ATWINC15x0 socket API to return the results of gethostbyname. By implication, this only occurs after the host MCU application has called the gethostbyname function. If successful, the callback provides the IP address for the desired domain name. 6.2.3.3 socket The socket function creates a new socket of a specified type and returns the corresponding socket ID. The API is a synchronous API. The socket ID is required by most other socket functions and is also passed as an argument to the socket event callback function to identify which socket generated the event. 6.2.3.4 connect The connect function is used with TCP sockets to establish a new connection to a TCP server. The connect function results in a SOCKET_MSG_CONNECT sent to the socket event handler callback upon completion. The connect event is sent when the TCP server accepts the connection or, if no remote host response is received, after a time-out interval of approximately 30 seconds. Note:  The SOCKET_MSG_CONNECT event callback provides a tstrSocketConnectMsg containing an error code. The error code value indicates: • Zero value to indicate the successful connection or ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 40 • Negative value to indicate an error due to a time-out condition or if connect is used with UDP socket. The following figure shows the ATWINC15x0 socket API connect to remote server host. Figure 6-1. TCP Client API Call Sequence 6.2.3.5 bind The bind function can be used for server operation for both UDP and TCP sockets. It is used to associate a socket with an address structure (port number and IP address). The bind function call results to a SOCKET_MSG_BIND event sent to the socket callback handler with the bind status. Calls to listen, send, sendto, recv, and recvfrom functions must not be issued until the bind callback is received. 6.2.3.6 listen The listen function is used for server operations with TCP stream sockets. After calling the listen API, the socket accepts a connection request from a remote host. The listen function causes a SOCKET_MSG_LISTEN event notification to be sent to the host after the socket port is ready to indicate listen operation success or failure. ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 41 When a remote peer establishes a connection, a SOCKET_MSG_ACCEPT event notification is sent to the application. 6.2.3.7 accept The accept function is deprecated and calling this API has no effect. It is kept only for backward compatibility. Note:  The listen API implicitly accepts the TCP remote peer connections request. Figure 6-2. TCP Server API Call Sequence Although the accept function is deprecated, the SOCKET_MSG_ACCEPT event occurs whenever a remote host connects to the ATWINC15x0 TCP server. The event message contains the IP address and port number of the connected remote host. 6.2.3.8 send The send function is used by the application to send data to a remote host. The send function can be used to send either UDP or TCP data depending on the type of socket. • For a TCP socket a connection must be established first. • For a UDP socket, the recommended way is to use sendto API, where the destination address is defined. However, it is possible to use send API instead of sendto API. For this, at least one successful call must be made to sendto API prior to the consecutive calls of send function. This ensures that the destination address is saved in the ATWINC15x0 firmware. The send function generates a SOCKET_MSG_SEND event callback after the data is transmitted to the remote host. For TCP sockets, this event guarantees that the data is delivered to the remote host TCP/IP stack (the remote application must use the recv function to read the data). For UDP sockets, it means that the data is transmitted, but there is no guarantee that the data is delivered to the remote host as per UDP protocol. The application is responsible to guarantee data delivery in the UDP sockets case. The SOCKET_MSG_SEND event callback returns the size of the data transmitted of the transmission in the success case and zero or negative value in case of an error. ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 42 6.2.3.9 sendto The sendto function is used by the application to send UDP data to a remote host. It can only be used with UDP sockets. The IP address and port of the destination remote host is included as a parameter to the sendto function. The SOCKET_MSG_SENDTO event callback returns the size of the data transmitted in the success case and zero or negative value in case of an error. 6.2.3.10 recv/recvfrom The recv and recvfrom functions are used to read data from TCP and UDP sockets, respectively, and their operation is otherwise identical. The host MCU application calls the recv or recvfrom function with a pre allocated buffer. When the SOCKET_MSG_RECV or SOCKET_MSG_RECVFROM event callback arrives, this buffer must have the received data. The received data size indicates the status as follows: • Positive – data is received • Zero – socket connection is terminated • Negative – indicates an error In the case of TCP sockets, it is recommended to call the recv function after each successful socket connection (client or server). Otherwise, the received data is buffered in the ATWINC15x0 firmware wasting the system's resources until the socket is explicitly closed using a close function call. 6.2.3.11 close The close function is used to release the resources allocated to the socket and, for a TCP stream socket, also terminate an open connection. Each call to the socket function must match with a call to the close function. In addition, sockets that are accepted on a server socket port must be closed using this function. 6.2.3.12 setsockopt The setsockopt function may be used to set socket options to control the socket behavior. The options supported are as follows: • SO_SET_UDP_SEND_CALLBACK – enables or disables the send /sendto event callbacks. The user may want to disable the sendto event callback for UDP sockets to enhance the socket connection throughput. • IP_ADD_MEMBERSHIP – enables subscribe to an IP Multicast address. • IP_DROP_MEMBERSHIP – enables unsubscribe to an IP Multicast address. • SOL_SSL_SOCKET – sets SSL Socket. The following are the options supported for SSL socket: – SO_SSL_BYPASS_X509_VERIF command allows opening of the SSL socket to bypass the X509 certification verification process. Example: struct sockaddr_in addr_in; int optVal =1; addr_in.sin_family = AF_INET; addr_in.sin_port = _htons(MAIN_HOST_PORT); addr_in.sin_addr.s_addr = gu32HostIp; /* Create secure socket */ if (tcp_client_socket < 0) { tcp_client_socket = socket(AF_INET, SOCK_STREAM, ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 43 SOCKET_FLAGS_SSL); } /* Check if socket was created successfully */ if (tcp_client_socket == -1) { printf("socket error.\r\n"); close(tcp_client_socket); return -1; } /* Enable X509 bypass verification */ setsockopt(tcp_client_socket, SOL_SSL_SOCKET,SO_SSL_BYPASS_X509_VERIF,&optVal,sizeof(optVal)); /* If success, connect to socket */ if (connect(tcp_client_socket, (struct sockaddr *)&addr_in, sizeof(struct sockaddr_in)) != SOCK_ERR_NO_ERROR) { printf("connect error.\r\n"); return SOCK_ERR_INVALID; } – SO_SSL_SNI command sets the Server Name Indicator (SNI). During TLS handshake process, client can indicate which hostname it is trying to connect by setting Server Name in (extended) client hello. SNI allows a server to present multiple certificates on the same IP address and TCP port number and hence allows multiple secure websites to be served by the same IP address without requiring all of the websites to use the same certificate. – SO_SSL_ENABLE_SNI_VALIDATION enables SNI validation functionality in case SNI is set. The server name validation is disabled by default. To enable server name validation, both SO_SSL_SNI and SO_SSL_ENABLE_SNI_VALIDATION must be set by the application through setsockopt() as shown in the example code snippet. When the SNI validation is enabled, the SNI is compared with the common name (CN) in the received server certificate. If the supplied SNI does not match the CN, the SSL connection will be forcibly closed by the ATWINC15x0 firmware. Example: #define MAIN_HOST_NAME "www.google.com" struct sockaddr_in addr_in; int optVal =1; addr_in.sin_family = AF_INET; addr_in.sin_port = _htons(MAIN_HOST_PORT); addr_in.sin_addr.s_addr = gu32HostIp; /* Create secure socket */ if (tcp_client_socket < 0) { tcp_client_socket = socket(AF_INET, SOCK_STREAM, SOCKET_FLAGS_SSL); } /* Check if socket was created successfully */ if (tcp_client_socket == -1) { printf("socket error.\r\n"); close(tcp_client_socket); return -1; } /* set SNI on SSL Socket */ setsockopt(tcp_client_socket, SOL_SSL_SOCKET,SO_SSL_SNI, MAIN_HOST_NAME,sizeof(MAIN_HOST_NAME)); /* Enable SSL SNI validation */ setsockopt(tcp_client_socket, SOL_SSL_SOCKET, SO_SSL_ENABLE_SNI_VALIDATION,&optVal,sizeof(optVal)); /* If success, connect to socket */ if (connect(tcp_client_socket, (struct sockaddr *)&addr_in, sizeof( ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 44 struct sockaddr_in)) != SOCK_ERR_NO_ERROR) { printf("connect error.\r\n"); return SOCK_ERR_INVALID; } – SO_SSL_ENABLE_SESSION_CACHING command allows the TLS to cache the session information to speed up the future TLS session establishment. Example: struct sockaddr_in addr_in; int optVal =1; addr_in.sin_family = AF_INET; addr_in.sin_port = _htons(MAIN_HOST_PORT); addr_in.sin_addr.s_addr = gu32HostIp; /* Create secure socket */ if (tcp_client_socket < 0) { tcp_client_socket = socket(AF_INET, SOCK_STREAM, SOCKET_FLAGS_SSL); } /* Check if socket was created successfully */ if (tcp_client_socket == -1) { printf("socket error.\r\n"); close(tcp_client_socket); return -1; } /* Enable SSL Session cache */ setsockopt(tcp_client_socket, SOL_SSL_SOCKET,SO_SSL_ENABLE_SESSION_CACHING,&optVal,sizeof(optVal)); /* If success, connect to socket */ if (connect(tcp_client_socket, (struct sockaddr *)&addr_in, sizeof(struct sockaddr_in)) != SOCK_ERR_NO_ERROR) { printf("connect error.\r\n"); return SOCK_ERR_INVALID; } WARNING SO_SSL_BYPASS_X509_VERIF is only provided for debugging and testing purposes. It is NOT recommended to use this socket option in production software applications. 6.2.3.13 gethostbyname The gethostbyname function is used to resolve a host name (for example, URL) to a host IP address via the Domain Name System (DNS). This is limited only to IPv4 addresses. The operation depends on the configuration of a DNS server IP address and access to the DNS hierarchy through the internet. After gethostbyname is called, a callback to the DNS resolver handler is made. If the IP address is determined, a positive value is returned. If it cannot be determined or if the DNS server is not accessible (30-second time-out), an IP address value of zero is indicated. Note:  An IP returns a zero value to indicate an error (for example, the internet connection is down or DNS is unavailable) and the host MCU application may try the function call gethostbyname again later. 6.2.4 Summary The following table summarizes the ATWINC15x0 socket API and shows its compatibility with BSD socket APIs. ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 45 Table 6-1. ATWINC15x0 Socket API Summary BSD API ATWINC15x0 API ATWINC15x0 API Type Server/ Client TCP/UD P Brief socket socket Synchronous Both Both Creates a new socket. connect connect Asynchronous Client TCP Initializes a TCP connection request to a remote server. bind bind Asynchronous Server Both Binds a socket to an address (address/port). listen listen Asynchronous Server TCP Allows a bound socket to listen to remote connections for its local port. accept accept Deprecated, Implicit accept in listen. send send Asynchronous Both Both Sends packet. sendto sendto Asynchronous Both UDP Sends packet over UDP sockets. write - Not supported recv recv Asynchronous Both Both Receives packet. recvfrom recvfrom Asynchronous Both Both Receives packet. read - Not supported close close Synchronous Both Both Terminates the TCP connection and release system resources. gethostbyname gethostbyname Asynchronous Both Both Gets the IP address of a certain host name gethostbyaddr - Not supported select - Not supported poll - Not supported setsockopt setsockopt Synchronous Both Both Sets socket option. getsockopt Not supported htons/ntohs _htons/_ntohs Synchronous Both Both Converts 2 byte integer from the host representation to the Network byte order representation (and vice versa). ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 46 ...........continued BSD API ATWINC15x0 API ATWINC15x0 API Type Server/ Client TCP/UD P Brief htonl/ntohl21 _htonl/_ntohl Synchronous Both Both Converts 4 byte integer from the host representation to the Network byte order representation (and vice versa). 6.3 Socket Connection Flow In the following sub-sections, the TCP and UDP (client and server) operations are described in details. Figure 6-3. Typical Socket Connection Flow ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 47 6.3.1 TCP Client Operation The following figure shows the flow for transferring data with a TCP client. Figure 6-4. TCP Client Sequence Diagram Note:  1. The host application must register a socket notification callback function. The function must be of tpfAppSocketCb type and must handle socket event notifications appropriately. 2. If the client knows the IP of the server, it may call connect directly as shown in the figure above. If only the server URL is known, then the application must resolve the server URL first calling the gethostbyname API. ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 48 6.3.2 TCP Server Operation Figure 6-5. TCP Server Sequence Diagram Note:  The host application must register a socket notification callback function. The function must be of type tpfAppSocketCb and must handle socket event notifications appropriately. 6.3.3 UDP Client Operation The following figure shows the flow for transferring data with a UDP client. Figure 6-6. UDP Client Sequence Diagram ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 49 Note:  1. The first send message must be performed with the sendto API with the destination address specified. 2. If further messages are sent to the same address, the send API can also be used. For more details, refer to send. 3. recv can be used instead of recvfrom. 6.3.4 UDP Server Operation The following figure shows the flow for transferring data after establishing a UDP server. Figure 6-7. UDP Server Sequence Diagram 6.3.5 DNS Host Name Resolution The following figure shows the flow of DNS host name resolution. Figure 6-8. DNS Resolution Sequence ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 50 Note:  1. The host application requests to resolve hostname (for example, http://www.foobar.com), by calling the function gethostbyname. 2. Before calling the gethostbyname, the application must register a DNS response callback function using the function registerSocketCallback. 3. After the ATWINC15x0 DNS_Resolver module obtains the IP Address (hostIP) corresponding to the given HostName, the dnsResolveCB is called with the hostIP. 4. If an error occurs or if the DNS request encounters a time-out, the dnsResolveCB is called with IP Address value zero indicating a failure to resolve the domain name. 6.4 Example Code This section provides code examples for different socket applications. For additional socket code examples, refer to the Wi-Fi Network Controller Software Programming Guide. 6.4.1 TCP Client Example Code SOCKET clientSocketHdl; uint8 rxBuffer[256]; /* Socket event handler. */ void tcpClientSocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg) { if(sock == clientSocketHdl) { if(u8Msg == SOCKET_MSG_CONNECT) { // Connect Event Handler. tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg; if(pstrConnect->s8Error == 0) { // Perform data exchange. uint8 acSendBuffer[256]; uint16 u16MsgSize; // Fill in the acSendBuffer with some data here // send data send(clientSocketHdl, acSendBuffer, u16MsgSize, 0); // Recv response from server. recv(clientSocketHdl, rxBuffer, sizeof(rxBuffer), 0); } else { printf("TCP Connection Failed\n"); } } else if(u8Msg == SOCKET_MSG_RECV) { tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg; if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0)) { // Process the received message. // Close the socket. close(clientSocketHdl); } } } } // This is the DNS callback. The response of gethostbyname is here. void dnsResolveCallback(uint8* pu8HostName, uint32 u32ServerIP) { struct sockaddr_in strAddr; ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 51 if(u32ServerIP != 0) { clientSocketHdl = socket(AF_INET,SOCK_STREAM,u8Flags); if(clientSocketHdl >= 0) { strAddr.sin_family = AF_INET; strAddr.sin_port = _htons(443); strAddr.sin_addr.s_addr = u32ServerIP; connect(clientSocketHdl, (struct sockaddr*)&strAddr, sizeof(struct sockaddr_in)); } } else { printf("DNS Resolution Failed\n"); } } /* This function needs to be called from main function. For the callbacks to be invoked correctly, the API m2m_wifi_handle_events should be called continuously from main. */ void tcpConnect(char *pcServerURL) { // Initialize the socket layer. socketInit(); // Register socket application callbacks. registerSocketCallback(tcpClientSocketEventHandler, dnsResolveCallback); // Resolve Server URL. gethostbyname((uint8*)pcServerURL); } 6.4.2 TCP Server Example Code SOCKET listenSocketHdl, acceptedSocketHdl; uint8 rxBuffer[256]; uint8 bIsfinished = 0; /* Socket event handler. */ void tcpServerSocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg) { if(u8Msg == SOCKET_MSG_BIND) { tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; if(pstrBind->status == 0) { listen(listenSocketHdl, 0); } else { printf("Bind Failed\n"); } } else if(u8Msg == SOCKET_MSG_LISTEN) { tstrSocketListenMsg *pstrListen = (tstrSocketListenMsg*)pvMsg; if(pstrListen->status != 0) { printf("listen Failed\n"); } } else if(u8Msg == SOCKET_MSG_ACCEPT) { // New Socket is accepted. tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg *)pvMsg; if(pstrAccept->sock >= 0) { // Get the accepted socket. acceptedSocketHdl = pstrAccept->sock; recv(acceptedSocketHdl, rxBuffer, sizeof(rxBuffer), 0); } else ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 52 { printf("Accept Failed\n"); } } else if(u8Msg == SOCKET_MSG_RECV) { tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg; if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0)) { // Process the received message // Perform data exchange uint8 acSendBuffer[256]; uint16 u16MsgSize; // Fill in the acSendBuffer with some data here // Send some data. send(acceptedSocketHdl, acSendBuffer, u16MsgSize, 0); // Recv response from client. recv(acceptedSocketHdl, rxBuffer, sizeof(rxBuffer), 0); // Close the socket when finished. if(bIsfinished) { close(acceptedSocketHdl); close(listenSocketHdl); } } } } /* This function needs to be called from main function. For the callbacks to be invoked correctly, the API m2m_wifi_handle_events should be called continuously from main. */ void tcpStartServer(uint16 u16ServerPort) { struct sockaddr_in strAddr; // Initialize the socket layer. socketInit(); // Register socket application callbacks. registerSocketCallback(tcpServerSocketEventHandler, NULL); // Create the server listen socket. listenSocketHdl = socket(AF_INET, SOCK_STREAM, 0); if(listenSocketHdl >= 0) { strAddr.sin_family = AF_INET; strAddr.sin_port = _htons(u16ServerPort); strAddr.sin_addr.s_addr = 0; //INADDR_ANY bind(listenSocketHdl, (struct sockaddr*)&strAddr, sizeof(struct sockaddr_in)); } } 6.4.3 UDP Client Example Code SOCKET clientSocketHdl; uint8 rxBuffer[256], acSendBuffer[256]; /* Socket event handler */ void udpClientSocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg) { if((u8Msg == SOCKET_MSG_RECV) || (u8Msg == SOCKET_MSG_RECVFROM)) { tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg; if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0)) { uint16 len; // Format a message in the acSendBuffer and put its length in len sendto(clientSocketHdl, acSendBuffer, len, 0, (struct sockaddr*)&strAddr, sizeof(struct sockaddr_in)); recvfrom(clientSocketHdl, rxBuffer, sizeof(rxBuffer), 0); ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 53 // Close the socket after finished close(clientSocketHdl); } } } /* This function needs to be called from main function. For the callbacks to be invoked correctly, the API m2m_wifi_handle_events should be called continuously from main.*/ void udpClientStart(char *pcServerIP) { struct sockaddr_in strAddr; // Initialize the socket layer. socketInit(); // Register socket application callbacks. registerSocketCallback(udpClientSocketEventHandler, NULL); clientSocketHdl = socket(AF_INET,SOCK_STREAM,u8Flags); if(clientSocketHdl >= 0) { uint16 len; strAddr.sin_family = AF_INET; strAddr.sin_port = _htons(1234); strAddr.sin_addr.s_addr = nmi_inet_addr(pcServerIP); // Format some message in the acSendBuffer and put its length in len sendto(clientSocketHdl, acSendBuffer, len, 0, (struct sockaddr*)&strAddr, sizeof(struct sockaddr_in)); recvfrom(clientSocketHdl, rxBuffer, sizeof(rxBuffer), 0); } } 6.4.4 UDP Server Example Code SOCKET serverSocketHdl; uint8 rxBuffer[256]; /* Socket event handler.*/ void udpServerSocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg) { if(u8Msg == SOCKET_MSG_BIND) { tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; if(pstrBind->status == 0) { // call Recv recvfrom(serverSocketHdl, rxBuffer, sizeof(rxBuffer), 0); } else { printf("Bind Failed\n"); } } else if(u8Msg == SOCKET_MSG_RECV) { tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg; if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0)) { // Perform data exchange. uint8 acSendBuffer[256]; uint16 u16MsgSize; // Fill in the acSendBuffer with some data // Send some data to the same address. sendto(acceptedSocketHdl, acSendBuffer, u16MsgSize, 0, pstrRecvMsg-> strRemoteAddr, sizeof(pstrRecvMsg-> strRemoteAddr)); // call Recv recvfrom(serverSocketHdl, rxBuffer, sizeof(rxBuffer), 0); // Close the socket when finished. close(serverSocketHdl); } ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 54 } } /* This function needs to be called from main function. For the callbacks to be invoked correctly, the API m2m_wifi_handle_events should be called continuously from main. */ void udpStartServer(uint16 u16ServerPort) { struct sockaddr_in strAddr; // Initialize the socket layer. socketInit(); // Register socket application callbacks. registerSocketCallback(udpServerSocketEventHandler, NULL); // Create the server listen socket. listenSocketHdl = socket(AF_INET, SOCK_DGRAM, 0); if(listenSocketHdl >= 0) { strAddr.sin_family = AF_INET; strAddr.sin_port = _htons(u16ServerPort); strAddr.sin_addr.s_addr = 0; //INADDR_ANY bind(serverSocketHdl, (struct sockaddr*)&strAddr, sizeof(struct sockaddr_in)); } } ATWINC15x0 Socket Programming © 2018 Microchip Technology Inc. User Guide DS00002389B-page 55 7. Transport Layer Security (TLS) Transport Layer Security (TLS) layer sits on top of TCP and provides security services including privacy, authenticity, and message integrity. Various security methods are available with TLS in the WINC firmware. 7.1 TLS Overview The ATWINC15x0 features an embedded low-memory footprint TLS protocol stack bundled within the WINC firmware. It features the following functionality: • Supports TLS versions TLS1.0, TLS1.1 and TLS1.2. • Supports TLS client operation with TLS client authentication. • Supports TLS Server mode. • A simple application interface to the TLS stack. The TLS functionality is abstracted by the ATWINC15x0 socket interface, hiding the implementation complexity from the application developer and minimizing the effort to port existing plain TCP code to TLS. 7.2 TLS Connection Establishment From the application’s point of view, the TLS functionality is wrapped behind the socket APIs. This hides the complexity of TLS from the application which can use the TLS in the same way as the TCP (non-TLS) client and server. The main difference between the TLS sockets and the regular TCP sockets is that the application sets the SOCKET_FLAGS_SSL while creating the TLS client and server listening sockets. The detailed sequence of TLS connection establishment is described in the following figure. Note:  • For proper TLS Client operation, ensure that both SOCKET_FLAGS_SSL flag and the correct port number is set in the TLS client application. For instance, an HTTP client application uses no flag when calling socket API function and connect to port 80. The same application source code becomes an HTTPS client application if you use the flag SOCKET_FLAGS_SSL and change the port number in connect API to port 433. • For proper TLS server operation, ensure that both SOCKET_FLAGS_SSL flag and the correct port number is set in the TLS server application. For instance, an HTTP server application uses no flag when calling socket API function and bind to port 80. The same application source code becomes an HTTPS server application, if you use the flag SOCKET_FLAGS_SSL and change the port number in bind API to port 443. ATWINC15x0 Transport Layer Security (TLS) © 2018 Microchip Technology Inc. User Guide DS00002389B-page 56 Figure 7-1. TLS Client Application Connection Establishment ATWINC15x0 Transport Layer Security (TLS) © 2018 Microchip Technology Inc. User Guide DS00002389B-page 57 Figure 7-2. TLS Server Application Connection Establishment 7.3 Server Certificate Installation 7.3.1 Technical Background 7.3.1.1 Public Key Infrastructure The TLS security is based on the Public Key Infrastructure PKI, in which: • A server has its public key stored in a digital certificate with X.509 standard format. • The server must have its X.509 certificate issued by Certificate Authority (CA) which in turn may be certified by another CA. ATWINC15x0 Transport Layer Security (TLS) © 2018 Microchip Technology Inc. User Guide DS00002389B-page 58 • This structure forms a chain of X.509 certificates known as chain of trust. • The top most CA of the Chain is known to be the Trusted Root Certificate Authority of the chain. 7.3.1.2 TLS Server Authentication • When a TLS client initiates a connection with a server, the server sends its X.509 certificate chain (may or may not include the root certificate) to the client. • The client must authenticate the Server (verify the Server identity) before starting data exchange. • The client must verify the entire certificate chain and also verify that the root certificate authority of the chain is in the client’s trusted root certificate store. 7.3.2 Adding a Certificate to the WINC Trusted Root Certificate Store • Before connecting to a TLS Server, the root certificate of the server must be installed on the ATWINC15x0. If this is not done, the TLS connection to the server is locally aborted by the WINC. • The root certificate must be in DER format. If it is not provided in DER format, it must be converted before installation. Refer to Section 17 “How to Generate Certificates” for certificate formats and conversion methods. • To install the certificate, execute root_certificate_downloader.exe with the following syntax: root_certificate_downloader.exe -n N File1.cer File2.cer .... FileN.cer 7.4 WINC TLS Limitations 7.4.1 Concurrent Connections Only 2 TLS concurrent connections are allowed. 7.4.2 TLS Supported Ciphers The ATWINC15x0 supports the following cipher suites (for both client and server modes). • TLS_DHE_RSA_WITH_AES_128_CBC_SHA • TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 • TLS_RSA_WITH_AES_128_CBC_SHA • TLS_RSA_WITH_AES_128_CBC_SHA256 The ATWINC15x0 also optionally support the following ECC cipher suites. • TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA • TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 • TLS_ECDHE_ ECDSA _WITH_AES_128_CBC_SHA256 7.4.3 Supported Hash Algorithms The current implementation (WINC firmware version 19.5.2 onwards) supports the following hash algorithms: • MD5 • SHA-1 • SHA256 • SHA384 • SHA512 • RSA 4096 ATWINC15x0 Transport Layer Security (TLS) © 2018 Microchip Technology Inc. User Guide DS00002389B-page 59 7.4.4 TLS Certificate Constraints For TLS server and TLS client authentication, the ATWINC15x0 can accept the following certificate types: • RSA certificates with key size no more than 2048 bits • ECDSA certificates only for NIST P256 EC Curve (secp256r1); conditionally supported 7.4.5 ECC Cipher Suite The ATWINC15x0 TLS library features support of ECC cipher suites. Although, the ATWINC15x0 device does not contain a built-in hardware accelerator for ECC math, the WINC TLS library leverages the ECC math from the host MCU. To perform the ECC computations needed by the ECC ciphers, an ECC hardware accelerator (or software library) on the host MCU is mandatory. The WINC TLS initializes with the ECC cipher suites disabled by default. The host MCU application can enable the ciphers via the API sslSetActiveCipherSuites. 7.5 SSL Client Code Example SOCKET sslSocketHdl; uint8 rxBuffer[256]; /* Socket event handler. */ void SSL_SocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg) { if(sock == sslSocketHdl) { if(u8Msg == SOCKET_MSG_CONNECT) { // Connect event tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg; if(pstrConnect->s8Error == 0) { // Perform data exchange. uint8 acSendBuffer[256]; uint16 u16MsgSize; // Fill in the acSendBuffer with some data here // Send some data. send(sock, acSendBuffer, u16MsgSize, 0); // Recv response from server. recv(sslSocketHdl, rxBuffer, sizeof(rxBuffer), 0); } else { printf("SSL Connection Failed\n"); } } else if(u8Msg == SOCKET_MSG_RECV) { tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg; if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0)) { // Process the received message here // Close the socket if finished. close(sslSocketHdl); } } } } /* This is the DNS callback. The response of gethostbyname is here. */ void dnsResolveCallback(uint8* pu8HostName, uint32 u32ServerIP) { struct sockaddr_in strAddr; if(u32ServerIP != 0) { ATWINC15x0 Transport Layer Security (TLS) © 2018 Microchip Technology Inc. User Guide DS00002389B-page 60 sslSocketHdl = socket(AF_INET,SOCK_STREAM,u8Flags); if(sslSocketHdl >= 0) { strAddr.sin_family = AF_INET; strAddr.sin_port = _htons(443); strAddr.sin_addr.s_addr = u32ServerIP; connect(sslSocketHdl, (struct sockaddr*)&strAddr, sizeof(struct sockaddr_in)); } } else { printf("DNS Resolution Failed\n"); } } /* This function needs to be called from main function. For the callbacks to be invoked correctly, the API m2m_wifi_handle_events should be called continuously from main.*/ void SSL_Connect(char *pcServerURL) { // Initialize the socket layer. socketInit(); // Register socket application callbacks. registerSocketCallback(SSL_SocketEventHandler, dnsResolveCallback); // Resolve Server URL. gethostbyname((uint8*)pcServerURL); } ATWINC15x0 Transport Layer Security (TLS) © 2018 Microchip Technology Inc. User Guide DS00002389B-page 61 8. Wi-Fi AP Mode 8.1 Overview This chapter provides an overview of the WINC Access Point (AP) mode and describes how to setup this mode and configure its parameters. In ATWINC1500 v19.6.1 firmware and above, the DHCP default gateway, DNS server and subnet mask can be customized when entering AP and provisioning modes. Earlier, the default gateway and DNS server is the same as the host IP of the WINC and the subnet mask is 255.255.255.0. Configuring these values allow the use of 0.0.0.0 for the default gateway and DNS server, allowing mobile devices to connect to the WINC AP without disconnecting from the mobile network. Using IPs other than 0.0.0.0 is possible but it is of no use since only one device can connect to the WINC AP at any time. 8.2 Setting the WINC AP Mode Set the WINC AP mode configuration parameters using the tstrM2MAPConfig structure. There are two functions to enable/disable the WINC AP mode: • sint8 m2m_wifi_enable_ap (CONST tstrM2MAPConfig* pstrM2MAPConfig) • sint8 m2m_wifi_disable_ap (void) For more details on API, refer to the Atmel Software Framework for ATWINC1500 (Wi-Fi). In ATWINC1500 v19.6.1 firmware and above, to maintain backwards compatibility with older drivers, new structures and APIs were introduced. To customize these fields when entering AP or provisioning mode the tstrM2MAPModeConfig structure must be populated and passed to the new m2m_wifi_enable_ap_ext() or m2m_wifi_start_provision_mode_ext() APIs. The tstrM2MAPModeConfig structure contains the original tstrM2MAPConfig structure for storing the AP SSID, password, and so on. and another tstrM2MAPConfigExt structure for configuring the default router, DNS server and subnet mask. 8.3 Limitations • The AP can only support a single associated station. Further connection attempts are rejected. • The ATWINC15x0 supports WPA2 security feature starting from the firmware version 19.5.x. • Concurrency (simultaneous STA and AP mode) is not supported. Prior to activating the AP mode, the host MCU application must disable the mode that is currently running. 8.4 Sequence Diagram Once AP mode is established, data interface does not exist before a station associates to the AP; therefore, the application needs to wait until it receives a notification via an event callback. This process is shown in the following figure. ATWINC15x0 Wi-Fi AP Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 62 Figure 8-1. ATWINC15x0 AP Mode Establishment 8.5 AP Mode Code Example The following example shows how to configure the ATWINC15x0 AP mode with WINC_SSID as broadcasted SSID on channel one with open security and an IP address equals 192.168.1.1. #include "m2m_wifi.h" #include "m2m_types.h" void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) { switch(u8WiFiEvent) { case M2M_WIFI_REQ_DHCP_CONF: { uint8 *pu8IPAddress = (uint8*)pvMsg; printf("Associated STA has IP Address \"%u.%u.%u.%u\"\n", pu8IPAddress[0], pu8IPAddress[1], pu8IPAddress[2], pu8IPAddress[3]); } break; default: break; } } int main() { tstrWifiInitParam param; /* Platform specific initializations. */ ATWINC15x0 Wi-Fi AP Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 63 param.pfAppWifiCb = wifi_event_cb; if (!m2m_wifi_init(¶m)) { tstrM2MAPConfig apConfig; strcpy(apConfig.au8SSID, "WINC_SSID"); // Set SSID apConfig.u8SsidHide = SSID_MODE_VISIBLE; // Set SSID to be broadcasted apConfig.u8ListenChannel = 1; // Set Channel apConfig.u8SecType = M2M_WIFI_SEC_WEP; // Set Security to WEP apConfig.u8KeyIndx = 0; // Set WEP Key Index apConfig.u8KeySz = WEP_40_KEY_STRING_SIZE; // Set WEP Key Size strcpy(apConfig.au8WepKey, "1234567890"); // Set WEP Key // IP Address apConfig.au8DHCPServerIP[0] = 192; apConfig.au8DHCPServerIP[1] = 168; apConfig.au8DHCPServerIP[2] = 1; apConfig.au8DHCPServerIP[3] = 1; // Start AP mode m2m_wifi_enable_ap(&apConfig); while(1) { m2m_wifi_handle_events(NULL); } } } Note:  Power Save mode is not supported in the ATWINC15x0 AP mode. ATWINC15x0 Wi-Fi AP Mode © 2018 Microchip Technology Inc. User Guide DS00002389B-page 64 9. Provisioning For normal operation the ATWINC15x0 device requires certain parameters to be loaded. In particular, when operating in Station mode, it must know the identity (SSID) and credentials of the access point to which it needs to connect. The entry of this information is facilitated through the following provisioning steps. The current ATWINC15x0 software supports the following methods of provisioning: • HTTP-based (browser) provisioning, while the WINC is in AP mode • Wi-Fi Protected Setup (WPS) 9.1 HTTP Provisioning In this method, the ATWINC15x0 is placed in AP mode and another device with a browser capability (mobile phone, tablet, PC, and so on) is instructed to connect to the ATWINC15x0 HTTP server. Once connected, the desired configuration can be entered. The HTTP Provisioning home page is as shown in the following figure. Figure 9-1. ATWINC15x0 HTTP Provisioning Page ATWINC15x0 Provisioning © 2018 Microchip Technology Inc. User Guide DS00002389B-page 65 9.1.1 Provisioning Control Flow Figure 9-2. HTTP Provisioning Sequence Diagram The preceding figure shows the provisioning operation for a WINC device. The detailed steps are described as follows: 1. The WINC device starts the HTTP Provisioning mode. 2. A user with a smartphone finds the WINC AP SSID in the Wi-Fi search list. 3. The user connects to the WINC AP. 4. The user launches the web browser and writes the WINC home page in the address bar. 5. If the HTTP redirect bit (bEnableHttpRedirect) is set in m2m_wifi_start_provision_mode API, then all http traffic (http://URL) from the associated device (Phone, PC, and so on) are redirected to the WINC HTTP Provisioning home page. Some phones display a notification message “sign in to Wi-Fi networks?” which, when accepted, automatically loads the WINC home page. The WINC home page, as shown in Figure 10.1, appears on the browser. 6. To discover the list of Wi-Fi APs in the area, the user can press “Refresh”. 7. The desired AP is then selected from the search list (by one click or one touch) and its name automatically appears in the “Network Name” text box. ATWINC15x0 Provisioning © 2018 Microchip Technology Inc. User Guide DS00002389B-page 66 8. The user must then enter the correct AP passphrase (for WPA/WPA2 personal security) in the “Pass Phrase” text box. If the desired AP uses open security, (M2M_WIFI_SEC_OPEN) then the Pass Phrase field is left empty. 9. A WINC device name may be optionally configured, if desired, by the user in the “Device Name” text box. 10. Then user should press Connect. The WINC turns off AP mode and start connecting to the provisioned AP. 9.1.2 HTTP Redirect Feature The ATWINC15x0 HTTP Provisioning server supports the HTTP redirect feature, which forces all HTTP traffic originating from the associated user device to be redirected to the ATWINC15x0 Provisioning home page. This simplifies the mechanism of loading the provisioning page instead of typing the exact web address of the HTTP Provisioning server. To enable this feature, set the redirect flag when calling the API m2m_wifi_start_provision_mode. For further details, refer to the following code example. 9.1.3 Provisioning Code Example void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) { if(u8WiFiEvent == M2M_WIFI_RESP_PROVISION_INFO) { tstrM2MProvisionInfo *provInfo = (tstrM2MProvisionInfo*)pvMsg; if(provInfo->u8Status == M2M_SUCCESS) { // connect to the provisioned AP. m2m_wifi_connect((char*)provInfo->au8SSID, strlen(provInfo ->au8SSID), provInfo->u8SecType, provInfo->au8Password, M2M_WIFI_CH_ALL); printf("PROV SSID : %s\n", provInfo->au8SSID); printf("PROV PSK : %s\n", provInfo->au8Password); } else { printf("(ERR) Provisioning Failed\n"); } } } int main() { tstrWifiInitParam param; // Platform specific initializations. // Driver initialization. param.pfAppWifiCb = wifi_event_cb; if(!m2m_wifi_init(¶m)) { tstrM2MAPConfig apConfig; uint8 bEnableRedirect = 1; strcpy(apConfig.au8SSID, "WINC_AP"); apConfig.u8ListenChannel = 1; apConfig.u8SecType = M2M_WIFI_SEC_OPEN; apConfig.u8SsidHide = 0; // IP Address apConfig.au8DHCPServerIP[0] = 192; apConfig.au8DHCPServerIP[1] = 168; apConfig.au8DHCPServerIP[2] = 1; apConfig.au8DHCPServerIP[0] = 1; m2m_wifi_start_provision_mode(&apConfig, "atmelconfig.com", bEnableRedirect); ATWINC15x0 Provisioning © 2018 Microchip Technology Inc. User Guide DS00002389B-page 67 while(1) { m2m_wifi_handle_events(NULL); } } } 9.2 Limitations The current implementation of the HTTP Provisioning has the following limitations: • The ATWINC15x0 AP limitations are applicable to the Provisioning mode. For a list of AP mode limitations, refer to Limitations. • Provisioning uses AP mode with open security. No Wi-Fi security nor application level security (for example, TLS) is used; therefore, the AP credentials entered by the user are sent on the clear and can be seen by eavesdroppers. • The WINC Provisioning home page is a static HTML page. No server-side scripting allowed in the WINC HTTP server. • Only APs with WPA-personal security (passphrase based) and no security (Open network) can be provisioned. WEP and WPA-Enterprise APs cannot be provisioned. • The Provisioning is responsible to deliver the connection parameters to the application, the connection procedure and the connection parameters validity are the application's responsibility. 9.3 Wi-Fi Protected Setup (WPS) Most modern Access Points support Wi-Fi Protected Setup method, typically using the push button method. From the user’s perspective WPS is a simple mechanism to make a device connect securely to an AP without remembering passwords or passphrases. WPS uses asymmetric cryptography to form a temporary secure link which is then used to transfer a passphrase (and other information) from the AP to the new station. After the transfer, secure connections are made as for normal static PSK configuration. 9.3.1 WPS Configuration Methods There are two authentication methods that can be used with WPS: 1. PBC (push button) method – A physical button is pressed on the AP which puts the AP into WPS mode for a limited period of time. WPS is initiated on the ATWINC15x0 by calling m2m_wifi_wps with input parameter WPS_PBC_TRIGGER. 2. PIN method – The AP is always available for WPS initiation but requires proof that the user has knowledge of an 8-digit PIN, usually printed on the body of the AP. Since the WINC is often used in headless devices (no user interface), it is necessary to reverse this process and force the AP to use a PIN number provided with the WINC device. Some APs allow the PIN to be changed through configuration. WPS is initiated on the ATWINC15x0 by calling m2m_wifi_wps with input parameter WPS_PIN_TRIGGER. Given the difficulty of this approach, it is not recommend for most applications. The flow of messages and actions for WPS operation is shown in the following figure. ATWINC15x0 Provisioning © 2018 Microchip Technology Inc. User Guide DS00002389B-page 68 9.3.2 WPS Control Flow Figure 9-3. WPS Operation for Push Button Trigger 9.3.3 WPS Limitations • WPS is used to transfer the WPA/WPA2 key only; other security types are not supported. • The WPS standard rejects the session (WPS response fail) if the WPS button is pressed on more than one AP in the same proximity, and the application can try again after a couple of minutes. • If no WPS button is pressed on the AP, the WPS scan will time-out after two minutes since the initial WPS trigger. • The WPS is responsible to deliver the connection parameters to the application, the connection procedure and the connection parameters’ validity is the application's responsibility. 9.3.4 WPS Code Example void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) { if(u8WiFiEvent == M2M_WIFI_REQ_WPS) { tstrM2MWPSInfo *pstrWPS = (tstrM2MWPSInfo*)pvMsg; if(pstrWPS->u8AuthType != 0) { printf("WPS SSID : %s\n",pstrWPS->au8SSID); printf("WPS PSK : %s\n",pstrWPS->au8PSK); printf("WPS SSID Auth Type : %s\n", pstrWPS->u8AuthType == M2M_WIFI_SEC_OPEN ? "OPEN" : "WPA/WPA2"); printf("WPS Channel : %d\n",pstrWPS->u8Ch + 1); // Establish Wi-Fi connection m2m_wifi_connect((char*)pstrWPS->au8SSID, (uint8)m2m_strlen(pstrWPS->au8SSID), pstrWPS->u8AuthType, pstrWPS->au8PSK, pstrWPS->u8Ch); } ATWINC15x0 Provisioning © 2018 Microchip Technology Inc. User Guide DS00002389B-page 69 else { printf("(ERR) WPS Is not enabled OR Timedout\n"); } } } int main() { tstrWifiInitParam param; // Platform specific initializations. // Driver initialization. param.pfAppWifiCb = wifi_event_cb; if(!m2m_wifi_init(¶m)) { // Trigger WPS in Push button mode. m2m_wifi_wps(WPS_PBC_TRIGGER, NULL); while(1) { m2m_wifi_handle_events(NULL); } } } ATWINC15x0 Provisioning © 2018 Microchip Technology Inc. User Guide DS00002389B-page 70 10. Over-The-Air Upgrade 10.1 Overview The ATWINC15x0 supports OTA upgrade of firmware on internal serial Flash. No host Flash memory resources are required to store the firmware. The ATWINC15x0 uses an internal HTTP client to retrieve the firmware from a remote server. 10.2 OTA Image Architecture The WINC serial Flash can store two copies of the firmware image: a working image and a rollback image. Upon first-time boot, the working image is the factory image and the rollback image will not be available in the WINC Flash. Instead ATE firmware will be available in rollback image firmware section. On performing the OTA firmware upgrade, the ATE firmware will be erased and the newly received firmware will be written into the Roll back image section. The WINC has insufficient internal memory to save the whole image in RAM during an OTA upgrade; therefore, each block of downloaded data is written to the Flash as it is received. In the event that the OTA fails, the existing (Working) image is retained and the rollback image is invalidated. If the transfer succeeds, the Flash control structure is updated to reflect a new working image and the existing image is marked as a valid rollback image. Figure 10-1. OTA Image Organization ATWINC15x0 Over-The-Air Upgrade © 2018 Microchip Technology Inc. User Guide DS00002389B-page 71 10.3 OTA Download Sequence Diagram Figure 10-2. OTA Image Download and Install 10.4 OTA Firmware Rollback Figure 10-3. OTA Image Rollback Sequence ATWINC15x0 Over-The-Air Upgrade © 2018 Microchip Technology Inc. User Guide DS00002389B-page 72 10.5 OTA Limitations • Rollback is allowed, only after at least one successful OTA download. • Rollback image is overwritten by any new successful or failed OTA attempt. 10.6 OTA Code Example /*! */ static void OtaUpdateCb(uint8 u8OtaUpdateStatusType ,uint8 u8OtaUpdateStatus) { if(u8OtaUpdateStatusType == DL_STATUS) { if(u8OtaUpdateStatus == OTA_STATUS_SUCSESS) { //switch to the upgraded firmware m2m_ota_switch_firmware(); } } else if(u8OtaUpdateStatusType == SW_STATUS) { if(u8OtaUpdateStatus == OTA_STATUS_SUCSESS) { M2M_INFO("Now OTA suceesfully done"); //start the host SW upgrade then system reset is required (Reintilize the driver) } } } void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) { case M2M_WIFI_REQ_DHCP_CONF: { //after suceesfull connection, start the over air upgrade m2m_ota_start_update(OTA_URL); } break; default: break; } int main (void) { tstrWifiInitParam param; tstr1xAuthCredentials gstrCred1x = AUTH_CREDENTIALS; nm_bsp_init(); m2m_memset((uint8*)¶m, 0, sizeof(param)); param.pfAppWifiCb = wifi_event_cb; //intilize the WINC Driver ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret) { M2M_ERR("Driver Init Failed <%d>\n",ret); while(1); } //intilize the ota module m2m_ota_init(OtaUpdateCb,NULL); //connect to AP that provide connection to the OTA server m2m_wifi_default_connect(); while(1) { while(m2m_wifi_handle_events(NULL) != M2M_SUCCESS) {} } } Note:  For more details on example codes, refer to the Wi-Fi Network Controller Software Programming Guide. ATWINC15x0 Over-The-Air Upgrade © 2018 Microchip Technology Inc. User Guide DS00002389B-page 73 11. Multicast Sockets 11.1 Overview The purpose of the multicast filters is to provide the ability to send/receive messages to/from multicast addresses. This feature is useful for one-to-many communication over networks, whether it’s intended to send Internet Protocol (IP) datagrams to a group of interested receivers in a single transmission, participate in a zero-configuration networking or listening to a multicast stream or any other application. 11.2 How to Use Filters Whenever the application wishes to use a multicast IP address, for either sending or receiving, a filter is needed. The application can establish this through setting the IP_ADD_MEMBERSHIP option for the required socket accompanied by the multicast address that the application wants to use. If subsequently the host wants to stop receiving the multicast stream, set the IP_DROP_MEMBERSHIP option for the required socket accompanied with the multicast address. Adding or removing a multicast address filter causes the WINC chip firmware to add/remove both MAC layer filter and IP layer filter in order to pass or prevent messages from reaching to the host. 11.3 Multicast Socket Code Example To illustrate the functionality, a simple example is implemented where the host application responds to mDNS (Multicast Domain Name System) queries sent from a computer/mobile application. The computer/ mobile is looking for devices which support the zero configuration service as indicated by an mDNS response. The WINC responds, notifying its presence and its capability of sending and receiving multicast messages. The example consists of a UDP server that binds on port 5353 (mDNS port) and waits for messages, parsing them and replying with a previously saved response message. • Server Initialization: void MDNS_ServerInit() { tstrSockAddr strAddr ; unsigned int MULTICAST_IP = 0xE00000FB; //224.0.0.251 socketInit(); dns_server_sock = socket( AF_INET, SOCK_DGRAM,0); MDNS_INFO("DNS_server_init \n"); setsockopt(dns_server_sock,1,IP_ADD_MEMBERSHIP,&MULTICAST_IP,sizeof(MULTICAST_IP)); strAddr.u16Port =HTONS(MDNS_SERVER_PORT); bind(dns_server_sock,(struct sockaddr*)&strAddr,sizeof(strAddr)); registerSocketCallback(UDP_SocketEventHandler,AppServerCb); } • Sockets Events Handler: void MDNS_RecvfromCB(signed char sock,unsigned char *pu8RxBuffer,signed short s16DataSize, unsigned char *pu8IPAddr,unsigned short u16Port,void *pvArg) { MDNS_INFO("DnsServer_RecvfromCB \n"); if((pu8RxBuffer != 0) && (s16DataSize > 0)) { tstrDnsHdr strDnsHdr; strdnsquery; MDNS_INFO("DNS Packet Recieved \n"); ATWINC15x0 Multicast Sockets © 2018 Microchip Technology Inc. User Guide DS00002389B-page 74 if(MDNS_ParseQuery(&pu8RxBuffer[0], &strDnsHdr,&strDnsQuery)) MDNS_SendResp (sock,pu8IPAddr, u16Port,&strDnsHdr,&strDnsQuery ); } else { MDNS_INFO("DnsServer_RecvfromCB Error !\n"); } } • Server Socket Callback: void MDNS_RecvfromCB(signed char sock,unsigned char *pu8RxBuffer,signed short s16DataSize,unsigned char *pu8IPAddr,unsigned short u16Port,void *pvArg) { MDNS_INFO("DnsServer_RecvfromCB \n"); if((pu8RxBuffer != 0) && (s16DataSize > 0)) { tstrDnsHdr strDnsHdr ; strdnsquery ; MDNS_INFO("DNS Packet Recieved \n"); if(MDNS_ParseQuery(&pu8RxBuffer[0], &strDnsHdr,&strDnsQuery)) MDNS_SendResp (sock,pu8IPAddr, u16Port,&strDnsHdr,&strDnsQuery ); } else { MDNS_INFO("DnsServer_RecvfromCB Error !\n"); } } • Parse mDNS Query: int MDNS_ParseQuery(unsigned char * pu8RxBuffer, tstrDnsHdr *pstrDnsHdr, strdnsquery *pstrDnsQuery ) { unsigned char dot_size,temp=0; unsigned short n=0,i=0,u16index=0; int bDNSmatch = 0; /* ----Identification--------------------------|QR| Opcode |AA|TC|RD|RA|Z|AD|CD| Rcode | */ /* ----Total Questions------------------------|-----------------Total Answer RRs---------------*/ /* ----Total Authority RRs --------------------|----------------Total Additional RRs------------*/ /* --------------------------------- Questions --------------------------------- */ /* ------------------------------------ Answer RRs ------------------------------------------*/ /* ----------------------------------- Authority RRs ----------------------------------*/ /* -----------------------------------Additional RRs ----------------------------------*/ MDNS_INFO("Parsing DNS Packet\n"); pstrDnsHdr->id = (( pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1])); MDNS_INFO ("id = %.4x \n",pstrDnsHdr->id); u16index+=2; pstrDnsHdr->flags1= pu8RxBuffer[u16index++]; pstrDnsHdr->flags2= pu8RxBuffer[u16index++]; MDNS_INFO ("flags = %.2x %.2x \n",pstrDnsHdr->flags1,pstrDnsHdr->flags2); pstrDnsHdr->numquestions = ((pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1])); MDNS_INFO ("numquestions = %.4x \n",pstrDnsHdr->numquestions); u16index+=2; pstrDnsHdr->numanswers = ((pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1])); MDNS_INFO ("numanswers = %.4x \n",pstrDnsHdr->numanswers); u16index+=2; pstrDnsHdr->numauthrr = ((pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1])); MDNS_INFO ("numauthrr = %.4x \n",pstrDnsHdr->numauthrr); u16index+=2; pstrDnsHdr->numextrarr = ((pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1])); MDNS_INFO ("numextrarr = %.4x \n",pstrDnsHdr->numextrarr); u16index+=2; dot_size =pstrDnsQuery->query[n++]= pu8RxBuffer[u16index++]; pstrDnsQuery->u16size=1; ATWINC15x0 Multicast Sockets © 2018 Microchip Technology Inc. User Guide DS00002389B-page 75 while (dot_size--!=0) //(pu8RxBuffer[++u16index] != 0) { pstrDnsQuery->query[n++]=pstrDnsQuery->queryForChecking[i++]=pu8RxBuffer[u16index++] ; pstrDnsQuery->u16size++; gu8pos=temp; if (dot_size == 0 ) { pstrDnsQuery->queryForChecking[i++]= '.' ; temp=u16index; dot_size =pstrDnsQuery->query[n++]= pu8RxBuffer[u16index++]; pstrDnsQuery->u16size++; } } pstrDnsQuery->queryForChecking[--i] = 0; MDNS_INFO("parsed query <%s>\n",pstrDnsQuery->queryForChecking); // Search for any match in the local DNS table. for(n = 0; n < DNS_SERVER_CACHE_SIZE; n++) { MDNS_INFO("Saved URL <%s>\n",gpacDnsServerCache[n]); if(strcmp(gpacDnsServerCache[n], pstrDnsQuery->queryForChecking) ==0) { bDNSmatch= 1; MDNS_INFO("MATCH \n"); } else { MDNS_INFO("Mismatch\n"); } } pstrDnsQuery->u16class = ((pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1])); u16index+=2; pstrDnsQuery->u16type= ((pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1])); return bDNSmatch; } • Send mDNS Response: void MDNS_SendResp (signed char sock,unsigned char * pu8IPAddr, unsigned short u16Port,tstrDnsHdr *pstrDnsHdr,strdnsquery *pstrDnsQuery) { unsigned short u16index=0; tstrSockAddr strclientAddr ; unsigned char * pu8sendBuf; char * serviceName2 = (char*)malloc(sizeof(serviceName)+1); unsigned int MULTICAST_IP = 0xFB0000E0; pu8sendBuf= gPu8Buf; memcpy(&strclientAddr.u32IPAddr,&MULTICAST_IP,IPV4_DATA_LENGTH); strclientAddr.u16Port=u16Port; MDNS_INFO("%s \n",pstrDnsQuery->query); MDNS_INFO("Query Size = %d \n",pstrDnsQuery->u16size); MDNS_INFO("class = %.4x \n",pstrDnsQuery->u16class); MDNS_INFO("type = %.4x \n",pstrDnsQuery->u16type); MDNS_INFO("PREPARING DNS ANSWER BEFORE SENDING\n"); /*----------------------------ID 2 Bytes -----------------------------*/ pu8sendBuf [u16index++] =0; //( pstrDnsHdr->id>>8); pu8sendBuf [u16index++] = 0;//( pstrDnsHdr->id)&(0xFF); MDNS_INFO ("(ResPonse) id = %.2x %.2x \n", pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]); /*----------------------------Flags 2 Bytes----------------------------*/ pu8sendBuf [u16index++] = DNS_RSP_FLAG_1; pu8sendBuf [u16index++] = DNS_RSP_FLAG_2; MDNS_INFO ("(ResPonse) Flags = %.2x %.2x \n", pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]); /*----------------------------No of Questions--------------------------*/ pu8sendBuf [u16index++] =0x00; pu8sendBuf [u16index++] =0x01; MDNS_INFO ("(ResPonse) Questions = %.2x %.2x \n", pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]); /*---------------------------No of Answers----------------------------*/ pu8sendBuf [u16index++] =0x00; pu8sendBuf [u16index++] =0x01; MDNS_INFO ("(ResPonse) Answers = %.2x %.2x \n", pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]); ATWINC15x0 Multicast Sockets © 2018 Microchip Technology Inc. User Guide DS00002389B-page 76 /*---------------------------No of Authority RRs------------------------*/ pu8sendBuf [u16index++] =0x00; pu8sendBuf [u16index++] =0x00; MDNS_INFO ("(ResPonse) Authority RRs = %.2x %.2x \n", pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]); /*----------------------------No of Additional RRs----------------------*/ pu8sendBuf [u16index++] =0x00; pu8sendBuf [u16index++] =0x00; MDNS_INFO ("(ResPonse) Additional RRs = %.2x %.2x \n", pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]); /*--------------------------------Query-----------------------------*/ memcpy(&pu8sendBuf[u16index],pstrDnsQuery->query,pstrDnsQuery->u16size); MDNS_INFO("\nsize = %d \n",pstrDnsQuery->u16size); u16index+=pstrDnsQuery->u16size; /*-------------------------------Query Type----------------------------*/ pu8sendBuf [u16index++] = ( pstrDnsQuery->u16type>>8);//MDNS_TYPE>>8; pu8sendBuf [u16index++] = ( pstrDnsQuery->u16type)&(0xFF);//(MDNS_TYPE&0xFF); MDNS_INFO ("Query Type = %.2x %.2x \n", pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]); /*------------------------------Query Class-----------------------------------*/ pu8sendBuf [u16index++] =MDNS_CLASS>>8;//(( pstrDnsQuery->u16class>>8)|0x80); pu8sendBuf [u16index++] = (MDNS_CLASS & 0xFF);//( pstrDnsQuery->u16class)&(0xFF); MDNS_INFO ("Query Class = %.2x %.2x \n", pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]); /*########################Answers#########################*/ /*------------------------------Name---------------------------------*/ pu8sendBuf [u16index++]= 0xC0 ; //pointer to query name location pu8sendBuf [u16index++]= 0x0C ; // instead of writing the whole query name again /*-----------------------------Type----------------------------------*/ pu8sendBuf [u16index++] =MDNS_TYPE>>8; //Type 12 PTR (domain name Pointer). pu8sendBuf [u16index++] =(MDNS_TYPE&0xFF); /*------------------------------Class-----------------------------------*/ pu8sendBuf [u16index++] =0x00;//MDNS_CLASS; //Class IN, Internet. pu8sendBuf [u16index++] =0x01;// (MDNS_CLASS & 0xFF); /*-----------------------------TTL----------------------------------*/ pu8sendBuf [u16index++] =(TIME_TO_LIVE >>24); pu8sendBuf [u16index++] =(TIME_TO_LIVE >>16); pu8sendBuf [u16index++] =(TIME_TO_LIVE >>8); pu8sendBuf [u16index++] =(TIME_TO_LIVE ); /*---------------------------Date Length----------------------------------*/ pu8sendBuf [u16index++] =(sizeof(serviceName)+2)>>8;//added 2 bytes for the pointer pu8sendBuf [u16index++] =(sizeof(serviceName)+2); /*-----------------------------DATA--------------------------------*/ convertServiceName(serviceName,sizeof(serviceName),serviceName2); memcpy(&pu8sendBuf[u16index],serviceName2,sizeof(serviceName)+1); u16index+=sizeof(serviceName); pu8sendBuf [u16index++] =0xC0;//Pointer to .local (from name) pu8sendBuf [u16index++] =gu8pos;//23 /*###########################################################*/ strclientAddr.u16Port=HTONS(MDNS_SERVER_PORT); // MultiCast RESPONSE sendto( sock, pu8sendBuf,(uint16)u16index,0,(struct sockaddr*)&strclientAddr,sizeof(strclientAddr)); strclientAddr.u16Port=u16Port; memcpy(&strclientAddr.u32IPAddr,pu8IPAddr,IPV4_DATA_LENGTH); } • Service Name: static char gpacDnsServerCache[DNS_SERVER_CACHE_SIZE][MDNS_HOSTNAME_SIZE] = { "_services._dns-sd._udp.local","_workstation._tcp.local","_http._tcp.local" }; unsigned char gPu8Buf [MDNS_BUF_SIZE]; unsigned char gu8pos ; signed char dns_server_sock ; #define serviceName "_ATMELWIFI._tcp" ATWINC15x0 Multicast Sockets © 2018 Microchip Technology Inc. User Guide DS00002389B-page 77 12. WINC Serial Flash Memory 12.1 Overview and Features The WINC has internal serial (SPI) Flash memory of 4 Mb capacity in the ATWINC1500 and 8 Mb capacity in the ATWINC1510. The Flash memory is used to store: • User configuration • Firmware • Connection Profiles During start-up and mode changes, firmware is loaded from the serial Flash into program memory (IRAM) in which the firmware is executed. The Flash is accessed at other points during run time to retrieve configuration and profile data. A minimum of 4 Mb Flash is required for OTA feature in order to store both working and rollback images. The Flash memory can be read, written and erased directly from the host without co-operation with the WINC firmware. However, if operational firmware is already loaded, it is necessary to halt any running WINC firmware first before accessing the serial Flash to avoid access conflict between the host and the WINC processor. 12.2 Accessing to Serial Flash • The host has transparent access to the serial (SPI) Flash through the WINC SPI Master. • The host can program the serial (SPI) Flash without the need for operational firmware in the WINC. The function m2m_wifi_download_mode must be called first. Figure 12-1. System Block Diagram showing SPI Flash Connection 12.3 Read/Write/Erase Operations SPI Flash can be accessed to be read, written and erased. It is required to change the WINC’s mode to Download mode first before attempting to access the SPI Flash by calling: sint32 m2m_wifi_download_mode(); ATWINC15x0 WINC Serial Flash Memory © 2018 Microchip Technology Inc. User Guide DS00002389B-page 78 All SPI Flash functions are blocking. A return of M2M_SUCCESS indicates that the requested operation is successfully completed. The following is a list of Flash functions that may be used: • Query the size of the SPI Flash: uint32 spi_flash_get_size(); This function returns with the size of the SPI Flash in Mb. • Read data from the SPI Flash: sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32offset, uint32 u32Sz) Where the size of data is limited by the SPI Flash size. • Erase sectors in the SPI Flash: sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz) Note:  The size is limited by the SPI Flash size. Prior to writing to any sector, erase this sector first. If some data needs to be changed within a sector, it is advised to read the sector first, modify the data and then erase and write the whole sector again. • Write data to the SPI Flash: sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz) If the application wants to write any number of bytes within any sector, it has to erase the entire sector first. It may be necessary to read the entire sector, erase the sector and then write back with modifications. It is also recommended to verify that data is written after it returns success by reading data again and compare it with the original. 12.3.1 Flash Read, Erase, and Write Code Examples #include "spi_flash.h" #define DATA_TO_REPLACE "THIS IS A NEW SECTOR IN FLASH" int main() { uint8 au8FlashContent[FLASH_SECTOR_SZ] = {0}; uint32u32FlashTotalSize = 0, u32FlashOffset = 0; // Platform specific initializations. ret = m2m_wifi_download_mode(); if(M2M_SUCCESS != ret) { printf("Unable to enter download mode\r\n"); } else { u32FlashTotalSize = spi_flash_get_size(); } while((u32FlashTotalSize > u32FlashOffset) && (M2M_SUCCESS == ret)) { ret = spi_flash_read(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); if(M2M_SUCCESS != ret) { printf("Unable to read SPI sector\r\n"); break; } memcpy(au8FlashContent, DATA_TO_REPLACE, strlen(DATA_TO_REPLACE)); ATWINC15x0 WINC Serial Flash Memory © 2018 Microchip Technology Inc. User Guide DS00002389B-page 79 ret = spi_flash_erase(u32FlashOffset, FLASH_SECTOR_SZ); if(M2M_SUCCESS != ret) { printf("Unable to erase SPI sector\r\n"); break; } ret = spi_flash_write(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); if(M2M_SUCCESS != ret) { printf("Unable to write SPI sector\r\n"); break; } u32FlashOffset += FLASH_SECTOR_SZ; } if(M2M_SUCCESS == ret) { printf("Successful operations\r\n"); } else { printf("Failed operations\r\n"); } while(1); return M2M_SUCCESS; } ATWINC15x0 WINC Serial Flash Memory © 2018 Microchip Technology Inc. User Guide DS00002389B-page 80 13. Host Interface (HIF) Protocol Communication between the user application and the WINC device is facilitated by the driver software. This driver implements the Host Interface (HIF) Protocol and exposes an API to the application with various services. The services are broadly divided in two categories: Wi-Fi device control and IP Socket. The Wi-Fi device control services allow actions such as channel scanning, network identification, connection and disconnection. The Socket services allow data transfer once a connection is established and similar to BSD socket definitions. The host driver implements services asynchronously. This means that when the application calls an API to request a service action, the call is non-blocking and returns immediately, often before the action is completed. Where appropriate a notification that an action has completed is provided in a subsequent message from the WINC device to the host which is delivered to the application via a callback function. In general, the WINC firmware uses asynchronous events to signal the host driver of certain status changes. Asynchronous operation is essential where functions (such as Wi-Fi connection) may take significant time. When an API is called, a sequence of layers is activated to format the request and arranging to transfer it to the WINC device through the serial protocol. Note:  Dealing with HIF messages in the host MCU application is an advanced topic. For most applications, it is recommended to use Wi-Fi and socket layers. Both layers hide the complexity of the HIF APIs. After the application sends request, the Host Driver (Wi-Fi/Socket layer) formats the request and sends it to the HIF layer which then interrupts the WINC device to notify that a new request is posted. Upon receipt, the WINC firmware parses the request and starts the required operation. Figure 13-1. WINC Driver Layers The Host Interface Layer is responsible for handling communication between the host MCU and the WINC device. This includes interrupt handling, DMA control and management of the communication logic between the firmware driver in the host and the WINC firmware. The Request/Response sequence between the host and the WINC chip is shown in the following figure. ATWINC15x0 Host Interface (HIF) Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 81 Figure 13-2. The Request/Response Sequence Diagram 13.1 Transfer Sequence Between the HIF Layer and the WINC Firmware The following section shows the individual steps taken during a HIF frame transmit (HIF message to the WINC) and a HIF frame receive (HIF message from the WINC). 13.1.1 Frame Transmit The following figure shows the steps and states involved in sending a message from the host to the WINC device. Figure 13-3. HIF Frame Transmit to WINC ATWINC15x0 Host Interface (HIF) Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 82 Table 13-1. Steps in HIF Frame Transmit to WINC Step Description Step (1) Wake up the WINC device Wake up the device to be able to receive the host requests. Step (2) Interrupt the WINC device Prepare and set the HIF layer header to NMI_STATE_REG register (4 bytes header describing the sent packet). Set BIT [1] of WIFI_HOST_RCV_CTRL_2 register to raise an interrupt to the WINC chip. Step (3) Poll for DMA address Wait until the WINC chip clears BIT [1] of WIFI_HOST_RCV_CTRL_2 register. Get the DMA address (for the allocated memory) from register 0x150400. Step (4) Write data Write the data blocks in sequence, the HIF header then the Control buffer (if any) then the Data buffer (if any). Step (5) TX Done Interrupt Send a notification that writing the data is completed by setting BIT [1] of WIFI_HOST_RCV_CTRL_3 register. Step (6) Allow the WINC device to Sleep Allow the WINC device to enter Sleep mode again (if it wishes). 13.1.2 Frame Receive The following figure shows the steps and states involved in sending a message from the WINC device to the host. Figure 13-4. HIF Frame Receive from WINC to Host Table 13-2. Steps in HIF Frame Receive from WINC to Host Step Description Step (1) Wake up the WINC device Wake up the device to be able to receive host requests. Step (2) Check for Interrupt Monitor BIT [0] of WIFI_HOST_RCV_CTRL_0 register. Disable the host from receiving interrupts (until this interrupt is processed). Step (3) Clear interrupt Write zero to BIT [0] of WIFI_HOST_RCV_CTRL_0 register. ATWINC15x0 Host Interface (HIF) Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 83 ...........continued Step Description Step (4) Read data Get the address of the data block from WIFI_HOST_RCV_CTRL_1 register. Read data block with size obtained from WIFI_HOST_RCV_CTRL_0 register BIT [13] <-> BIT [2]. Step (5) Process Request Parse the HIF header at the start of the data and forward the data to the appropriate registered Callback function. Step (6) HOST RX Done Raise an interrupt for the chip to free the memory holding the data by setting BIT [1] of WIFI_HOST_RCV_CTRL_0 register. Enable host interrupt reception again. Step (7) Allow the WINC device to Sleep Allow the WINC device to enter Sleep mode again (if it wishes). 13.2 HIF Message Header Structure The HIF message is the data structure exchanged back and forth between the Host Interface and the WINC firmware. The HIF message header structure consists of three fields: • The Group ID (8-bit) – a group ID is the category of the message. Valid categories are enumerated in tenuM2mReqGroup. • Op Code (8-bit) – is a command number. Valid command number is a value enumerated in: tenuM2mConfigCmd and tenuM2mStaCmd, tenuM2mApCmd, and tenuM2mP2pCmd corresponding to configuration, STA mode, AP mode, and P2P mode commands. Note:  • Refer to the m2m_types.h for the full list of commands. • The P2P mode is not supported after release v19.5.3. • Payload Length (16-bit) – the payload length is shown in bytes (does not include header). 13.3 HIF Layer APIs The interface between the application and the driver is done at the higher layer API interface (Wi-Fi / Socket.) As explained previously, the driver upper layer uses a lower layer API to access the services of the Host Interface Protocol. This section describes the Host Interface APIs that the upper layers use: The following API functions are described: ATWINC15x0 Host Interface (HIF) Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 84 • hif_chip_wake • hif_chip_sleep • hif_register_cb • hif_isr • hif_receive • hif_send • hif_set_sleep_mode • hif_get_sleep_mode For all functions, the return value is either M2M_SUCCESS (zero) in case of success or a negative value in case of failure. • sint8 hif_chip_wake (void) – this function wakes the WINC chip from Sleep mode using clockless register access. It sets bit '1' of register 0x01 and sets the value of WAKE_REG register to WAKE_VALUE. • sint8 hif_chip_sleep (void) – this function enables Sleep mode for the WINC chip by setting the WAKE_REG register to a value of SLEEP_VALUE and clearing bit '1' of register 0x01. • sint8 hif_register_cb (uint8 u8Grp, tpfHifCallBack fn) – this function sets the callback function for different components (for example, M2M_WIFI, M2M_HIF, M2M_OTA and so on.). A callback is registered by upper layers to receive specific events of a specific message group. • sint8 hif_isr (void) – this is the host interface interrupt service routine. It handles interrupts generated by the WINC chip and parses the HIF header to call back the appropriate handler. • sint8 hif_receive (uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 is Done) – this function causes the host driver to read data from the WINC chip. The location and length of the data must be known in advance and specified. This is typically extracted from an earlier part of a transaction. • sint8 hif_send (uint8 u8Gid, uint8 u8Opcode, uint8 *pu8CtrlBuf, uint16 u16CtrlBufSize, uint8 *pu8DataBuf, uint16 u16DataSize, uint16 16DataOffset) – this function causes the host driver to send data to the WINC chip. The WINC chip must be prepared for reception according to the flow described in the previous section. • void hif_set_sleep_mode (uint8 u8Pstype) – this function is used to set the Sleep mode of the HIF layer. • uint8 hif_get_sleep_mode (void) – this function return the Sleep mode of the HIF layer. 13.4 Scan Code Example The following code example illustrates the Request/Response flow on a Wi-Fi Scan request. Note:  For more details on example codes, refer to the Wi-Fi Network Controller Software Programming Guide. • The application requests a Wi-Fi scan. { m2m_wifi_request_scan(M2M_WIFI_CH_ALL); } • The host driver Wi-Fi layer formats the request and forward it to HIF (Host Interface) layer. sint8 m2m_wifi_request_scan(uint8 ch) { tstrM2MScan strtmp; sint8 s8Ret = M2M_ERR_SCAN_IN_PROGRESS; ATWINC15x0 Host Interface (HIF) Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 85 strtmp.u8ChNum = ch; s8Ret = hif_send(M2M_REQ_GRP_WIFI, M2M_WIFI_REQ_SCAN, (uint8*)&strtmp, sizeof(tstrM2MScan),NULL, 0,0); return s8Ret; } • The HIF layer sends the request to the WINC chip. sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) { sint8 ret = M2M_ERR_SEND; volatile tstrHifHdr strHif; strHif.u8Opcode = u8Opcode&(~NBIT7); strHif.u8Gid = u8Gid; strHif.u16Length = M2M_HIF_HDR_OFFSET; if(pu8DataBuf != NULL) { strHif.u16Length += u16DataOffset + u16DataSize; } else { strHif.u16Length += u16CtrlBufSize; } /* TX STEP (1) */ ret = hif_chip_wake(); if(ret == M2M_SUCCESS) { volatile uint32 reg, dma_addr = 0; volatile uint16 cnt = 0; reg = 0UL; reg |= (uint32)u8Gid; reg |= ((uint32)u8Opcode<<8); reg |= ((uint32)strHif.u16Length<<16); ret = nm_write_reg(NMI_STATE_REG,reg); if(M2M_SUCCESS != ret) goto ERR1; reg = 0; /* TX STEP (2) */ reg |= (1<<1); ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); if(M2M_SUCCESS != ret) goto ERR1; dma_addr = 0; for(cnt = 0; cnt < 1000; cnt ++) { ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_2,(uint32 *)®); if(ret != M2M_SUCCESS) break; if (!(reg & 0x2)) { /* TX STEP (3) */ ret = nm_read_reg_with_ret(0x150400,(uint32 *)&dma_addr); if(ret != M2M_SUCCESS) { /*in case of read error clear the dma address and return error*/ dma_addr = 0; } /*in case of success break */ break; } } if (dma_addr != 0) { volatile uint32 u32CurrAddr; u32CurrAddr = dma_addr; strHif.u16Length=NM_BSP_B_L_16(strHif.u16Length); /* TX STEP (4) */ ret = nm_write_block(u32CurrAddr, (uint8*)&strHif, M2M_HIF_HDR_OFFSET); if(M2M_SUCCESS != ret) goto ERR1; u32CurrAddr += M2M_HIF_HDR_OFFSET; if(pu8CtrlBuf != NULL) { ret = nm_write_block(u32CurrAddr, pu8CtrlBuf, u16CtrlBufSize); if(M2M_SUCCESS != ret) goto ERR1; u32CurrAddr += u16CtrlBufSize; } ATWINC15x0 Host Interface (HIF) Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 86 if(pu8DataBuf != NULL) { u32CurrAddr += (u16DataOffset - u16CtrlBufSize); ret = nm_write_block(u32CurrAddr, pu8DataBuf, u16DataSize); if(M2M_SUCCESS != ret) goto ERR1; u32CurrAddr += u16DataSize; } reg = dma_addr << 2; reg |= (1 << 1); /* TX STEP (5) */ ret = nm_write_reg(WIFI_HOST_RCV_CTRL_3, reg); if(M2M_SUCCESS != ret) goto ERR1; } else { /* ERROR STATE */ M2M_DBG("Failed to alloc rx size\r"); ret = M2M_ERR_MEM_ALLOC; goto ERR1; } } else { M2M_ERR("(HIF)Fail to wakup the chip\n"); goto ERR1; } /* TX STEP (6) */ ret = hif_chip_sleep(); ERR1: return ret; } • The WINC chip processes the request and interrupts the host after finishing the operation. • The HIF layer then receives the response. static sint8 hif_isr(void) { sint8 ret = M2M_ERR_BUS_FAIL; uint32 reg; volatile tstrHifHdr strHif; /* RX STEP (1) */ ret = hif_chip_wake(); if(ret == M2M_SUCCESS) { /* RX STEP (2) */ ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®); if(M2M_SUCCESS == ret) { /* New interrupt has been received */ if(reg & 0x1) { uint16 size; nm_bsp_interrupt_ctrl(0); /*Clearing RX interrupt*/ ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®); if(ret != M2M_SUCCESS)goto ERR1; reg &= ~(1<<0); /* RX STEP (3) */ ret=nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); if(ret != M2M_SUCCESS)goto ERR1; /* read the rx size */ ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®); if(M2M_SUCCESS != ret) { M2M_ERR("(hif) WIFI_HOST_RCV_CTRL_0 bus fail\n"); nm_bsp_interrupt_ctrl(1); goto ERR1; } gu8HifSizeDone = 0; size = (uint16)((reg >> 2) & 0xfff); if (size > 0) { uint32 address = 0; /** start bus transfer **/ ATWINC15x0 Host Interface (HIF) Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 87 /* RX STEP (4) */ ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_1, &address); if(M2M_SUCCESS != ret) { M2M_ERR("(hif) WIFI_HOST_RCV_CTRL_1 bus fail\n"); nm_bsp_interrupt_ctrl(1); goto ERR1; } ret = nm_read_block(address, (uint8*)&strHif, sizeof(tstrHifHdr)); strHif.u16Length = NM_BSP_B_L_16(strHif.u16Length); if(M2M_SUCCESS != ret) { M2M_ERR("(hif) address bus fail\n"); nm_bsp_interrupt_ctrl(1); goto ERR1; } if(strHif.u16Length != size) { if((size - strHif.u16Length) > 4) { M2M_ERR("(hif) Corrupted packet Size = %u \n", size, strHif.u16Length, strHif.u8Gid, strHif.u8Opcode); nm_bsp_interrupt_ctrl(1); ret = M2M_ERR_BUS_FAIL; goto ERR1; } } /* RX STEP (5) */ if(M2M_REQ_GRP_WIFI == strHif.u8Gid) { if(pfWifiCb) { pfWifiCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); } } else if(M2M_REQ_GRP_IP == strHif.u8Gid) { if(pfIpCb) { pfIpCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); } } else if(M2M_REQ_GRP_OTA == strHif.u8Gid) { if(pfOtaCb) { pfOtaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); } } else { M2M_ERR("(hif) invalid group ID\n"); ret = M2M_ERR_BUS_FAIL; goto ERR1; } /* RX STEP (6) */ if(!gu8HifSizeDone) { M2M_ERR("(hif) host app didn't set RX Done\n"); ret = hif_set_rx_done(); } } else { ret = M2M_ERR_RCV; M2M_ERR("(hif) Wrong Size\n"); goto ERR1; } } else ATWINC15x0 Host Interface (HIF) Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 88 { #ifndef WIN32 M2M_ERR("(hif) False interrupt %lx",reg); #endif } } else { M2M_ERR("(hif) Fail to Read interrupt reg\n"); goto ERR1; } } else { M2M_ERR("(hif) FAIL to wakeup the chip\n"); goto ERR1; } /* RX STEP (7) */ ret = hif_chip_sleep(); ERR1: return ret; } • The appropriate handler in the Wi-Fi layer (called from the HIF layer). static void m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) { // …code eliminated… else if (u8OpCode == M2M_WIFI_RESP_SCAN_DONE) { tstrM2mScanDone strState; gu8scanInProgress = 0; if(hif_receive(u32Addr, (uint8*)&strState, sizeof(tstrM2mScanDone), 0) == M2M_SUCCESS) { gu8ChNum = strState.u8NumofCh; if (gpfAppWifiCb) gpfAppWifiCb(M2M_WIFI_RESP_SCAN_DONE, &strState); } } // …code eliminated… } • The Wi-Fi layer sends the response to the application through its callback function. if (u8MsgType == M2M_WIFI_RESP_SCAN_DONE) { tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*) pvMsg; if( (gu8IsWiFiConnected == M2M_WIFI_DISCONNECTED) && (gu8WPS == WPS_DISABLED) && (gu8Prov == PROV_DISABLED) ) { gu8Index = 0; gu8Sleep = PS_WAKE; if (pstrInfo->u8NumofCh >= 1) { m2m_wifi_req_scan_result(gu8Index); gu8Index++; } else { m2m_wifi_request_scan(M2M_WIFI_CH_ALL); } } } ATWINC15x0 Host Interface (HIF) Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 89 14. WINC SPI Protocol The WINC main interface is SPI. The WINC device employs a protocol to allow exchange of formatted binary messages between the WINC firmware and the host MCU application. The WINC protocol uses raw bytes exchanged on the SPI bus to form high level structures like requests and callbacks. The WINC SPI protocol consists of three layers: • Layer 1 – the WINC SPI Slave protocol, which allows the host MCU application to perform register/ memory read and write operation in the ATWINC15x0 device using raw SPI data exchange. • Layer 2 – the host MCU application uses the register and memory read and write capabilities to exchange the host interface frames with the WINC firmware. It also provides asynchronous callback from the WINC firmware to the host MCU through interrupts and the host interface RX frames. For more information on this layer, refer to Section 15 “Host Interface (HIF) Protocol”. • Layer 3 – allows the host MCU application to exchange high level messages (for example, Wi-Fi scan, socket connection, or TCP data received) with the WINC firmware to employ in the host MCU application logic. Figure 14-1. WINC SPI Protocol Layers 14.1 Introduction The WINC SPI Protocol is implemented as a command-response transaction and assumes one party is the Master and the other is the Slave. The roles correspond to the Master and Slave devices on the SPI bus. Each message has an identifier in the first byte indicating the type of message: • Command • Response ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 90 • Data In the case of Command and Data messages, the last byte is used as data integrity check. The format of Command and Response and Data frames are described in the following sections. The following points apply: • There is a response for each command. • Transmitted/received data is divided into packets with fixed size. • For a WR transaction (Slave is receiving data packets), the Slave sends a response for each data packet. • For a RD transaction (Master is receiving data packets), the Master does not send a response. If there is an error, the Master requests a retransmission on the lost data packet. • Protection of commands and data packets by CRC is optional. 14.1.1 Command Format The following frame format is used for commands where the host supports a DMA address of three bytes. The first byte contains two fields: • The CMD/Data Start field indicates that this is a Command frame. • The CMD type field specifies the command to be executed. The CMD type may be one of 15 commands: • DMA write • DMA read • Internal register write • Internal register read • Transaction termination • Repeat data packet • DMA extended write • DMA extended read • DMA single-word write • DMA single-word read • Soft Reset The Payload field contains command specific data and its length depends on the CMD type. The CRC field is optional and generally computed in software. The Payload field can be one of four types each having a different length: • A: Three bytes • B: Five bytes • C: Six bytes • D: Seven bytes ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 91 Type A commands include: • DMA single-word RD • internal register RD • Transaction termination command • Repeat data PKT command • Soft Reset command Type B commands include: • DMA RD Transaction • DMA WR Transaction Type C commands include: • DMA Extended RD transaction • DMA Extended WR transaction • Internal register WR Type D commands include: • DMA single-word WR Full details of the frame format fields are provided in the following table: Table 14-1. Frame Format Fields Field Size Description CMD Start 4 bits Command Start: 4’b1100 CMD Type 4 bits Command type: 4’b0001: DMA write transaction 4’b0010: DMA read transaction 4’b0011: Internal register write 4’b0100: Internal register read 4’b0101: Transaction termination 4’b0110: Repeat data Packet command 4’b0111: DMA extended write transaction 4’b1000: DMA extended read transaction 4’b1001: DMA single-word write 4’b1010: DMA single-word read 4’b1111: Soft Reset command ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 92 ...........continued Field Size Description Payload A: 3 The Payload field may be of Type A, B, C, or D Type A (length 3) 1- DMA single-word RD Param: Read Address: Payload bytes: B0: ADDRESS[23:16] B1: ADDRESS[15:8] B2: ADDRESS[7:0] 2- internal register RD Param: Offset address (two bytes): Payload bytes: B0: OFFSET-ADDR[15:8] B1: OFFSET-ADDR[7:0] B2: 0 3- Transaction termination command Param: none Payload bytes: B0: 0 B1: 0 B2: 0 4- Repeat Data PKT command Param: none Payload bytes: B0: 0 B1: 0 B2: 0 5- Soft Reset command Param: none Payload bytes: B0: 0xFF B1: 0xFF B2: 0xFF ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 93 ...........continued Field Size Description Payload B: 5 Type B (length 5) 1- DMA RD Transaction Params: DMA Start Address: 3 bytes DMA count: 2 bytes Payload bytes: B0: ADDRESS[23:16] B1: ADDRESS[15:8] B2: ADDRESS[7:0] B3: COUNT[15:8] B4: COUNT[7:0] 2- DMA WR Transaction Params: DMA Start Address: 3 bytes DMA count: 2 bytes Payload bytes: B0: ADDRESS[23:16] B1: ADDRESS[15:8] B2: ADDRESS[7:0] B3: COUNT[15:8] B4: COUNT[7:0] ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 94 ...........continued Field Size Description Payload C: 6 Type C (length 6) 1- DMA Extended RD transaction Params: DMA Start Address: 3 bytes DMA extended count: 3 bytes Payload bytes: B0: ADDRESS[23:16] B1: ADDRESS[15:8] B2: ADDRESS[7:0] B3: COUNT[23:16] B4: COUNT[15:8] B5: COUNT[7:0] 2- DMA Extended WR transaction Params: DMA Start Address: 3 bytes DMA extended count: 3 bytes Payload bytes: B0: ADDRESS[23:16] B1: ADDRESS[15:8] B2: ADDRESS[7:0] B3: COUNT[23:16] B4: COUNT[15:8] B5: COUNT[7:0] ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 95 ...........continued Field Size Description Payload C: 6 3- Internal register WR* Params: Offset address: 3 bytes Write data: 3 bytes * “clocked or clockless registers” Payload bytes: B0: OFFSET-ADDR[15:8] B1: OFFSET-ADDR [7:0] B2: DATA[31:24] B3: DATA [23:16] B4: DATA [15:8] B5: DATA [7:0] Payload D: 7 Type D (length 7) 1- DMA single-word WR Params: Address: 3 bytes DMA Data: 4 bytes Payload bytes: B0: ADDRESS[23:16] B1: ADDRESS[15:8] B2: ADDRESS[7:0] B3: DATA[31:24] B4: DATA [23:16] B5: DATA [15:8] B6: DATA [7:0] CRC7 1 byte Optional data integrity field comprising two subfields: bit 0: fixed value ‘1’ bits 1-7: 7 bit CRC value computed using polynomial G(x) = X^7 + X^3 + 1 with seed value: 0x7F ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 96 The following table summarizes the different commands according to the payload type (DMA address = 3 bytes): Table 14-2. Commands in Payload Payload Type Payload Size Command Packet Size with CRC Commands Type A 3 bytes 5 bytes 1- DMA Single-Word Read 2- Internal Register Read 3- Transaction Termination 4- Repeat Data Packet 5- Soft Reset Type B 5 bytes 7 bytes 1- DMA Read 2- DMA Write Type C 6 bytes 8 bytes 1- DMA Extended Read 2- DMA Extended Write 3- Internal Register Write Type D 7 bytes 9 bytes 1- DMA Single-Word Write 14.1.2 Response Format The following frame format is used for responses sent by the WINC device as the result of receiving a Command or certain Data frames. The Response message has a fixed length of two bytes. The first byte contains two fields of four bits each to identify the response message and the response type. The second byte indicates the status of the WINC after receiving and, where possible, executing the command/data. This byte contains two sub fields: • B0-B3: Error state • B4-B7: DMA state States that may be indicated are: • DMA state: – DMA ready for any transaction – DMA engine is busy • Error state: – No error – Unsupported command – Receiving unexpected data packet – Command CRC7 error ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 97 Table 14-3. Response Format Field Size Description Response Start 4 bits Response Start : 4’b1100 Response Type 4 bits If the response packet is for Command: • Contains of copy of the Command Type field in the Command. If the response packet is for received Data Packet: • 4’b0001: first data packet is received • 4’b0010: Receiving data packets • 4’b0011: last data packet is received • 4’b1111: Reserved value State 1 byte This field is divided into two subfields: DMA State : • 4’b0000: DMA ready for any transaction • 4’b0001: DMA engine is busy Error State: • 4’b0000: No error • 4’b0001: Unsupported command • 4’b0010: Receiving unexpected data packet • 4’b0011: Command CRC7 error • 4’b0100: Data CRC16 error • 4’b0101: Internal general error 14.1.3 Data Packet Format The Data Packet Format is used in either direction (Master to Slave or Slave to Master) to transfer opaque data. A command frame is used either to inform the Slave that a data packet is about to be sent or to request the Slave to send a data packet to the Master. In the case of Master to Slave, the Slave sends a response after the command and each subsequent data frame. The format of a data packet is shown below. To support DMA hardware, a large data transfer may be fragmented into multiple smaller Data Packets. This is controlled by the value of DATA_PACKET_SIZE which is agreed between the Master and the Slave in software and is a fixed value such as 256B, 512B, 1KB (default), 2KB, 4KB, or 8KB. If a transfer has a length of m, which exceeds DATA_PACKET_SIZE, the sender must split it into multiple DATA_PACKET_SIZE as shown in Equation 1: ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 98 (m – (n-1)* DATA_PACKET_SIZE) -------------------------- Equation 1 Where, 1.. n-1 = length of the DATA_PACKET_SIZE n = frame length This is illustrated below. • If DMA count <= DATA_PACKET_SIZE: The data packet is “DATA_Header + DMA count +optional CRC16“, that is no padding. • If DMA count > DATA_PACKET_SIZE: • If remaining data < DATA_PACKET_SIZE, the last data packet is: “DATA_Header + remaining data + optional CRC16 “, that is no padding. The frame fields are described in detail in the following table: Table 14-4. Frame Field Field Size Description Data Start 4 bits 4’b1111 (Default) (Can be changed to any value by programming DATA_START_CTRL register) Packet Order 4 bits 4’b0001: First packet in this transaction 4’b0010: Neither the first or the last packet in this transaction 4’b0011: Last packet in this transaction 4’b1111: Reserved Data bytes DATA_PACKET_SIZE User data CRC16 2 bytes Optional data integrity field comprising a 16-bit CRC value encoded in two bytes. The most significant 8 bits are transmitted first in the frame. The CRC16 value is computed on data bytes only based on the polynomial: G(x) = X^16 + X^12 + X^5 + 1, seed value: 0xFFFF ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 99 14.1.4 Error Recovery Mechanism Table 14-5. Error Recovery Mechanism Error Type Recovery Mechanism Master CRC error in command 1. Error response received from Slave. 2. Retransmit the command. CRC error in received data 1. Issue a repeat command for the data packet that has a CRC error. 2. Slave sends a response to the previous command. 3. Slave keeps the start DMA address of the previous data packet, so it can retransmit it. 4. Receive the data packet again. No response is received from Slave • Synchronization is lost between the Master and Slave. • The worst case is when Slave is in receiving data state. • Solution: The Master must wait for max DATA_PACKET_SIZE period then generate a Soft Reset command. Unexpected response Retransmit the command. TX/RX Data count error Retransmit the command. No response to Soft Reset command • Transmit all ones until Master receives a response of all ones from the Slave. • Then deactivate the output data line. Slave Unsupported command • Send response with error. • Returns to command monitor state. Receive command CRC error • Send response with error. • Wait for command retransmission. Received data CRC error • Send response with error. • Wait for retransmission of the data packet. Internal general error • The Master must do a Soft Reset on the Slave. TX/RX Data count error • Only the Master can detect this error. • Slave operates with the data count received until the count finishes or the Master terminates the transaction. • In both cases, the Master can retry the command from the start. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 100 ...........continued Error Type Recovery Mechanism No response to Soft Reset command 1. First received 4’b1001, it decides data start. 2. Then received packet order 4’b1111 that is reserved value. 3. Then monitors for 7 bytes all ones to decide Soft Reset action. 4. The Slave must activate the output data line. 5. Waits for deactivation for the received line. 6. The Slave then deactivates the output data line and returns to the CMD/ DATA start monitor state. General Notes • The Slave must monitor the received line for command reception at any time. • When a CMD start is detected, the Slave receives 8 bytes then return again to the command reception state. • When the Slave is transmitting data, it must also monitor for command reception. • When the Slave is receiving data, it monitors for command reception between the data packets. • Issuing a Soft Reset command is detected in all cases. 14.1.5 Clockless Registers Access Clockless register access allows a host device to access registers on the WINC device while it is held in a reset state. This type of access can only be done using the “internal register read” and “internal register write” commands. For clockless access, bit 15 of the Offset_addr in the command must be ‘1’ to differentiate between the Clockless and Clocked access mode. For Clockless register write: - the protocol Master must wait for the response as shown here: For Clockless register read: - according to the interface, the protocol Slave may not send CRC16. One or two byte padding depends on three or four byte DMA addresses. 14.2 Message Flow for Basic Transactions This section shows the essential message exchanges and timings associated with the following commands: • Read Single Word • Read Internal Register (clockless) ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 101 • Read Block • Write Single Word • Write Internal Register (clockless) • Write Bock 14.2.1 Read Single Word 14.2.2 Read Internal Register (for clockless registers) 14.2.3 Read Block Normal transaction: Master - issues a DMA read transaction and waits for a response. Slave - sends a response after CMD_RES_PERIOD. Master - waits for a data packet start. Slave - sends the data packets, separated by DATA_DATA_PERIOD[1] where DATA_DATA_PERIOD is controlled by software and has one of these values: NO_DELAY (default), 4_BYTE_PERIOD, 8_BYTE_PERIOD, and 16_BYTE_PERIOD. Slave - continues sending until the count ends. Master - receives data packets. No response is sent for data packets but a termination/retransmit command may be sent if there is an error. The message sequence for this case is shown below: Termination command is issued: Master - can issue a termination command at any time during the transaction. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 102 Master - monitors for RES_START after CMD_RESP_PERIOD. Slave - cuts off the current running data packet if there is any. Slave - responds to the termination command after CMD_RESP_PERIOD from the end of the termination command packet. Repeat command is issued: 1. Master - can issue a repeat command at any time during the transaction. 2. Master - monitors for RES_START after CMD_RESP_PERIOD. 3. Slave - cuts off the current running data packet, if any. 4. Slave - responds to the repeat command after CMD_RESP_PERIOD from the end of the repeat command packet. 5. Slave - sends the data packet again that has an error then continues the transaction as normal. [1] The period between the data packets is “DATA_DATA_PERIOD + DMA access time.” The Master monitors for DATA_START directly after DATA_DATA_PERIOD. 14.2.4 Write Single Word 1. Master - issues DMA single-word write command, including the data. 2. Slave - takes the data and sends a command response. 14.2.5 Write Internal Register (for clockless registers) 1. Master - issues an internal register write command, including the data. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 103 2. Slave - takes the data and sends a command response. 14.2.6 Write Block • Case 1: Master waits for a command response: 1.1. Master - issues a DMA write command and waits for a response. 1.2. Slave - sends response after CMD_RES_PERIOD. 1.3. Master - sends the data packets after receiving response. 1.4. Slave - sends a response packet for each data packet received after DATA_RES_PERIOD. 1.5. Master - does not wait for the data response before sending the following data packet notes: CMD_RES_PERIOD is controlled by SW taking one of the values: NO_DELAY (default), 1_BYTE_PERIOD, 2_BYTE_PERIOD and 3_BYTE_PERIOD The Master must monitor for RES_START after CMD_RES_PERIOD DATA_RES_PERIOD is controlled by SW taking one of the values: NO_DELAY (default), 1_BYTE_PERIOD, 2_BYTE_PERIOD and 3_BYTE_PERIOD • Case 2: Master does not wait for a command response: 2.1. Master - sends the data packets directly after the command but it still monitors for a command response after CMD_RESP_PERIOD. 2.2. Master - retransmits the data packets if there is an error in the command. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 104 14.3 SPI Level Protocol Example To illustrate how the WINC SPI protocol works, the SPI bytes from the scan request example are dumped and the sequence is described below. 14.3.1 TX (Send Request) 1. First step in hif_send() API is to wake up the chip. sint8 nm_clkless_wake(void) { ret = nm_read_reg_with_ret(0x1, ®); /* Set bit 1 */ ret = nm_write_reg(0x1, reg | (1 << 1)); // Check the clock status ret = nm_read_reg_with_ret(clk_status_reg_adr, &clk_status_reg); // Tell Firmware that Host waked up the chip ret = nm_write_reg(WAKE_REG, WAKE_VALUE); return ret; } Command CMD_INTERNAL_READ: 0xC4 /* internal register read */ BYTE [0] = CMD_INTERNAL_READ BYTE [1] = address >> 8; /* address = 0x01 */ BYTE [1] |= (1 << 7); /* clockless register */ BYTE [2] = address; BYTE [3] = 0x00; 2. The WINC acknowledges the command by sending three bytes [C4] [0] [F3]. 3. The WINC chip sends the value of the register 0x01 which equals 0x01. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 105 Command CMD_INTERNAL_WRITE: C3 /* internal register write */ BYTE [0] = CMD_INTERNAL_WRITE BYTE [1] = address >> 8; /* address = 0x01 */ BYTE [1] |= (1 << 7); /* clockless register */ BYTE [2] = address; BYTE [3] = u32data >> 24; /* Data = 0x03 */ BYTE [4] = u32data >> 16; BYTE [5] = u32data >> 8; BYTE [6] = u32data; 4. The WINC acknowledges the command by sending two bytes [C3] [0]. Command CMD_INTERNAL_READ: 0xC4 /* internal register read */ BYTE [0] = CMD_INTERNAL_READ BYTE [1] = address >> 8; /* address = 0x0F */ BYTE [1] |= (1 << 7); /* clockless register */ BYTE [2] = address; BYTE [3] = 0x00; 5. The WINC acknowledges the command by sending three bytes [C4] [0] [F3]. 6. The WINC chip sends the value of the register 0x01 which equals 0x07. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 106 Command CMD_SINGLE_WRITE:0XC9 /* single word write */ BYTE [0] = CMD_SINGLE_WRITE BYTE [1] = address >> 16; /* WAKE_REG address = 0x1074 */ BYTE [2] = address >> 8; BYTE [3] = address; BYTE [4] = u32data >> 24; /* WAKE_VALUE Data = 0x5678 */ BYTE [5] = u32data >> 16; BYTE [6] = u32data >> 8; BYTE [7] = u32data; 7. The chip acknowledges the command by sending two bytes [C9] [0]. 8. At this point, HIF finishes executing the clockless wake up of the WINC chip. 9. The HIF layer prepares and sets the HIF layer header to NMI_STATE_REG register (4 byte or 8 byte header describing the packet to be sent). 10. Set bit '1' of WIFI_HOST_RCV_CTRL_2 register to raise an interrupt to the chip. sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) { volatile tstrHifHdr strHif; volatile uint32 reg; strHif.u8Opcode = u8Opcode&(~NBIT7); strHif.u8Gid = u8Gid; strHif.u16Length = M2M_HIF_HDR_OFFSET; strHif.u16Length += u16CtrlBufSize; ret = nm_clkless_wake(); reg = 0UL; reg |= (uint32)u8Gid; reg |= ((uint32)u8Opcode<<8); reg |= ((uint32)strHif.u16Length<<16); ret = nm_write_reg(NMI_STATE_REG,reg); ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 107 reg = 0; reg |= (1<<1); ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); Command CMD_SINGLE_WRITE:0XC9 /* single word write */ BYTE [0] = CMD_SINGLE_WRITE BYTE [1] = address >> 16; /* NMI_STATE_REG address = 0x108c */ BYTE [2] = address >> 8; BYTE [3] = address; BYTE [4] = u32data >> 24; /* Data = 0x000C3001 */ BYTE [5] = u32data >> 16; /* 0x0C is the length and equals 12 */ BYTE [6] = u32data >> 8; /* 0x30 is the Opcode = M2M_WIFI_REQ_SET_SCAN_REGION */ BYTE [7] = u32data; /* 0x01 is the Group ID = M2M_REQ_GRP_WIFI */ 11. The WINC acknowledges the command by sending two bytes [C9] [0]. Command CMD_SINGLE_WRITE:0XC9 /* single word write */ BYTE [0] = CMD_SINGLE_WRITE BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_2address = 0x1078*/ BYTE [2] = address >> 8; BYTE [3] = address; BYTE [4] = u32data >> 24; /* Data = 0x02 */ BYTE [5] = u32data >> 16; BYTE [6] = u32data >> 8; BYTE [7] = u32data; ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 108 12. The WINC acknowledges the command by sending two bytes [C9] [0]. 13. Then HIF polls for DMA address. for (cnt = 0; cnt < 1000; cnt ++) { ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_2,(uint32 *)®); if(ret != M2M_SUCCESS) break; if (!(reg & 0x2)) { ret = nm_read_reg_with_ret(0x150400,(uint32 *)&dma_addr); /*in case of success break */ break; } } Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */ BYTE [0] = CMD_SINGLE_READ BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_2 address = 0x1078 */ BYTE [2] = address >> 8; BYTE [3] = address; 14. The WINC acknowledges the command by sending three bytes [CA] [0] [F3]. 15. The WINC chip sends the value of the register 0x1078, which equals 0x00. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 109 Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */ BYTE [0] = CMD_SINGLE_READ BYTE [1] = address >> 16; /* address = 0x1504 */ BYTE [2] = address >> 8; BYTE [3] = address; 16. The WINC acknowledges the command by sending three bytes [CA] [0] [F3]. 17. The WINC chip sends the value of the register 0x1504, which equals 0x037AA0. 18. The WINC writes the HIF header to the DMA memory address. u32CurrAddr = dma_addr; strHif.u16Length=NM_BSP_B_L_16(strHif.u16Length); ret = nm_write_block(u32CurrAddr, (uint8*)&strHif, M2M_HIF_HDR_OFFSET); Command CMD_DMA_EXT_WRITE: 0xC7 /* DMA extended write */ BYTE [0] = CMD_DMA_EXT_WRITE BYTE [1] = address >> 16; /* address = 0x037AA0 */ BYTE [2] = address >> 8; BYTE [3] = address; BYTE [4] = size >> 16; /* size = 0x08 */ BYTE [5] = size >> 8; BYTE [6] = size; ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 110 19. The WINC acknowledges the command by sending three bytes [C7] [0] [F3]. 20. The HIF layer writes the data. 21. The HIF writes the Control Buffer data (part of the framing of the request). if (pu8CtrlBuf != NULL) { ret = nm_write_block(u32CurrAddr, pu8CtrlBuf, u16CtrlBufSize); if(M2M_SUCCESS != ret) goto ERR1; u32CurrAddr += u16CtrlBufSize; } Command CMD_DMA_EXT_WRITE: 0xC7 /* DMA extended write */ BYTE [0] = CMD_DMA_EXT_WRITE BYTE [1] = address >> 16; /* address = 0x037AA8 */ BYTE [2] = address >> 8; BYTE [3] = address; BYTE [4] = size >> 16; /* size = 0x04 */ BYTE [5] = size >> 8; BYTE [6] = size; ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 111 22. The WINC acknowledges the command by sending three bytes [C7] [0] [F3]. 23. The HIF layer writes the data. 24. The HIF finished writing the request data to memory and is going to interrupt the chip notifying that host TX is done. reg = dma_addr << 2; reg |= (1 << 1); ret = nm_write_reg(WIFI_HOST_RCV_CTRL_3, reg); Command CMD_SINGLE_WRITE:0XC9 /* single word write */ BYTE [0] = CMD_SINGLE_WRITE BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_3 address = 0x106C */ BYTE [2] = address >> 8; BYTE [3] = address; BYTE [4] = u32data >> 24; /* Data = 0x000DEA82 */ BYTE [5] = u32data >> 16; BYTE [6] = u32data >> 8; BYTE [7] = u32data; ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 112 25. The WINC acknowledges the command by sending two bytes [C9] [0]. 26. The HIF layer allows the chip to enter Sleep mode again. sint8 hif_chip_sleep(void) { sint8 ret = M2M_SUCCESS; uint32 reg = 0; ret = nm_write_reg(WAKE_REG, SLEEP_VALUE); /* Clear bit 1 */ ret = nm_read_reg_with_ret(0x1, ®); if(reg&0x2) { reg &=~(1 << 1); ret = nm_write_reg(0x1, reg); } } Command CMD_SINGLE_WRITE:0XC9 /* single word write */ BYTE [0] = CMD_SINGLE_WRITE BYTE [1] = address >> 16; /* WAKE_REG address = 0x1074 */ BYTE [2] = address >> 8; BYTE [3] = address; BYTE [4] = u32data >> 24; /* SLEEP_VALUE Data = 0x4321 */ BYTE [5] = u32data >> 16; BYTE [6] = u32data >> 8; BYTE [7] = u32data; 27. The WINC acknowledges the command by sending two bytes [C9] [0]. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 113 Command CMD_INTERNAL_READ: 0xC4 /* internal register read */ BYTE [0] = CMD_INTERNAL_READ BYTE [1] = address >> 8; /* address = 0x01 */ BYTE [1] |= (1 << 7); /* clockless register */ BYTE [2] = address; BYTE [3] = 0x00; 28. The WINC acknowledges the command by sending three bytes [C4] [0] [F3]. 29. The WINC chip sends the value of the register 0x01 which equals 0x03. Command CMD_INTERNAL_WRITE: C3 /* internal register write */ BYTE [0] = CMD_INTERNAL_WRITE BYTE [1] = address >> 8; /* address = 0x01 */ BYTE [1] |= (1 << 7); /* clockless register */ BYTE [2] = address; BYTE [3] = u32data >> 24; /* Data = 0x01 */ BYTE [4] = u32data >> 16; BYTE [5] = u32data >> 8; BYTE [6] = u32data; ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 114 30. The WINC chip acknowledges the command by sending two bytes [C3] [0]. 31. At this point, the HIF layer has completed posting the scan Wi-Fi request to the WINC chip for processing. 14.3.2 RX (Receive Response) After finishing the required operation (scan Wi-Fi), the WINC interrupts the host to notify of the processing of the request. The host handles this interrupt to receive the response. 1. First step in hif_isr is to wake up the WINC chip. sint8 nm_clkless_wake(void) { ret = nm_read_reg_with_ret(0x1, ®); /* Set bit 1 */ ret = nm_write_reg(0x1, reg | (1 << 1)); // Check the clock status ret = nm_read_reg_with_ret(clk_status_reg_adr, &clk_status_reg); // Tell Firmware that Host waked up the chip ret = nm_write_reg(WAKE_REG, WAKE_VALUE); return ret; } Command CMD_INTERNAL_READ: 0xC4 /* internal register read */ BYTE [0] = CMD_INTERNAL_READ BYTE [1] = address >> 8; /* address = 0x01 */ BYTE [1] |= (1 << 7); /* clockless register */ BYTE [2] = address; BYTE [3] = 0x00; 2. The WINC acknowledges the command by sending three bytes [C4] [0] [F3]. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 115 3. The WINC chip sends the value of the register 0x01 which equals 0x01. Command CMD_INTERNAL_WRITE: C3 /* internal register write */ BYTE [0] = CMD_INTERNAL_WRITE BYTE [1] = address >> 8; /* address = 0x01 */ BYTE [1] |= (1 << 7); /* clockless register */ BYTE [2] = address; BYTE [3] = u32data >> 24; /* Data = 0x03 */ BYTE [4] = u32data >> 16; BYTE [5] = u32data >> 8; BYTE [6] = u32data; 4. The WINC acknowledges the command by sending two bytes [C3] [0]. Command CMD_INTERNAL_READ: 0xC4 /* internal register read */ BYTE [0] = CMD_INTERNAL_READ BYTE [1] = address >> 8; /* address = 0x0F */ BYTE [1] |= (1 << 7); /* clockless register */ BYTE [2] = address; BYTE [3] = 0x00; 5. The WINC acknowledges the command by sending three bytes [C4] [0] [F3]. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 116 6. Then WINC chip sends the value of the register 0x01 which equals 0x07. Command CMD_SINGLE_WRITE:0XC9 /* single word write */ BYTE [0] = CMD_SINGLE_WRITE BYTE [1] = address >> 16; /* WAKE_REG address = 0x1074 */ BYTE [2] = address >> 8; BYTE [3] = address; BYTE [4] = u32data >> 24; /* WAKE_VALUE Data = 0x5678 */ BYTE [5] = u32data >> 16; BYTE [6] = u32data >> 8; BYTE [7] = u32data; 7. The chip acknowledges the command by sending two bytes [C9] [0]. 8. Read register WIFI_HOST_RCV_CTRL_0 to check if there is a new interrupt, and clear it. static sint8 hif_isr(void) { sint8 ret ; uint32 reg; volatile tstrHifHdr strHif; ret = hif_chip_wake(); ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®); if(reg & 0x1) /* New interrupt has been received */ ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 117 { uint16 size; /*Clearing RX interrupt*/ ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®); reg &= ~(1<<0); ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */ BYTE [0] = CMD_SINGLE_READ BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */ BYTE [2] = address >> 8; BYTE [3] = address; 9. The WINC acknowledges the command by sending three bytes [CA] [0] [F3]. 10. The WINC chip sends the value of the register 0x1070 which equals 0x31. Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */ BYTE [0] = CMD_SINGLE_READ BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */ BYTE [2] = address >> 8; BYTE [3] = address; 11. The WINC acknowledges the command by sending three bytes [CA] [0] [F3]. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 118 12. The WINC chip sends the value of the register 0x1070 which equals 0x31. 13. Clear the WINC Interrupt. Command CMD_SINGLE_WRITE:0XC9 /* single word write */ BYTE [0] = CMD_SINGLE_WRITE BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */ BYTE [2] = address >> 8; BYTE [3] = address; BYTE [4] = u32data >> 24; /* Data = 0x30 */ BYTE [5] = u32data >> 16; BYTE [6] = u32data >> 8; BYTE [7] = u32data; 14. The chip acknowledges the command by sending two bytes [C9] [0]. 15. The HIF reads the data size. /* read the rx size */ ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®); Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */ BYTE [0] = CMD_SINGLE_READ BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */ BYTE [2] = address >> 8; BYTE [3] = address; ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 119 16. The WINC acknowledges the command by sending three bytes [CA] [0] [F3]. 17. The WINC chip sends the value of the register 0x1070 which equals 0x30. 18. The HIF reads hif header address. /** start bus transfer**/ ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_1, &address); Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */ BYTE [0] = CMD_SINGLE_READ BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_1 address = 0x1084 */ BYTE [2] = address >> 8; BYTE [3] = address; 19. The WINC acknowledges the command by sending three bytes [CA] [0] [F3]. 20. The WINC chip sends the value of the register 0x1078 which equals 0x037AB0. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 120 21. The HIF reads the hif header data (as a block). ret = nm_read_block(address, (uint8*)&strHif, sizeof(tstrHifHdr)); Command CMD_DMA_EXT_READ: C8 /* dma extended read */ BYTE [0] = CMD_DMA_EXT_READ BYTE [1] = address >> 16; /* address = 0x037AB0*/ BYTE [2] = address >> 8; BYTE [3] = address; BYTE [4] = size >> 16; BYTE [5] = size >>; BYTE [6] = size; 22. The WINC acknowledges the command by sending three bytes [C8] [0] [F3]. 23. The WINC sends the data block (four bytes). 24. The HIF calls the appropriate handler according to the hif header received which tries to receive the Response data payload. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 121 Note:  hif_receive obtains additional data. sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone) { uint32 address, reg; uint16 size; sint8 ret = M2M_SUCCESS; ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®); size = (uint16)((reg >> 2) & 0xfff); ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_1,&address); /* Receive the payload */ ret = nm_read_block(u32Addr, pu8Buf, u16Sz); } Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */ BYTE [0] = CMD_SINGLE_READ BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */ BYTE [2] = address >> 8; BYTE [3] = address; 25. The WINC acknowledges the command by sending three bytes [CA] [0] [F3]. 26. The WINC chip sends the value of the register 0x1070 which equals 0x30. Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */ BYTE [0] = CMD_SINGLE_READ BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_1 address = 0x1084 */ BYTE [2] = address >> 8; BYTE [3] = address; 27. The WINC acknowledges the command by sending three bytes [CA] [0] [F3]. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 122 28. The WINC chip sends the value of the register 0x1078 which equals 0x037AB0. Command CMD_DMA_EXT_READ: C8 /* dma extended read */ BYTE [0] = CMD_DMA_EXT_READ BYTE [1] = address >> 16; /* address = 0x037AB8*/ BYTE [2] = address >> 8; BYTE [3] = address; BYTE [4] = size >> 16; BYTE [5] = size >>; BYTE [6] = size; 29. The WINC acknowledges the command by sending three bytes [C8] [0] [F3]. 30. The WINC sends the data block (four bytes). ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 123 31. After the HIF layer received the response, it interrupts the chip to send the notification that the host RX is done. static sint8 hif_set_rx_done(void) { uint32 reg; sint8 ret = M2M_SUCCESS; ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®); /* Set RX Done */ reg |= (1<<1); ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); } Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */ BYTE [0] = CMD_SINGLE_READ BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */ BYTE [2] = address >> 8; BYTE [3] = address; 32. The WINC acknowledges the command by sending three bytes [CA] [0] [F3]. 33. The WINC chip sends the value of the register 0x1070 which equals 0x30. Command CMD_SINGLE_WRITE:0XC9 /* single word write */ BYTE [0] = CMD_SINGLE_WRITE BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */ BYTE [2] = address >> 8; BYTE [3] = address; BYTE [4] = u32data >> 24; /* Data = 0x32*/ BYTE [5] = u32data >> 16; BYTE [6] = u32data >> 8; BYTE [7] = u32data; ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 124 34. The chip acknowledges the command by sending two bytes [C9] [0]. 35. The HIF layer allows the chip to enter Sleep mode again. sint8 hif_chip_sleep(void) { sint8 ret = M2M_SUCCESS; uint32 reg = 0; ret = nm_write_reg(WAKE_REG, SLEEP_VALUE); /* Clear bit 1 */ ret = nm_read_reg_with_ret(0x1, ®); if(reg&0x2) { reg &=~(1 << 1); ret = nm_write_reg(0x1, reg); } } Command CMD_SINGLE_WRITE:0XC9 /* single word write */ BYTE [0] = CMD_SINGLE_WRITE BYTE [1] = address >> 16; /* WAKE_REG address = 0x1074 */ BYTE [2] = address >> 8; BYTE [3] = address; BYTE [4] = u32data >> 24; /* SLEEP_VALUE Data = 0x4321 */ BYTE [5] = u32data >> 16; BYTE [6] = u32data >> 8; BYTE [7] = u32data; 36. The WINC acknowledges the command by sending two bytes [C9] [0]. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 125 Command CMD_INTERNAL_READ: 0xC4 /* internal register read */ BYTE [0] = CMD_INTERNAL_READ BYTE [1] = address >> 8; /* address = 0x01 */ BYTE [1] |= (1 << 7); /* clockless register */ BYTE [2] = address; BYTE [3] = 0x00; 37. The WINC acknowledges the command by sending three bytes [C4] [0] [F3]. 38. Then WINC chip sends the value of the register 0x01 which equals 0x03. Command CMD_INTERNAL_WRITE: C3 /* internal register write */ BYTE [0] = CMD_INTERNAL_WRITE BYTE [1] = address >> 8; /* address = 0x01 */ BYTE [1] |= (1 << 7); /* clockless register */ BYTE [2] = address; BYTE [3] = u32data >> 24; /* Data = 0x01 */ BYTE [4] = u32data >> 16; BYTE [5] = u32data >> 8; BYTE [6] = u32data; 39. The WINC chip acknowledges the command by sending two bytes [C3] [0]. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 126 40. Scan Wi-Fi request is sent to the WINC chip and the response is successfully sent to the host. ATWINC15x0 WINC SPI Protocol © 2018 Microchip Technology Inc. User Guide DS00002389B-page 127 15. Appendix A. How to Generate Certificates 15.1 Introduction This chapter explains the required procedures to create and sign custom certificates using OpenSSL. To use this guide you must install OpenSSL on your machine. OpenSSL is an open-source implementation of the SSL and TLS protocols. The core library, written in the C programming language, implements basic cryptographic functions and provides various utility functions. OpenSSL can be downloaded from the following URL: https://www.openssl.org/related/binaries.html. 15.2 Steps After installing OpenSSL, open a CMD prompt and navigate to the directory where OpenSSL was installed (For example: C:\OpenSSL-Win64\bin). 1. Generate a key for the CA (certification authority). To generate a 4096-bit long RSA (creates a new file CA_KEY.key to store the random key), using the following command (CMD): openssl genrsa -out CA_KEY.key 4096 2. Create your self-signed root CA certificate CA_CERT.crt; you need to provide some data for your Root certificate, using the following command (CMD): openssl req -new -x509 -days 1826 -key CA_KEY.key -out CA_CERT.crt 3. Create the custom certificate, which is signed by the CA root certificate created earlier. First, generate the Custom.key, using the following command (CMD): openssl genrsa -out Custom.key 4096 4. To generate a certificate request file (CSR) using this generated key, use the following command (CMD): openssl req -new -key Custom.key -out CertReq.csr 5. Process the request for the certificate and get it signed by the root CA, using the following command (CMD): openssl x509 -req -days 730 -in CertReq.csr -CA CA_CERT.crt -CAkey CA_KEY.key - set_serial 01 -out CustomCert.crt 15.3 Limitations The following are the limitations of BigInt_ModExp() API. 1. DHE greater than 2048-bit is not supported. 2. RSA signature verification greater than 2048-bit is done in software; 4096-bit takes 4 seconds per verification, assuming a typical public key of 2^16+1. 3. RSA signature generation greater than 2048-bit is not supported. ATWINC15x0 Appendix A. How to Generate Certificates © 2018 Microchip Technology Inc. User Guide DS00002389B-page 128 16. Appendix B. X.509 Certificate Format and Conversion 16.1 Introduction The most known encodings for the X.509 digital certificates are PEM and DER formats. The PEM format is base64 encoding of the DER enclosed with messages "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----". 16.2 Conversion Between Different Formats The current implementation of the WINC root_certificate_downloader supports only DER format. If the certificate is not in DER format, it must be converted first. The conversion between different formats are done in several methods: 16.2.1 Using Windows From Windows® 7, double click on the .crt certificate file and then go to the Details Tab and press “Copy to File”. Follow the Certificate Export Wizard until the Finish button. 16.2.2 Using OpenSSL The OpenSSL is used for certificate conversion by the following command. openssl x509 -outform der -in certificate.pem -out certificate.der ATWINC15x0 Appendix B. X.509 Certificate Format and C... © 2018 Microchip Technology Inc. User Guide DS00002389B-page 129 16.2.3 Online Conversion There are useful online tools which provide conversion between the certificate formats, which can be found through searching online using keywords such as "OpenSSL". ATWINC15x0 Appendix B. X.509 Certificate Format and C... © 2018 Microchip Technology Inc. User Guide DS00002389B-page 130 17. References The following documents can be used for further study: • ATWINC15x0 Wi-Fi Network Controller Software Programming Guide • ATWINC15x0-MR210xB Data Sheet The following web page can be referred for further study on API: • Atmel Software Framework for ATWINC1500 (Wi-Fi) ATWINC15x0 References © 2018 Microchip Technology Inc. User Guide DS00002389B-page 131 18. Document Revision History Rev B - 10/2018 Section Changes 6.2.3.12 setsockopt Added SOL_SSL_SOCKET information with example. 10. Over-The-Air Upgrade Removed “no HTTPS supported” from the chapter. 8.5 AP Mode Code Example Added Power Save note. Document Removed the content related to Wi-Fi Direct mode and Wi-Fi Sniffer mode. 4.2 WINC Modes of Operation Updated WINC modes of operation. 8.1 Overview and 8.2 Setting the WINC AP Mode Updated the Wi-Fi AP mode chapter corresponding to WINC1500 v19.6.1 firmware. 5. Wi-Fi Station Mode Added support for Encrypted Credential Storage, Simple Roaming, Multiple Gain Table, and Host File Download for Wi-Fi Station mode. Rev A - 05/2017 Section Changes Document • Updated from Atmel to Microchip template. • Assigned a new Microchip document number. Previous version is Atmel 42420 revision B. • ISBN number added. ATWINC15x0 Document Revision History © 2018 Microchip Technology Inc. User Guide DS00002389B-page 132 The Microchip Web Site Microchip provides online support via our web site at http://www.microchip.com/. This web site is used as a means to make files and information easily available to customers. Accessible by using your favorite Internet browser, the web site contains the following information: • Product Support – Data sheets and errata, application notes and sample programs, design resources, user’s guides and hardware support documents, latest software releases and archived software • General Technical Support – Frequently Asked Questions (FAQ), technical support requests, online discussion groups, Microchip consultant program member listing • Business of Microchip – Product selector and ordering guides, latest Microchip press releases, listing of seminars and events, listings of Microchip sales offices, distributors and factory representatives Customer Change Notification Service Microchip’s customer notification service helps keep customers current on Microchip products. Subscribers will receive e-mail notification whenever there are changes, updates, revisions or errata related to a specified product family or development tool of interest. To register, access the Microchip web site at http://www.microchip.com/. Under “Support”, click on “Customer Change Notification” and follow the registration instructions. Customer Support Users of Microchip products can receive assistance through several channels: • Distributor or Representative • Local Sales Office • Field Application Engineer (FAE) • Technical Support Customers should contact their distributor, representative or Field Application Engineer (FAE) for support. Local sales offices are also available to help customers. A listing of sales offices and locations is included in the back of this document. Technical support is available through the web site at: http://www.microchip.com/support Microchip Devices Code Protection Feature Note the following details of the code protection feature on Microchip devices: • Microchip products meet the specification contained in their particular Microchip Data Sheet. • Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the intended manner and under normal conditions. • There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data Sheets. Most likely, the person doing so is engaged in theft of intellectual property. • Microchip is willing to work with the customer who is concerned about the integrity of their code. ATWINC15x0 © 2018 Microchip Technology Inc. User Guide DS00002389B-page 133 • Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not mean that we are guaranteeing the product as “unbreakable.” Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of our products. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such acts allow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act. Legal Notice Information contained in this publication regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer’s risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights unless otherwise stated. Trademarks The Microchip name and logo, the Microchip logo, AnyRate, AVR, AVR logo, AVR Freaks, BitCloud, chipKIT, chipKIT logo, CryptoMemory, CryptoRF, dsPIC, FlashFlex, flexPWR, Heldo, JukeBlox, KeeLoq, Kleer, LANCheck, LINK MD, maXStylus, maXTouch, MediaLB, megaAVR, MOST, MOST logo, MPLAB, OptoLyzer, PIC, picoPower, PICSTART, PIC32 logo, Prochip Designer, QTouch, SAM-BA, SpyNIC, SST, SST Logo, SuperFlash, tinyAVR, UNI/O, and XMEGA are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. ClockWorks, The Embedded Control Solutions Company, EtherSynch, Hyper Speed Control, HyperLight Load, IntelliMOS, mTouch, Precision Edge, and Quiet-Wire are registered trademarks of Microchip Technology Incorporated in the U.S.A. Adjacent Key Suppression, AKS, Analog-for-the-Digital Age, Any Capacitor, AnyIn, AnyOut, BodyCom, CodeGuard, CryptoAuthentication, CryptoAutomotive, CryptoCompanion, CryptoController, dsPICDEM, dsPICDEM.net, Dynamic Average Matching, DAM, ECAN, EtherGREEN, In-Circuit Serial Programming, ICSP, INICnet, Inter-Chip Connectivity, JitterBlocker, KleerNet, KleerNet logo, memBrain, Mindi, MiWi, motorBench, MPASM, MPF, MPLAB Certified logo, MPLIB, MPLINK, MultiTRAK, NetDetach, Omniscient Code Generation, PICDEM, PICDEM.net, PICkit, PICtail, PowerSmart, PureSilicon, QMatrix, REAL ICE, Ripple Blocker, SAM-ICE, Serial Quad I/O, SMART-I.S., SQI, SuperSwitcher, SuperSwitcher II, Total Endurance, TSHARC, USBCheck, VariSense, ViewSpan, WiperLock, Wireless DNA, and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. SQTP is a service mark of Microchip Technology Incorporated in the U.S.A. Silicon Storage Technology is a registered trademark of Microchip Technology Inc. in other countries. GestIC is a registered trademark of Microchip Technology Germany II GmbH & Co. KG, a subsidiary of Microchip Technology Inc., in other countries. All other trademarks mentioned herein are property of their respective companies. ATWINC15x0 © 2018 Microchip Technology Inc. User Guide DS00002389B-page 134 © 2018, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved. ISBN: 978-1-5224-3632-4 Quality Management System Certified by DNV ISO/TS 16949 Microchip received ISO/TS-16949:2009 certification for its worldwide headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona; Gresham, Oregon and design centers in California and India. The Company’s quality system processes and procedures are for its PIC® MCUs and dsPIC® DSCs, KEELOQ® code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory and analog products. In addition, Microchip’s quality system for the design and manufacture of development systems is ISO 9001:2000 certified. ATWINC15x0 © 2018 Microchip Technology Inc. User Guide DS00002389B-page 135 AMERICAS ASIA/PACIFIC ASIA/PACIFIC EUROPE Corporate Office 2355 West Chandler Blvd. Chandler, AZ 85224-6199 Tel: 480-792-7200 Fax: 480-792-7277 Technical Support: http://www.microchip.com/ support Web Address: www.microchip.com Atlanta Duluth, GA Tel: 678-957-9614 Fax: 678-957-1455 Austin, TX Tel: 512-257-3370 Boston Westborough, MA Tel: 774-760-0087 Fax: 774-760-0088 Chicago Itasca, IL Tel: 630-285-0071 Fax: 630-285-0075 Dallas Addison, TX Tel: 972-818-7423 Fax: 972-818-2924 Detroit Novi, MI Tel: 248-848-4000 Houston, TX Tel: 281-894-5983 Indianapolis Noblesville, IN Tel: 317-773-8323 Fax: 317-773-5453 Tel: 317-536-2380 Los Angeles Mission Viejo, CA Tel: 949-462-9523 Fax: 949-462-9608 Tel: 951-273-7800 Raleigh, NC Tel: 919-844-7510 New York, NY Tel: 631-435-6000 San Jose, CA Tel: 408-735-9110 Tel: 408-436-4270 Canada - Toronto Tel: 905-695-1980 Fax: 905-695-2078 Australia - Sydney Tel: 61-2-9868-6733 China - Beijing Tel: 86-10-8569-7000 China - Chengdu Tel: 86-28-8665-5511 China - Chongqing Tel: 86-23-8980-9588 China - Dongguan Tel: 86-769-8702-9880 China - Guangzhou Tel: 86-20-8755-8029 China - Hangzhou Tel: 86-571-8792-8115 China - Hong Kong SAR Tel: 852-2943-5100 China - Nanjing Tel: 86-25-8473-2460 China - Qingdao Tel: 86-532-8502-7355 China - Shanghai Tel: 86-21-3326-8000 China - Shenyang Tel: 86-24-2334-2829 China - Shenzhen Tel: 86-755-8864-2200 China - Suzhou Tel: 86-186-6233-1526 China - Wuhan Tel: 86-27-5980-5300 China - Xian Tel: 86-29-8833-7252 China - Xiamen Tel: 86-592-2388138 China - Zhuhai Tel: 86-756-3210040 India - Bangalore Tel: 91-80-3090-4444 India - New Delhi Tel: 91-11-4160-8631 India - Pune Tel: 91-20-4121-0141 Japan - Osaka Tel: 81-6-6152-7160 Japan - Tokyo Tel: 81-3-6880- 3770 Korea - Daegu Tel: 82-53-744-4301 Korea - Seoul Tel: 82-2-554-7200 Malaysia - Kuala Lumpur Tel: 60-3-7651-7906 Malaysia - Penang Tel: 60-4-227-8870 Philippines - Manila Tel: 63-2-634-9065 Singapore Tel: 65-6334-8870 Taiwan - Hsin Chu Tel: 886-3-577-8366 Taiwan - Kaohsiung Tel: 886-7-213-7830 Taiwan - Taipei Tel: 886-2-2508-8600 Thailand - Bangkok Tel: 66-2-694-1351 Vietnam - Ho Chi Minh Tel: 84-28-5448-2100 Austria - Wels Tel: 43-7242-2244-39 Fax: 43-7242-2244-393 Denmark - Copenhagen Tel: 45-4450-2828 Fax: 45-4485-2829 Finland - Espoo Tel: 358-9-4520-820 France - Paris Tel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79 Germany - Garching Tel: 49-8931-9700 Germany - Haan Tel: 49-2129-3766400 Germany - Heilbronn Tel: 49-7131-67-3636 Germany - Karlsruhe Tel: 49-721-625370 Germany - Munich Tel: 49-89-627-144-0 Fax: 49-89-627-144-44 Germany - Rosenheim Tel: 49-8031-354-560 Israel - Ra’anana Tel: 972-9-744-7705 Italy - Milan Tel: 39-0331-742611 Fax: 39-0331-466781 Italy - Padova Tel: 39-049-7625286 Netherlands - Drunen Tel: 31-416-690399 Fax: 31-416-690340 Norway - Trondheim Tel: 47-72884388 Poland - Warsaw Tel: 48-22-3325737 Romania - Bucharest Tel: 40-21-407-87-50 Spain - Madrid Tel: 34-91-708-08-90 Fax: 34-91-708-08-91 Sweden - Gothenberg Tel: 46-31-704-60-40 Sweden - Stockholm Tel: 46-8-5090-4654 UK - Wokingham Tel: 44-118-921-5800 Fax: 44-118-921-5820 Worldwide Sales and Service © 2018 Microchip Technology Inc. User Guide DS00002389B-page 136

MPLAB Harmony Help MPLAB Harmony Copyright (c) 2013 Microchip Technology Inc. All rights reserved. Table of Contents 1 Start Here 1-1 MPLAB Harmony Help 1 1 Start Here This topic describes how to get started using the MPLAB Harmony Integrated Software Framework. 1. First Time Users Name Description Before You Start Before you start using MPLAB Harmony, be sure to install the MPLAB X IDE Plug-In modules. What is MPLAB Harmony? This topic provides an overview of key concepts necessary to understand the MPLAB Harmony architecture. Project Layout This topic explains how an MPLAB Harmony project is organized. The Main File This topic describes the logic of the "main.c" file and the C-language "main" function in an MPLAB Harmony project. The Application File(s) This topic describes the normal structure of MPLAB Harmony application files. More Information Describes what is available from the MPLAB Harmony web page. Description Software Building Blocks MPLAB Harmony is a framework of software modules that serve as building blocks for your application. If this is the first time you've used MPLAB Harmony, the "First Time Users" section is the best place to start learning. If you're an experienced MPLAB Harmony developer, be sure to look at the "Release Notes & Information" section to find out what is in this release and what is new. 1 MPLAB Harmony Help 1-1 1.1 1. First Time Users 1.1.1 Before You Start Before you start using MPLAB Harmony, be sure to install the MPLAB X IDE Plug-In modules. Description Before you start using MPLAB Harmony, you should install the following MPLAB X IDE plug in modules, included in the MPLAB Harmony installation. 1. The MPLAB Harmony "Help" plug-in module. (Located at: /doc/org-microchip-harmony_help.nbm) 2. The MPLAB Harmony Configurator plug-in module. (Located at: /utilities/configurator/com-microchip-harmonyconfigurator.nbm) Installing the Plug In Modules 1. Start MPLAB X IDE and select "Plugins" from the "Tools" menu as shown below. 2. Click the "Add Plugins..." button, navigate to and open the "com-microchip-harmonyconfigurator.nbm" plug-in file, as shown below. 1.1 1. First Time Users MPLAB Harmony Help Before You Start 1-2 3. Ensure that the box under "Install" for the "MPLAB Harmony Configurator" plug-in is selected and click "Install" as shown below. 1.1 1. First Time Users MPLAB Harmony Help Before You Start 1-3 4. Follow the prompts from the installation and continue until the installation completes. (Do not worry if the version you're installing is "signed" but not "trusted". Just click "continue"). Once the installation has finished you can close the "Plugins" dialog box. You should now see a "MPLAB Harmony Configurator" option under the "Tools" menu. This indicates that the project Configurator has been successfully installed. 1.1.2 What is MPLAB Harmony? This topic provides an overview of key concepts necessary to understand the MPLAB Harmony architecture. Description Introduction Microchip MPLAB® Harmony is the result of a holistic, aggregate approach to creating firmware solutions for embedded systems using Microchip microcontrollers. MPLAB® Harmony Block Diagram 1.1 1. First Time Users MPLAB Harmony Help What is MPLAB Harmony? 1-4 MPLAB Harmony Overview Designed almost completely in the C language (with support for C++), MPLAB Harmony takes key elements of modular and object-oriented design, adds in the flexibility to use a Real-Time Operating System (RTOS) or work without one if you prefer, and provides a framework of software modules that are easy to use, configurable for your specific needs, and that work together in complete harmony. Portability Portability is a concern that is often overlooked when a silicon manufacturer provides software. However, breadth of solutions is a hallmark strength of Microchip, and MPLAB Harmony provides simple libraries to abstract away part-specific details and make Microchip microcontrollers easy to use, regardless of which part you choose. Any time you design a new product or update an existing one you have to balance capabilities against cost, but cost is more than just the bill of materials. It’s also the Non-Refundable Engineering (NRE) cost to design and develop your solution. MPLAB Harmony provides peripheral libraries, device drivers, and other libraries that use clear and consistent interfaces, requiring little or no change in your application code and minimizing the engineering time and effort for each new design. Device Drivers The primary purpose of an MPLAB Harmony device driver (or “driver”) is to provide a simple and highly abstracted interface to a peripheral, allowing your application (or other module in the system) to interact with a peripheral through a consistent set of functions. A device driver is responsible for managing access to a peripheral, so that requests from different modules do not conflict with each other, and for managing the state of that peripheral so that it always operates correctly. Peripheral Libraries A Peripheral Library (PLIB) is a simple access library that provides a consistent (but very low level) interface to a peripheral that is “on board” the microcontroller. PLIBs hide register details, making it easier to write drivers that support multiple microcontroller families, but they are not normally used by applications directly to interact with peripherals, as they provide little abstraction, and because they require the caller to manage the detailed operation of a peripheral (including preventing conflicting requests from other modules). Because of the lack of conflict protection in a PLIB, only one module in a system should directly access the PLIB for a peripheral. Therefore, PLIBs are primarily used to implement device drivers (and some system services) to make them portable. Modularity MPLAB Harmony libraries are modular software “building blocks” that allow you to divide-and-conquer your firmware design. The interface to each library consists of a highly cohesive set of functions (not globally accessible variables or shared registers), so that each module can manage its own resources. If one module needs to use the resources of another module, it calls that module’s interface functions to do so. Interfaces between modules are kept simple with minimal inter-dependencies so that modules are loosely coupled to each other. This approach helps to eliminate conflicts between modules and allows them to be more easily used together like building blocks to create the solutions you need. 1.1 1. First Time Users MPLAB Harmony Help What is MPLAB Harmony? 1-5 Middleware Libraries The normal usage models of some of the more complex peripherals, (i.e., USB or network interfaces) requires interpreting complex protocols or may require substantial additional processing to produce useable results, such as drawing graphical images on an LCD screen with an LCD controller peripheral. Therefore, while a device driver may be completely sufficient for a simple peripheral like a UART, some peripherals require what is frequently called “middleware” (aptly named because it sits between your application and the hardware abstraction layer or “driver” layer). MPLAB Harmony provides several middleware library “stacks” to manage these more complex peripherals and provide the functionality you need and expect. MPLAB Harmony middleware “stacks” are usually built upon device drivers and system services (explained below) so that they can be supported on any Microchip microcontroller for which the required driver or service is supported. However, special purpose implementations may be available that integrate the driver, certain services, and various modules within the “stack” for efficiency. System Services MPLAB Harmony system services are responsible for managing shared resources so that other modules (drivers, middleware, and applications) do not conflict on shared resources. For example, if the TCP/IP, USB, and Graphics stacks attempted to concurrently use the Timer2 peripheral to perform some periodic task, they would very likely interfere with each other. However, if instead they used a timer system service (as the following image illustrates), it is the responsibility of the system service to keep the separate requests from interfering with each other. The timer service can be configured as desired for a specific system (for example, you might decide to use Timer3 instead of Timer2) isolating the necessary changes to the configuration of a single module and preventing potential conflicts. The use of a system service is very similar the use of a device driver, except that a driver normally requires the caller to “open” it to create unique client-to-driver association. A system service does not normally require the caller to open the service before using it because system services are frequently shared by many clients within the system. Compatibility MPLAB Harmony modules (drivers, system services, and middleware – excluding PLIBs) are “active”. This means when an application calls a module’s interface function, the call will usually return immediately and the module will continue working on its own to complete the operation. Most modules will then provide a notification mechanism so the caller (i.e., client) can determine when the operation has finished. Harmony modules are implemented as cooperative state machines. The following image shows the basic idea of how this works. Each module has an “Initialize” function and each module has one (or more) “Tasks” function(s) to maintain its state machine(s). The state machines of all modules are initialized, shortly after the system comes out of reset in “main”. After that (in a polled 1.1 1. First Time Users MPLAB Harmony Help What is MPLAB Harmony? 1-6 configuration, with no OS), the system drops into a “super loop” where each module’s state machine function is repeatedly called, one after the other, to allow it to do the next “task” necessary to keep its state machine running. This allows the system to keep all modules running using a cooperative or shared “multi-tasking” technique. Modules (under control of your application) interact with each other by calling the interface functions of other modules (as illustrated below) and the system-wide “super loop” keeps all modules in the system running so they stay “active” and do their jobs. This method is not suitable for all needs; therefore, other configurations are possible. However, a polled configuration is the simplest to understand and it best illustrates the basic concept of how MPLAB Harmony modules work together, as shown below. It is also easy to implement, easy to understand, and easy to debug. Flexibility The basic MPLAB Harmony model of cooperating state-machine driven modules, when combined with a little configurability, becomes flexible enough to meet the needs of almost any embedded system. For example, if you’re using multiple identical peripherals, MPLAB Harmony has “dynamic” driver implementations that can manage all instances of a peripheral with a single instance of the driver code. You might also have a need for multiple “client” modules to use the same instance of a peripheral at the same time (like the timer example, described previously). To manage this need, MPLAB Harmony has driver implementations that are intelligent enough to manage requests from multiple clients. On the other hand, your needs may be simpler than that. So, static and single client drivers are also available to help reduce the amount of code and data storage needed for your system. Or, your system may need to combine several middleware stacks and multiple, potentially independent, applications. If that is the 1.1 1. First Time Users MPLAB Harmony Help What is MPLAB Harmony? 1-7 case, the simple polling operation, using the “super loop” method frequently seen in simple embedded systems may not be sufficient. However, when you start adding more modules, it becomes more and more difficult to meet the timing requirements of all peripherals using a simple polled super loop. Fortunately, MPLAB Harmony modules are written so that (where appropriate) their state machines can be run directly from an Interrupt Service Routine (ISR) or an RTOS thread. Using an ISR allows you to eliminate the latency of waiting for the execution of other modules in the loop to finish before a time-critical event is serviced, and it allows you to use the interrupt prioritization capabilities available on some Microchip devices to ensure that your system responds to events in the real world in real-time. Additionally, the ability to schedule and prioritize different tasks for different modules can be obtained for modules that are not associated with a specific processor interrupt (such as many middleware modules and your application) using a Real-Time Operating System (RTOS). In fact, that is one of the main reasons to use an RTOS. When your system becomes complex enough that you start struggling to meet your timing requirements using the super loop method, it’s time to use an RTOS. Fortunately, the MPLAB Harmony module state machines functions can be called from a loop in an RTOS thread just as easily as they can be called from a polled “super loop” in a system without an RTOS. To allow this, modules are designed to be “thread safe” by calling semaphore and mutex operations (and a few others, as necessary) through an Operating System Abstraction Layer (OSAL). The OSAL provides a consistent set of functions to call, regardless of which RTOS is being used (or even if no RTOS is used). The choice of RTOS to use, if any, is a configuration option. MPLAB Harmony supports several OS and non-OS configurations and support for more operating systems is possible. All that is required is to implement the OSAL functions appropriately for the desired OS. Configurability Most MPLAB Harmony libraries support a variety of build-time configuration options. • Selection of supported Microchip microcontroller • Interrupt-driven or polled execution • Static-or-dynamic peripheral instance selection (for drivers) • Single-or-multi-client support (for drivers) • Other library-specific options The need for selection of the microcontroller and execution environment has been previously explained. In addition, most drivers and other library modules are designed to allow you to select a variety of configuration options to tailor them to your specific usage. For example, you may be able to select buffer sizes for data transfer modules or clock sources for timer modules. The set of configuration options for each module is identified and explained in the help documentation (along with the interface and usage information) and peripheral initializer (MPLAB Harmony “Pi”) and configuration tools are provided to help simplify the process of configuring your system exactly the way you want and to get you started with a set of initial source files for your project. Project Structure To facilitate configurability, MPLAB Harmony projects are normally structured in a way that isolates the code necessary to 1.1 1. First Time Users MPLAB Harmony Help What is MPLAB Harmony? 1-8 configure a “system” from the library modules themselves and from your application code. The following illustrates this concept, while the second figure shows how the files might appear in an MPLAB X IDE project. In an MPLAB Harmony project, the “main.c” file is kept very simple and consistent (containing primarily, just the super-loop previously discussed). The application files (app.c and app.h in the example to the left) are separate from the configuration files in the “system_config” folder, so it is possible for a single application to have more than one configuration. (Usage of this capability can be seen in example and demonstration projects included with the installation of MPLAB Harmony.) The library modules that make up the MPLAB Harmony framework (in the “framework” folder) use the definitions provided in the selected configuration header (system_config.h, highlighted in the illustration) to specify the configuration options you selected when you configured the project. Finally the processor-specific peripheral libraries (if used) are provided as both a prebuilt binary (“.a” linker file) and as in-line source code to allow for maximum build efficiency for your firmware projects. Conclusion MPLAB Harmony provides a complete framework for developing your firmware solutions using Microchip microcontrollers and development tools. The firmware libraries and tools that make up the MPLAB Harmony framework are modular and compatible, making them simple to use. They’re flexible and configurable, making them easy to tailor to your specific needs. And, they’re portable across a wide range of Microchip microcontrollers so you’re sure to find a supported part that meets your needs. 1.1 1. First Time Users MPLAB Harmony Help Project Layout 1-9 1.1.3 Project Layout This topic explains how an MPLAB Harmony project is organized. Description A sample project has been created to show you the structure of an MPLAB Harmony project. The "sample" project is available in the following folder, directly under your MPLAB Harmony installation root folder. /apps/examples/sample/firmware/sample.X You should open this project in MPLAB X IDE and follow along with this guide. An MPLAB Harmony Project is organized as shown below within MPLAB X IDE. This organization consists of a few key "logical" folders and C-language files, as described below. The "app" folder, which contains: • The "main.c" file • The "app.c" file The "app" (short for "application") folder holds all of the application's firmware source files for the project. In a simple project, the "app" folder will directly contain the "main.c" file and the "app.c" file. More complex projects will very likely contain additional files, as needed. In an MPLAB Harmony project, the "main.c" file normally contains the C-language "main" function and little or nothing else. This "main" logic is usually consistent across all MPLAB Harmony projects and should not need to be changed. The "app.c" file normally contains the logic of the application itself. This is where the desired over-all behavior of your system is usually implemented (although complex applications may have additional files). The "system_config" folder 1.1 1. First Time Users MPLAB Harmony Help Project Layout 1-10 The "system_config" folder contains one or more subdirectories, each of which corresponds to a configuration of your application or, more accurately, "system". MPLAB Harmony projects may have multiple configuration. In each configuration, you can select a different set of libraries or modules, different build parameters for each module and different source files for your application. A configuration consists of a specific set of properties (tools settings) in MPLAB X IDE and a set of source files that define the build parameters and source code that control which modules are initialized and maintained in your system. In MPLAB X IDE, the tools configuration can be selected by using a "pull down" menu in the tool bar at the top of the window or buy "Right-clicking' on the project name and selecting "Properties". In most example and demo projects distributed with MPLAB Harmony, name of each MPLAB X IDE configuration will match the name of the associated folder under the "system_config" folder in the project (the "pic32mx_default" folder in the sample project). When a specific MPLAB X IDE configuration is selected, the configuration files for that configuration are included in the build and the configuration files in other configuration folders are excluded from the build. Note: This is project convention used by example and demo projects provided with MPLAB Harmony. You, of course, may organize your own projects any way you wish. But, we recommend following this convention if you use multiple configurations in your projects. We think you'll appreciate the power and flexibility of it. Configuration Files • The "system_config.h" file • The "system_init.c" file • The "system_tasks.c" file • The "system_int.c" file (optionally) A set of three or four files normally make up a complete configuration of the system. The purpose of each of these files is described in more detail in the following sections. But, the basic idea is that you may want different configurations of your application for different physical hardware boards, different Microchip microcontrollers, or different feature sets, depending on your specific needs. Allowing different configurations of the same application logic makes your application more flexible and provides a well-organized way to deal with the sort of variation that usually occurs in any project of sufficient size and complexity. This technique helps to eliminate the duplication of code (and labor) that would otherwise be necessary to manage multiple related projects. Of course, if you don't need or want that flexibility, all of these files are specifically created for your project and you can make any modifications to them that you like. The choice is always yours. 1.1 1. First Time Users MPLAB Harmony Help Project Layout 1-11 Important! The relative path, from the MPLAB X IDE project folder to the configuration folder (containing the "system_config.h" file) for each project configuration must be placed in the "Includes directories" list in the compiler properties for each configuration of the MPLAB X IDE project. The "framework" folder The "framework" logical folder contains the source files for the MPLAB Harmony framework and libraries. Depending on your project configuration, there can be many, many files and sub folders under this folder. These files are for MPLAB Harmony libraries that you should not need to edit. In fact, the framework source files are not normally located in your project. Instead, these files are included in your project directly from the MPLAB Harmony installation (using relative directory paths). All of the actual files stay in the MPLAB Harmony installation folder, out of the way. Notes 1. You always have the option of copying the framework files directly into your project's source folder, if desired. In fact, doing so is a good idea if you plan to move or distribute your project separately from the MPLAB Harmony installation. 2. In most cases, the "logical folder" organization within the MPLAB X IDE project matches exactly with the physical directory organization within the MPLAB Harmony installation (and within your project directory) on your disk drive. This is done to keep things simple and consistent so you only need to learn a single layout. But, there are a couple of notable exceptions. • MPLAB has a convention of splitting out "Header Files" (".h" files) and "Source Files" (".c" files), so the virtual folder organization in the MPLAB X IDE project separates the files in to these two groups and the physical directories on disk do not. • In an MPLAB Harmony example or demo project, the "app" folder will correspond to the "src" directory on disk under the application's main folder. 1.1.4 The Main File This topic describes the logic of the "main.c" file and the C-language "main" function in an MPLAB Harmony project. Description The C-language entry point for an MPLAB Harmony embedded application is the "main" function. This function is defined in the "main.c" file, contained in the project's "app" folder (or "src" directory on disk). The "main" function (see example, below) implements a simple "super loop", commonly used in embedded applications that do not make use of an operating system. Example "main" Function Logic int main ( void ) { /* Initialize the system. */ SYS_Initialize ( NULL ); while ( true ) { /* Perform system tasks. */ SYS_Tasks ( ); } /* Should not come here during normal operation. */ SYS_ASSERT ( false , "Error! Exiting main" ); return ( EXIT_FAILURE ); } The "SYS_Initialize" Function 1.1 1. First Time Users MPLAB Harmony Help The Main File 1-12 The first thing the main function does is call a function called "SYS_Initialize". The purpose of the "SYS_Initialize" function is to initialize every software module in the system. MPLAB Harmony is based upon a model of cooperating state machines. So, this function must ensure that every module's state machine is placed in a valid initial state. The implementation of this function is one of the things that must be done to configure an MPLAB Harmony system. This function's definition is normally located in the "system_init.c" file and is normally implemented by you since you're the only one who knows which software modules you want to include in your project. However, MPLAB Harmony provide a project Configurator to help you get started. Note: The "SYS_Initialize" function signature has a "void *" input parameter. This is so that it may later be implemented in a library and an arbitrary initialization data structure may be passed into it. However, for a statically implemented "SYS_Initialize" function (which will normally be the case if you implement it yourself), this parameter is unnecessary and can be passed as "NULL". (Note: You could eliminate the parameter, but that may lead to future incompatibilities and the compiler will remove it automatically for you when optimizations are enabled.) The "Super Loop" After all of the modules in the system have been initialized, the "main" function executes an infinite loop to keep the system running. This is commonly called a "super loop" as it is the outer-most loop, within which the entire system operates. This loop never exits. So, the code that exists after the end of that loop should never be executed and is only included there for safety, clarity, and syntactical completeness. The "SYS_Tasks" Function Inside of the "super loop", the "main" function calls the "SYS_Tasks" function. The purpose of the "SYS_Tasks" function is to poll every module in the system to ensure that it continues to operate. This is how the system maintains the state machine of all polled modules. (Note that some modules may be interrupt driven and thus, not called from the "SYS_Tasks" function.) The implementation of the "SYS_Tasks" function is also one of the things that you must normally do as part of the system configuration, again because you are the only one who knows which modules you want to include in your project. You might also have guessed that this function's definition is normally located in the "system_tasks.c" file. Of course, the MPLAB Harmony project Configurator can help with this also. 1.1.5 The Application File(s) This topic describes the normal structure of MPLAB Harmony application files. Description From the point of view of an MPLAB Harmony system, an application consists of two basic functions. • APP_Initialize() • APP_Tasks() The application's initialization function (APP_Initialize) is normally called from the "SYS_Initialize" function, called from "main" before entering the top-level loop. The application's "tasks" function (APP_Tasks) is normally called from the "SYS_Tasks" function, called from "main" from inside the top-level loop. This is how the application's state machine is initialized and "polled" so that it can do it's job. The "SYS_Initialize" function is normally implemented in the "system_init.c" file and the "SYS_Tasks" function is normally implemented in the "sys_tasks.c" file. That is the convention for example and demo projects distributed with MPLAB Harmony and that is the case for the sample project. You may do as you choose in your own projects, but we recommend following this convention as it will make it easier to manage multiple configurations if you need them and it will be consistent with the MPLAB Harmony project Configurator and other tools. Application Initialization An application's initialization function places the application's state machine in its initial state and may perform additional initialization if necessary. This function must not block and it should not call the routines of any other modules that may block. If 1.1 1. First Time Users MPLAB Harmony Help The Application File(s) 1-13 something needs to be initialized that may take time to complete, that initialization should be done in the application's state machine (i.e. in it's "Tasks" function). Sample Application Initialization Function: void APP_Initialize( void ) { /* Copy the message string to a buffer. */ strncpy(appData.buffer, APP_HELLO_STRING, APP_BUFFER_SIZE); /* Prepare a buffer object for transfer using the USART driver. */ appData.bufferObject.buffer = appData.buffer; appData.bufferObject.bufferSize = min(APP_BUFFER_SIZE, strlen(appData.buffer)); appData.bufferObject.flags = DRV_USART_BUFFER_FLAG_WRITE; /* Place the App state machine in it's initial state. */ appData.state = APP_STATE_INIT; } The sample project's initialization function initializes an internal buffer to prepare a "Hello World" message for transmission on a USART and places the application's state machine in its initial state by assigning the "APP_STATE_INIT" enumeration value into the "state" member of the data structure that contains all of the data required by the application (appData). This structure is defined globally, but is only ever accessed by the application itself. The application's initialization function is called from the "SYS_Initialize" function (defined in "system_init.c") which is called from "main" after a system reset. Using this technique, the application is initialized (along with the rest of the system) whenever the system comes out of reset. Application Tasks The application's state machine breaks up the job that the application must do into several short "tasks" that it can complete quickly, but between which it must wait for some other module to complete some tasks of its own. (In this case the other module is the USART driver.) Once each short task has completed successfully, the application transitions to another state to perform the next short task. Example Application Tasks Function: void APP_Tasks( void ) { /* Status of USART driver */ DRV_USART_CLIENT_STATUS usartStatus; /* Status of buffer submitted to USART */ DRV_USART_BUFFER_STATUS bufferStatus; /* Check the application state*/ switch ( appData.state ) { /* Keep trying to open the driver until we succeed. */ case APP_STATE_INIT: { /* open an instance of USART driver */ appData.usartHandle = DRV_USART_Open(SYS_USART_DRIVER_INDEX, DRV_IO_INTENT_READWRITE); if (appData.usartHandle != DRV_HANDLE_INVALID ) { /* Update the state */ appData.state = APP_STATE_WAIT_FOR_READY; } break; } /* Send the message when the driver is ready. */ case APP_STATE_WAIT_FOR_READY: { 1.1 1. First Time Users MPLAB Harmony Help The Application File(s) 1-14 /* Get the USART driver status */ usartStatus = DRV_USART_ClientStatus( appData.usartHandle ); if ( usartStatus == DRV_USART_CLIENT_STATUS_READY ) { /* Submit buffer to USART */ appData.usartBufferHandle = DRV_USART_BufferAdd(appData.usartHandle, &appData.bufferObject); if ( appData.usartBufferHandle != DRV_HANDLE_INVALID ) { /* Buffer is accepted. Driver will transmit. */ appData.state = APP_STATE_WAIT_FOR_DONE; } } break; } case APP_STATE_WAIT_FOR_DONE: { bufferStatus = DRV_USART_BufferStatus(appData.usartHandle, appData.usartBufferHandle); if ( DRV_USART_BUFFER_COMPLETED == bufferStatus ) { /* Work is done, move to idle state. */ appData.state = APP_STATE_IDLE; } } /* Idle state (do nothing) */ case APP_STATE_IDLE: default: break; } } Sample Application States The sample application's "tasks" function breaks the operation of the application down in to the following states using a "switch" statement with the following "cases". • APP_STATE_INIT • APP_STATE_WAIT_FOR_READY • APP_STATE_WAIT_FOR_DONE • APP_STATE_IDLE The sample application is placed into the "APP_STATE_INIT" state when by the application's initialization function before the "tasks" function is ever called. So, the first time the "APP_Tasks" function is called, the switch statement executes the code under this case and the first short "task" the sample application attempts to do is open the USART driver to obtain a handle so that it can transfer data over the USART. Notice that the application checks the value of the handle returned from the "DRV_USART_Open" function to ensure that it is valid before it transitions to the "APP_STATE_WAIT_FOR_READY" state. If the value of the handle retuned be the driver's "open" function is invalid (equal to "DRV_HANDLE_INVALID"), then the application stays in the "APP_STATE_INIT" state and keeps trying to open the USART driver every time it's "tasks" function is called. Once the application has a valid handle to the USART driver, it executes the code under the "APP_STATE_WAIT_FOR_READY" case the next time its "APP_Tasks" function is called . In this state, the application calls a USART driver status routine (DRV_USART_ClientStatus) to see if the driver is ready to transfer data . If the driver is ready, the application calls a USART driver data transfer routine (DRV_USART_BufferAdd) to send the data buffer it prepared in the "APP_Initiaize" function to the USART. Then, it checks the handle returned by the "DRV_USART_BufferAdd" routine to see if it is valid. If the buffer handle is valid, it indicates that the USART driver has accepted the buffer and will take responsibility for the 1.1 1. First Time Users MPLAB Harmony Help The Application File(s) 1-15 data transfer from that point forward. The application does not have to do anything else to cause the data transfer to occur, but it may want to know when the transfer has completed, so it transitions to the "APP_STATE_WAIT_FOR_DONE" state. However, if the buffer is not accepted by the driver (in which case the handle returned by the "DRV_USART_BufferAdd" function would be invalid), the application stays in the "APP_STATE_WAIT_FOR_READY" and tries again the next time the "APP_Tasks" function is called by the system (i.e. the "SYS_Tasks" function). Once the application is in the "APP_STATE_WAIT_FOR_DONE" state, it calls a buffer status routine (DRV_USART_BufferStatus) to check and see if the buffer it sent has completed. Note that it passes the handle value returned from the "DRV_USART_BufferAdd" function (stored in the "usartBufferHandle" member of the global "appData" structure) into the buffer status function to identify the buffer on which it wishes to check status. If the buffer status routine returns "DRV_USART_BUFFER_COMPLETED", then the transfer has completed and the application transitions to the "APP_STATE_IDLE" state where it stays and does nothing any time its "tasks" function is called. It's job is done! A more complex application would go on to some other task or potentially begin the process again. But, this is a simple "Hello World" sample application. Note: The application is normally initialized last, after all other modules in the system have been initialized. But, it should never assume that any other module that it must call has completed its initialization when the application is initialized or when it's "tasks" function is first called. Instead, it should always check the return value or status from any other module it calls to ensure that the call succeeded before moving on to the next state. Following this rule makes applications more robust and allows then to handle errors more effectively. 1.1.6 System Configurations 1.1.6.1 system_config.h This topic describes the purpose of system configuration header file. Description System Configuration In MPLAB Harmony, most library modules have a set of build time configuration options that define a variety of parameters (such as buffer sizes, maximum or minimum limits, and default behavior). These configuration options normally have acceptable default values. However, if you want to configure a library for your specific needs, its configuration options can be defined using C-language pre-processor "#define" statements. The set of configuration options supported is described for each library in the "Configuring the Library" section of its help document and most libraries provide a template and example configuration header files in a "config" sub-folder under their "src" folder. To obtain its build configuration options, every library includes the same common top-level configuration file that must be called "system_config.h" and that must be defined as part of your application or, more specifically, as part of your system configuration. The relative directory path to configuration directory that contains this file must be defined in the build properties of your project so that the compiler can find it in it's include file search path. Example Configuration "system_config.h" Header // ***************************************************************************** // ***************************************************************************** // Section: Application Configuration // ***************************************************************************** // ***************************************************************************** 1.1 1. First Time Users MPLAB Harmony Help System Configurations 1-16 /* Define the size of the application's message buffer. */ #define APP_BUFFER_SIZE 15 #define APP_UART_BAUDRATE 9600 /* Define the application's "hello world" message string. */ #define APP_HELLO_STRING "Hello World\r\n" // ***************************************************************************** // ***************************************************************************** // Section: System Services Configuration // ***************************************************************************** // ***************************************************************************** /* Define the index for the driver we'll use. */ #define SYS_USART_DRIVER_INDEX DRV_USART_INDEX_0 /* Define the hardware (PLIB) index associted with this instance of the driver. */ #define SYS_USART_ID USART_ID_2 // ***************************************************************************** // ***************************************************************************** // Section: UART Driver Configuration // ***************************************************************************** // ***************************************************************************** #define DRV_USART_INSTANCES_NUMBER 1 #define DRV_USART_CLIENTS_NUMBER 1 #define DRV_USART_INTERRUPT_MODE false #define DRV_USART_XFER_BUFFER_NUMBER 10 #define DRV_USART_INTERRUPT_SOURCE_TX INT_SOURCE_USART_2_TRANSMIT #define DRV_USART_CONFIG_BYTE_Q_SIZE_TX 1 #define DRV_USART_CONFIG_BYTE_Q_SIZE_RX 1 #define DRV_USART_CONFIG_BLOCK_DEVICE_MODE #define DRV_USART_INTERRUPT_MODE false #define DRV_USART_INSTANCES_NUMBER 1 #define DRV_USART_CLIENTS_NUMBER 1 #define DRV_USART_INTERRUPT_SOURCE_TX INT_SOURCE_USART_2_TRANSMIT #define DRV_USART_INTERRUPT_SOURCE_RX INT_SOURCE_USART_2_RECEIVE The example above defines configuration options for the application, system services, and USART driver used in the "pic32mx_default" configuration of the sample project.. 1.1.6.2 system_init.c This topic describes the purpose of the system initialization file. Description In an MPLAB Harmony project, the "SYS_Initialization" function is called from the "main" function in order to initialize all modules in the system. This function is implemented as part of a system configuration, normally in a file called "system_init.c". This file may also include other necessary global system items that must be implemented in order to initialize a system such as processor configuration bits and system-wide global data structures. Example "system_init.c" File // **************************************************************************** 1.1 1. First Time Users MPLAB Harmony Help System Configurations 1-17 // **************************************************************************** // Section: Configuration Bits // **************************************************************************** // **************************************************************************** #pragma config FPLLODIV = DIV_1, FPLLMUL = MUL_20, FPLLIDIV = DIV_2 #pragma config FWDTEN = OFF, FCKSM = CSECME, FPBDIV = DIV_1 #pragma config OSCIOFNC = ON, POSCMOD = XT, FSOSCEN = ON, FNOSC = PRIPLL #pragma config CP = OFF, BWP = OFF, PWP = OFF #pragma config ICESEL = ICS_PGx2 // ***************************************************************************** // ***************************************************************************** // Section: Driver Initialization Data // ***************************************************************************** // ***************************************************************************** static DRV_USART_INIT uartInit = { /* System module initialization */ .moduleInit = {0} , /* Identifies USART hardware module (PLIB-level) ID */ .usartID = SYS_USART_ID , /* Operation Modes of the driver */ .operationMode = DRV_USART_OPERATION_MODE_RS232 , /* Flags for the usart initialization */ .initFlags = 0 , /* Control the line control configuration */ .lineControlMode = DRV_USART_LINE_CONTROL_MODE_8NONE1 , /* Baud Rate value to be used, if not using auto baud */ .brgValue = APP_UART_BAUDRATE , /* Operation mode initialization data */ .operationModeInit = {{0}}, /* Handshake Mode */ .handShakeMode = DRV_USART_HANDSHAKE_MODE_NONE , /* Interrupt Source for TX Interrupt */ .txInterruptSource = INT_SOURCE_USART_2_TRANSMIT , /* Interrupt Source for RX Interrupt */ .rxInterruptSource = INT_SOURCE_USART_2_RECEIVE , /* Interrupt Source for Error Interrupt */ .errorInterruptSource = INT_SOURCE_USART_2_ERROR, /* Receive Queue length */ .rxQueueSize = 3, /* Transmit Queue length */ .txQueueSize = 3 }; // ***************************************************************************** // ***************************************************************************** // Section: System Data // ***************************************************************************** // ***************************************************************************** 1.1 1. First Time Users MPLAB Harmony Help System Configurations 1-18 /* Structure to hold the sample application's system data. */ SAMPLE_SYSTEM_OBJECTS sysSample; // **************************************************************************** // **************************************************************************** // Section: System Initialization // **************************************************************************** // **************************************************************************** void SYS_Initialize ( void* data ) { /* Inialize the system */ sysSample.usart = DRV_USART_Initialize(SYS_USART_DRIVER_INDEX, (SYS_MODULE_INIT *)&uartInit ); /* Initialize the Application */ APP_Initialize ( ); } In addition to the "SYS_Initialize" function implementation, the above example "system_init.c" file from the "pic32mx_default" configuration of the "sample" project defines the processor configuration bits, a data structure used to initialize the USART driver, and a global "sysSample" data structure used to hold a global handle to the USART driver object returned by the driver's initialization function. Notice that the "SYS_Initialize" function initializes first the driver, then the application. These are the only two active modules in this system. 1.1.6.3 system_tasks.c This topic describes the purpose of the system tasks file. Description Since MPLAB Harmony modules are state machine driven, they each have a "Tasks" function that must be called repeatedly (from the system-wide "super" loop in "main" or from an ISR or OS thread). The "Tasks" functions are all called from the top-level "SYS_Initialize" function that is normally implemented in a file called "system_tasks.c" that is part of a system configuration. Example "system_tasks.c" File void SYS_Tasks ( void ) { /* Call the "tasks" functions for any modules in the system. */ DRV_USART_TasksTX(sysSample.usart); /* Call the application's tasks routine */ APP_Tasks ( ); } The "system_tasks.c" file for the "pic32mx_default" configuration of the "sample" project, contains only the implementation of the "SYS_Tasks" function for that configuration. This function calls the USART driver's transmitter tasks function "DRV_USART_TasksTX", passing in the driver's object handle returned from the driver's initialization routine, and it calls the application's tasks function "APP_Tasks" to keep both the driver and the application's state machines running. 1.1.6.4 system_int.c This topic describes the purpose of the system interrupts file. 1.1 1. First Time Users MPLAB Harmony Help System Configurations 1-19 Description In an interrupt-driven configuration, any modules (such as drivers or system services) that can be driven from an interrupt must have their interrupt-capable tasks function(s) called from an Interrupt Service Routine (ISR) "vector" function instead of from the "SYS_Tasks" function. The form of the definition of the ISR vector function is dependent on what type of PIC microcontroller on which the system is running. So, any vector functions required are normally implemented as part of the a specific system configuration in a file normally called "system_int.c" Example "system_int.c" File void __ISR ( _UART_2_VECTOR ) _InterruptHandler_USART_2_stub ( void ) { if ( SYS_INT_SourceStatusGet ( APP_USART_INT_SOURCE_TX ) ) { /* Call the USART driver's "Tasks" routine */ DRV_USART_TasksTX ( sysSample.usart ); } } Notice that, in this example, the ISR function must determine if the interrupt occurred because of a transmitter (TX) interrupt because on the PIC32 part used by this configuration of the application, this interrupt vector is shared with other types of interrupts for this USART. Once it has determined that the interrupt is indeed a transmitter interrupt, the ISR calls the USART driver's TX tasks routine and passed in the USART object handle returned from the driver's initialization function. Note: The USART driver's "DRV_USART_TasksTX" function is interrupt capable when the USART driver is built with the correct configuration options. 1.1.7 More Information Describes what is available from the MPLAB Harmony web page. Description Information on MPLAB Harmony is available from microchip.com/harmony. From this landing page, information on additional downloads, links to a MPLAB Harmony discussion forum, among others is available. 1.1 1. First Time Users MPLAB Harmony Help More Information 1-20 1.2 2. Creating Your Own Applications This section describes the steps necessary to create your own MPLAB Harmony applications. Description To support the framework, the application (or MPLAB Harmony "system") is responsible for the following: 1. Create a New Project: This can be accomplished by either running the MPLAB X IDE new project wizard or copying and using a basic template located in the /apps/examples/templates directory. If you copy the template to a new location, you may be required you to modify your include paths. To use the project wizard, select Microchip Embedded > Standalone Project. Next, choose the device. The device you choose will determine what peripheral libraries are included in your MPLAB Harmony project. Continue in the new project Wizard, selecting your hardware and software tools. When you name and locate your project, there are two choices: 1) You can locate it in the ‘apps’ folder of the MPLAB Harmony installation or 2) You can locate it outside of the Harmony installation. Placing the project in the ‘apps’ folder of MPLAB Harmony will require you to copy it if you install a new version of MPLAB Harmony. Installing your project outside of the MPLAB Harmony installation will require you to modify your include paths when a new version of MPLAB Harmony is installed. It is recommend to use relative paths when installing in the ‘apps’ folder in MPLAB Harmony. Make sure that your new project is set to the main (active) project. 2. Determine which MPLAB Harmony Modules are needed for your Application: Modules are divided into four categories; Peripheral Libraries, System Services, Device Drivers and other libraries (commonly called middleware). To determine your needs, read the MPLAB Harmony Overview and the Introductory sections for the modules of interest. Some modules have dependencies while others do not. Peripheral Libraries have no dependencies. Drivers depend on peripheral libraries. System Services depend on Peripheral Libraries and or Drivers. Your application or its middleware will typically use drivers or system services. 3. Add the required Module Source Files to your Project: This can be accomplished by reading the help for each module to determine what source files you need and manually entering them into your project. Alternatively, the MPLAB Harmony Configurator can be used to select the modules from a list or tree and it will automatically insert the source files into your project and optionally generate a skeletal template for your project. Note that some modules have multiple implementations each optimized for different purposes. Others may implement optional features in multiple files. Be sure to select the source file right for your implementation and be sure to include the pre-built peripheral library binary “.a” file for the processor you selected in your project. 4. Configure The Modules: With the exceptions of the Peripheral Libraries, every MPLAB Harmony module will require some set of build time configuration options implemented using ‘c’ language macros ‘#define’. Descriptions of the supported options are available in the "Configuring the Library" section in the help document for every MPLAB Harmony library. These options must be defined in the system_config.h header that is part of your project template generated by the MPLAB Harmony Configurator. Every MPLAB Harmony source file that supports build time configuration options will include this header. As such, this file must be part of every MPLAB Harmony Project. 5. Initialize System: This task involves completing the system_init.c file. First add the necessary configuration bits for your processor. These are defined in the Special Features section of your device's data sheet. The next step is to complete the SYS_Initialize function. Finish any necessary processor initialization (wait states, cache control, etc.) MPLAB Harmony may provide services to accomplish this in the System Services Module. Initialize any features specific to the board that are not initialized by other modules such as drivers or system services. Next, initialize all library modules selected in step 2 above used by your application. To do this you must first define the initialization data structure for each module. This can be done statically in the system_init.c file and passed in by pointer to the appropriate initialization function for each library. Needed initialization structures can be found in the help section for each module. Add a call to the initialization function for each library module into the SYS_Initialize function. Each initialization function will return an object handle for the module instance. These should be captured so that they can be passed to the module task routine. Finally, add the call to APP_Initialize function into the SYS_Initialize function. 6. Call System State Machine Tasks: The system must call the various task state machine functions at appropriate times. This is accomplished by either adding the call into the SYS_Tasks function for polled modules or adding the call to the interrupt handler for interrupt driven modules. The object handle saved during the initialization process is used as an argument for the various task state machine functions. The SYS_Tasks function is typically implemented in the system_tasks.c file while the interrupt handlers are defined in the system_int.c file. 1.2 2. Creating Your Own Applications MPLAB Harmony Help 1-21 7. Develop Application State Machine: You are now ready to develop your application. Since Harmony is based on cooperative state machines, your application should also be state machine driven. At minimum, the APP_Initialize function must put your application in its initial state. It may perform other initialization as long as it does not have to wait for other modules. Any initialization that depends on other modules should be implemented as part of the application state machine. Finally, complete your application functionality by implementing the APP_Tasks state machine function. 1.2 2. Creating Your Own Applications MPLAB Harmony Help 1-22 1.3 3. Release Notes & Information This section contains release notes for this release and information on version numbers and release types. 1.3.1 Release Notes Release notes for MPLAB Harmony v0.70b. Target Release Date: November 18, 2013. Description Please refer to Release Contents for a complete list of modules that are provided in this release. MPLAB Harmony is a framework of system services, device drivers, and other libraries that are built upon a base of portable peripheral libraries to provide flexible, portable, and consistent software “building blocks” which you can use to develop your embedded PIC32 applications. This is the first fully public release of MPLAB Harmony. Previous releases were internal to Microchip and had very limited external distribution. A complete list of the contents of this release is provided in the Release Contents section. You can find these contents under the installation folder you selected in the following sub-folders: • “apps” – Contains all demo and example applications provide with this installation. • “bin” – Contains pre-built binary libraries (“.a” files) for the MPLAB Harmony peripheral libraries for each supported processor and for key libraries provided in binary form. • “bsp” – Contains MPLAB Harmony board support packages provided for selected Microchip demo and development boards. • “build” – Provides MPLAB X IDE projects that you can use to re-build the libraries provide under the “bin” folder (in case you want to use different build settings). • “doc” – Contains the MPLAB Harmony help documentation in PDF and MPLAB X IDE “.nbm” plug-in formats. • “framework” – Contains source code and API headers for all MPLAB Harmony libraries that are provided in source form. • “third_party” – Contains MPLAB Harmony compatible libraries and Real-Time Operating Systems (RTOS) provided with this installation. • “utilities” – Contains design and development utilities and MPLAB X IDE plug-in utilities provided with MPLAB Harmony. Please review the following key help topics (and their subtopics) to gain an initial understanding of what MPLAB Harmony is and how to use it. • Start Here > First Time Users • Start Here > Creating your Own Applications • MPLAB Harmony Configurator Help • The “Introduction” sections of the individual help topics for the system services, drivers, and libraries that are of interest to you • Applications Help > Applications Overview • The “Introduction” sections of the individual applications help topics Once you have a basic understanding of MPLAB Harmony, you can begin using the provided demo and example applications to explore it’s capabilities and begin developing your own applications. 1.3 3. Release Notes & Information MPLAB Harmony Help Release Notes 1-23 Before developing your own applications, be sure to look at the example “template” application provided in the “/apps/examples/templates” folder. The following sections provide a brief overview of items that are new in this release and known issues at the time of the release. Refer to the “Release Notes” section under the help topic for each individual library, application, or utility for additional details. Refer to the “Using the Library” section for each individual library for a description of how to use library functions to accomplish the tasks that the library was intended to support. Refer to the “Library Interface” section for each individual library for a programmer’s reference or dictionary of functions and data types defined by that library’s interface. New This Release: • Significant SD Card Driver improvements. • The SPI driver has had configuration and interoperability improvements. • The NVM driver now handles sector erasing during writes. • USB Driver demonstrations • TCP/IP Stack updates (see the TCP/IP Stack Library Help) • Graphics Library API has been updated • File System Service Library has been updated • The following System Services have been added: Clock and Device Control • USART Driver has been updated • USB Driver has been updated • Peripheral Libraries now support PIC32MZ devices • FreeRTOS now supports PIC32MZ devices • CyaSSL Library has been added Known Issues: • The SD Card driver has had limited testing and is missing a few desired features • The SPI driver does not support slave mode or DMA • The NVM driver has only been tested in it’s current memory configuration • NVM Driver demonstration has limited testing • SPI Driver demonstration has limited testing and hardware support • USART Driver demonstration does not support PIC32MZ devices • USB demonstrations (see the related Release Notes) • USB Host Stack has limited testing and functional limitations (see the related Release Notes) • USB Device Stack has limited testing and functional limitations (see the related Release Notes) • No multi-display support for the Graphics Primitive Library • File System Service Library does not support MIP16 mode, has limited testing and functional limitations (see the related Release Notes) • USART Driver has flow control and parity mode limitations and no multi-client support • MRF24W Wi-Fi Driver Library has limited demonstration support and testing (see the related Release Notes) 1.3 3. Release Notes & Information MPLAB Harmony Help Release Contents 1-24 1.3.2 Release Contents This topic lists the contents of this release and identifies the individual version numbers of each module. Description This table lists the contents of this release, including a brief description of each module. Cryptographic Applications: /apps/crypto/ Crypto Demonstration Crypto Library Demonstration 1.00 Example Applications: /apps/examples/ peripheral/blocking/pic32mz Simple blocking PLIB examples. 1.00 peripheral/blocking/pic32mx Simple blocking PLIB examples 1.00 state_driven Simple MPLAB Harmony compliant state-driven Peripheral Library examples 1.00 sample Sample “Hello World” demonstration used in “Getting Started” guide in Help system N/A DEMOS: Driver Application demos: /apps/driver/ nvm demo NVM demonstration application 1.00 usart demo USART demonstration application 1.00 spi demo SPI demonstration application 1.00 DEMOS : RTOS Application demos: /apps/rtos/ freertos FreeRTOS demonstration application 1.00 openrtos OpenRTOS demonstration application 1.00 File System Applications: /apps/fs/ nvm_fat_single_disk Single-disk Non-Volatile Memory FAT FS Demonstration 1.00 nvm_sdcard_fat_multi_disk Multi-disk Non-Volatile Memory FAT FS Demonstration 1.00 sdcard_fat_single_disk SD Card FAT Disk demonstration 1.00 nvm_mpfs_single_disk Single-disk Non-Volatile Memory 1.00 nvm_sdcard_fat_mpfs_multi_disk Multi-disk Non-Volatile Memory FAT MPFS Demostration 1.00 DEMOS: Graphics Applications: /apps/gfx/ lcc Low-Cost Controllerless Graphics Demonstration 4.00b object Graphics Object Layer Demonstration 4.00b primitive Graphics Primitives Layer Demonstration 4.00b s1d13517 Epson S1D13517 LCD Controller Demonstration 4.00b ssd1926 Solomon Systech SSD1926 Controller Demonstration 4.00b 1.3 3. Release Notes & Information MPLAB Harmony Help Release Contents 1-25 DEMOS: TCP/IP Applications & Utilities: /apps/tcpip/ tcpip_web_server TCP/IP Web Server Demonstration 1.01 bsd_tcp_server TCP/IP BSD Server Demonstration 1.00 bsd_tcp_client TCP/IP BSD Client Demonstration 1.00 bsd_udp_server TCP/IP BSD Server Demonstration 1.00 bsd_udp_client TCP/IP BSD Client Demonstration 1.00 tcpip_tcp_server TCP/IP TCP Server Demonstration 1.00 tcpip_tcp_client TCP/IP TCP Client Demonstration 1.00 tcpip_udp_server TCP/IP UDP Server Demonstration 1.00 tcpip_udp_client TCP/IP UDP Client Demonstration 1.00 wolf_ssl wolf ssl Demonstration 1.00 wifi_console TCP/IP Wi-Fi Console Demonstration wifi_easyconf TCP/IP Wi-Fi Easy Configuration Demonstration DEMOS: USB Device (Function) Applications: /apps/usb/device/ audio_speaker USB Audio Device Speaker Demonstration 1.00 cdc_com_port_dual CDC Dual Serial COM Ports Emulation Demonstration 1.00 cdc_com_port_single CDC Single Serial COM Port Emulation Demonstration 1.00 generic_device Microchip Generic USB Device Demonstration 1.00 hid_basic Basic USB Human Interface Device (HID) Demonstration 1.00 hid_joystick USB HID-Class Joystick Device Demonstration 1.00 hid_keyboard USB HID-Class Keyboard Device Demonstration 1.00 hid_mouse USB HID-Class Mouse Device Demonstration 1.00 msd_basic USB Mass Storage Device Demonstration 1.00 cdc_serial_emulator CDC Serial Emulation Demonstration 1.00 DEMOS: USB Host Applications: /apps/usb/host/ msd_simple_thumb_drive USB MSD Host Simple Thumb Drive Demonstration 1.00 cdc_basic USB CDC Basic Demonstration 1.00 cdc_serial USB CDC Serial Demonstration 1.00 hid_keyboard USB HID-Class Joystick Host Demonstration 1.00 hid_mouse USB HID-Class Mouse Host Demonstration 1.00 generic_device Microchip Generic USB Host Demonstration 1.00 Pre-built Binaries: /bin/ framework/peripheral Pre-built Peripheral Libraries 1.00 framework/math/dsp Pre-built DSP libraries for PIC32MZ devices 1.00 framework/math/libq Pre-built fixed-point math libraries for PIC32MZ devices 1.00 1.3 3. Release Notes & Information MPLAB Harmony Help Release Contents 1-26 Board Support Packages (BSPs): /bsp/ explorer16/pic32mx795f512l Explorer 16 Development Board and PIC32MX795F512L PIM 1.00 sk_pic32_mx_usb PIC32 USB Starter Kit 1.00 sk_pic32_mz PIC32MZ Embedded Connectivity (EC) Starter Kit 1.00 usb_audio_pic32mx PIC32 USB Starter Kit II 1.00 gfx Graphics (GFX) boards 1.00 Documentation: /doc doc/org-microchip-harmony_help.nbm MPLAB Harmony Help MPLAB X IDE Plug-In 0.70b doc/harmony_help.pdf MPLAB Harmony Help 0.70b Middleware & Libraries: /framework/ Crypto (Software) Microchip Cryptographic Libraries 1.00 GFX Graphics Library 4.00b MATH/DSP API header for PIC32MZ DSP Libraries 1.00 MATH/LIBQ API header for PIC32MX fixed-point libraries 1.00 AAC/MP3 Audio Decoder Libraries 1.00 TCP/IP TCP/IP Network Stack 7.10 USB Host USB Host Stack 0.02b USB Device USB Device Stack 0.05b Device Drivers: /framework/driver/ adc Analog-to-Digital Converter Driver 0.01b ethmac Ethernet Media Access Controller Driver 7.10 ethphy Ethernet Physical Interface Driver 7.10 gfx/gfx_lcc Low-Cost Controllerless Graphics Driver 4.00b gfx/gfx_otm2201a OTM LCD Controller Driver 4.00b gfx/gfx_s1d13517 Epson S1D13517 LCD Controller Driver 4.00b gfx/gfx_ssd1926 Solomon Systech SSD1926 Controller Driver 4.00b nvm Non-Volatile Memory Driver 0.50b pmp Parallel Master Port Driver 0.50b sdcard SD Card Driver (Client of SPI Driver) 0.50b spi Serial Peripheral Interface (SPI) Driver 0.50b tmr Timer Driver 0.50b usart Universal Synchronous/Asynchronous Receiver/Transmitter (USART) Driver 0.50b usb/usbhs Universal Serial Bus (USB) Controller Driver 0.05b wifi/mrf24w Wi-Fi MAC driver for the MRF24W controller 3.0.0 1.3 3. Release Notes & Information MPLAB Harmony Help Release Contents 1-27 Operating System Abstraction Layer (OSAL): /framework/osal osal.h OSAL Interface 0.52b osal_freertos.h osal_freertos.c OSAL Implementation for FreeRTOS 0.52b osal_openrtos.h osal_openrtos.c OSAL Implementation for OpenRTOS 0.52b osal_impl_basic.h OSAL “bare metal” (no OS) implementation 0.52b osal_imple_none.h OSAL implementation that removes the OSAL when not used 0.52b osal_ucos3.h osal_ucos3.c OSAL Implementation for Micrium µCOS-III 0.52b osal_ucos2.h osal_ucos2.c OSAL Implementation for Micrium µCOS-II N/A osal_threadx.h OSAL Implementation for Express Logic ThreadX N/A osal_threadx.c N/A Peripheral Libraries: / framework/peripheral Peripheral Library Source Code for all Supported PIC32 Processors 0.70b Build Framework: /build/framework/ crypto/test Test Vector App for crypto/zlib 1.00 crypto/zlib zlib library 1.00 crypto/crypto crypto library 1.00 peripheral Peripheral Library build project 1.00 math/libq libq library build project 1.00 math/DSP DSP library build project 1.00 System Services: /framework/system/ clk Clock Services Library 0.04a common Common Services 0.02a devcon Devcon Services Library 0.02b fs File System Services Library 0.50b int Interrupt Services Library 0.04a msg Message Services Library 0.01a ports Input/Output Ports Services Library 0.02b tmr Software Timer Services Library 0.02a wdt Watchdog Timer Services Library 0.02b Third-Party Software: /third_party/ 1.3 3. Release Notes & Information MPLAB Harmony Help Release Contents 1-28 rtos/FreeRTOSV7.5.2 FreeRTOS Source Distribution v7.5 with support for PIC32MZ devices Yes (Vendor Version) rtos/FreeRTOSVX.XX.XX FreeRTOS Source Distribution v7.5 with support for PIC32MX devices Yes (Vendor Version) rtos/OpenRTOSVx.x.x OpenRTOS Source Distribution vx.x.x with support for PIC32MZ devices Yes (Vendor Version) rtos/OpenRTOSVx.x.x OpenRTOS Source Distribution vx.x.x with support for PIC32MX devices Yes (Vendor Version) uC/OS-III Micrium uC/OS-III Binary Demonstration with support for PIC32MZ devices Yes (Vendor Version) uC/OS-III Micrium uC/OS-III Binary Demonstration with support for PIC32MX devices Maybe (Vendor Version) uC/OS-II Micrium uC/OS-II Binary Demonstration (PIC32MZ) uC/OS-II Micrium uC/OS-II Binary Demonstration (PIC32MX) ThreadX Express Logic (ThreadX) Demonstration with Support for PIC32MZ devices CyaSSL Embedded SSL Library Open Source based demonstration 2.8.0 (Vendor Version) CyaSSL Embedded SSL Library Open Source based demonstration Yes (Vendor Version) InterNiche Technologies, Inc. Suitable TCP/IP demonstrations Yes (Vendor Version) Utilities: /utilities/ MPLAB Configurator MPLAB Harmony Project/Library Configurator MPLAB X IDE Plug-In 0.02a gfx/gdd Graphics Display Designer 2.00b gfx/grc Graphics Resource Compiler 4.00.39 mib2bib/mib2bib.jar Compiles Custom Microchip MIB script (snmp.mib) to generate snmp.bib and mib.h 2.00 mpfs_generator/mpfs2.jar TCP/IP MPFS File Generator and Upload Utility 2.02.06 tcpip_discoverer/tcpip_discoverer.jar TCP/IP Microchip Node Discoverer Utility 2.00 1.3.3 Version Numbers This section describes the version numbers and their meaning. 1.3 3. Release Notes & Information MPLAB Harmony Help Version Numbers 1-29 Description MPLAB Harmony Version Numbering Scheme Libraries released with MPLAB Harmony each have their own version number, using the following scheme. .[.<“dot”>][] • Major revision (architecture or paradigm shift) • Minor revision (new features, regular releases) • “Dot” release (bug fixes, unscheduled releases) • Release Type (‘a’ = alpha, ‘b’ = beta, Full release versions 1.0 or above have no type letter) Items in square brackets are only present when needed (see examples, below). Examples: • MPLAB Harmony USB Library v2.6 (“dot” of ‘0’ implied) • MPLAB Harmony Graphics Library v1.12.02 Note: The version number of the over all MPLAB Harmony release is not related to the version numbers of each individual library or module included in the release and has no bearing on the versions of any libraries it includes. It is merely a way to keep track of what libraries (and what versions of what libraries) are included in each release. Refer to the current release notes to identify what libraries are included and what their version numbers are. 1.3.4 Release Types This section describes the release types and their meaning. Description MPLAB Harmony module releases can be of three different types, based on the version type. Alpha Release An alpha release version of a module is usually an initial release. Alpha releases will have complete implementations of their basic feature set, they are unit tested (usually by the original developer) and will build correctly in their basic configuration. An 1.3 3. Release Notes & Information MPLAB Harmony Help Release Types 1-30 alpha release is a great "preview" of what a new development Microchip is working on and it can be very helpful for exploring new features. However, it has not gone through a formal test process and it is almost certain that some of its interface will change before the full version is released. It is not recommended for production use. Beta Release A beta release version of a module has gone through the internal interface review process and has had formal testing of its functionality. Also, issues reported from the alpha release will have been fixed or documented. When a module is in a beta version, you can expect it to function correctly in normal circumstances and you can expect that its interface is very close to the final form (although changes can still be made if required). However, it has not had stress testing or been tested and it may not fail gracefully if used incorrectly. A beta release is not recommended for production use, but it can be used for development. 1.0+ Release By the time a module is released as a 1.0 version or above, it is feature complete, fully tested, and its interface is "frozen". All known issues from previous releases will have been fixed or documented. The existing interface will not change in future releases. It may be expanded with additional features and additional interface functions, but existing interface functions will not change. This is stable code with a stable Application Program Interface (API) that you can rely on for production purposes. 1.3 3. Release Notes & Information MPLAB Harmony Help Release Types 1-31 1.4 4. Previous Releases This topic contains information about past version(s) of MPLAB Harmony. 1.4.1 v0.51.03b Release notes for MPLAB Harmony v0.51.03b. Description This topic contains the release notes for MPLAB Harmony v0.51.03b. Please refer to the Release Contents topic for a complete list modules that are provided in this release. This release will support MPLAB X IDE v1.95 and XC32 v1.30 tc9 and above. New this Release • Updated the Documentation • Updated Peripheral Pre-Built Binary Libraries (".a" files) • Added IPv6 API for generation of the Unique Local Address (ULA) Known Issues 1. No documentation available for the Crypto libraries and peripheral libraries example applications. 2. For TCP/IP stack running on PIC32MZ platforms the write-back mode is not supported yet. Write-through has to be used for now. 3. Early samples of the PIC32MZ silicon do not have a factory pre-programmed MAC address. This will cause the TCP/IP stack and related applications to not properly run in most network configuration. Manual update of the related "network_config.h" file with a valid MAC address is required. 4. The Wi-Fi driver for the TCP/IP stack and the supporting demos are not part of this release. This table lists the contents of this release, gives a brief description Module Description Version File System Applications: /apps/fs/ nvm_fat_single_disk Single-disk Non-Volatile Memory FAT FS Demonstration 0.02a nvm_sdcard_fat_multi_disk Multi-disk Non-Volatile Memory FAT FS Demonstration 0.02a sdcard_fat_single_disk SD-Card FAT Disk Demonstration 0.02a nvm_mpfs_single_disk Single-disk Non-Volatile Memory MPFS Demonstration 0.02a nvm_sdcard_fat_mpfs_multi_disk Multi-disk Non-Volatile Memory FAT MPFS Demonstration 0.02a Graphics Applications: /apps/gfx/ lcc Low-Cost Controllerless Graphics Demonstration 0.51b object Graphics Object Layer Demonstration 0.51b 1.4 4. Previous Releases MPLAB Harmony Help v0.51.03b 1-32 primitive Graphics Primitives Layer Demonstration 0.51b ssd1926 Solomon Systech SSD1926 Controller Demonstration 0.51b TCP/IP Applications & Utilities: /apps/tcpip/ tcpip_web_server TCPIP Web Server Demonstration 7.02a utilities/mpfs_generator/mpfs2.jar TCP/IP MPFS File Generator and Upload Utility 2.2.5 utilities/tcpip_dicoverer/tcpip_discoverer.jar TCP/IP Microchip Node Discoverer Utility 2.0 utilities/mib2bib/mib2bib.jar Compiles Custom Microchip MIB script ( snmp.mib) to generate snmp.bib and mib.h 2.0 USB Device (Function) Applications: /apps/usb/device/ audio_speaker USB Audio Device - Speaker Demonstration 0.51b cdc_com_port_dual CDC Dual Serial COM Ports Emulation Demonstration 0.51b cdc_com_port_single CDC Single Serial COM Ports Emulation Demonstration 0.51b generic_device Generic USB Device Demonstration 0.51b hid_basic USB Human Interface Device (HID) Demonstration 0.51b hid_joystick USB HID Joystick Device Demonstration 0.51b hid_keyboard USB HID Keyboard Device Demonstration 0.51b hid_mouse USB HID Mouse Device Demonstration 0.51b msd_basic USB Mass Storage Device Demonstration 0.51b USB Host Applications: /apps/usb/host/ cdc_serial USB CDC Host Demonstration 0.51b Crypto Applications: /apps/ crypto Wolf SSL Cryptographic Demonstration 0.01a PIC32MZ Applications: /apps/ pic32mz PIC32MZ Device Demonstration 0.51.01b Example Applications: /apps/examples peripheral Peripheral Demonstration 0.51b sample Sample Demonstration 0.51b Board Support Packages (BSPs): /bsp/ explorer16/pic32mx795f512l Explorer 16 Development Board and PIC32MX795F512L PIM pic32_sk/pic32_usb_sk PIC32 USB Starter Kit pic32_sk\pic32mz_sk PIC32MZ Starter Kit pic32mx_usb_audio PIC32 USB Digital Audio Accessory Board Third Party Software: /third_party/ rtos/FreeRTOSV7.5.0 FreeRTOS Source Distribution v7.5.0 7.5.0 Middleware: /framework/ 1.4 4. Previous Releases MPLAB Harmony Help v0.51.03b 1-33 gfx Graphics Library 0.51b tcpip TCP/IP Network Stack 7.02a usb USB Host & Device Stack 0.51b Crypto Library: /framework/ crypto Wolf SSL Cryptographic Libraries 0.01a System Services: /framework/system/ clk Clock Services Library 0.03a debug Debug Services Library 0.01a fs File System Services Library 0.02a int Interrupt Services Library 0.03a msg Message Services Library 0.01a ports Input-Output Ports Services Library 0.01a reset System Reset Services Library 0.01a tmr Software Timer Services Library 0.01a wdt Watchdog Timer Services Library 0.01a Device Drivers: /framework/driver/ adc Analog-to-Digital Converter Driver 0.01a ethmac Ethernet Media Access Controller Driver 0.03a ethphy Ethernet Physical Interface Driver 0.03a gfx/gfx_lcc Low-Cost Controllerless Graphics Driver 0.51b gfx/gfx_s1d13517 Epson S1D13517 LCD Controller Driver 0.51b gfx/gfx_ssd1926 Solomon Systech SSD1926 Controller Driver 0.51b nvm Non-Volatile Memory Driver 0.01a pmp Parallel Master Port Driver 0.01a sdcard SD Card Driver (Client of SPI Driver) 0.01a spi Serial Peripheral Interface (SPI) Driver 0.01a tmr Timer Driver 0.01a usart Universal Synchronous/Asynchronous Receiver/Transmitter (USART) Driver 0.01a usb Universal Serial Bus (USB) Controller Driver 0.51b usbhs Hi-Speed USB Controller Driver 0.51b wifi Wi-Fi Driver 0.01a Peripheral Libraries (PLIBs): / framework/peripheral Peripheral Library Source Code 0.51b bin/framework/peripheral Peripheral Pre-Built Binary Libraries for all PIC32 Processors 0.51b build/framework/peripheral Project used for Peripheral Library Prebuilt Binary Libraries Creation 0.51b 1.4 4. Previous Releases MPLAB Harmony Help v0.51.03b 1-34 Operating System Abstraction Layer (OSAL): /framework/osal/ osal.h osal.c OSAL interface 0.51b osal_impl_none.h OSAL implementation that removes the OSAL when not used 0.51b osal_impl_basic.h OSAL "bare metal" (no OS) implemenrtation 0.51b osal_freertos.h osal_freertos.c OSAL implementation for FreeRTOS 0.51b osal_ucos.h osal_ucos.c OSAL implementation for Micrium uCOS-III 0.51b 1.4 4. Previous Releases MPLAB Harmony Help v0.51.03b 1-35 1.5 5. Tips and Tricks This topic provides a few helpful tips and tricks to keep in mind while developing your MPLAB Harmony projects. Description You may find the following MPLAB Harmony "tips" and "tricks" helpful when developing your own MPLAB Harmony projects. 1. After creating a new MPLAB X IDE project, use the project wizard to add MPLAB Harmony libraries to your project and create a set if initial files for your project. After that, your job is to ensure that the necessary initialization and configuration data and definitions are in place and to write your own application. 2. You can use MPLAB Harmony example and demo projects to put together a "first approximation" of your application. 1. Copy the source files from the various example or demo apps to your project. 2. Rename the "APP_Initialize" and "APP_Tasks" functions so that they are all different and will build in your application by simply appending a descriptive name to the end of the existing function names. (Note: you may also need to rename any global data "objects" that conflict with each other from the examples). 3. Call the individual "APP_Initialize" and "APP_Tasks" functions from the "SYS_Initialize" and "SYS_Tasks" functions in your application's configuration files. 4. Use the project wizard to add any required drivers, services, or middleware. 5. At this point, you now have your application made out of several independent state machines. Now, you can begin to develop your own custom application code and modifying any of the code copied from the provided applications to behave as you desire. 1.5 5. Tips and Tricks MPLAB Harmony Help 1-36 1.6 6. Glossary This section contains a glossary of general MPLAB Harmony terms. Description Glossary of Harmony Terms Term Definition Application One or more application modules define the over all behavior of an MPLAB Harmony system. Applications are either demonstrations or examples provided with the installation or are implemented by you, using MPLAB Harmony libraries to accomplish a desired task. Client A client module is any module that uses the services (calls the interface functions) of another module. Configuration An MPLAB Harmony configuration consists of static definitions (C-language "#define" statements), executable source code, and other definitions in a set of files that are necessary to create a working MPLAB Harmony system. (See Start Here for additional information.) Configuration Options Configuration options are the specific set of "#define" statements that are required by any specific MPLAB Harmony library to specify certain parameters (such as buffer sizes, minimum and maximum values, etc.) build that library. Configuration options are defined in the "system_config.h" system-wide configuration header. Driver A "driver" (AKA device driver) is an MPLAB Harmony software module designed to control and provide access to a specific peripheral, either built into the microcontroller or external to it. Driver Index Dynamic MPLAB Harmony drivers (and other dynamic modules) can manage the more than one instance of the peripheral (and other resources) that they control. The "driver index" is a static index number (0, 1, 2,...) that identifies which instance of the driver is to be used. Note: The driver index is not necessarily identical to the peripheral index. The association between these two is made when the driver is initialized. Driver Instance An instance of a driver (or other module) consists of a complete set of the memory (and other resources) controlled by the driver's code. Selection of which set of resources to control is made using a driver index. Note: Even though there may be multiple instances of the resources managed by a dynamic driver, there is only ever one instance of the actual object code. However, static drivers always maintain a 1:1 relationship between resource and code instances. Framework The MPLAB Harmony framework consists of a set of libraries (and the rules and conventions used to create those libraries) that can be used to create MPLAB Harmony systems. Initialization Overrides Initialization overrides are configuration options that can be defined to statically override (at build time) parameters that are normally passed into the "Initialize" function of a driver or other MPLAB Harmony module. This mechanism allows you to statically initialize a module, instead of dynamically initializing the module. Interface The interface to a module is the set of functions, data types, and other definitions that must be used to interact with that module. Middleware The term "middleware" is used to describe any software that fits between the application and the device drivers within an MPLAB Harmony system. It is something of a catch all term that is loosely used to describe libraries that use drivers to access peripheral and then implement communication protocols (such as TCP/IP, USB protocols, and graphics image processing) and other more complex processing that is required to use certain peripherals, but is not properly part of controlling the peripheral itself. Module An MPLAB Harmony software module is a closely related group of functions controlling a related set of resources (memory and registers) that can be initialized and maintained by the system. Most MPLAB Harmony modules provide an interface for client interaction. However, "headless" modules with no interface are possible. 1.6 6. Glossary MPLAB Harmony Help 1-37 Peripheral Index A peripheral index is a static label (usually an C-language "enum" value) that is used to identify a specific instance of a peripheral. Note: Unlike a driver index, which always starts at '0', a peripheral index may be internally represented as any number, letter, or even a base address and the user should not rely on the value itself - only the label. Peripheral Instance An instance of a peripheral is a complete set of the registers (and internal physical resources) necessary to provide the core functionality of a given type of peripheral (either built into the microcontroller or external to it). Note: A specific peripheral instance is identified using a peripheral index. System An MPLAB Harmony system is a complete set of libraries, applications, and configuration items loaded and executing on a specific hardware platform (microcontroller, board, and external peripherals) or the source items necessary to build such a system. Note: Since a system can multiple configurations, one MPLAB Harmony project may support multiple systems through multiple supported configurations. See the demo applications included in the installation for examples. System Service A system service is an MPLAB Harmony module that provides access to and/or control of common system resources (memory and registers) with which other modules (drivers, middleware, libraries and application) may interact. Note: System services, much like drivers, manage sharing of resources so as to avoid conflicts between modules that would otherwise occur if each module attempted to manage the share resource itself. But, unlike drivers, system services do not normally need to be "opened" in order to use them. 1.6 6. Glossary MPLAB Harmony Help 1-38 2 MPLAB Harmony Configurator Help 2 MPLAB Harmony Help 2-39 2.1 MPLAB Harmony Configurator 2.1.1 Introduction This topic provides an overview of the MPLAB Harmony Configurator. Description The MPLAB Harmony Configurator is a MPLAB X IDE plug-in. It must be installed into your MPLAB X IDE installation to be used. 2.1.2 Release Notes MPLAB Harmony Version: v0.70b Release Date: 18Nov2013 Description ==================================== Version 0.02a MPLAB Harmony Configurator Plug-in November 2013 ==================================== Operating System Support MPLAB Harmony Configurator Plug-in was tested on the following operating systems:. • Windows XP SP3 and Windows 7 • Linux OS - Ubuntu • Mac OS v8 Supported Features: • Provides a simple hierarchical way for users to select the MPLAB Harmony modules to be used in the project and adds the selected module source files with the necessary configuration and project settings (include path) into the created MPLAB X IDE project. • Supports importing project related files from relative path. • Adds predefined source and header template files to the MPLAB X IDE project. • Library Configuration is supported only for the TCP/IP and USB libraries. Unsupported Features: • System-related API calls are not added automatically to the system_init.c, main.c, and system_tasks.c files. Only the standard C templates are added to the project. The application code must be added by the user in the application source and header 2.1 MPLAB Harmony Configurator MPLAB Harmony Help Release Notes 2-40 files for a successful compilation of the project. • Library Configuration is not supported for the Graphics library, OSAL, Drivers and Third-Party libraries. However, the corresponding source and header files of the selected modules could be added to the created MPLAB X IDE project using this Configurator. Notes for Users: 1. The terms "MPLAB Configurator" and "MPLAB Configuration Wizard" are used interchangeably throughout the MPLAB Harmony Help. 2. Check for "TODO" tags that are placed in added template files for directions on what sections in the code should be modified or code to be added by the user. Look for system_config.h, system_init.c, system_int.c, system_tasks.c, app.c, app.h, and main.c files. Known Issues: • The Configurator Plug-in generated template files are stored in the MPLAB X IDE project folder (inside the MPLABX_Project.X folder). Users need to add the current directory ‘.’ Path in the MPLAB X Project “properties” > gcc >” include path settings” for removing “the template file not found error”. • The created project may compile but not work, as application and system related API calls are not added automatically to the system_init.c, main.c and system_tasks.c. Only the standard C templates are added to the project. • The MPLAB Harmony Configurator version during installation or in the plug-in description is shown as 0.0.2 where as the actual version of the tool is “0.02a”. • Certain TCP/IP configuration files are getting modified from the default MPLAB Harmony installation directory if the TCP/IP stack is configured using the Configurator. It is recommended to backup these default configuration files: tcpip_config.h, http_config.h, snmp_config.h, ssl_config.h, and telnet_config.h, in case it is necessary to revert back to the default configuration. • TCPIP system_config.h file is not modified in this release of the Configurator to add the configurations from “ * *_config.h”. As explained above, the specific module files get updated. • The Configurator is not preserving the previous project configuration if the TCP/IP sub-modules are selected using the ‘Select to add default modules’ checkbox in the “TCPIP Stack -> tcpip” module tree. • Warning message about ‘template files getting overwritten (if already present)’ is not shown if the USB library configuration is selected. 2.1.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 2.1 MPLAB Harmony Configurator MPLAB Harmony Help SW License Agreement 2-41 2.2 Using the Configurator 2.2.1 Installing the Configurator Plug-in The MPLAB Harmony Configurator is a MPLAB X IDE plug-in. It must be installed into your MPLAB X IDE installation to be used. Description Location The MPLAB Harmony Configurator (MPLAB X IDE plug-in) is located in the following folder in the MPLAB Harmony installation. \utilities\configurator\com-microchip-harmonyconfigurator.nbm Installation 1. Start MPLAB X IDE and select "Plugins" from the "Tools" menu as shown below. 2. Select the “Downloaded” tab. 3. Click the "Add Plugins..." button, browse to \utilities\configurator\ and open the plug in file "com-microchip-harmonyconfigurator.nbm" as shown below 2.2 Using the Configurator MPLAB Harmony Help Installing the Configurator Plug-in 2-42 4. Ensure that the Check box for the "MPLAB Harmony Configurator" plug-in is selected. Click "Install" as shown below. 2.2 Using the Configurator MPLAB Harmony Help Installing the Configurator Plug-in 2-43 5. Follow the prompts from the installation wizard and continue until the installation completes. Just click "continue”. Once the installation wizard has finished you can close the "Plugins" dialog box. You should now see a "MPLAB Harmony Configurator" option under the "Tools" menu. This indicates that the project wizard was successfully installed. 2.2.2 Running the Configurator Plug-in This session describes how to run the MPLAB Harmony Configurator to add required files from selected modules into MPLAB X IDE project. Note: This version of the Configurator provides Project Configuration (to add files into MPLAB X IDE project) and limited Library Configuration (only for configuring a few sub-modules of the TCP/IP and USB middleware) capability. Description 1. To run the Configurator, select "MPLAB Harmony Configurator" from the "Tools" menu. 2. Browse to the root installation folder of the version of MPLAB Harmony that you're using. This folder must contain "manifest.xml". This file has the information and the path of various software modules available in the installed MPLAB Harmony version. manifest.xml file should not be moved or deleted from Root directory. Click "Next" when the root path is set. 2.2 Using the Configurator MPLAB Harmony Help Running the Configurator Plug-in 2-44 Note: It is recommended that you create and maintain your MPLAB X IDE project under a subdirectory of the "/apps" folder and use a relative path to this project. 3. In the Left-hand pane of the "Select Modules and Configurations" dialog, select the desired modules and respective sub-modules. The right-hand pane shows a brief introduction of the selected module. Click "Next" when the required modules for the project are selected. 2.2 Using the Configurator MPLAB Harmony Help Running the Configurator Plug-in 2-45 The tool has two configuration sections. • Project Configuration: All the required modules and Sub modules could be selected here. The respective files would be added into the MPLAB X IDE project. (example: Graphics, TCP/IP, USB CDC, USB HID selection) • Library Configuration: The individual configuration of each module could be done here. (Configuration for selected module from the selected section.) If the user is required to add their custom module into the MPLAB Harmony directory structure and add the files into the project through Configurator, the manifest.xml should be modified to accommodate the custom module files. This would allow the Project Configurator to add the files to the MPLAB X IDE project from the manifest.xml for the custom module. This would not provide custom configuration capability, however the files can be added to the MPLAB X IDE project. 4. If there are any XML modifications those can be reflected by reloading the tree. To reload the project tree structure, right-click on “harmony” tree node and click "Reload Tree". 5. To get back to default project configuration of MPLAB Harmony, right-click on “harmony” tree node and click "Load default". 2.2 Using the Configurator MPLAB Harmony Help Running the Configurator Plug-in 2-46 Note: Next window pane is for individual library (Modules and Sub modules) configuration. Currently only TCP/IP and USB library configuration is supported. Though all the sub-modules of TCP/IP can be enabled or disabled through project configuration window pane, the individual sub module configuration is supported only for HTTP, SSL, SNMP and Telnet server. For USB, only CDC and HID class configuration basic support is provided. Library Configuration 1. In the "Project configuration" pane, to configure USB CDC select the respective modules and click “Next”. Next window pane is Library Configuration window as shown below. Configure USB CDC as required, click “Next”. 2.2 Using the Configurator MPLAB Harmony Help Running the Configurator Plug-in 2-47 2. In the "Application Template" pane, select the "Include application template" check box and select "Finish" to add the module files and template files to the MPLAB X IDE project. 2.2 Using the Configurator MPLAB Harmony Help Running the Configurator Plug-in 2-48 Note: The generate project may compile for PIC32MZ devices, but not necessarily work on the hardware. The set of template files added to the MPLAB X IDE project would require to be modified with additional configuration information and the custom application code. Later versions of the configuration tool may provide additional configuration options and sample application code for each library, to create a executable project. 2.2.3 Tutorial This tutorial explains about creating a new MPLAB X IDE project and configuring this project using the MPLAB Harmony Configurator. The tutorial provides step by step instructions on how to create a MPLAB X IDE project for the TCP/IP Stack. Description This tutorial explains about creating a MPLAB X IDE project for TCP/IP library by adding required configurations and TCP/IP library files, template files and Peripheral Library modules to the selected MPLAB X IDE project using the Configurator. In this tutorial user would, 1. Create a new project in MPLAB X IDE. 2. Add required source and header files with required configurations for TCP/IP application using MPLAB Harmony Configurator to the MPLAB X IDE project. 3. Add the required Peripheral header files and template files to the MPLAB X IDE project. 2.2 Using the Configurator MPLAB Harmony Help Tutorial 2-49 Creating an MPLAB X IDE Project 1. Open MPLAB X IDE, and select File > New Project to open a project explorer window. 2. In Categories, select “Microchip Embedded” and in Projects, select “Standalone Project”. Click Next. 3. Select the PIC device. 4. Select optional Debug Header. Click Next. 2.2 Using the Configurator MPLAB Harmony Help Tutorial 2-50 5. Select a hardware tool and Click Next. 6. Select the appropriate compiler. Click Next. 7. Name the MPLAB X IDE project and specify its path. 2.2 Using the Configurator MPLAB Harmony Help Tutorial 2-51 For this tutorial, create a project by name “MyHarmoyConfDemoProject”. Set the project as main project. Click Finish. Now the project MyHarmonyConfDemoProject” is created. Note: It is recommended that you maintain your project under a subdirectory of the "/apps" folder and use a relative path to your project. Once the MPLAB X IDE project is created, you should see a screen similar to the picture as shown below. 2.2 Using the Configurator MPLAB Harmony Help Tutorial 2-52 Using MPLAB Harmony Configurator 1. After creating the MPLAB X IDE project, select “Tools -> MPALB Harmony Configuration wizard” to open this plug-in with MPLAB X IDE. "MPLAB Harmony Configurator" will open in a new dialogue, as shown below. 2.2 Using the Configurator MPLAB Harmony Help Tutorial 2-53 2. Browse to the root directory path under "MPLAB Harmony Root Directory" option. This path is remembered by the Configurator for subsequent usage. Check or uncheck the "Relative Path" check box as required. Once the path is set, click "Next". 2.2 Using the Configurator MPLAB Harmony Help Tutorial 2-54 3. Now configure required middleware modules and Peripheral Library modules. Peripheral Library headers are selected by default by the tool. For this tutorial user will configure TCP/IP Library. Select the required configuration modules of TCP/IP modules and also other middleware modules in the Tree structure. Click "Next" once the selection is complete. 2.2 Using the Configurator MPLAB Harmony Help Tutorial 2-55 For this release, both the TCP/IP and USB module Library Configuration Pane will appear. For this Tutorial, the TCP/IP module is selected (default selection ”tcpip ”node) in tree, we get the Library Configuration as below. 2.2 Using the Configurator MPLAB Harmony Help Tutorial 2-56 4. Select the required configurable items of TCP/IP, and click next (Next button in “Library configuration navigation pane) which takes to next TCP/IP configuration pane, and continue until the last configuration pane. Once TCP/IP configuration is done, click Next(Next button at the bottom of TCP/IP Library configuration pane) which takes into the next window "Application Template" to include template files. 5. Select to Include MPLAB Harmony Application template files. Tool would add template files (main.c, app.c, system_init.c, system_tasks.c, system_int.c, system_config.h and app.h) to MPLAB X IDE project. Click "Finish". 2.2 Using the Configurator MPLAB Harmony Help Tutorial 2-57 6. Check for selected files being added in MPLAB X IDE project. The following figure shows the MPLAB X IDE project with the added files. 2.2 Using the Configurator MPLAB Harmony Help Tutorial 2-58 The "MPLAB Harmony Assembly Generator" window in MPLAB X IDE shows the list of files added from "MPLAB Harmony Configurator" to the MPLAB X IDE project. 2.2 Using the Configurator MPLAB Harmony Help Tutorial 2-59 2.2 Using the Configurator MPLAB Harmony Help Tutorial 2-60 3 Applications Help 3 MPLAB Harmony Help 3-61 3.1 Applications Overview Applications use MPLAB Harmony libraries and define the behavior of a system. Description Applications determine how MPLAB Harmony libraries (device drivers, middleware, and system services) are used to do something useful. In an MPLAB Harmony system, there may be one main application, there may be multiple independent applications or there may be one or more Operating System (OS) specific applications. Applications interact with MPLAB Harmony libraries through well defined interfaces. Applications may operate in a strictly polling environment, they may be interrupt driven, they may be executed in OS-specific threads, or they may be written so as to be flexible and easily configured for any of these environments. Applications generally fit into one of the following categories: Demo Applications: Demos applications are provided (with MPLAB Harmony or in separate installations) to demonstrate typical or interesting usage models of one or more MPLAB Harmony libraries. Demonstration applications can demonstrate realistic solutions to real-life problems. Sample Applications: Sample applications are extremely simple applications provided with MPLAB Harmony as examples of how to use individual features of a library. They will not normally accomplish anything useful on their own. They are provided primarily as "documentation" to show how to use a library. Skeletal Applications: Skeletal applications are provided as bare-bones “skeletons” (potentially targeted to a specific usage or market) that MPLAB Harmony developers can use as a starting point to for writing their own applications. Skeleton applications contain the necessary calls, configuration definitions and subroutine stubs with “To Do” items clearly marked for MPLAB Harmony developers to fill in as desired to create a working application. Customer Applications: Customer applications are (of course) not provide by Microchip. Rather, they are any applications developed by customers to suit specific hardware and software needs. Refer to the Start Here help topic for information on the structure and to learn how to develop your own MPLAB Harmony applications. Application Directories Applications are contained in the "/apps" folder. Under the "apps" folder, they are grouped by technology, board, and/or market segment. Examples: Folder Type of Demos /apps/examples/peripheral Contains simple peripheral library example applications /apps/fs Contains graphics library demonstration applications /apps/gfx Contains TCP/IP networking stack demonstration applications /apps/tcpip Contains USB device demonstration applications 3.1 Applications Overview MPLAB Harmony Help 3-62 /apps/usb/device Contains USB host demonstration applications Additional Information Refer to Release Notes & Information for a complete listing of applications included with this release. Refer to the help documentation for each individual application for build instructions and information on required hardware and application usage. 3.1.1 System Overview To support the framework, the application (or application developer) is responsible for the following: • Configuring the Framework - Required, unless using a pre-built library. Each driver, middleware layer, and system service require build-time configuration options that must be defined for the specific application, board, and processor that is used by any particular demo or customer application. Please refer to the help file of that module on the list of configuration options, and how they apply to the application.The application can use the board support package configuration file or define its own configuration for the board. • Building the Framework Library - Required, unless using a prebuilt library • Implementing the System Initialization service. Please refer to the help file for the system initialization service for information on implementing it statically or dynamically • Implementing a Interrupt Service Routine (ISR) - Required, unless polled. Please refer to the help file for system tasks service for examples on implementing ISRs. • Implementing the System Tasks routine - Please refer to the help file for system tasks service for how to implement it statically or dynamically 3.1 Applications Overview MPLAB Harmony Help System Overview 3-63 3.2 File System Demonstrations 3.2.1 Introduction MPLAB Harmony File System Demonstration Help Description This help file contains instructions and associated information about MPLAB Harmony File System demonstration applications, which are contained in the MPLAB Harmony Library distribution. 3.2.2 Release Notes MPLAB Harmony Version: v0.70b File System Demonstrations Version : 0.01a Release Date: 18Nov2013 The interface can change in the beta and\or 1.0 release. For the latest release information, please refer to the File System Service Library Release Notes section. New This Release: Nothing to report for this release. Known Issues: Nothing to report for this release. 3.2.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have 3.2 File System Demonstrations MPLAB Harmony Help SW License Agreement 3-64 paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 3.2.4 Demonstrations Provides instructions on how to run the demonstration applications. Description The following demonstration applications are available in this release of the MPLAB Harmony File System framework. 3.2.4.1 Overview Provides an overview of how most of the File System Demonstration applications are structured. Description The MPLAB Harmony File System Demonstration Applications show example usage of the File System framework. These demonstration applications also contain example configurations of media drivers such as Internal Flash and SD Card, that can be used readily in the end application with the some changes to initialization parameters, if required. A demonstration application may have multiple MPLAB X IDE project configurations (for different demonstration hardware and microcontrollers). The relevant configuration should be selected in the MPLAB X IDE before compiling the demonstration. Figure 1 shows the dialog box in MPLAB X IDE that allows selection of different configurations. Figure 1: Demonstration MPLAB X IDE Configurations The project will contain files which are configuration specific. Wherever applicable, these configuration files are placed in separate MPLAB X IDE project logical folders. Figure 2 shows how the configuration dependant nvm_disk_images.c file is included in the project. In this case two configurations (pic32mx_usb_sk_Int_dyn and pic32mz_sk_int_dyn) are supported in the project. Figure 2: Configuration specific file in File System Demonstration Projects. Note that some demonstration projects may not support all configurations. In general, the following the demonstration project contain the following MPLAB X IDE configurations: • pic32mx_usb_sk_int_dyn: This configuration runs on the PIC32 USB Starter Kit. The media drivers are configured for interrupt and dynamic operation 3.2 File System Demonstrations MPLAB Harmony Help Demonstrations 3-65 • pic32mz_sk_int_dyn: This configuration runs on the PIC33MZ Embedded Connectivity (EC) Starter Kit. Some demonstration projects that support this configuration may need the Multimedia Expansion Board II (MEB II) to attached to the starter kit. The media drivers in this configuration are configured for interrupt and dynamic operation. Unless specified, the File System demonstration application are structured as indicated in Figure 3. Figure 3: File System Demonstration Application General Architecture Here are some general notes while working with the demonstration applications: 1. The system and application is initialized in SYS_Initialize() function, implemented in sys_init.c. The sys_init.c file is configuration specific. The SYS_Initialize() function initializes the application (APP_Initialize() function) and the BSP (BSP_Initialize() function). 2. The application then calls SYS_Tasks() function in an infinite loop. This function updates the state machines of all system components in the demonstration application and also calls the APP_Tasks() function. The is implemented in file sys_tasks.c which is configuration specific. 3. All Interrupt service routines are implemented in sys_interrupt.c. This file is configuration specific. 3.2.4.2 nvm_fat_single_disk This demonstration uses a FAT12 image of file on NVM flash memory and demonstrates the working of all file system functions. Description This demonstration shows an example of implementing a FAT12 disk in device Flash memory. The demonstration contains a FAT12 disk image consisting of a Master Boot Record (MBR) sector, Logical Boot Sector, File Allocation Table, Root Directory Area. The demonstration opens an existing file named "FILE.TXT" and performs all file system related function calls on the file viz. SYS_FS_FileStat, SYS_FS_FileSize, SYS_FS_FileSeek, SYS_FS_FileEOF. Finally, the string "Hello World" is written to this file. The file is then closed and reopend for read. The read string is then compared with the string which was written to the file. If the string compare is successful, LED indication is provided. 3.2 File System Demonstrations MPLAB Harmony Help Demonstrations 3-66 3.2.4.2.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Following board is supported for PIC32MX devices: - Demonstration Board (click link for board information) Notes PIC32 USB Starter Kit II - Following board is supported for PIC32MZ devices: - Demonstration Board (click link for board information) Notes PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.2.4.2.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.2.4.2.3 Running the Demonstration Provides instructions on how to build and run the NVM FAT single disk demonstration. Description Select the MPLAB X IDE project configuration: - • pic32mx_usb_sk_int_dyn -- For PIC32MX devices • pic32mz_sk_int_dyn -- For PIC32MZ devices Build the selected configuration in the MPLAB X IDE project and program the demonstration board. The execution status (pass/fail) of the demonstration is indicated by LEDs on the demonstration board. Demonstration Board Demonstration Successful Demonstration Failure PIC32 USB Starter Kit II LED3 LED1 PIC32MZ Embedded Connectivity (EC) Starter Kit Green LED Red LED About the demonstration: This demonstration shows an example of - implementing a FAT12 disk in device Flash memory. - opening a file for read or write. - implements all the file system functions. 3.2 File System Demonstrations MPLAB Harmony Help Demonstrations 3-67 - closing a file. The demonstration contains a FAT12 disk image consisting of a Master Boot Record (MBR) sector, Logical Boot Sector, File Allocation Table, Root Directory Area. This image is implemented in the file nvm_disk_images.c (this is project configuration specific file and is contained in the nvm_disk_images logical folder in the MPLAB X IDE project). The image contains a single file named "FILE.TXT" which contains the string "Data". The demonstration opens an existing file named "FILE.TXT" and performs all file system related function calls on the file viz. SYS_FS_FileStat, SYS_FS_FileSize, SYS_FS_FileSeek, SYS_FS_FileEOF. Finally, the string "Hello World" is written to this file. The file is then closed and reopened for read. The read string is then compared with the string which was written to the file. If the string compare is successful, LED indication is provided. The demonstration application logic is implemented as a state machine in the APP_Tasks() function in the file main.c. 1. The disk is first mounted using the SYS_FS_Mount() function. The "/dev/nvma1" path instructs the mount command to mount an internal flash volume. The volume is mounted against a FAT type file system and mounted at "/mnt/myDrive/". 2. If the mount is successful, the application opens a file "FILE.TXT" for reading and writing (SYS_FS_FILE_OPEN_READ_PLUS) with a SYS_FS_FileOpen() function. The valid file handle is received once a successful opening of file is performed. 3. If file open is successful, the status of file "FILE.TXT" is stored in the appData.fileStatus structure, using SYS_FS_FileStat() function. 4. If the file status check is successful, the size of the "FILE.TXT" is checked by passing the file handle to the SYS_FS_FileSize() function. 5. If the file size check is successful, the size of file is compared with the size element received earlier as a part of appData.fileStatus structure. If both value matches, then the code moves to the next step of file seek. 6. The file pointer is then moved by 4 bytes from the start of the file by calling the function SYS_FS_FileSeek() and passing parameter as SYS_FS_SEEK_SET (seek from the beginning of the file). 7. If the file seek operation is successful, the file pointer should have reached the end of the file. This is because, the content of the FILE.TXT had only 4 byte string = "Data". The end of file is verified by calling the function SYS_FS_FileEOF(). If the function returns "true" (end of file reached), the next step is performed. 8. In the next step, the file pointer is moved again by [(-1)*size of file], from the end of the file by calling the function SYS_FS_FileSeek() and passing parameter SYS_FS_SEEK_END (seek from the end of the file). 9. If the file seek operation is successful, the file pointer should have reached the beginning of the file. 4 Bytes are read from the file using SYS_FS_FileRead() function (into a buffer). 10. If the read is successful, the content of file (present in the buffer) is compared with the "Data" string. If the comparison passed, the code moves to the next step. 11. In the next step, the file pointer is moved again by [(-1)*size of file], from the end of the file by calling the function SYS_FS_FileSeek() and passing parameter SYS_FS_SEEK_END (seek from the end of the file). 12. If the file seek operation is successful, the string "Hello World" is written to the file using SYS_FS_FileWrite() function. 13. If the write operation is successful, the file is closed. 14. The file "FILE.TXT" is opened again in read mode (SYS_FS_FILE_OPEN_READ). 15. If the file open is successful, the content of the file is read using SYS_FS_FileRead() function (into a buffer). 16. If the read operation is successful, the content of the file (present in the buffer) is compared with the "Hello World" string using the strcmp() function. A LED indicates the success of the demonstration. 3.2 File System Demonstrations MPLAB Harmony Help Demonstrations 3-68 3.2.4.3 sd_card_fat_single_disk This demonstration uses the SDTM Card with FAT file system as media and performs a read/ write / verify operation on the files using long file names (LFN). Description This demonstration shows an example of using the MPLAB Harmony File System to access and modify the contents of an SDTM Card. The demonstration opens a file "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG" on the SD Card, reads the content of the file and writes the content into another file "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" (create a copy of one file into another file). The input file "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG" is not provided along with the release package. It could be any arbitrary JPG (picture) file chosen by user and then suitably renamed to "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG". The reason for choosing a JPG file for test purpose is that the duplicate file "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" created by the FS demonstration could be easily verified for correctness by inserting the SD card in computer and opening the "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" file. If the file "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" opens for viewing on the computer, the test is deemed to have passed. Otherwise, if the "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" does not open (is corrupted), the test will be considered as failed. 3.2.4.3.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Following board is supported for PIC32MX devices: - Demonstration Board (click link for board information) PIC32MX795F512L Plug-In-Module (PIM) PICtail Daughter Board for SD and MMC Note: This board can not be used by itself. An Explorer 16 Development Board is required. Following board is supported for PIC32MZ devices: - Demonstration Board (click link for board information) Notes PIC32MZ Embedded Connectivity (EC) Starter Kit - Note: This board can not be used by itself. An Multimedia Expansion Board II (MEB II) is required to run the demonstration. 3.2.4.3.2 Configuring the Hardware Describes how to configure the supported hardware. Description Explorer 16 Development Board Based Demonstrations Use the following instructions for all Explorer 16 Development Board-based demonstration boards: PIC32MX795F512L PIM 1. Insert the PIM into the Explorer 16 Development Board PIM connector. 3.2 File System Demonstrations MPLAB Harmony Help Demonstrations 3-69 2. Jumpers JP1, JP2 and JP3 on the SD Card PICtail Daughter Board should connect to points 2 and 3 on their respective connectors as shown here. 3. Insert the SD Card PICtail Daughter Board into the PICtail Plus connector on the Explorer 16 Development Board. 4. Insert a SD card into the SD card connector on the SD Card PICtail Daughter Board. 5. Power up the board. Multimedia Expansion Board II (MEB II) No hardware setting change is required. Insert the micro SD card into the connector and power up the board. 3.2.4.3.3 Running the Demonstration Provides instructions on how to build and run the SD card FAT single disk demonstration. Description Select the MPLAB X IDE project configuration: - • exp16_32mx_int_dyn -- For PIC32MX devices • pic32mz_sk_int_dyn -- For PIC32MZ devices Insert the SD card, which contains the file "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG". The file can be of any size. Compile the selected configuration in the MPLAB X IDE project and run the code. After a few seconds, once the LED glows, remove the SD card from the SD Card PICtail Daughter Board (for PIC32MX) or MEB2 Board (for PIC32MZ) and insert it into the SD card reader on a PC. Examine the contents of the SD card and another file named "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" would have been created. "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" will be a copy of "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG". Verify both the files opens for viewing on the PC. Demonstration Board Demonstration Successful Demonstration Failure Explorer 16 Development Board LED5 (D5) LED6 (D6) PIC32MZ Embedded Connectivity (EC) Starter Kit Green LED Red LED About the demonstration: This demonstration shows an example of - implementing a FAT File system (FAT16/ FAT32) on SD card. - implementing long file name (LFN). - opening a file for read or write. - closing a file. The demonstration opens a file "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG" on the SD Card, reads the content of the file and writes the content into another file "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" (create a copy of one file into another file). The demonstration application logic is implemented as a state machine in the APP_Tasks() function in the file main.c. 1. The disk is first mounted using the SYS_FS_Mount() function. The "/dev/mmcblka1" path instructs the mount command to mount a SD card volume. The volume is mounted against a FAT type file system and mounted at "/mnt/myDrive/". 2. If mount is successful, the volume is unmouned by passing the mount name "/mnt/myDrive" to SYS_FS_Unmount() function. This unmounting is done for demonstration purpose only. Real application do not need to unmount unless it is required for the application. 3.2 File System Demonstrations MPLAB Harmony Help Demonstrations 3-70 3. If unmount is successful, the mounting process is repeated. 4. If the mount is successful, the application opens a file "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG" for reading with a SYS_FS_FileOpen() function. 3. If the file open is successful, the application opens a file "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" for writing with SYS_FS_FileOpen() function. The attributes for file write is selected as "SYS_FS_FILE_OPEN_WRITE". Hence, if the file does not exist on the drive, the file is created. 4. If the file open is successful, 512Bytes from the file "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG" is read into application buffer using SYS_FS_FileRead() function. 5. If the file read successful, the 512Bytes is written from the application buffer to the FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG file using SYS_FS_FileWrite() function. 6. If the write operation is successful, the end of file for FILE_TOO_LONG_NAME_EXAMPLE_123.JPG is checked. If the end of file is not reached, the process of reading and writing continues (step - 4 and step - 5). 7. Once end of file is reached, both the files are closed with SYS_FS_FileClose() function. 8. Finally, a LED indicates the success of the demonstration. 3.2.4.4 nvm_sdcard_fat_multi_disk This demonstration uses NVM and SDTM Card as 2 media and reads files from one media and write onto another media. Description This demonstration shows an example of using the MPLAB Harmony File System to access files across multiple media. The demonstration contains a FAT12 disk image consisting of a Master Boot Record (MBR) sector, Logical Boot Sector, File Allocation Table, Root Directory Area, placed in the internal flash memory (NVM). Also, a SD card is used as another disk, which might have FAT16 or FAT32 implemented on it (depends on the formatting of SD card).The demonstration reads the contents of "FILE.TXT" in NVM and copies the contents to "FILE.TXT" in the SDTM Card. If the write operation is successful, LED indication is provided. 3.2.4.4.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Following board is supported for PIC32MX devices: - Demonstration Board (click link for board information) PIC32MX795F512L Plug-In-Module (PIM) PICtail Daughter Board for SD and MMC Note: This board can not be used by itself. An Explorer 16 Development Board is required. Following board is supported for PIC32MZ devices: - Demonstration Board (click link for board information) Notes PIC32MZ Embedded Connectivity (EC) Starter Kit - Note: This board can not be used by itself. An Multimedia Expansion Board II (MEB II) is required to run the demonstration. 3.2 File System Demonstrations MPLAB Harmony Help Demonstrations 3-71 3.2.4.4.2 Configuring the Hardware Describes how to configure the supported hardware. Description Explorer 16 Development Board Based Demonstrations Use the following instructions for all Explorer 16 Development Board-based demonstration boards: PIC32MX795F512L PIM 1. Insert the PIM into the Explorer 16 Development Board PIM connector. 2. Jumpers JP1, JP2 and JP3 on the SD Card PICtail Daughter Board should connect to points 2 and 3 on their respective connectors as shown here. 3. Insert the SD Card PICtail Daughter Board into the PICtail Plus connector on the Explorer 16 Development Board. 4. Insert a SD card into the SD card connector on the SD Card PICtail Daughter Board. 5. Power up the board. Multimedia Expansion Board II (MEB II) No hardware setting change is required. Insert the micro SD card into the connector and power up the board. 3.2.4.4.3 Running the Demonstration Provides instructions on how to build and run the NVM SD card FAT multi disk demonstration. Description Select the MPLAB X IDE project configuration: - • exp16_32mx_int_dyn -- For PIC32MX devices • pic32mz_sk_int_dyn -- For PIC32MZ devices Insert the SD card, which contains the file "FILE.TXT" and the file contains "abc" (some arbitrary existing content). Compile the selected configuration in the MPLAB X IDE project and run the code. After a few seconds, once the LED glows, remove the SD card from the Board and insert it into the SD card reader on a PC. Examine the contents of the file named "FILE.TXT". The file should contain the string "This data is from NVM Disk". Demonstration Board Demonstration Successful Demonstration Failure Explorer 16 Development Board LED5 (D5) LED6 (D6) PIC32MZ Embedded Connectivity (EC) Starter Kit Green LED Red LED About the demonstration: This demonstration shows an example of: - implementing a multi disk demonstration with FAT12 on internal flash memory (NVM) and FAT File system (FAT16/ FAT32) on SD card. - opening two files from two different disks, read content of file from first disk and write into the file of second disk. - closing the files. The demonstration contains a FAT12 disk image consisting of a Master Boot Record (MBR) sector, Logical Boot Sector, File Allocation Table, Root Directory Area, placed in the internal flash memory (NVM). Also, a SD card is used as another disk, which 3.2 File System Demonstrations MPLAB Harmony Help Demonstrations 3-72 might have FAT16 or FAT32 implemented on it (depends on the formatting of SD card).The demonstration reads the contents of "FILE.TXT" in NVM and copies the contents to "FILE.TXT" in the SDTM Card. If the write operation is successful, LED indication is provided. The demonstration application logic is implemented as a state machine in the APP_Tasks() function in the file main.c. 1. The first disks is mounted using the SYS_FS_Mount() function. The "/dev/nvma1" path instructs the mount command to mount a internal flash volume. The volume is mounted against a FAT type file system and mounted at "/mnt/myDrive1/". 2. If the mount is successful, the second disks is mounted using the SYS_FS_Mount() function. The "/dev/mmcblka1" path instructs the mount command to mount a SD card volume. The volume is mounted against a FAT type file system and mounted at "/mnt/myDrive2/". 3. If the mount is successful, the application opens a file "FILE.TXT" from "/mnt/myDrive1/" for reading and "FILE.TXT" from "/mnt/myDrive2/" for writing with a SYS_FS_FileOpen() function. 4. If the file open is successful, the application reads 27Bytes from "FILE.TXT" of internal flash volume using SYS_FS_FileRead(). 5. If the read is successful, the application closes the "FILE.TXT" from internal flash volume and then writes the 27Bytes into "FILE.TXT" of SD card volume using SYS_FS_FileWrite(). 6. If the write is successful, the application closes the "FILE.TXT" from SD card volume. 7. If file close is successful, LED indicates the success of the operation. 3.2.4.5 nmv_mpfs_single_disk This demonstration uses a MPFS image of 3 files on NVM flash memory and demonstrates the working of all file system functions. Description This demonstration shows an example of implementing a MPFS disk in device Flash memory. The demonstration contains a MPFS disk image in the internal flash memory. The disk image contains 3 files named: - "FILE.txt" , Size = 11Bytes. The content of the file is -- "Hello World". "ABC.txt", Size = 31744Bytes. The content of the file is not important. Just a file of sufficiently big size. "TEST.txt" , Size = 72Bytes. The content of the file is -- "This file contains a test string and it is meant for testing. 1234567890". The demonstration performs all file system related function calls on the file viz. SYS_FS_FileRead, SYS_FS_FileStat, SYS_FS_FileSize, SYS_FS_FileSeek, SYS_FS_FileEOF. If all the test succeeds, LED indication is provided. 3.2.4.5.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Following board is supported for PIC32MX devices: - Demonstration Board (click link for board information) Notes PIC32 USB Starter Kit II - 3.2 File System Demonstrations MPLAB Harmony Help Demonstrations 3-73 Following board is supported for PIC32MZ devices: - Demonstration Board (click link for board information) Notes PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.2.4.5.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.2.4.5.3 Running the Demonstration Provides instructions on how to build and run the NVM MPFS single disk demonstration. Description Select the MPLAB X IDE project configuration: - • pic32mx_usb_sk_int_dyn -- For PIC32MX devices • pic32mz_sk_int_dyn -- For PIC32MZ devices Build the selected configuration in the MPLAB X IDE project and program the demonstration board. The execution status (pass/fail) of the demonstration is indicated by LEDs on the demo board. Demonstration Board Demonstration Successful Demonstration Failure PIC32 USB Starter Kit II LED3 LED1 PIC32MZ Embedded Connectivity (EC) Starter Kit Green LED Red LED About the demonstration: This demonstration shows an example of - implementing a MPFS disk in device Flash memory. - opening a file for read. - implements all the file system functions. - closing a file. This demonstration shows an example of implementing a MPFS disk in device Flash memory. The demonstration contains a MPFS disk image in the internal flash memory. The disk image contains 3 files named: - "FILE.txt" , Size = 11Bytes. The content of the file is -- "Hello World". "ABC.txt", Size = 31744Bytes. The content of the file is not important. Just a file of sufficiently big size. "TEST.txt" , Size = 72Bytes. The content of the file is -- "This file contains a test string and it is meant for testing. 1234567890". The demonstration application logic is implemented as a state machine in the APP_Tasks() function in the file main.c. 3.2 File System Demonstrations MPLAB Harmony Help Demonstrations 3-74 1. The disk is first mounted using the SYS_FS_Mount() function. The "/dev/nvma1" path instructs the mount command to mount an internal flash volume. The volume is mounted against a MPFS2 type file system and mounted at "/mnt/myDrive/". 2. If the mount is successful, the application opens a file "FILE.txt" for reading with a SYS_FS_FileOpen() function. 3. If the open is successful, the application opens another file "TEST.txt" for reading with SYS_FS_FileOpen() function. 4. If open is successful, the application checks the status of another file "ABC.txt" using SYS_FS_FileStat() function and stores the status of the file into the structure "appData.fileStatus". 5. If file status check is successful, the application compares the size of file (from "appData.fileStatus" structure) with the known value of 31744 (Bytes). 6. If the comparison is successful, the application checks for size of file "FILE.txt", by passing the handle obtained during file open, to the function SYS_FS_FileSize(). 7. If the file size matches the known value of 11 (Bytes), the application moves the file pointer for the file "TEST.txt" 10Bytes from the end of file, using the function SYS_FS_FileSeek(). 8. If file seek is successful, 10 Bytes of content of the file "TEST.txt" is read into the application buffer, using the function SYS_FS_FileRead(). 9. If read is successful, the application buffer content is compared with the known string of "1234567890" using the strncmp() function. 10. If the comparison is successful, the application checks if the file pointer for file "TEST.txt" has reached the end of file using the SYS_FS_FileEOF() function. 11. If end of file is reached, a LED indicates the success of the demonstration. 3.2.4.6 nvm_sdcard_fat_mpfs_multi_disk This demonstration uses NVM and SDTM Card with MPFS and FAT image of file and performs a read/ write/ verify operation from file of one media to another media. Description This demonstration shows an example of using the MPLAB Harmony File System to access files across multiple disks and multiple file system. The demonstration contains a MPFS disk image in the internal flash memory. The disk image contains a file named "abc.txt" with content "Hello World". Another disk is a SD card, which is formatted to FAT (FAT16 or FAT32). The demonstration reads the contents of "abc.txt" from the disk implemented on internal flash memory and writes the contents to "FILE.TXT" on the SDTM Card. A successful write is indicated by a LED glow. 3.2.4.6.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Following board is supported for PIC32MX devices: - Demonstration Board (click link for board information) PIC32MX795F512L Plug-In-Module (PIM) PICtail Daughter Board for SD and MMC Note: This board can not be used by itself. An Explorer 16 Development Board is required. 3.2 File System Demonstrations MPLAB Harmony Help Demonstrations 3-75 Following board is supported for PIC32MZ devices: - Demonstration Board (click link for board information) Notes PIC32MZ Embedded Connectivity (EC) Starter Kit - Note: This board can not be used by itself. An Multimedia Expansion Board II (MEB II) is required to run the demonstration. 3.2.4.6.2 Configuring the Hardware Describes how to configure the supported hardware. Description Explorer 16 Development Board Based Demonstrations Use the following instructions for all Explorer 16 Development Board-based demonstration boards: PIC32MX795F512L PIM 1. Insert the PIM into the Explorer 16 Development Board PIM connector. 2. Jumpers JP1, JP2 and JP3 on the SD Card PICtail Daughter Board should connect to points 2 and 3 on their respective connectors as shown here. 3. Insert the SD Card PICtail Daughter Board into the PICtail Plus connector on the Explorer 16 Development Board. 4. Insert a SD card into the SD card connector on the SD Card PICtail Daughter Board. 5. Power up the board. Multimedia Expansion Board II (MEB II) No hardware setting change is required. Insert the micro SD card into the connector and power up the board. 3.2.4.6.3 Running the Demonstration Provides instructions on how to build and run the NVM SD card FAT MPFS multi disk demonstration. Description Select the MPLAB X IDE project configuration: - • exp16_32mx_int_dyn -- For PIC32MX devices • pic32mz_sk_int_dyn -- For PIC32MZ devices Insert the SD card, which contains the file "FILE.TXT" and the file contains "abc" (some arbitrary existing content). Compile the selected configuration in the MPLAB X IDE project and run the code. After a few seconds, once the LED glows, remove the SD card from the SD Card PICtail Daughter Board and insert it into the SD card reader on a PC. Examine the contents of the file named "FILE.TXT". The file should contain the string "Hello World". Demonstration Board Demonstration Successful Demonstration Failure Explorer 16 Development Board LED5 (D5) LED6 (D6) PIC32MZ Embedded Connectivity (EC) Starter Kit Green LED Red LED About the demonstration: This demonstration shows an example of - implementing a multi disk demonstration with MPFS on internal flash memory (NVM) and FAT File system (FAT16/ FAT32) on 3.2 File System Demonstrations MPLAB Harmony Help Demonstrations 3-76 SD card. - opening two files from two different disks, read content of file from first disk and write into the file of second disk. - closing the files. The demonstration contains a MPFS disk image in the internal flash memory. The disk image contains a file named "abc.txt" with content "Hello World". Another disk is a SD card, which is formatted to FAT (FAT16 or FAT32). The demonstration reads the contents of "abc.txt" from the disk implemented on internal flash memory and writes the contents to "FILE.TXT" on the SDTM Card. A successful write is indicated by a LED glow. The demonstration application logic is implemented as a state machine in the APP_Tasks() function in the file main.c. 1. The first disks is mounted using the SYS_FS_Mount() function. The "/dev/nvma1" path instructs the mount command to mount a internal flash volume. The volume is mounted against a MPFS2 type file system and mounted at "/mnt/myDrive1/". 2. If the mount is successful, the second disks is mounted using the SYS_FS_Mount() function. The "/dev/mmcblka1" path instructs the mount command to mount a SD card volume. The volume is mounted against a FAT type file system and mounted at "/mnt/myDrive2/". 3. If the mount is successful, the application opens a file "abc.txt" from "/mnt/myDrive1/" for reading and "FILE.TXT" from "/mnt/myDrive2/" for writing with a SYS_FS_FileOpen() function. 4. If the file open is successful, the application reads 13Bytes from "abc.txt" of internal flash volume using SYS_FS_FileRead(). 5. If the read is successful, the application closes the "abc.txt" from internal flash volume and then writes the 13Bytes into "FILE.TXT" of SD card volume using SYS_FS_FileWrite(). 6. If the write is successful, the application closes the "FILE.TXT" from SD card volume. 7. If file close is successful, LED indicates the success of the operation. 3.2.5 Demonstration Board Information Information on Hardware used by the File System Demonstration Applications. Description The File System Library Demonstration Applications can be tried across different hardware boards. This section provide details on these hardware boards. 3.2.5.1 PIC32 USB Starter Kit II Hardware Information: 3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information 3-77 SW1 - Application switch. Tied to RD6. SW2 - Application switch. Tied to RD7. SW3 - Application switch. Tied to RD13. LED1 - Application LED. Tied to RD0. LED2 - Application LED. Tied to RD1. LED3 - Application LED. Tied to RD2. More Information Product webpage 3.2.5.2 Explorer 16 Development Board Hardware Information: 3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information 3-78 S1 - Reset button (MCLR) S2 - Processor switch. This switch determines which processor is running, the processor on the board or the processor on the Plug-In-Module (PIM). S3, S4, S5, S6 - Application switches. For information about what pin is connected to this switch, please refer to the information for the PIM in use. D3 through D10 - Application LEDs. For information about what pin is connected to this LED, please refer to the information for the PIM in use. More Information: Product webpage 3.2.5.3 PIC32MX795F512 Plug-In-Module (PIM) More Information Product webpage 3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information 3-79 3.2.5.4 PICtail Daughter Board for SD and MMC More Information: Product webpage. 3.2.5.5 PIC32MZ Embedded Connectivity (EC) Starter Kit Provides details information on the PIC32MZ Embedded Connectivity (EC) Starter Kit. Description Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto) The top assembly of the board includes these key features, as indicated in Figure 1: 1. PIC32MZ2048ECH144 32-bit microcontroller. 2. Green power indicator LED. 3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz). 4. USB connectivity for on-board debugger communications. 5. Green debug indicator LED. 6. Three push button switches for user-defined inputs. 7. Three user-defined indicator LEDs. 8. USB Type A receptacle connectivity for PIC32 host-based applications. 9. HOST mode power jumper. 10. Daughter board connectors for flexible Ethernet PHY options. 11. 32 kHz oscillator for RTCC and Timer1 (optional). 12. External 2 GB SQI memory for expanded memory application. 13. Jumper for using or disconnecting the on-board debugger. NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto the Vbus from one port on the host to another (or from one host to another). 3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information 3-80 Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front) The bottom assembly of the board includes these key features, as indicated in Figure 2: 1. PIC24FJ256GB106 USB microcontroller for on-board debugging. 2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board. 3. Connector for various expansion boards. 4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications. 5. 50 MHz Ethernet PHY oscillator. 6. USB Host and OTG power supply for powering PIC32 USB applications. Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back) 3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information 3-81 3.2.5.6 Multimedia Expansion Board II (MEB II) Provides details information on the Multimedia Expansion Board II (MEB) II. Description Microchip Part Number: DM320005-2 Product Page The front side of the MEB II includes these key features, as shown in Figure 1: 1. Display daughter board connector (60-pin Hirose board-to-board connector). 2. mTouch™ buttons. 3. Push Button. 4. Power LED. 5. User LEDs. 6. VGA Camera (OVM7690). 7. PICtail™ Connector. 8. Analog temperature sensor. Figure 1: Multimedia Expansion Board II Layout (Front) The underside of the MEB II includes these key features, as shown in Figure 2: 1. Regulated 5V and 3.3V power supply for powering the board via a 9-15V DC Adapter. 2. PIC32 Starter Kit connector (168-pin Hirose board-to-board connector). 3. 24-bit stereo audio codec (AK4953A). 4. Integrated 802.11bg wireless module (MRF24WG0MA). 5. Low-cost Bluetooth® HCI transceiver (BTM805). 6. EBI SRAM memory (IS61WV102416BLL). 7. microSD slot. 3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information 3-82 8. Analog accelerometer (ADXL325). Figure 2: Multimedia Expansion Board II Layout (Back) 3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information 3-83 3.3 Graphics Demonstrations 3.3.1 Introduction Graphics Library Demonstrations Applications Help Description This distribution package contains a variety of Graphics-related firmware projects that demonstrate the capabilities of the MPLAB Harmony Graphics library. This help file describes the hardware requirement and procedures to run these firmware projects on Microchip graphics boards. To know more about MPLAB Harmony Graphics, configuring the library and the APIs provided; refer to the Graphics Library documentation. Graphic Demonstration Description Primitive Cyclically demonstrates various types of shapes and images, which include circles, lines, and rectangles that can be created from the Graphics Library. Object Touch interactive demonstration of various pages of objects that can be created from the Graphics Library. ssd1926 Touch interactive demonstration of JPEG decoded images from an SD card utilizing the JPEG decoder of the Solomon Systech SSD1926 graphics controller. lcc Demonstrates the advanced capabilities of the Graphics Library utilizing the software graphics controller. 3.3.2 Release Notes MPLAB Harmony Version: v0.70b Graphics Demonstrations Version : 4.00b Release Date: 18Nov2013 New This Release: Nothing to report for this release. Known Issues: LCC Demonstration: For the PIC32MZ Embedded Connectivity (EC) Starter Kit, after programming, the application may not display the UI folders as expected. If this occurs, to activate the UI display, touch the screen in the folder icons area. This issue will be addressed in the next release of MPLAB Harmony. 3.3 Graphics Demonstrations MPLAB Harmony Help SW License Agreement 3-84 3.3.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 3.3.4 Demonstrations This topic provides information on how to run the Graphics Library demonstration applications included in this release. Description All demonstrations provided should be built using the MPLAB X IDE development environment tool supplied by Microchip. The information that follows, communicate the general steps to building the graphics demos. • Using MPLAB X IDE, click the File drop-down, select "Open Project...". Navigate to your Harmony installation folder. The default location on Windows will be: C:\Microchip\Harmony\\apps\gfx. • In the \app\gfx folder there will be the object, primitive, lcc, and ssd1926 demonstration applications. • Within each demonstration folder, there will be a firmware folder. In the firmware folder will exist the MPLAB X IDE project specific to each demonstration. • Select the project and click "Open Project" • To configure the project specific to a preset board configuration, right click on the project and select "Set Configuration". This will set the build configuration to match the supported board configuration. 3.3.4.1 lcc_demo Demonstrates the advanced capabilities of the Graphics Library utilizing the software graphics controller. Description This demonstration provides the ability to display alpha blend and gradient colors through the software graphics controller. The demonstration renders four folders for alpha blend, gradient, picture-in-picture (PIP), and performance for all PIC32 devices. For PIC32MX devices, the demonstration runs on the PICtail Plus LCC Daughter Board, and on PIC32MZ devices, it runs on the Multimedia Expansion Board II (MEB II). 3.3 Graphics Demonstrations MPLAB Harmony Help Demonstrations 3-85 3.3.4.1.1 Supported Demonstration Boards Lists supported demo and development hardware boards. Description Demo Board (click link for board information) Notes PIC32 USB Starter Kit II - Graphics PICtail LCC Board AC164144 - WQVGA 480x272 Board AC164127-6 - Multimedia Expansion Board II (MEB II) - PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.3.4.1.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. Multimedia Expansion Board II (MEB II) The MEB II has two memory options: External or Internal. This demonstration requires External EBI memory, which is configured using the following J9 jumper settings: • EBIOE and LCD_PCLK (jumper is closed) • EBIWE (jumper is open) 3.3.4.1.3 Running the Demonstration Provides instructions on how to build and run the LCC demo. Description Select one of the following build configurations to build the LCC demo: • pic32mxusbsk_pictaillcc_wqvga -- For PIC32MX devices • pic32mzsk_meb2_wqvga -- For PIC32MZ devices Build the selected configuration in the MPLAB X IDE project and program the demonstration board. The demonstration renders four folders for alpha blend, gradient, picture-in-picture (PIP), and performance. Touch one of the folders to activate the demonstration. Short Name Long Name pic32mxusbsk PIC32 USB Starter Kit II pic32mzsk PIC32MZ Embedded Connectivity (EC) Starter Kit meb2 Multimedia Expansion Board II (MEB II) 3.3 Graphics Demonstrations MPLAB Harmony Help Demonstrations 3-86 wqvga Graphics Display Powertip 4.3" 480 × 272 Board (AC164127-6) 3.3.4.2 primitive_demo An example of primitive drawing capabilities of the Graphics Library. Description The Primitive example demonstrates the various types of shapes and images which include: circles, lines, rectangles that exist in the Graphics Library. This example shows the following primitives: • GFX_LineDraw • GFX_CircleDraw • GFX_CircleFillDraw • GFX_RectangleRoundDraw • GFX_RectangleRoundFillDraw • GFX_RectangleFillDraw • GFX_ArcDraw • GFX_PolygonDraw • GFX_FontSet • GFX_TextStringXYPut • GFX_ImageDraw • GFX_ScreenClear 3.3.4.2.1 Supported Demonstration Boards Lists supported demo and development hardware boards. Description Following boards are supported for PIC32MX devices: Demo Board (click link for board information) Notes PIC32 USB Starter Kit II - Graphics LCD Controller PICtail Plus SSD1926 Board AC164127-5 - QVGA 320x240 Board AC164127-4 - Following board is supported for PIC32MZ devices: Demo Board (click link for board information) Notes PIC32MZ Embedded Connectivity (EC) Starter Kit - Multimedia Expansion Board II (MEB II) - 3.3 Graphics Demonstrations MPLAB Harmony Help Demonstrations 3-87 3.3.4.2.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.3.4.2.3 Running the Demonstration Provides instructions on how to build and run the primitive demo. Description Navigate to the apps/gfx/primitive/firmware folder and open the primitive project, and then select one of the following build configurations to build the Primitive demo: • pic32mxusbsk_pictails1d_wqvga -- For PIC32MX devices • pic32mxusbsk_pictailssd_qvga -- For PIC32MX devices • pic32mzsk_meb2_wqvga -- For PIC32MZ devices Once the project is loaded and executed on the target board, a continuous display of primitive graphics will appear on the LCD. Short Name Long Name pic32mxusbsk PIC32 USB Starter Kit II pic32mzsk PIC32MZ Embedded Connectivity (EC) Starter Kit pictails1d Graphics LCD Controller PICtail Plus S1D1357 Board pictailssd Graphics LCD Controller PICtail Plus SSD1926 Board meb2 Multimedia Expansion Board II (MEB II) qvga Graphics Display Truly 3.2" 240 × 320 Board (AC164127-4) wqvga Graphics Display Powertip 4.3" 480 × 272 Board (AC164127-6) 3.3.4.3 object_demo An example of standard user-interface widgets of the Graphics Library. Description The Object example demonstrates the standard types of objects/widgets that exist in the Graphics Library Graphics Object Layer (GOL). The demonstration is composed of several pages of examples. The demonstration requires that the user touch the screen to begin the demo. The user is expected to navigate to the next or previous page by selecting the buttons on the far right and left locations of the screen. This example shows the following widgets: • GFX_GOL_ButtonCreate 3.3 Graphics Demonstrations MPLAB Harmony Help Demonstrations 3-88 • GFX_GOL_ButtonTextSet • GFX_GOL_CheckboxCreate • GFX_GOL_GroupboxCreate • GFX_GOL_RadioButtonCreate • GFX_GOL_GroupboxCreate • GFX_GOL_StaticTextCreate • GFX_GOL_ScrollBarCreate • GFX_GOL_ProgressBarCreate • GFX_GOL_ListboxCreate • GFX_GOL_ScrollBarCreate • GFX_GOL_Editbox_Create • GFX_GOL_MeterCreate • GFX_GOL_DigitalMeterCreate • GFX_GOL_RoundDialCreate • GFX_GOL_PictureCreate • GFX_GOL_CustomControlCreate 3.3.4.3.1 Supported Demonstration Boards Lists supported demo and development hardware boards. Description Following boards are supported for PIC32MX devices: Demo Board (click link for board information) Notes PIC32 USB Starter Kit II - Graphics LCD Controller PICtail Plus SSD1926 Board AC164127-5 - QVGA 320x240 Board AC164127-4 - Following board is supported for PIC32MZ devices: Demo Board (click link for board information) Notes PIC32MZ Embedded Connectivity (EC) Starter Kit - Multimedia Expansion Board II (MEB II) - 3.3.4.3.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit 3.3 Graphics Demonstrations MPLAB Harmony Help Demonstrations 3-89 No hardware related configuration or jumper setting changes are necessary. 3.3.4.3.3 Running the Demonstration Provides instructions on how to build and run the object demo. Description Navigate to the apps/gfx/object/firmware and open the object project, and then select one of the following build configurations to build the Object demo: • pic32mxusbsk_pictailssd_qvga -- For PIC32MX devices • pic32mzsk_meb2_wqvga -- For PIC32MZ devices Once the project is loaded and executed on the target board, various objects are displayed. Touch the forward or back arrow to view additional objects. Short Name Long Name pic32mxusbsk PIC32 USB Starter Kit II pic32mzsk PIC32MZ Embedded Connectivity (EC) Starter Kit pictailssd Graphics LCD Controller PICtail Plus SSD1926 Board meb2 Multimedia Expansion Board II (MEB II) qvga Graphics Display Truly 3.2" 240 × 320 Board (AC164127-4) 3.3.4.4 ssd_demo Shows how to display JPEG images using the Solomon Systech (SSD1926) graphics controller that resides on the PICtail™ Plus SSD1926 Board. Description The SSD1926 demo shows how to decode of JPEG images from an SD card utilizing the JPEG decoder capabilities of the Solmon Systech SSD1926 graphics controller. 3.3.4.4.1 Supported Demonstration Boards Lists supported demo and development hardware boards. Description Following board is supported for PIC32MX devices: Demo Board (click link for board information) Notes PIC32 USB Starter Kit II - Graphics LCD Controller PICtail Plus SSD1926 Board AC164127-5 - QVGA 320x240 Board AC164127-4 - 3.3.4.4.2 Configuring the Hardware Describes how to configure the supported hardware. 3.3 Graphics Demonstrations MPLAB Harmony Help Demonstrations 3-90 Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. 3.3.4.4.3 Running the Demonstration Provides instructions on how to build and run the SSD1926 demo. Description Navigate to the apps/gfx/ssd1926/firmware and open the ssd1926 project, and then select one of the following build configurations to build the SSD1926 demo: • pic32mxusbsk_pictailssd_qvga -- For PIC32MX devices Once the project is loaded and executed on the target board, various JPEG images, which are stored on a SD card are displayed. Short Name Long Name pic32mxusbsk PIC32 USB Starter Kit II pictalssd Graphics LCD Controller PICtail Plus SSD13517 Board qvga Graphics Display Truly 3.2" 240 × 320 Board (AC164127-4) 3.3.5 Demonstration Board Information This topic provides specific information about the development boards available for the demonstration applications. 3.3.5.1 PIC32 USB Starter Kit II Provides information on the PIC32 USB Starter II. Description SW1 - Application switch. Tied to RD6. SW2 - Application switch. Tied to RD7. 3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information 3-91 SW3 - Application switch. Tied to RD13. LED1 - Application LED. Tied to RD0. LED2 - Application LED. Tied to RD1. LED3 - Application LED. Tied to RD2. This board supports the following USB Device demonstrations: • CDC Single COM port (cdc_com_port_single). • CDC Dual COM port (cdc_com_port_dual) • HID Basic (hid_basic) • HID Mouse (hid_mouse) • HID Keyboard (hid_keyboard) • HID Joystick (hid_joystick) • MSD Flash Drive (msd_basic) • Generic USB Device (generic_device) More Information Microchip Part Number : DM320003-2 3.3.5.2 PIC32MZ Embedded Connectivity (EC) Starter Kit Provides details information on the PIC32MZ Embedded Connectivity (EC) Starter Kit. Description Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto) The top assembly of the board includes these key features, as indicated in Figure 1: 1. PIC32MZ2048ECH144 32-bit microcontroller. 2. Green power indicator LED. 3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz). 4. USB connectivity for on-board debugger communications. 5. Green debug indicator LED. 6. Three push button switches for user-defined inputs. 7. Three user-defined indicator LEDs. 8. USB Type A receptacle connectivity for PIC32 host-based applications. 9. HOST mode power jumper. 10. Daughter board connectors for flexible Ethernet PHY options. 11. 32 kHz oscillator for RTCC and Timer1 (optional). 12. External 2 GB SQI memory for expanded memory application. 13. Jumper for using or disconnecting the on-board debugger. NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto the Vbus from one port on the host to another (or from one host to another). 3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information 3-92 Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front) The bottom assembly of the board includes these key features, as indicated in Figure 2: 1. PIC24FJ256GB106 USB microcontroller for on-board debugging. 2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board. 3. Connector for various expansion boards. 4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications. 5. 50 MHz Ethernet PHY oscillator. 6. USB Host and OTG power supply for powering PIC32 USB applications. Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back) 3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information 3-93 Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto) The top assembly of the board includes these key features, as indicated in Figure 1: 1. PIC32MZ2048ECH144 32-bit microcontroller. 2. Green power indicator LED. 3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz). 4. USB connectivity for on-board debugger communications. 5. Green debug indicator LED. 6. Three push button switches for user-defined inputs. 7. Three user-defined indicator LEDs. 8. USB Type A receptacle connectivity for PIC32 host-based applications. 9. HOST mode power jumper. 10. Daughter board connectors for flexible Ethernet PHY options. 11. 32 kHz oscillator for RTCC and Timer1 (optional). 12. External 2 GB SQI memory for expanded memory application. 13. Jumper for using or disconnecting the on-board debugger. NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto the Vbus from one port on the host to another (or from one host to another). Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front) The bottom assembly of the board includes these key features, as indicated in Figure 2: 1. PIC24FJ256GB106 USB microcontroller for on-board debugging. 2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board. 3. Connector for various expansion boards. 4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications. 5. 50 MHz Ethernet PHY oscillator. 3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information 3-94 6. USB Host and OTG power supply for powering PIC32 USB applications. Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back) 3.3.5.3 PICtail Plus SSD1926 Daughter Board This topic provides information about the Graphics LCD Controller PICtail™ Plus SSD1926 Board. Description More Information Microchip Part Number: AC164127-5 Microchip Product Page 3.3.5.4 PICtail Plus S1D13517 Daughter Board This topic provides information about the Graphics LCD Controller PICtail™ Plus SSD1926 Daughter Board. Description More Information Microchip Part Number: AC164127-7 Microchip Product Page 3.3.5.5 PICtail Plus LCC Daughter Board This topic provides information about the Graphics LCD Controller PICtail™ Plus LCC Daughter Board. Description More Information 3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information 3-95 Microchip Part Number: AC164144 Microchip Product Page 3.3.5.6 PIC32MX795F512L Plug-In-Module (PIM) Provides information on the PIC32MX795F512L Plug-In-Module (PIM). Description This PIM is required while using the Explorer 16 Development Board. More Information Microchip Part Number: MA320003 microchipDIRECT Product Page 3.3.5.7 Multimedia Expansion Board (MEB) This topic provides information about the Multimedia Expansion Board (MEB). 3.3.5.8 Multimedia Expansion Board II (MEB II) Provides details information on the Multimedia Expansion Board II (MEB) II. Description Description Microchip Part Number: DM320005-2 Product Page The front side of the MEB II includes these key features, as shown in Figure 1: 1. Display daughter board connector (60-pin Hirose board-to-board connector). 2. mTouch™ buttons. 3. Push Button. 4. Power LED. 5. User LEDs. 6. VGA Camera (OVM7690). 7. PICtail™ Connector. 8. Analog temperature sensor. 3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information 3-96 Figure 1: Multimedia Expansion Board II Layout (Front) The underside of the MEB II includes these key features, as shown in Figure 2: 1. Regulated 5V and 3.3V power supply for powering the board via a 9-15V DC Adapter. 2. PIC32 Starter Kit connector (168-pin Hirose board-to-board connector). 3. 24-bit stereo audio codec (AK4953A). 4. Integrated 802.11bg wireless module (MRF24WG0MA). 5. Low-cost Bluetooth® HCI transceiver (BTM805). 6. EBI SRAM memory (IS61WV102416BLL). 7. microSD slot. 8. Analog accelerometer (ADXL325). Figure 2: Multimedia Expansion Board II Layout (Back) 3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information 3-97 3.4 Peripheral Library Example Applications This topic describes the peripheral library example applications. 3.4.1 Introduction Peripheral Library Example Applications for MPLAB Harmony The example applications for MPLAB peripheral libraries (PLIBs) provide very simple single-purpose examples of how to use MPLAB Harmony peripheral libraries. Description Peripheral libraries (PLIBs) are the lowest level libraries provided with MPLAB Harmony. They provide a functional abstraction of the peripherals available on Microchip microcontrollers to hide differences in register details that can exist from part to part. However, they do not maintain any state data (at least not any that isn't stored in the hardware registers) from call to call and they do not provide any protection of the peripheral's resources. As such, any code that calls the PLIB for a peripheral must take responsibility for ownership of that peripheral and is responsible for managing the behavior of that peripheral. As such, PLIBs are normally only used by MPLAB Harmony device drivers or system services. However, there are some times when it is necessary and appropriate to interact with a PLIB directly from an application. So, simple examples are provided to show how to use the interfaces the peripheral libraries. These examples are available in the MPLAB Harmony installation in the following location. Location of Example Applications /apps/examples/peripheral Examples are divided into two different groups: • Blocking Examples • State-Driven Examples Most MPLAB Harmony applications use a state-machine driven structure. So, examples are provided that follow this structure in the "state_driven" subdirectory. However, it is sometimes easier to understand a simple blocking example (one that sits in a loop for ever or until its task is done). So, simple blocking examples are also provided in the "blocking" subdirectory. Blocking examples are divided into PIC32MX and PIC32MZ variants. PIC32MX examples are written for the Explorer16 Development Board with a PIC32MX795F512L PIM. PIC32MZ examples are written for the PIC32MZ Embedded Connectivity (EC) Starter Kit. The state-driven examples are tested and working on the Explorer 16 Development Board, the PIC32 USB Starter Kit II, and the PIC32MZ Embedded Connectivity (EC) Starter Kit, and the appropriate board configuration for each project can be selected in MPLAB X IDE. 3.4 Peripheral Library Example Applications MPLAB Harmony Help Release Notes 3-98 3.4.2 Release Notes MPLAB Harmony Version: v0.70b Peripheral Library Example Applications Version: 0.01a Release Date: 18Nov2013 The interface can change in the beta and\or 1.0 release. New This Release: Nothing to report for this release. Known Issues: Nothing to report for this release. 3.4.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 3.4.4 Blocking Applications This topic contains a list of the MPLAB Harmony blocking peripheral library (PLIB) example applications. Description The tables below list and summarizes the simple blocking peripheral library example applications. Location /apps/examples/peripheral/blocking/pic32mx PIC32MX PLIB-based Applications 3.4 Peripheral Library Example Applications MPLAB Harmony Help Blocking Applications 3-99 Name Subdirectory Description ADC Potentiometer adc/adc_pot Repeatedly reads the Explorer 16 Development Board potentiometer and outputs a pattern on the LEDs corresponding to the potentiometer's position. Memory Partition bmx/mem_partition Partitions flash memory and ram. Explorer 16 Development Board LEDs are turned on if the RAM partition sizes are correct and the partitioning completed successfully. Simple Comparator cmp/simple_comparator Toggles the LEDs on the Explorer 16 Development Board, depending on which input of the comparator is at a higher voltage. Triangle Wave cvref/triangle_wave This example will generate a triangular wave on the CVREF output pin. LED Pattern dma/led_pattern Blinks LEDs on the Explorer 16 Development Board using a pattern stored in Flash memory. It uses the DMA controller to transfer data from flash to the I/O port controlling the LEDs. Master-Slave i2c/master_slave The I2C1 module is setup to operate as the master, while the I2C2 module operates as the slave. The master sends a string to the slave, which stores the data into an array. Simple Input-Capture ic/simple_input_capture When a rising edge is output to the Input Capture 1 pin (RD8), it triggers an interrupt, which then stores the captured timer value into the 'CaptureTime' variable. Flash Modify nvm/flash_modify Reads, writes and erases data in the program Flash memory. PWM Example oc/oc_pwm Generates a 40 kHz PWM with a 25% duty cycle on the OC1 output pin. Oscillator Configuration osc/osc_config Demonstrates how to change the system clock source and PLL values during run-time. LCD Example pmp/pmp_lcd Writes two lines of text to the LCD screen on the Explorer 16 Development Board. Blinky Leds ports/blinky_leds Toggles the Explorer 16 Development Board LEDs in an infinite loop. Change Notice ports/cn_interrupt When SW4 (the right most button on Explorer 16 Development Board) is pressed, it triggers a change notice interrupt, which then toggles the Explorer 16 Development Board LEDs. Sleep Mode power/sleep_mode This example demonstrates how to put the device into Sleep mode and then awake the device using the Watchdog Timer. Reset Handler reset/reset_handler This example does checks on various reset flags, assigning each one to an Explorer 16 Development Board LED. If the flag is set, the LED is turned on and the reset flag is cleared. RTCC Alarm rtcc/rtcc_alarm Sets up the RTCC module to function as an alarm, which goes off at 6:00am every morning. SPI Loopback spi/spi_loopback This example assumes that the SPI SDO (output) is connected to the SDI (input). Data is then transferred directly from the output to the input and the Explorer 16 Development Board LEDs are turned on if the data transfer is successful. Timer Example tmr/timer2_interrupt Uses Timer2 in 32-bit mode to generate an interrupt every one second, blinking the LEDs on the Explorer 16 Development Board. Simple UART uart/simple_uart When the Explorer 16 Development Board is connected to a PC with an RS-232 cable, the device will echo what characters the user types into a terminal program (e.g., Putty) and write the corresponding 8-bit character pattern to the Explorer 16 Development Board LEDs. Simple WDT wdt/simple_wdt Demonstrates how to setup the Watchdog Timer and detect whether or not a time-out reset has occurred. Location /apps/examples/peripheral/blocking/pic32mz 3.4 Peripheral Library Example Applications MPLAB Harmony Help Blocking Applications 3-100 PIC32MZ PLIB-based Applications Name Subdirectory Description Triangle Wave cvref/triangle_wave This example will generate a triangular wave on the CVref output pin. LED Pattern dma/led_pattern Blinks LEDs on the PIC32MZ Starter-Kit using a pattern stored in flash memory. It uses the DMA controller to transfer data from flash to the I/O port controlling the LEDs. Master-Slave i2c/master_slave The I2C1 module is setup to operate as the master, while the I2C2 module operates as the slave. The master sends a string to the slave, which stores the data into an array. Flash Modify nvm/flash_modify Reads, writes and erases data in the program flash memory. PWM Example oc/oc_pwm Generates a 40KHz PWM with a 25% duty cycle on the OC1 output pin. Oscillator Configuration osc/osc_config Demonstrates how to change the system clock source and PLL values during run-time. Blinky Leds ports/blinky_leds Toggles the PIC32MZ Starter-Kit LEDs in an infinite loop. Change Notice ports/cn_interrupt When SW1 is pressed, it triggers a change notice interrupt, which then toggles the PIC32MZ Starter-Kit LEDs. Sleep Mode power/sleep_mode This example demonstrates how to put the device into sleep mode and then awake the device using the watchdog timer. Reset Handler reset/reset_handler This example does checks on various reset flags, assigning each one to an LED. If the flag is set, the LED is turned on and the reset flag is cleared. RTCC Alarm rtcc/rtcc_alarm Sets up the RTCC module to function as an alarm, which goes off at 6:00am every morning. SPI Loopback spi/spi_loopback This example assumes that the SPI SDO (output) is connected to the SDI (input). Data is then transferred directly from the output to the input and the LEDs are turned on if the data transfer is successful. Timer Example tmr/timer2_interrupt Uses Timer 2 in 32-bit mode to generate an interrupt every one second, blinking the LEDs on the PIC32MZ Starter-Kit. Simple UART uart/simple_uart When the PIC32MZ Starter-Kit is connected to a PC with an RS-232 cable, the device will echo what characters the user types into a terminal program (e.g. Putty). Simple WDT wdt/simple_wdt Demonstrates how to setup the watchdog timer and detect whether or not a timeout reset has occurred. 3.4.5 State-Driven Applications Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony. 3.4 Peripheral Library Example Applications MPLAB Harmony Help State-Driven Applications 3-101 3.5 NVM Driver Demonstration 3.5.1 Introduction This help file contains instructions and associated information about MPLAB Harmony NVM driver application demonstrations, which are contained in the MPLAB Harmony Library distribution. Description This application demonstrates the capabilities of the MPLAB Harmony NVM driver. This help file describes the hardware requirement and procedures to build, run the demo project on Microchip development tools. In this demo application, NVM driver is used to access the internal flash memory of PIC32 MX and PIC32 MZ Devices to perform Write and Read operations and indicates the result by LED display. To know more about MPLAB Harmony NVM driver, configuring the NVM driver and API's provided by the NVM driver, refer to MPLAB Harmony NVM Driver Library documentation. 3.5.2 Release Notes MPLAB Harmony Version: v0.70b NVM Driver Demonstration Version: 0.01a Release Date: 18Nov2013 New This release: This is the first release of this NVM Driver demonstration application. This demonstration has been developed to support PIC32MX and PIC32MZ devices. Known Issues: • This Demo application is tested only up to 150 bytes in interrupt mode in PIC32MZ devices • Changes in NVM driver interfaces will have impact on this demo application as well in subsequent releases 3.5.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO 3.5 NVM Driver Demonstration MPLAB Harmony Help SW License Agreement 3-102 YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 3.5.4 Hardware This section describes how to select and use an appropriate development board and steps to configure the hardware to run this NVM driver demo. 3.5.4.1 Required Hardware This section describes the overview of required hardware family and supported demonstration boards for running this NVM driver demo application. Description To run this demonstration project. you will require one of the following sets of hardware. 3.5.4.1.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Following board is supported for PIC32MX devices: - Demo Board (click link for board information) Notes PIC32 USB Starter Kit II - Explorer 16 Development Board - PIC32MX795F512L Plug-in Module (PIM) - Following board is supported for PIC32MZ devices: - Demo Board (click link for board information) Notes PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.5.4.1.2 Hardware Information Information on hardware used by the NVM driver demo application. Description The NVM driver demo application can be tried on different hardware boards. This section provide details on the different hardware boards that this demo application supports. 3.5 NVM Driver Demonstration MPLAB Harmony Help Hardware 3-103 3.5.4.1.2.1 PIC32 USB Starter Kit II Provides information on the PIC32 USB Starter Kit II. Description SW1 - Application switch. Tied to RD6. SW2 - Application switch. Tied to RD7. SW3 - Application switch. Tied to RD13. LED1 - Application LED. Tied to RD0. LED2 - Application LED. Tied to RD1. LED3 - Application LED. Tied to RD2. More Information Microchip Part Number : DM320003-2 3.5.4.1.2.2 Explorer 16 Development Board Provides information on the Explorer 16 Development Board. 3.5 NVM Driver Demonstration MPLAB Harmony Help Hardware 3-104 Description S1 - Reset button (MCLR) S2 - Processor switch. This switch determines which processor is running, the processor on the board or the processor on the Plug-In-Module (PIM). S3, S4, S5, S6 - Application switches. For information about what pin is connected to this switch, please refer to the information for the PIM in use. D3 through D10 - Application LEDs. For information about what pin is connected to this LED, please refer to the information for the PIM in use. More Information: Microchip Part Number: DM240001 3.5.4.1.2.3 PIC32MX795F512L Plug-in Module (PIM) Provides information on the PIC32MX795F512L Plug-In-Module (PIM). Description This PIM is required while using the Explorer 16 Development Board. 3.5 NVM Driver Demonstration MPLAB Harmony Help Hardware 3-105 More Information Microchip Part Number: MA320003 microchipDIRECT Product Page 3.5.4.1.2.4 PIC32MZ Embedded Connectivity (EC) Starter Kit Provides information on the PIC32MZ Embedded Connectivity (EC) Starter Kit. Description Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto) The top assembly of the board includes these key features, as indicated in Figure 1: 1. PIC32MZ2048ECH144 32-bit microcontroller. 2. Green power indicator LED. 3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz). 4. USB connectivity for on-board debugger communications. 5. Green debug indicator LED. 6. Three push button switches for user-defined inputs. 7. Three user-defined indicator LEDs. 8. USB Type A receptacle connectivity for PIC32 host-based applications. 9. HOST mode power jumper. 10. Daughter board connectors for flexible Ethernet PHY options. 11. 32 kHz oscillator for RTCC and Timer1 (optional). 12. External 2 GB SQI memory for expanded memory application. 13. Jumper for using or disconnecting the on-board debugger. NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto the Vbus from one port on the host to another (or from one host to another). 3.5 NVM Driver Demonstration MPLAB Harmony Help Hardware 3-106 Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front) The bottom assembly of the board includes these key features, as indicated in Figure 2: 1. PIC24FJ256GB106 USB microcontroller for on-board debugging. 2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board. 3. Connector for various expansion boards. 4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications. 5. 50 MHz Ethernet PHY oscillator. 6. USB Host and OTG power supply for powering PIC32 USB applications. Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back) 3.5.4.1.2.5 Multimedia Expansion Board II (MEB II) Provides information on the Multimedia Expansion Board II (MEB II). Description Microchip Part Number: DM320005-2 Product Page The front side of the MEB II includes these key features, as shown in Figure 1: 1. Display daughter board connector (60-pin Hirose board-to-board connector). 2. mTouch™ buttons. 3. Push Button. 4. Power LED. 5. User LEDs. 6. VGA Camera (OVM7690). 7. PICtail™ Connector. 8. Analog temperature sensor. 3.5 NVM Driver Demonstration MPLAB Harmony Help Hardware 3-107 Figure 1: Multimedia Expansion Board II Layout (Front) The underside of the MEB II includes these key features, as shown in Figure 2: 1. Regulated 5V and 3.3V power supply for powering the board via a 9-15V DC Adapter. 2. PIC32 Starter Kit connector (168-pin Hirose board-to-board connector). 3. 24-bit stereo audio codec (AK4953A). 4. Integrated 802.11bg wireless module (MRF24WG0MA). 5. Low-cost Bluetooth® HCI transceiver (BTM805). 6. EBI SRAM memory (IS61WV102416BLL). 7. microSD slot. 8. Analog accelerometer (ADXL325). Figure 2: Multimedia Expansion Board II Layout (Back) 3.5 NVM Driver Demonstration MPLAB Harmony Help Hardware 3-108 3.5.4.2 Configuring the Hardware Describes how to configure the supported hardware. Description Explorer 16 Development Board This demonstration application is demonstrated using Explorer 16 Development Board, PIC32 USB Starter Kit II and PIC32MZ Embedded Connectivity (EC) Starter Kit. The following hardware configuration should be set up before running this application. 1. Before attaching the PIC32MX795F512L PIM to the Explorer 16 Development Board, ensure that the processor select switch (S2) is in the PIM Position. 2. Short JP2 on the Explorer 16 Development Board to enable the LEDs. PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.5.5 Building the Application This section describes how to build this demonstration project. Description Once the hardware is configured, you are ready to build this application. Project Setup : From the MPLAB X IDE, Select "open project" and browse to this demo location. This demo application is available in "/apps/driver/nvm/nvm_read_write/firmware/nvm_read_write.X". This directory contains all the application related source files, header files as well as MPLAB X IDE project related workspace files. How to build this demonstration application: To build this demo in debug mode, Go to "Run" menu in MPLAB X IDE and select "Build Main Project" or select "Build Main Project" in toolbar. Once the project gets compiled successfully, you can run this demonstration application. For more information on how to compile and program projects, refer to the MPLAB X IDE help available through the help menu in MPLAB X IDE. Note:The appropriate project configurations should be selected before building the project for the configured hardware. 3.5.5.1 Configuring the Application This section describes the list of configuration options, build options, and how they are configured for this demonstration application. Build options: This application supports both PIC32MX and PIC32MZ devices. From project properties of MPLAB X IDE, select "pic32mx_usb_starterkit_II" configuration if the target hardware is a PIC32MX device, or select "pic32mz_sk" configuration if the 3.5 NVM Driver Demonstration MPLAB Harmony Help Building the Application 3-109 target hardware is a PIC32MZ device. The default target device is "PIC32MX795F512L" for "pic32mx_usb_starterkit_II" configuration and "PIC32MZ2048ECH144" for "pic32mz_sk" configuration with optimization level as "0". The various optimization levels can be selected from the list to run this demonstration. Note: If the target device is changed, the appropriate PIM needs to be used to run this demonstration application. Configuration options: All of the demonstration application related configuration options are available in "system_config.h" file. This file is available in the "apps/driver/nvm/nvm_read_write/firmware/src/system_config/pic32mx_usb_starterkit_II" or "apps/driver/nvm/nvm_read_write/firmware/src/system_config/pic32mz_sk"directory based on the configuration selected. This file has the following list of configurations: • General System Clock Services • NVM Driver • Interrupt services Note: Based on the configurations, the demo application behavior will be changed. 3.5.5.2 Configuring the Libraries This section describes the configuration options provided by MPLAB Harmony Libraries used by the application. Macro Name Description #define DRV_NVM_INSTANCES_NUMBER This definition selects the maximum number of hardware instances that can be supported by the dynamic NVM driver #define DRV_NVM_CLIENTS_NUMBER This definition selects the maximum number of clients that the NVM driver can support at run time #define DRV_NVM_INTERRUPT_MODE This macro controls the operation of the driver in the interrupt mode of operation #define DRV_NVM_ROW_SIZE This macro defines the row size of target Flash #define DRV_NVM_PAGE_SIZE This macro selects the NVM page size size #define NVM_BASE_ADDRESS This macro defines the address to which the data is written and read 3.5.5.3 Customizing the Application This section explains the steps involved in customizing the existing demonstration application. Customizing Existing Demonstration Application: In this demo application, the NVM driver operates in interrupt mode. Following are the steps to be used to customize this application in olling mode. 1. Change #define DRV_NVM_INTERRUPT_MODE as false in "system_config.h" file 2. Remove the NVM ISR routine from "system_int.c" file 3. Call the DRV_NVM_Tasks function in "system_task.c" file After changing the above configurations, compile the customized application and program the target device. 3.5 NVM Driver Demonstration MPLAB Harmony Help Running the Application 3-110 3.5.6 Running the Application This section demonstrates how to run the NVM Driver demonstration. Description This is a simple demonstration to show how to configure and make use of NVM driver API's to implement and access on-board Flash memory of PIC32MX and PIC32MZ devices. How to run this demonstration application: Once the demonstration application is compiled successfully, you are ready to program the firmware in the target device. To run the demonstration in debug mode, below are the steps to be followed. 1. Select appropriate configuration from project properties based on the target hardware. 2. Select your device programmer from the "hardware tool" in MPLAB X IDE. 3. Select the "Debug Main Project" in "Debug" menu or select the "Debug Main Project" in toolbar. Build the selected configuration in the MPLAB X IDE project and program the demonstration board. The execution status (pass/fail) of the demonstration is indicated by LEDs on the demonstration board. Demonstration Board Successful Indication Failure Indication PIC32 USB Starter Kit II LED2 LED1 PIC32MZ Embedded Connectivity (EC) Starter Kit Green LED Red LED This demonstration first reads the data from specific NVM address define in system_config.h header file and erases the entire sector, write 150 bytes of data and reads back. The Pass/Fail criteria is indicated using LEDs as defined above. 3.5.7 Files This section provides a complete list of source files required by the application and describes the purpose of adding each files. MPLAB Harmony installation follows a standard directory structure for all application solutions. In this directory structure, the driver, plib, system services related source files, header files for this demonstration application are available in "/framework/". Below are the list of files added in this demonstration application. Files Description driver.h Driver Library Interface Header drv_common.h This file defines all common macros and definitions used by the driver drv_nvm.h NVM device driver interface file. system.h System Service Interface Headers sys_common.h This file contains system Common definitions and declarations sys_module.h This file contains system module definitions system_config.h This is file contains all the system configurations system_definitions.h This contains system prototypes and definitions 3.5 NVM Driver Demonstration MPLAB Harmony Help Files 3-111 app.h This file contains application related definitions and prototypes config_performance.c BSP file for Explorer 16 Development Board drv_nvm_dynamic.c This file contains NVM device driver dynamic implementation plib_int_pic32.c Interrupt Source implementation for PIC32 devices sys_int_pic32.c This file contains functions related to the Interrupt System Service for PIC32 devices app.c This file contains application related implementations main.c This file contains application's main entry point system_init.c This file contains source code necessary to initialize the system system_int.c This file contains a definitions of the raw ISRs required to support the interrupt sub-system system_tasks.c This file will contain any source code necessary to maintain various tasks in the system 3.5 NVM Driver Demonstration MPLAB Harmony Help Files 3-112 3.6 RTOS Demonstrations 3.6.1 Introduction RTOS Demonstration Applications Help Description This distribution package contains a variety of RTOS based firmware projects that demonstrate the capabilities of the MPLAB Harmony services and stacks integrated with RTOS running on PIC32 devices. This help file describes the hardware requirement and procedures to run these firmware projects on Microchip demonstration and development boards. To learn more about MPLAB Harmony stacks and libraries refer to the related Framework help documentation. 3.6.2 Release Notes MPLAB Harmony Version: v0.70b RTOS Demonstrations Version: 0.01a Release Date: 18Nov2013 New This Release: This release contains the FreeRTOS basic project. Known Issues: Nothing to report for this release. 3.6.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. 3.6 RTOS Demonstrations MPLAB Harmony Help SW License Agreement 3-113 MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 3.6.4 Demonstrations This topic provides information on how to run the RTOS demonstration applications included in this release. Description All demonstrations provided should be built using the MPLAB X IDE development environment tool supplied by Microchip. The following information communicates the general steps to building the demonstrations. • Using MPLAB X IDE, click the File drop-down, select "Open Project...". Navigate to your Harmony installation folder. The default location on Windows will be: C:\Microchip\Harmony\\apps\rtos • In the \app\rtos folder there will be the demonstration applications. • Within each demonstration folder, there will be a MPLAB X IDE project specific to each demonstration • Select the project and click "Open Project" • To configure the project specific to a preset board configuration, right click on the project and select "Set Configuration" This will set the build configuration to match the supported board configuration. 3.6.4.1 FreeRTOS_basic_demo 3.6.4.1.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Demonstration Board (click link for board information) Notes PIC32 USB Starter Kit II - PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.6.4.1.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.6 RTOS Demonstrations MPLAB Harmony Help Demonstrations 3-114 3.6.4.1.3 Running the Demonstration Provides instructions on how to build and run the FreeRTOS basic demonstration. Description Please use the following procedure to run the demonstration: 1. Load demonstration project into MPLAB X IDE. 2. Connect the mini-B debugger port on-board the PIC32MX or PIC32MZ Starter board to an USB port on the development computer using the USB cable provided in the kit. 3. Build, Download, and Run demonstration project on the target board. The demonstration application features the following: • Application creates one queue and four tasks. One task that sends the data using FreeRTOS queue to the two tasks that waits for the data in the queue. (QueueReceiveTask2 priority is higher than the QueueReceiveTask1 priority.) • QueueReceiveTask2 receives the data first, toggles the LED, and then sleeps for the specified time • QueueReceiveTask1 receives the next data since QueueReceiveTask2 is not in running state • QueueReceiveTask1 receives the data, toggles the LED and waits for the data arrival 3.6.4.2 uC_OS_III_basic_demo 3.6.4.2.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Demonstration Board (click link for board information) Notes PIC32 USB Starter Kit II - PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.6.4.2.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.6.4.2.3 Running the Demonstration Provides instructions on how to build and run the uC_OS_III basic demonstration. 3.6 RTOS Demonstrations MPLAB Harmony Help Demonstrations 3-115 Description Demonstration applications are available in the following folders: • \app\rtos\freeRTOS\gfx • \app\rtos\uC_OS_III\gfx • \app\rtos\freeRTOS\basic • \app\rtos\uC_OS_III\basic Within each demonstration folder, there will be a MPLAB X IDE project specific to each demonstration Select the project and click "Open Project" These demos will show the following: • <\gfx> The selected RTOS integrated in with the Harmony compliant Graphics stack. • <\basic> The basic blink LED demo showing the selected RTOS running with the hardware. Once the demo is up running an LED will toggle every 500ms. This demo will show the RTOS running with the selected hardware. 3.6.4.3 FreeRTOS RTOS with Graphics 3.6.4.3.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Demonstration Board (click link for board information) Notes PIC32 USB Starter Kit II - PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.6.4.3.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.6.4.3.3 Running the Demonstration Provides instructions on how to build and run the FreeRTOS RTOS with Graphics demonstration. 3.6 RTOS Demonstrations MPLAB Harmony Help Demonstrations 3-116 Description Demonstration applications are available in the following folders: • \app\rtos\freeRTOS\gfx • \app\rtos\uC_OS_III\gfx • \app\rtos\freeRTOS\basic • \app\rtos\uC_OS_III\basic Within each demonstration folder, there will be a MPLAB X IDE project specific to each demonstration Select the project and click "Open Project" These demos will show the following: • <\gfx> The selected RTOS integrated in with the Harmony compliant Graphics stack. • <\basic> The basic blink LED demo showing the selected RTOS running with the hardware. Once the demo is up running the screen color on the graphics display will change once every 500ms. A LED will toggle every 500ms. The projects have been setup to use relative paths from the project folder and must remain under the apps\rtos\ root folders in order to build correctly. 3.6.4.4 Micrium uC_OS_III with Graphics 3.6.4.4.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Demonstration Board (click link for board information) Notes PIC32 USB Starter Kit II - PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.6.4.4.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.6 RTOS Demonstrations MPLAB Harmony Help Demonstrations 3-117 3.6.4.4.3 Running the Demonstration Provides instructions on how to build and run the Micrium uC_OS_III with Graphics demonstration. Description Demonstration applications are available in the following folders: • \app\rtos\freeRTOS\gfx • \app\rtos\uC_OS_III\gfx • \app\rtos\freeRTOS\basic • \app\rtos\uC_OS_III\basic Within each demonstration folder, there will be a MPLAB X IDE project specific to each demonstration Select the project and click "Open Project" These demos will show the following: • <\gfx> The selected RTOS integrated in with the Harmony compliant Graphics stack. • <\basic> The basic blink LED demo showing the selected RTOS running with the hardware. Once the demo is up running the screen color on the graphics display will change once every 500ms. A LED will toggle every 500ms. The projects have been setup to use relative paths from the project folder and must remain under the apps\rtos\ root folders in order to build correctly. Under the uC_OS_III\ folder, an extra step must be taken to build the project successfully. The RTOS source code and appropriate port for the selected hardware must be download from Micrium and installed into the follow folder, \third_party\rtos\. 3.6.5 Demonstration Board Information 3.6.5.1 PIC32 USB Starter Kit II Provides information on the PIC32 USB Starter II. 3.6 RTOS Demonstrations MPLAB Harmony Help Demonstration Board Information 3-118 Description SW1 - Application switch. Tied to RD6. SW2 - Application switch. Tied to RD7. SW3 - Application switch. Tied to RD13. LED1 - Application LED. Tied to RD0. LED2 - Application LED. Tied to RD1. LED3 - Application LED. Tied to RD2. More Information Microchip Part Number : DM320003-2 3.6.5.2 PIC32MZ Embedded Connectivity (EC) Starter Kit Provides details information on the PIC32MZ Embedded Connectivity (EC) Starter Kit. Description Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto) The top assembly of the board includes these key features, as indicated in Figure 1: 1. PIC32MZ2048ECH144 32-bit microcontroller. 2. Green power indicator LED. 3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz). 4. USB connectivity for on-board debugger communications. 5. Green debug indicator LED. 6. Three push button switches for user-defined inputs. 7. Three user-defined indicator LEDs. 8. USB Type A receptacle connectivity for PIC32 host-based applications. 9. HOST mode power jumper. 10. Daughter board connectors for flexible Ethernet PHY options. 11. 32 kHz oscillator for RTCC and Timer1 (optional). 12. External 2 GB SQI memory for expanded memory application. 3.6 RTOS Demonstrations MPLAB Harmony Help Demonstration Board Information 3-119 13. Jumper for using or disconnecting the on-board debugger. NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto the Vbus from one port on the host to another (or from one host to another). Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front) The bottom assembly of the board includes these key features, as indicated in Figure 2: 1. PIC24FJ256GB106 USB microcontroller for on-board debugging. 2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board. 3. Connector for various expansion boards. 4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications. 5. 50 MHz Ethernet PHY oscillator. 6. USB Host and OTG power supply for powering PIC32 USB applications. 3.6 RTOS Demonstrations MPLAB Harmony Help Demonstration Board Information 3-120 Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back) Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto) The top assembly of the board includes these key features, as indicated in Figure 1: 1. PIC32MZ2048ECH144 32-bit microcontroller. 2. Green power indicator LED. 3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz). 4. USB connectivity for on-board debugger communications. 5. Green debug indicator LED. 6. Three push button switches for user-defined inputs. 7. Three user-defined indicator LEDs. 8. USB Type A receptacle connectivity for PIC32 host-based applications. 9. HOST mode power jumper. 10. Daughter board connectors for flexible Ethernet PHY options. 11. 32 kHz oscillator for RTCC and Timer1 (optional). 12. External 2 GB SQI memory for expanded memory application. 13. Jumper for using or disconnecting the on-board debugger. NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto the Vbus from one port on the host to another (or from one host to another). 3.6 RTOS Demonstrations MPLAB Harmony Help Demonstration Board Information 3-121 Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front) The bottom assembly of the board includes these key features, as indicated in Figure 2: 1. PIC24FJ256GB106 USB microcontroller for on-board debugging. 2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board. 3. Connector for various expansion boards. 4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications. 5. 50 MHz Ethernet PHY oscillator. 6. USB Host and OTG power supply for powering PIC32 USB applications. Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back) 3.6 RTOS Demonstrations MPLAB Harmony Help Demonstration Board Information 3-122 3.7 SPI Driver Demonstrations 3.7.1 Introduction This help file contains instructions and associated information about MPLAB Harmony SPI driver application demonstrations, which are contained in the MPLAB Harmony Library distribution. Description This application demonstrates the capabilities of the MPLAB Harmony SPI driver. This help file describes the hardware requirement and procedures to build, run the demo project on Microchip development tools. In this demo application, SPI driver is used to access the external EEPROM in the Explorer 16 Development Board to perform Write and Read operations and indicates the result by LED display. To know more about MPLAB Harmony SPI driver, configuring the SPI driver and API's provided by the SPI driver, refer to the SPI Driver Library documentation. 3.7.2 Release Notes MPLAB Harmony Version: v0.70b SPI Driver Demonstrations Version: 0.01a Release Date: 18Nov2013 New This release: This is the first release of this SPI driver demonstration application. This demo has been developed to support PIC32MX devices only. The following demonstration shows the usage of the SPI driver: • serial_eeprom Limitations and Known Issues: • Demo application is only developed and tested in Interrupt mode • Changes in SPI driver interfaces will have impact on this demo application as well in subsequent releases • This demo will support to run only on Explorer 16 Development Board 3.7.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, 3.7 SPI Driver Demonstrations MPLAB Harmony Help SW License Agreement 3-123 FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 3.7.4 Hardware This section describes how to select and use an appropriate development board and steps to configure the hardware to run this SPI driver demo. 3.7.4.1 Required Hardware This section describes the overview of required hardware family and supported demonstration boards for running this SPI driver demo application. Description To run this demonstration project. you will require one of the following sets of hardware. 3.7.4.1.1 Supported Demonstration Boards The following demo boards are supported in this release. Description Demonstration Board Notes Explorer 16 Development board - 3.7.4.1.2 Hardware Information Information on hardware used by the SPI driver demo application. Description The SPI driver demo application can be tried across on hardware boards. This section provide details on the different hardware boards that are used by the demo application. 3.7.4.1.2.1 Explorer 16 Development Board Provides information on the Explorer 16 Development Board . 3.7 SPI Driver Demonstrations MPLAB Harmony Help Hardware 3-124 Description S1 - Reset button (MCLR) S2 - Processor switch. This switch determines which processor is running, the processor on the board or the processor on the Plug-In-Module (PIM). S3, S4, S5, S6 - Application switches. For information about what pin is connected to this switch, please refer to the information for the PIM in use. D3 through D10 - Application LEDs. For information about what pin is connected to this LED, please refer to the information for the PIM in use. More Information: Microchip Part Number: DM240001 3.7.4.1.2.2 PIC32MX795F512L Plug-in Module (PIM) Provides information on the PIC32MX795F512L Plug-In-Module (PIM). Description This PIM is required while using the Explorer 16 Development Board. 3.7 SPI Driver Demonstrations MPLAB Harmony Help Hardware 3-125 More Information Microchip Part Number: MA320003 Information Sheet 3.7.4.2 Configuring the Hardware Describes how to configure the supported hardware. Description serial_eeprom demo This application is demonstrated using Explorer 16 Development Board. the following hardware configuration should be done before running this application. 1. Before attaching the PIC32MX795F512L PIM to the Explorer 16 Development Board, ensure that the processor select switch (S2) is in the PIM Position. 2. Short JP2 on the Explorer 16 Development Board to enable the LEDs. Complete the previously described hardware configuration setup to to run this demo. 3.7.5 Building the Application This section describes how to build this demo project. Description Once the hardware is configured, you are ready to build this application. Project Setup : From MPLAB X IDE, Select "open project" and browse to this demo location. This demo application is available in "/apps/driver/spi/serial_eeprom.X". This directory contains all the application related source files, header files as well as MPLAB X IDE project related workspace files. How to build this demo application: To build this demo in debug mode, Go to "Run" menu in MPLAB X IDE and select "Build Main Project" or select "Build Main Project" in toolbar. Once the project gets compiled successfully, you can run this demo application. For more information on how to compile and program projects, refer to the MPLAB X IDE help available through the help menu in MPLAB X IDE. Note: The appropriate project configurations should be selected before building the project for the configured hardware. 3.7.5.1 Customizing the Application This section explains the steps involved in customizing the existing demo application. Customizing Existing Demo Application: In this demo application, the SPI driver is operates in interrupt mode. Below are the steps to be followed to customize this application in polling mode. 3.7 SPI Driver Demonstrations MPLAB Harmony Help Building the Application 3-126 1. Change #define DRV_SPI_INTERRUPT_MODE as false in "system_config.h" file 2. Remove the SPI interrupt source Priority and sub priority set functions calls from "system_init.c" file 3. Remove the SPI ISR routine from "system_int.c" file 4. Call the DRV_SPI_Tasks function in "system_task.c" file After changing the above configurations, compile the customized application and program the target device. 3.7.5.2 Configuring the Libraries This section describes the configuration options provided by MPLAB Harmony Libraries used by the application. #define DRV_SPI_INSTANCES_NUMBER This definition selects the maximum number of hardware instances that can be supported by the dynamic SPI driver #define DRV_SPI_CLIENTS_NUMBER This definition selects the maximum number of clients that the SPI driver can support at run time #define DRV_SPI_INTERRUPT_MODE This macro controls the operation of the driver in the interrupt mode of operation #define DRV_SPI_PORTS_REMAP_USAGE This macro selects the SPI pins remap #define DRV_SPI_BUFFER_SIZE This macro selects the SPI buffer size #define DRV_SPI_FRAME_SYNC_PULSE_DIRECTION This macro selects the SPI frame sync pulse direction #define DRV_SPI_FRAME_SYNC_PULSE_POLARITY This macro selects the SPI frame sync pulse polarity #define DRV_SPI_FRAME_SYNC_PULSE_EDGE This macro selects the SPI frame sync pulse edge 3.7.5.3 Configuring the Application This section describes the list of configuration options , build options and how they are configured for this demo application. Build options: This application supports only to demonstrate the SPI driver in master mode. This option "spi_master_explorer16" can be selected from the project properties in MPLAB X IDE or from the configuration drop down in toolbar. The default target device is selected as "PIC32MX795F512L" with optimization level as "0". The various optimization levels can be selected from the list to run this demo. Note: If the target device is changed, then appropriate PIM needs to be used to run this demo application Configuration options: All the demo application related configuration options are available in "system_config.h" file. This file is available in the "/apps/driver/spi/src/system_config/" directory based on the configured hardware. This file has the followingconfigurations, • General System Clock Services • SPI Driver Note: Based on the configurations, the demo application behavior will be changed. 3.7 SPI Driver Demonstrations MPLAB Harmony Help Running the Application 3-127 3.7.6 Running the Application This section demonstrates how to run the SPI driver demo. Description This is a simple demo to show how to configure and make use of SPI driver API's to implement and access on board EEPROM chip in the Explorer 16 Development Board. How to run this demo application Once the demo application is compiled successfully, you are ready to program the firmware in the target device. To run the demo in debug mode, below are the steps to be followed. 1. Select your device programmer from the "hardware tool" in MPLAB X IDE. 2. Select the "Debug Main Project" in "Debug" menu or select the "Debug Main Project" in toolbar. Once the device is successfully programmed, you can observe LED in the Explorer 16 Development Board will be turned ON. This shows the demo project has ran successfully and based on the LED "D4" or "D3" the demo application indicates the PASS/FAIL. Notes: If LED "D3" is turned ON, it indicates the EEPROM W/R functionality has failed. If LED "D4" is turned ON, it indicates the EEPROM W/R functionality has passed. 3.7.7 Files This section provides a complete list of source files required by the application and describes the purpose of adding each files. MPLAB Harmony installation follows a standard directory structure for all application solutions. In this directory structure, the driver, plib, system services related source files, header files for this demo application are available in "/framework/". Below are the list of files added in this demo application. Files Description driver.h Driver Library Interface Header drv_common.h This file defines all common macros and definitions used by the driver drv_spi.h SPI device driver interface file. system.h System Service Interface Headers sys_common.h This file contains system Common definitions and declarations sys_module.h This file contains system module definitions system_config.h This is file contains all the system configurations system_definitions.h This contains system prototypes and definitions app.h This file contains application related definitions and prototypes config_performance.c BSP file for Explorer 16 Development Board drv_spi_dynamic.c This file contains SPI device driver dynamic implementation 3.7 SPI Driver Demonstrations MPLAB Harmony Help Files 3-128 plib_int_pic32.c Interrupt Source implementation for PIC32 devices sys_clk.c This file contains clock system service implementation sys_clk_pic32.c This file contains clock system service implementation specific to PIC32 devices sys_queue.c This file contains system queue services sys_int_pic32.c This file contains functions related to the Interrupt System Service for PIC32 devices sys_ports.c This file contains Ports System Service interface implementation. app.c This file contains application related implementations main.c This file contains application's main entry point system_init.c This file contains source code necessary to initialize the system system_int.c This file contains a definitions of the raw ISRs required to support the interrupt sub-system system_tasks.c This file will contain any source code necessary to maintain various tasks in the system 3.7 SPI Driver Demonstrations MPLAB Harmony Help Files 3-129 3.8 TCP/IP Demonstrations 3.8.1 Introduction TCP/IP Web Server Demonstration Applications Help Description Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony. 3.8.2 Release Notes MPLAB Harmony Version: v0.70b TCP/IP Demonstrations Version: 0.01a Release Date: 18Nov2013 The interface can change in the beta and\or 1.0 release. New This Release: Nothing to report for this release. Known Issues: Nothing to report for this release. 3.8.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstrations 3-130 3.8.4 Demonstrations Description of TCP/IP Stack Library Demonstration Application Description This section describes Microchip's TCP/IP Demonstration projects, including information about demonstration-hardware compatibility and also provides the information about how to configure and run the demonstration. 3.8.4.1 web_server 3.8.4.1.1 pic32_ethernet_starter_kit This section describes the steps necessary to begin using Microchip's TCP/IP Web server Demonstration Application. Description This section describes Microchip's TCP/IP Web Server Demonstration project, including information about demonstration-hardware compatibility and also provides the information about how to configure and run the demonstration. 3.8.4.1.1.1 Supported Hardware Lists supported demonstration and development hardware boards. Description Demo Board (click link for board information) Notes PIC32 Ethernet Starter Kit -- PIC32MZ Embedded Connectivity (EC) Starter Kit -- 3.8.4.1.1.2 Configuring the Hardware Describes how to configure the supported hardware. Description No hardware related configuration or jumper setting changes are necessary. 3.8.4.1.1.3 Running the Demonstration Provides instructions on how to build and run the TCP/IP Web Server demonstration. Description This demonstration hosts a HTTP server when connected to a network. To view the web page hosted by the demonstration application open a web browser, type http://mchpboard in the address bar and press the enter key. Please use the following procedure to run the demonstration: 1. Load demonstration project into MPLAB X IDE. 3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstrations 3-131 2. Connect the mini-B debugger port on-board the PIC32MZ Embedded Connectivity (EC) Starter Kit or PIC32MZ Ethernet Starter Kit board to an USB port on the development computer using the USB cable provided in the kit. 3. Connect the RJ-45 Ethernet port on the PIC32MZ Embedded Connectivity (EC) Starter Kit or PIC32MZ Ethernet Starter Kit board to a network hub or an Ethernet port on the development computer using the Ethernet patch cord provided in the kit. 4. Build, Download, and Run demonstration project on the target board. 5. A HTTP server is hosted by the demonstration application. Open a web browser, type http://mchpboard in the address bar and press the enter key. The demonstration application features following: a) Real-time hardware control and Dynamic Variables - On the Overview page the the LEDs can be clicked to toggle LEDs on the Ethernet Starter Board. The buttons on Ethernet Starter Board can be pressed to see the Buttons on the webpage toggle. The dynamic variables can be updated in real time on the HTTP server. b) Form Processing - Input can be handled from the client by using GET and POST methods. c) Authentication - Shows an example to restricted access feature commonly used. d) File Uploads - Shows an example of file upload using POST method. The HTTP server can accept a user defined MPFS/MPFS2 image file for webpages. e) Board Configuration - MAC address, host name and IP address of the PIC32 Ethernet starter board can be viewed in the Network Configuration page and some configuration can be updated. Note: LED functionality part of the demonstration is not implemented for PIC32MZ devices. 3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstrations 3-132 3.8.4.1.2 web_server_sdcard_fatfs This section describes the steps necessary to begin using Microchip's TCP/IP Web server Demonstration Application. Description The TCP/IP SDCARD FATFS web server demo (‘apps/tcpip/web_server_sdcard_fatfs/firmware/pic32_ethernet_starter_kit.X’) exercises the HTTP web server running on PIC32 devices. SDCARD (Secure Digital Card) FATFS (File Allocation Table File System) web server demo has the web pages stored in external SD CARD and accessed through FATFS API. This demo currently only works with PIC32MZ using the Multimedia Expansion Board II (MEB II) Setup. PIC32MZ Testing and Fixes in progress. 3.8.4.1.2.1 Supported Hardware Lists supported demonstration and development hardware boards. Description Demo Board (click link for board information) Notes PIC32MZ Embedded Connectivity (EC) Starter Kit -- Multimedia Expansion Board II (MEB II) -- 3.8.4.1.2.2 Configuring the Hardware Describes how to configure the supported hardware. Description • Plug the PIC32MZ Embedded Connectivity (EC) Starter Kit into application board connector on the MEB II • Make sure a microSD card is formatted and loaded with the web pages provided under ‘apps/tcpip/web_server_sdcard_fatfs/firmware/src/web_pages2_sdcard’ directory • Insert the microSD card with the web pages into the microSD card slot (J8) on the MEB II 3.8.4.1.2.3 Running the Demonstration This section provides instructions on how to build and run the TCP/IP SD CARD FS Web Server demonstration. Description To view the web page hosted by the demonstration application open a web browser, type http://mchpboard_e in the address bar and press the Enter key. Please use the following procedure to run the demonstration: 1. Load demonstration project into MPLAB X IDE. 2. Connect the mini-B debugger port on-board the PIC32MZ Embedded Connectivity (EC) Starter Kit or PIC32MZ Ethernet Starter Kit to a USB port on the Development computer using the USB cable provided in the kit. 3. Connect the RJ-45 Ethernet port on the PIC32MZ Embedded Connectivity (EC) Starter Kit or PIC32MZ Ethernet Starter Kit board to a network hub or an Ethernet port on the development computer using the Ethernet patch cord provided in the kit. 4. Make sure the microSD card with the web pages is inserted into the microSD card slot on the MEB II. 5. Build, Download, and Run demonstration project on the target board. 6. A HTTP server is hosted by the demonstration application. Open a web browser, type http://mchpboard_e in the address bar and press the Enter key. The demonstration application features following: 3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstrations 3-133 a. Real-time hardware control and Dynamic Variables - On the Overview page the LEDs can be clicked to toggle LEDs on the Ethernet Starter Board. The buttons on Ethernet Starter Board can be pressed to see the Buttons on the web page toggle. The dynamic variables can be updated in real time on the HTTP server. Note: LED functionality part of the demonstration is somewhat limited due to errata items related to the functional multiplexing on GPIO and Ethernet pins. b. Form Processing - Input can be handled from the client by using GET and POST methods. c. Authentication - Shows an example to restricted access feature commonly used. d. Cookies – Shows the example of storing small text stings on the client side. e. File Uploads - Shows an example of file upload using POST method. The HTTP server can accept a user defined MPFS/MPFS2 image file for web pages. f. Send E-mail – Shows a simple SMTP POST methods. g. Dynamic DNS – Exercise Dynamic DNS capabilities. h. Network Configuration - MAC address, host name and IP address of the PIC32 Ethernet starter board can be viewed in the Network Configuration page and some configuration can be updated. 3.8.4.1.3 web_server_nvm_mpfs This section describes the steps necessary to begin using Microchip's TCP/IP Web server Demonstration Application. 3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstrations 3-134 Description The TCP/IP NVM MPFS web server demo (‘apps/tcpip/web_server_nvm_mpfs/firmware/pic32_ethernet_starter_kit.X’) exercises the HTTP web server running on PIC32 devices. The Non-Volatile Memory (NVM) MPFS (Microchip Proprietary File System) web server demonstration has the web pages stored in internal Flash and accessed through the MPFS API. 3.8.4.1.3.1 Supported Hardware Lists supported demonstration and development hardware boards. Description Demo Board (click link for board information) Notes PIC32 Ethernet Starter Kit -- PIC32MZ Embedded Connectivity (EC) Starter Kit -- 3.8.4.1.3.2 Configuring the Hardware Describes how to configure the supported hardware. Description No hardware related configuration or jumper setting changes are necessary. 3.8.4.1.3.3 Running the Demonstration This section provides instructions on how to build and run the TCP/IP Web Server demonstration. Description To view the web page hosted by the demonstration application open a web browser, type http://mchpboard_e in the address bar and press the enter key. Please use the following procedure to run the demonstration: 1. Load demonstration project into MPLAB X IDE. 2. Connect the mini-B debugger port on-board the PIC32MZ Embedded Connectivity (EC) Starter Kit or PIC32MZ Ethernet Starter KitStarter board to a USB port on the Development computer using the USB cable provided in the kit. 3. Connect the RJ-45 Ethernet port on the PIC32MZ Embedded Connectivity (EC) Starter Kit or PIC32MZ Ethernet Starter Kit board to a network hub or an Ethernet port on the development computer using the Ethernet patch cord provided in the kit. 4. Build, Download, and Run demonstration project on the target board. 5. A HTTP server is hosted by the demonstration application. Open a web browser, type http://mchpboard_e in the address bar and press the enter key. The demonstration application features following: a. Real-time hardware control and Dynamic Variables - On the Overview page the LEDs can be clicked to toggle LEDs on the Ethernet Starter Board. The buttons on Ethernet Starter Board can be pressed to see the Buttons on the web page toggle. The dynamic variables can be updated in real time on the HTTP server. Note: LED functionality part of the demonstration is somewhat limited due to errata items related to the functional multiplexing on GPIO and Ethernet pins. b. Form Processing - Input can be handled from the client by using GET and POST methods. c. Authentication - Shows an example to restricted access feature commonly used. d. Cookies – Shows the example of storing small text stings on the client side. 3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstrations 3-135 e. File Uploads - Shows an example of file upload using POST method. The HTTP server can accept a user defined MPFS/MPFS2 image file for web pages. f. Send E-mail – Shows a simple SMTP POST methods. g. Dynamic DNS – Exercise Dynamic DNS capabilities. h. Network Configuration - MAC address, host name and IP address of the PIC32 Ethernet starter board can be viewed in the Network Configuration page and some configuration can be updated. 3.8.5 Demonstration Board Information Information on Hardware used by the TCP/IP Demonstration Applications. Description This section provide details on the different hardware boards that are used by the demonstration applications. 3.8.5.1 PIC32 Ethernet Starter Kit Information on PIC32 Ethernet Starter Kit Hardware. Description This board provides a low-cost, modular development system for Microchip’s line of 32-bit Microcontrollers (MCUs) 3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstration Board Information 3-136 PIC32 Ethernet Starter Kit More Information Microchip Part Number: DM320004 Microchip Product Page 3.8.5.2 PIC32MZ Embedded Connectivity (EC) Starter Kit Information on the PIC32MZ Embedded Connectivity (EC) Starter Kit. Description Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto) The top assembly of the board includes these key features, as indicated in Figure 1: 1. PIC32MZ2048ECH144 32-bit microcontroller. 2. Green power indicator LED. 3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz). 4. USB connectivity for on-board debugger communications. 5. Green debug indicator LED. 6. Three push button switches for user-defined inputs. 7. Three user-defined indicator LEDs. 8. USB Type A receptacle connectivity for PIC32 host-based applications. 9. HOST mode power jumper. 10. Daughter board connectors for flexible Ethernet PHY options. 11. 32 kHz oscillator for RTCC and Timer1 (optional). 12. External 2 GB SQI memory for expanded memory application. 13. Jumper for using or disconnecting the on-board debugger. NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto the Vbus from one port on the host to another (or from one host to another). 3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstration Board Information 3-137 Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front) The bottom assembly of the board includes these key features, as indicated in Figure 2: 1. PIC24FJ256GB106 USB microcontroller for on-board debugging. 2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board. 3. Connector for various expansion boards. 4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications. 5. 50 MHz Ethernet PHY oscillator. 6. USB Host and OTG power supply for powering PIC32 USB applications. Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back) 3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstration Board Information 3-138 Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto) The top assembly of the board includes these key features, as indicated in Figure 1: 1. PIC32MZ2048ECH144 32-bit microcontroller. 2. Green power indicator LED. 3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz). 4. USB connectivity for on-board debugger communications. 5. Green debug indicator LED. 6. Three push button switches for user-defined inputs. 7. Three user-defined indicator LEDs. 8. USB Type A receptacle connectivity for PIC32 host-based applications. 9. HOST mode power jumper. 10. Daughter board connectors for flexible Ethernet PHY options. 11. 32 kHz oscillator for RTCC and Timer1 (optional). 12. External 2 GB SQI memory for expanded memory application. 13. Jumper for using or disconnecting the on-board debugger. NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto the Vbus from one port on the host to another (or from one host to another). Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front) The bottom assembly of the board includes these key features, as indicated in Figure 2: 1. PIC24FJ256GB106 USB microcontroller for on-board debugging. 2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board. 3. Connector for various expansion boards. 4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications. 5. 50 MHz Ethernet PHY oscillator. 3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstration Board Information 3-139 6. USB Host and OTG power supply for powering PIC32 USB applications. Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back) 3.8.5.3 Multimedia Expansion Board II (MEB II) Provides details information on the Multimedia Expansion Board II (MEB) II. Description Microchip Part Number: DM320005-2 Product Page The front side of the MEB II includes these key features, as shown in Figure 1: 1. Display daughter board connector (60-pin Hirose board-to-board connector). 2. mTouch™ buttons. 3. Push Button. 4. Power LED. 5. User LEDs. 6. VGA Camera (OVM7690). 7. PICtail™ Connector. 8. Analog temperature sensor. 3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstration Board Information 3-140 Figure 1: Multimedia Expansion Board II Layout (Front) The underside of the MEB II includes these key features, as shown in Figure 2: 1. Regulated 5V and 3.3V power supply for powering the board via a 9-15V DC Adapter. 2. PIC32 Starter Kit connector (168-pin Hirose board-to-board connector). 3. 24-bit stereo audio codec (AK4953A). 4. Integrated 802.11bg wireless module (MRF24WG0MA). 5. Low-cost Bluetooth® HCI transceiver (BTM805). 6. EBI SRAM memory (IS61WV102416BLL). 7. microSD slot. 8. Analog accelerometer (ADXL325). Figure 2: Multimedia Expansion Board II Layout (Back) 3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstration Board Information 3-141 3.9 USART Driver Demonstration 3.9.1 Introduction This help manual contains instructions and information about MPLAB Harmony USART driver demo application, which are contained in the MPLAB Harmony Library distribution. Description This application demonstrates how to use the MPLAB Harmony USART driver. This help manual describes the hardware requirement and procedures to build and execute the demo project on Microchip development tools. In this demo application, USART driver will initially transmit strings of data and then accept and characters received and transmit the data back. Error or success status is indicated by LED display. To know more about MPLAB Harmony USART driver, configuring the USART driver and API's provided by the USART driver, refer to USART Driver Library documentation. 3.9.2 Release Notes MPLAB Harmony Version: v0.70b USART Driver Demonstration: 0.01a Release Date: 18Nov2013 New This Release: This is the first release of this USART driver demo application. This demo has been developed to support PIC32MX devices only. Known Issues: • Changes in USART driver interfaces will have impact on this demo application as well in subsequent releases • This demo is has not been developed to run on PIC32MZ devices. Users must add a new configuration if intended to run on PIC32MZ devices. 3.9.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS 3.9 USART Driver Demonstration MPLAB Harmony Help SW License Agreement 3-142 BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 3.9.4 Hardware This section describes how to select and use an appropriate development board and steps to configure the hardware to run this USART driver demo. 3.9.4.1 Required Hardware This section describes the overview of required device family and supported demonstration boards to run this USART driver demo application. Description This section describes the hardware required to execute the Harmony USART driver demo application. 3.9.4.1.1 Supported Demonstration Boards Lists supported demonstration and hardware development boards. Description Demonstration Board Notes Explorer 16 Development Board - 3.9.4.1.2 Hardware Information Information on hardware used by the USART driver demo application. Description The USART driver demo application can be tried across on hardware boards. This section provide details on the different hardware boards that are used by the demo application. 3.9.4.1.2.1 Explorer 16 Development Board Provides information on the Explorer 16 Development Board . 3.9 USART Driver Demonstration MPLAB Harmony Help Hardware 3-143 Description S1 - Reset button (MCLR) S2 - Processor switch. This switch determines which processor is running, the processor on the board or the processor on the Plug-In-Module (PIM). S3, S4, S5, S6 - Application switches. For information about what pin is connected to this switch, please refer to the information for the PIM in use. D3 through D10 - Application LEDs. For information about what pin is connected to this LED, please refer to the information for the PIM in use. More Information: Microchip Part Number: DM240001 3.9.4.1.2.2 PIC32MX795F512L Plug-in Module (PIM) Provides information on the PIC32MX795F512L Plug-In-Module (PIM). Description This PIM is required while using the Explorer 16 Development Board. 3.9 USART Driver Demonstration MPLAB Harmony Help Hardware 3-144 More Information Microchip Part Number: MA320003 Information Sheet 3.9.4.2 Configuring the Hardware This section describes how to configure the supported hardware. Description Explorer 16 Development Board Below are the hardware hardware configuration settings required to execute this demo 1. Before attaching the PIC32MX795F512L PIM to the Explorer 16 Deveolpment Board, ensure that the processor select switch (S2) is in the PIM Position. 2. Short JP2 on the Explorer 16 Development Board to enable the LEDs. 3.9.5 Building the Application This section describes how to build this demo project. 3.9 USART Driver Demonstration MPLAB Harmony Help Building the Application 3-145 Description Once the hardware is configured, you are ready to build this application. Project Setup: From MPLAB X IDE, Select "open project" and browse to this demo project location. This demo application is available in "/apps/driver/usart/usart_echo/firmware/usart_echo.X". This directory contains all the application related source files, header files as well as MPLAB X IDE project related workspace files. How to build this demo application: To build this demo in debug mode, Go to "Run" menu in MPLAB X IDE and select "Build Main Project" or select "Build Main Project" in toolbar. Once the project gets compiled successfully, you can run this demo application. For more information on how to compile and program projects, refer to the MPLAB X IDE help available through the help menu in MPLAB X IDE. Note: The appropriate project configurations should be selected before building the project for the configured hardware. 3.9.5.1 Configuring the Application This section describes the list of configuration options , build options and how they are configured for this demo application. Build options: The default target device is selected as "PIC32MX795F512L" with optimization level as "0". The various optimization levels can be selected from the list to run this demo. Note: If the target device is changed, then appropriate PIM needs to be used to run this demo application Configuration options: All the demo application related configuration options are available in "system_config.h" file. This file is available in the "apps/driver/usart/usart_echo/firmware/src/system_config/pic32mx_default" directory based on the configured hardware. Note: Based on the configurations, the demo application behavior will be changed. 3.9.5.2 Configuring the Libraries This section describes the configuration options provided by MPLAB Harmony Libraries used by the application. The below parameters are defined in "system_config.h" header file. Parameter Name Description #define DRV_USART_INSTANCES_NUMBER This macro defines the maximum number of hardware instances that will be used by the application. The USART driver will support a maximum of that many hardware instances. #define DRV_USART_CLIENTS_NUMBER This macro defines the maximum number of clients that will be used by the application. The USART driver will support a maximum of that many clients. #define DRV_USART_INTERRUPT_MODE If this macro is set to "true", the application will run in interrupt mode. If this macro is set to "false", the application will run in polling mode #define DRV_USART_INTERRUPT_SOURCE_TX This macro defines the transmit interrupt source #define DRV_USART_INTERRUPT_SOURCE_RX This macro defines the receive interrupt source 3.9 USART Driver Demonstration MPLAB Harmony Help Building the Application 3-146 #define SYS_USART_ID This macro defines the USART module number used in the appilcation #define DRV_USART_XFER_BUFFER_NUMBER This macro defines the number of transfer buffers used in the application #define APP_UART_BAUDRATE This macro defines the baud rate to be used 3.9.5.3 Customizing the Application This section explains the steps involved in customizing the existing demo application. Customizing Existing Demo Application: Changing the USART module In system_config.h header file, modify the SYS_USART_ID macro to change the USART module number. Changing the demo to interrupt mode By default, the USART demo application will run in polling mode. Below are the steps to be followed to run the demo in interrupt mode. 1. Change #define DRV_USART_INTERRUPT_MODE to true in "system_config.h" file 2. Remove the DRV_USART_Tasks function call in sys_tasks in "system_task.c" file 3. Call the DRV_USART_Tasks function in ISR in "system_int.c" file Changing USART settings To change the USART related parameters such as baud rate, parity settings, number of stop bits, etc., select appropriate values in drvUSARTInit structure in system_init.c file After changing the above configurations, compile the customized application and program the target device. 3.9.6 Running the Application This section demonstrates how to run the USART driver demo. Description Once the demo application has been compiled successfully for the intended configuration, program the firmware into the target device. Upon execution, the application will transmit the following strings through USART with settings as defined in the application. /**************************************************** Welcome to Microchip USART Echo Demo App. Press any character. Data will be echoed back. Press 'ESC' key to exit the application /**************************************************** After transmitting the above text, the firmware will read any characters received through USART and it will transmit back the same data. If the received character is "ESC" (0x1B), the program will enetr into idle mode. Once in Idle mode, the firmware will neither transmit nor receive any data. If the application enters Idle mode, LED 5 of the Explorer 16 Development Board will 3.9 USART Driver Demonstration MPLAB Harmony Help Running the Application 3-147 illuminate. If any error occurs, LED 9 of the Explorer 16 Development Board will illuminate. 3.9.7 Files This section provides a complete list of source and header files used by the application and describes the purpose of adding each files. MPLAB Harmony installation follows a standard directory structure for all application solutions. In this directory structure, the driver, plib, system services related source files, header files for this demo application are available in "/framework/". Below are the list of files added in this demo application. Files Description driver.h Driver Library Interface Header drv_common.h This file defines all common macros and definitions used by the driver drv_usart.h USART device driver interface file. system.h System Service Interface Headers sys_common.h This file contains system Common definitions and declarations sys_module.h This file contains system module definitions system_config.h This is file contains all the system configurations system_definitions.h This contains system prototypes and definitions app.h This file contains application related definitions and prototypes config_performance.c BSP file for the Explorer 16 Development Board drv_usart_dynamic.c This file contains USART device driver dynamic implementation plib_int_pic32.c Interrupt Source implementation for PIC32 devices sys_clk.c This file contains clock system service implementation sys_clk_pic32.c This file contains clock system service implementation specific to PIC32 devices sys_queue.c This file contains system queue services sys_int_pic32.c This file contains functions related to the Interrupt System Service for PIC32 devices sys_ports.c This file contains Ports System Service interface implementation. app.c This file contains application related implementations main.c This file contains application's main entry point system_init.c This file contains source code necessary to initialize the system system_int.c This file contains a definitions of the raw ISRs required to support the interrupt sub-system system_tasks.c This file will contain any source code necessary to maintain various tasks in the system 3.9 USART Driver Demonstration MPLAB Harmony Help Files 3-148 3.10 USB Demonstrations 3.10.1 USB Demonstrations 3.10.1.1 Introduction USB Library Demonstration Applications Help Description This distribution package contains a variety of USB-related firmware projects that demonstrate the capabilities of the MPLAB Harmony USB stack. This help file describes the hardware requirement and procedures to run these firmware projects on Microchip demonstration and development boards. To know more about MPLAB Harmony USB stack and configuring the USB stack and the APIs provided by the USB stack, refer to the USB Library documentation. 3.10.1.2 Release Notes MPLAB Harmony Version: v0.70b USB Demonstration: 0.01a Release Date: 18Nov2013 New This Release: Nothing to report in this release. Known Issues: Device Stack Demonstration Applications: All Device Stack Demonstration applications uses a custom Board Support Package (BSP) to access demonstration board switches and LEDs. The board support package does not use PORTS Peripheral Library. In the next release, all Device Stack Demonstration Applications will be updated to use the standard Harmony BSP. The demonstration application specific issues are listed here: cdc_com_port_single: Nothing to report in this release. cdc_com_port_dual: Nothing to report in this release. cdc_serial emulator: • This version of the demo does not support baud rate change. The supported baud rate is 9600bps, 1 stop bit and no parity. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-149 • The application code accesses the UART2 peripheral SFR directly. This will be updated in the next release to use the USART driver and the System Clock Service. hid_basic: Nothing to report in this release. hid_keyboard: Nothing to report in this release. hid_joystick: Nothing to report in this release. hid_mouse: Nothing to report in this release. audio_speaker: While running the pic32mz_sk_meb2_int_dyn configuration, a periodic glitch is heard in the output audio. This is a known issue and will be fixed in the next release of the stack. Host Stack Demonstration Applications: All Host Stack Demonstration applications uses a custom Board Support Package (BSP) to access demonstration board switches and LEDs. The board support package does not use PORTS Peripheral Library. In the next release, all Host Stack Demonstration Applications will be updated to use the standard Harmony BSP. cdc_basic: This demo is not tested for the pic32mx_usb_sk_int_dyn configuration and may not function when built for this configuration. msd_basic: While running this demo, if the USB Flash drive already contains a file named “File.txt”, the file contents may become corrupted. 3.10.1.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-150 3.10.1.4 Demonstration Application Configurations This topic provides information on the USB demonstration project configuration that are available in MPLAB Harmony. Description The available USB Demonstration application MPLAB X IDE projects feature support for multiple configurations. Selecting these configurations allow for the demonstration projects to run across different PIC32 microcontrollers and development boards. The following project configurations are available: • pic32mx_usb_sk_int_dyn – Selecting this configuration will set up the demonstration application to run on the PIC32 USB Starter Kit II development board, with the PIC32MX795F512L microcontroller. The system will be configured for interrupt mode operation and drivers will be configured for dynamic operation mode. • pic32mz_sk_int_dyn – Selecting this configuration will set up the demonstration application to run on the PIC32MZ Embedded Connectivity (EC) Starter Kit development board, with the PIC32MZ2048ECH144 microcontroller. The system will be configured for interrupt mode operation and drivers will be configured for dynamic operation mode. • explorer16_pic32mx795f512l_int_dyn – Selecting this configuration will set up the demonstration application to run on the Explorer 16 Development Board along with the PIC32MX795F512L microcontroller Plug In Module . The system will be configured for interrupt mode operation and drivers will be configured for dynamic operation mode. • pic32mx_usb_audio_int_dyn - Selecting this configuration will set up the demonstration application to run on PIC32 USB Digital Audio Accessory Board along with the PIC32MX250F128B microcontroller. The system will be configured for interrupt mode operation and drivers will be configured for dynamic operation mode. • pic32mz_sk_meb2_int_dyn – Selecting this configuration will set up the demonstration application to run on the PIC32MZ EC Starter Kit development board, with the PIC32MZ2048ECH144 microcontroller board attached to the Multimedia Expansion Board II (MEB II). The system will be configured for interrupt mode operation and drivers will be configured for dynamic operation mode. The following figure shows how a configuration can be selected in MPLAB X IDE. Alternatively, the active configuration can be selected in the Project Properties dialog box. The following table shows the availability of a configuration across available USB device demonstration applications. Green indicates support. Red indicates no support. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-151 The following table shows the availability of a configuration across available USB device demonstration applications. Green indicates support. Red indicates no support. 3.10.1.5 Demonstrations Description of USB Demonstrations Description The USB Demonstrations are grouped into USB Device Stack and USB Host Stack Demonstrations. 3.10.1.5.1 Device 3.10.1.5.1.1 cdc_com_port_single Demonstrates a USB CDC device, emulating a serial COM port. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-152 Description This demonstration application creates a USB CDC Device that enumerates as a single COM port on the host PC. The application demonstrates two-way communication between the USB device and the PC host. 3.10.1.5.1.1.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Demonstration Board (click link for board information) Notes PIC32 USB Starter Kit II - PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.10.1.5.1.1.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.10.1.5.1.1.3 Running the Demonstration Provides instructions on how to build and run the CDC single COM port demonstration. Description This demonstration allows the device to appear like a serial (COM) port to the host. In order to run this demonstration first compile and program the target device. While compiling, select the pic32mx_usb_sk_xxx_xxx configurations for the PIC32M USB Starter Kit II or select the pic32mz_sk_xxx_xxx configurations for PIC32MZ Embedded Connectivity (EC) Starter Kit. Attach the device to the host. If the host is a PC and this is the first time you have plugged this device into the computer then you may be asked for a .inf file. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-153 Select the “Install from a list or specific location (Advanced)” option. Point to the “/apps/usb/device/cdc_com_port_single/inf” directory. Once the device is successfully installed, open up a terminal program, such as HyperTerminal. Select the appropriate COM port. On most machines this will be COM5 or higher. Once connected to the device, there are two ways to run this example project. Typing a key in the terminal window will result in the device echoing the key pressed. So if the user presses “b”, the device will echo “c”. If the pushbutton SW1 is pressed the device will echo "PUSH BUTTON PRESSED" to the terminal window. Note: Some terminal programs, like HyperTerminal, require users to click the disconnect button before removing the device from the computer. Failing to do so may result in having to close and open the program again in order to reconnect to the device. 3.10.1.5.1.2 cdc_com_port_dual Demonstrates a USB CDC device, emulating dual serial COM ports - one looping back into the other. Description This demonstration application creates a USB CDC Device that enumerates as 2 serial ports on USB Host PC. This application demonstrates the ability of the MPLAB Harmony USB stack to support multiple instances of the same device class. 3.10.1.5.1.2.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Demonstration Board (click link for board information) Notes PIC32 USB Starter Kit II - PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.10.1.5.1.2.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-154 No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.10.1.5.1.2.3 Running the Demonstration Provides instructions on how to build and run the CDC dual COM port demonstration. Description This demonstration allows the device to appear like dual serial (COM) ports to the host. In order to run this demonstration first compile and program the target device. While compiling, select the pic32mx_usb_sk_xxx_xxx configurations for the PIC32 USB Starter Kit II or select the pic32mz_sk_xxx_xxx configurations for PIC32MZ Embedded Connectivity (EC) Starter Kit. Attach the device to the host. If the host is a PC and this is the first time you have plugged this device into the computer then you may be asked for a .inf file. Select the “Install from a list or specific location (Advanced)” option. Point to the “/apps/usb/device/cdc_com_port_dual/inf” directory. Once the device is successfully installed, open up two instances of a terminal program, such as HyperTerminal. Select the appropriate COM port for each of these terminal instance. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-155 To run the demonstration, type a character or string in one terminal window. The same character or string appears on the second terminal window. Similarly, any character typed on second window appears on the first window. Note: Some terminal programs, like HyperTerminal, require users to click the disconnect button before removing the device from the computer. Failing to do so may result in having to close and open the program again in order to reconnect to the device. 3.10.1.5.1.3 cdc_serial_emulator This application demonstrates the use of the CDC device class in implementing a USB-to-Serial Dongle. Description This application demonstrates the use of the CDC device class in implementing a USB-to-Serial Dongle. The application enumerates a COM port on the PC. Data received through the CDC USB interface is forwarded to a UART. Data received on the UART is forwarded to the CDC USB interface. This emulates a USB-to-Serial Dongle. 3.10.1.5.1.3.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Demonstration Board (click link for board information) Notes PIC32 USB PIC32MX795F512L Plug-In Module (PIM) 1 Any commercially available USB-to-Serial dongle - Note 1: This board cannot be used by itself. It requires an Explorer 16 Development Board (DM240001) and a USB PICtail Plus Daughter Board (AC164131) in order to operate. 3.10.1.5.1.3.2 Configuring the Hardware Describes how to configure the supported hardware. Description Explorer 16 Development Board Based Demonstrations For all of the Explorer 16-based demonstration boards, please follow the following instructions: 1. Connect the USB PICtail Plus Daughter Board to the Explorer 16 Development Board. 2. Short JP2 and JP3 on the USB PICtail Plus Daughter Board 3. Open JP1 and JP4 on the USB PICtail Plus Daughter Board 4. Make sure that S2 on the Explorer 16 Development Board is switched to the "PIM" setting. 5. Short JP2 on the Explorer 16 Development Board to enable the LEDs. 6. Follow any processor specific instructions below. All instructions apply to the PIM unless otherwise stated: PIC32MX795F512L PIM 7. Open J10. 8. Short pins 1 (marked "USB") and pin 2 (center) of jumpers J1 and J2. 3.10.1.5.1.3.3 Running the Demonstration Provides instructions on how to build and run the CDC Serial Emulator Demonstration. Please refer to Release Notes for demonstration limitations, if any. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-156 Description This application demonstrates the use of the CDC device class in implementing a USB to Serial Dongle. The application enumerates a COM port on the PC. Data received through the CDC USB interface is forwarded to a UART. Data received on the UART is forwarded to the CDC USB interface. This emulates a USB-to-Serial Dongle. 1. Open the project in MPLAB X IDE. Make sure that exp16_pic32mx795f512l_int_dyn configuration is selected. 2. Build the code and program the device. 3. Connect the USB PICtail Plus Daughter Board to the Explorer 16 Development Board. 4. Power up the Explorer 16 Development Board and connect a debugger/programmer of your choice to the Explorer 16 Development Board. 5. Build the code and program the device. 6. Connect the mini-B device connector on the USB PICtail Plus Daughter Board to the PC. If the host is a PC and this is the first time you have plugged this device into the computer, you may be asked for a .inf file. 7. Select the “Install from a list or specific location (Advanced)” option. Point to the “/apps/usb/device/cdc_serial_emulator/inf” directory. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-157 When enumerated successfully, LED D5 will be the only LED illuminated on the Explorer 16 Development board. 8. Open a terminal emulation program of your choice and select the enumerated USB COM port. 9. Connect the USB-to-Serial Dongle to the same PC. 10. Open another instance of the terminal emulation program and select the USB-to-Serial Dongle. 11. Connect the serial connector of the USB-to-Serial Dongle to the UART connector (P1) on the Explorer 16 Development Board. 12. Choose a baud rate of 9600, 1 stop bit and no parity while opening both of the terminal emulation programs. The setup should be similar to the following diagram. Any text entered into the terminal 1 program will be echoed on terminal 2 and vice versa. 3.10.1.5.1.4 hid_basic This demonstration application creates a custom HID device that can be controlled by a PC based utility. Description This application creates a custom HID device that can be controlled by a PC based utility. The device allows the USB Host utility to control the LEDs on the board and query the status of a switch. 3.10.1.5.1.4.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Demonstration Board (click link for board information) Notes PIC32 USB Starter Kit II - PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.10.1.5.1.4.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-158 PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.10.1.5.1.4.3 Running the Demonstration Provides instructions on how to build and run the HID Basic demonstration. Description This demonstration uses the selected hardware platform as a HID class USB device, but uses the HID class for general purpose I/O operations. While compiling, select the pic32mx_usb_sk_xxx_xxx configurations for the PIC32 USB Starter Kit II or select the pic32mz_sk_xxx_xxx configurations for PIC32MZ Embedded Connectivity (EC) Starter Kit. Typically, the HID class is used to implement human interface products, such as mice and keyboards. The HID protocol is however quite flexible, and can be adapted and used to send/receive general purpose data to/from a USB device. Using the HID class for general purpose I/O operations is quite advantageous, in that it does not require any kind of custom driver installation process. HID class drivers are already provided by and are distributed with common operating systems. Therefore, upon plugging in a HID class device into a typical computer system, no user installation of drivers is required, the installation is fully automatic. HID devices primarily communicate through one interrupt IN endpoint and one interrupt OUT endpoint. In most applications, this effectively limits the maximum achievable bandwidth for full speed HID devices to 64 kBytes/s of IN traffic, and 64 kBytes/s of OUT traffic (64 kB/s, but effectively “full duplex”). The GenericHIDSimpleDemo.exe program, and the associated firmware demonstrate how to use the HID protocol for basic general purpose USB data transfer. Before you can run the GenericHIDSimpleDemo.exe executable, you will need to have the Microsoft® .NET Framework Version 2.0 Redistributable Package (later versions probably okay, but not tested) installed on your computer. Programs which were built in the Visual Studio® .NET languages require the .NET redistributable package in order to run. The redistributable package can be freely downloaded from Microsoft’s website. Users of Windows Vista® operating systems will not need to install the .NET framework, as it comes pre-installed as part of the operating system. To launch the application, simply double click on the executable “GenericHIDSimpleDemo.exe” in the “\apps\usb\device\hid_basic\bin” directory. A window like that shown below should appear: If instead of this window, an error message pops up while trying to launch the application, it is likely the Microsoft .NET Framework Version 2.0 Redistributable Package has not yet been installed. Please install it and try again. In order to begin sending/receiving packets to the device, you must first find and “connect” to the device. As configured by default, the application is looking for HID class USB devices with VID = 0x04D8 and PID = 0x003F. The device descriptor in the firmware project meant to be used with this demonstration uses the same VID/PID. If you plug in a USB device programmed with the correct pre-compiled .hex file, and hit the “Connect” button, the other push buttons should become enabled. If hitting the connect button has no effect, it is likely the USB device is either not connected, or has not been programmed with the correct firmware. Hitting the Toggle LED(s) should send a single packet of general purpose generic data to the HID class USB peripheral device. The data will arrive on the interrupt OUT endpoint. The firmware has been configured to receive this generic data packet, parse the packet looking for the “Toggle LED(s)” command, and should respond appropriately by controlling the LED(s) on the demonstration board. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-159 The “Get Pushbutton State” button will send one packet of data over the USB to the peripheral device (to the interrupt OUT endpoint) requesting the current pushbutton state. The firmware will process the received Get Pushbutton State command, and will prepare an appropriate response packet depending upon the pushbutton state. Following table shows the button that has to be pressed on the demonstration board to see the push button state changing. Demonstration Board Button PIC32 USB Starter Kit II SW1 3.10.1.5.1.5 hid_mouse Demonstrates a USB HID device, emulating a mouse pointing device. Description This demonstration application creates a USB HID based 2 button mouse device. When connected, the device emulates mouse operation by moving the cursor in a circular pattern. 3.10.1.5.1.5.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Demonstration Board (click link for board information) Notes PIC32 USB Starter Kit II - PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.10.1.5.1.5.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.10.1.5.1.5.3 Running the Demonstration Provides instructions on how to build and run the HID Mouse Demonstration. Description This demonstration uses the selected hardware platform as a USB mouse. While compiling, select the pic32mx_usb_sk_xxx_xxx configurations for the PIC32 USB Starter Kit II or select the pic32mz_sk_xxx_xxx configurations for PIC32MZ Embedded Connectivity (EC) Starter Kit. Before connecting the board to the computer through the USB cable please be aware that the device will start moving the mouse cursor around on the computer. There are two ways to stop the device from making the cursor to continue to move. The first way is to disconnect the device from the computer. The second is to press the correct button on the hardware platform. Pressing the button again will cause the mouse cursor to start moving in a circle again. Following table shows the button that has to be pressed on the demonstration board to stop the circular motion: 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-160 Demonstration Board Button PIC32 USB Starter Kit II SW1 3.10.1.5.1.6 hid_keyboard Demonstrates a USB HID device, emulating a keyboard. Description This demonstration application creates a Generic HID keyboard. Pressing a key on the board emulates a keyboard key press. 3.10.1.5.1.6.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Demonstration Board (click link for board information) Notes PIC32 USB Starter Kit II - PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.10.1.5.1.6.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.10.1.5.1.6.3 Running the Demonstration Provides instructions on how to build and run the USB HID Keyboard demonstration. Description This demonstration uses the selected hardware platform as a USB keyboard. While compiling, select the pic32mx_usb_sk_xxx_xxx configurations for the PIC32 USB Starter Kit II or select the pic32mz_sk_xxx_xxx configurations for PIC32MZ Embedded Connectivity (EC) Starter Kit. Before pressing the button, select a window in which it is safe to type text freely. Pressing the button on the demonstration board will cause the device to print a character on the screen. Following table shows the button that has to be pressed on the demonstration board to print a character. Demonstration Board Button PIC32 USB Starter Kit II SW1 3.10.1.5.1.7 hid_joystick Demonstrates a USB HID device emulating a joystick. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-161 Description This demonstration application creates a custom HID joystick. This application is only intended to demonstrate creation of Joystick HID Report descriptors and may not be a definite end solution. The end application requirements may need the report descriptor to be modified. 3.10.1.5.1.7.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Demonstration Board (click link for board information) Notes PIC32 USB Starter Kit II - PIC32MZ Embedded Connectivity (EC) Starter Kit - 3.10.1.5.1.7.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Starter Kit II No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit No hardware related configuration or jumper setting changes are necessary. 3.10.1.5.1.7.3 Running the Demonstration Provides instructions on how to build and run the USB HID Josytick demonstration. Description This demonstration uses the selected hardware platform as a USB Joystick. While compiling, select the pic32mx_usb_sk_xxx_xxx configurations for the PIC32 USB Starter Kit II or select the pic32mz_sk_xxx_xxx configurations for PIC32MZ Embedded Connectivity (EC) Starter Kit. To test the joystick feature, go to the “\apps\usb\device\generic_device\bin” directory. A window like that shown below should appear: If instead of this window, an error message pops up while trying to launch the application, it is likely the Microsoft .NET Framework Version 3.5 Redistributable Package has not yet been installed. Please install it and try again. In order to begin sending/receiving packets to the device, you must first find and “connect” to the device. As configured by default, the application is looking for USB devices with VID = 0x04D8 and PID = 0x0204. The device descriptor in the firmware project meant to be used with this demonstration uses the same VID/PID. To run the demonstration program the USB device with the correct precompiled .hex file. If you are connecting the device for the first time, Windows pops up a window asking you 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-165 to install the driver for the device. When asked for the driver point it to the inf file provided along with the demonstration. Windows takes while to install the driver for the USB device that is just plugged in. Open the Device manager and ensure that the USB device is listed under the ‘Libusb Demo Devices’. Once the driver is installed hit the “Connect” button, the other pushbuttons should become enabled. If hitting the connect button has no effect, it is likely the USB device is either not connected, or has not been programmed with the correct firmware. If a different VID/PID combination from the default is desired, then the descriptors in the firmware must be changed as well as the inf file. The easiest way to change the inf file is to use the utility provided with the LibUSB download for windows on the LibUSB website. This utility can create a new inf file based on a connected device. So make sure to change the VID/PID combination first in the firmware, connect the device, and then run the inf file creator utility. After completing the utility, a new signed driver with inf file is created. Once the driver is installed hit the “Connect” button, the other pushbuttons should become enabled. If hitting the connect button has no effect, it is likely the USB device is either not connected, or has not been programmed with the correct firmware. Hitting the Toggle LED(s) should send a single packet of general purpose generic data to the Custom class USB peripheral device. The data will arrive on the Bulk OUT endpoint. The firmware has been configured to receive this generic data packet, parse the packet looking for the “Toggle LED(s)” command, and should respond appropriately by controlling the LED(s) on the demonstration board. The “Get Pushbutton State” button will send one packet of data over the USB to the peripheral device (to the Bulk OUT endpoint) requesting the current pushbutton state. The firmware will process the received Get Pushbutton State command, and will prepare an appropriate response packet depending upon the pushbutton state. The PC then requests a packet of data from the device (which will be taken from the Bulk IN endpoint). Once the PC application receives the response packet, it will update the pushbutton state label. Try experimenting with the application by holding down the appropriate pushbutton on the demonstration board, and then simultaneously clicking on the “Get Pushbutton State” button. Then try to repeat the process, but this time without holding down the pushbutton on the demonstration board. Following table shows the button that has to be pressed on the demonstration board to see the push button state changing. Demonstration Board Button PIC32 USB Starter Kit II SW1 3.10.1.5.1.10 audio_speaker Demonstrates a USB Audio Device that emulates a USB speaker. Description This demonstration application creates uses the USB Audio Device class to implement a speaker. 3.10.1.5.1.10.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Demonstration Board (click link for board information) Notes PIC32 USB Digital Audio Accessory Board - PIC32MZ Embedded Connectivity (EC) Starter Kit - Multimedia Expansion Board II (MEB II) - 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-166 3.10.1.5.1.10.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32 USB Digital Audio Accessory Board No hardware related configuration or jumper setting changes are necessary. PIC32MZ Embedded Connectivity (EC) Starter Kit and Multimedia Expansion Board II (MEB II) 1) Fix the PIC32MZ Embedded Connectivity (EC) Starter Kit on the MEB II board. 2) Connect a Headphone to the HP OUT jack on the MEB II board. 3.10.1.5.1.10.3 Running the Demonstration Provides instructions on how to build and run the Audio Speaker Demonstration. Description This demonstration functions as a speaker when plugged into a computer. Using any feature on the computer that normal produces sound on the speaker will work with this demonstration. The feature unit only supports the Mute control. Please note that some applications lock into a sound source when they open or close (such as some web browsers or plug-ins), so that if you plug in the speaker with the web page or video already playing, the sound might not get redirected to the USB based speakers until you close and reopen the browser. The audio device created in this demonstration has the following characteristics: • Sampling rate of 48 kHz • 2 Channel (Stereo) • PCM Format - 16 bits per Sample • Asynchronous Audio Endpoint 3.10.1.5.2 Host 3.10.1.5.2.1 cdc_basic This application demonstrates the use of the CDC Host Class Driver to enumerate and operate a CDC Device. Description This application demonstrates the use of the CDC Host Class Driver to enumerate and operate a CDC Device. The application uses the USB Host layer and CDC class driver to enumerate a CDC USB device. The demonstration host application then operates and uses the functionality of the attached CDC Device. 3.10.1.5.2.1.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-167 Description Demonstration Board (click link for board information) Notes PIC32MZ Embedded Connectivity (EC) Starter Kit - PIC32 USB Starter Kit II - Hardware required for USB Device CDC Serial Emulator Demonstration Application - 3.10.1.5.2.1.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32MZ Embedded Connectivity (EC) Starter Kit This hardware does not require any configuration. PIC32 Starter Kit USB II This hardware does not require any configuration. 3.10.1.5.2.1.3 Running the Demonstration Provides instructions on how to build and run the USB Host CDC Basic Demo. Please refer to the Release Notes for demonstration limitations, if any. Description This application demonstrates the use of the CDC Host Class Driver to enumerate and operate a CDC Device. The application uses the USB Host layer and CDC class driver to enumerate a CDC USB device. The demonstration host application then operates and uses the functionality of the attached CDC Device. 1. Open the project in MPLAB X IDE and select the desired project configuration. 2. Build the code and program the device. 3. Follow the directions for setting up and running the cdc_serial_emulator USB device demonstration. 4. Connect the UART (P1) port on the Explorer 16 Development Board (running the cdc_serial_emulator demonstration) to a USB Host PC via a commercially available Serial-to-USB Dongle. 5. Start a terminal program on the USB Host PC and select the Serial-to-USB Dongle as the communication port. Select the baud rate as 9600, no parity, 1 stop bit and no flow control. 6. Connect the mini – B connector on the USB PICtail Plus Daughter Board , of the cdc_serial_emulator demonstration setup, to the Type – A USB host connector on the starter kit. 7. A prompt (“LED : “) will be displayed immediately on the terminal emulation program. 8. Pressing either the 1, 2, or 3 key on the USB Host keyboard will cause LED 1, 2, or 3 on the PIC32 Starter kit (running the USB CDC Host application) to switch on, respectively. 9. The prompt will again be displayed on terminal emulation program, and step 8 can be repeated. The setup should be similar to the following diagram. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-168 The cdc_serial_emulator demonstration emulates a USB-to-Serial Dongle. The CDC Host (running the cdc_basic demonstration application) sends the prompt message to the CDC device. The CDC device forwards the prompt to the UART port from where it is transmitted to the PC USB Host through the USB-to-Serial Dongle. A key press on the PC USB Host is transmitted to the CDC device, which in turn presents the key press data to the CDC host. The cdc_basic demonstration then analyzes the key press data and switches on the respective LED. 3.10.1.5.2.2 msd_basic This application demonstrates the use of the MSD Host Class Driver to write a file to USB Flash Drive. Description This application demonstrates the use of the MSD Host Class Driver to write a file to a USB Flash drive. The application uses the USB Host layer , MSD class driver and the MPLAB Harmony File System Framework to enumerate a USB Flash drive and to write a file to it. 3.10.1.5.2.2.1 Supported Demonstration Boards Lists supported demonstration and development hardware boards. Description Demonstration Board (click link for board information) Notes PIC32MZ Embedded Connectivity (EC) Starter Kit - PIC32 USB Starter Kit II - 3.10.1.5.2.2.2 Configuring the Hardware Describes how to configure the supported hardware. Description PIC32MZ Embedded Connectivity (EC) Starter Kit This hardware does not require any configuration. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-169 PIC32 Starter Kit USB II This hardware does not require any configuration. 3.10.1.5.2.2.3 Running the Demonstration Provides instructions on how to build and run the USB Host MSD Basic demonstration. Please refer to theRelease Notes for demonstration limitations, if any. Description This application demonstrates the use of the MSD Host Class Driver to write a file to USB Flash drive. The application uses the USB Host layer, MSD class driver and the MPLAB Harmony File System Framework to enumerate a USB Flash drive and to write a file to it. 1. Open the project in MPLAB X IDE and select the desired project configuration. 2. Build the code and program the device. 3. With the code running, attach a USB Flash drive to the Host connector on the starter kit. 4. The demonstration application will then create a file named “File.txt”. It will then write the text “Hello World” to this file, and then close the file. 5. The demonstration will then move to Idle mode, which is indicated when LED 2 on the starter kit lights up. 6. The USB Flash drive can then be attached to a USB Host PC to verify the demonstration application operation. 7. Steps 3 through 6 can be repeated. 8. If the USB Flash drive already contains a file with the name “File.txt”, the demonstration application will append the text “Hello World” to the end of the file name. 3.10.1.6 Demonstration Board Information Information on Hardware used by the USB Library Demo Applications. Description The USB Library Demo Applications can be tried across on hardware boards. This section provide details on the different hardware boards that are used by the demo applications. 3.10.1.6.1 PIC32 USB Starter Kit II Provides details information on the PIC32 USB Starter II. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-170 Description SW1 - Application switch. Tied to RD6. SW2 - Application switch. Tied to RD7. SW3 - Application switch. Tied to RD13. LED1 - Application LED. Tied to RD0. LED2 - Application LED. Tied to RD1. LED3 - Application LED. Tied to RD2. This board supports the following USB Device demonstrations: • CDC Single COM port (cdc_com_port_single). • CDC Dual COM port (cdc_com_port_dual) • HID Basic (hid_basic) • HID Mouse (hid_mouse) • HID Keyboard (hid_keyboard) • HID Joystick (hid_joystick) • MSD Flash Drive (msd_basic) • Generic USB Device (generic_device) More Information Microchip Part Number : DM320003-2 3.10.1.6.2 Explorer 16 Development Board Provides information on the Explorer 16 Development Board 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-171 Description S1 - Reset button (MCLR) S2 - Processor switch. This switch determines which processor is running, the processor on the board or the processor on the Plug-In-Module (PIM). S3, S4, S5, S6 - Application switches. For information about what pin is connected to this switch, please refer to the information for the PIM in use. D3 through D10 - Application LEDs. For information about what pin is connected to this LED, please refer to the information for the PIM in use. This board support the following USB Host demos: 1. CDC Host (cdc_serial) More Information: Microchip Part Number: DM240001 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-172 3.10.1.6.3 PIC32MX795F512L Plug-In-Module (PIM) Provides information on the PIC32MX795F512L Plug-In-Module (PIM). Description This PIM is required while using the Explorer 16 Development Board. More Information Microchip Part Number: MA320003 Information Sheet 3.10.1.6.4 PIC32 USB Digital Audio Accessory Board Provides information on the PIC32 USB Digital Audio Accessory Board Description This board support the following USB Device demonstration: Audio Speaker (audio_speaker) More Information: Microchip Part Number: DM320014 3.10.1.6.5 PIC32MZ Embedded Connectivity (EC) Starter Kit Provides details information on the PIC32MZ Embedded Connectivity (EC) Starter Kit. Description Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto) The top assembly of the board includes these key features, as indicated in Figure 1: 1. PIC32MZ2048ECH144 32-bit microcontroller. 2. Green power indicator LED. 3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz). 4. USB connectivity for on-board debugger communications. 5. Green debug indicator LED. 6. Three push button switches for user-defined inputs. 7. Three user-defined indicator LEDs. 8. USB Type A receptacle connectivity for PIC32 host-based applications. 9. HOST mode power jumper. 10. Daughter board connectors for flexible Ethernet PHY options. 11. 32 kHz oscillator for RTCC and Timer1 (optional). 12. External 2 GB SQI memory for expanded memory application. 13. Jumper for using or disconnecting the on-board debugger. NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto the Vbus from one port on the host to another (or from one host to another). 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-173 Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front) The bottom assembly of the board includes these key features, as indicated in Figure 2: 1. PIC24FJ256GB106 USB microcontroller for on-board debugging. 2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board. 3. Connector for various expansion boards. 4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications. 5. 50 MHz Ethernet PHY oscillator. 6. USB Host and OTG power supply for powering PIC32 USB applications. Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back) 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-174 3.10.1.6.6 Multimedia Expansion Board II (MEB II) Provides details information on the Multimedia Expansion Board II (MEB) II. Description Microchip Part Number: DM320005-2 Product Page The front side of the MEB II includes these key features, as shown in Figure 1: 1. Display daughter board connector (60-pin Hirose board-to-board connector). 2. mTouch™ buttons. 3. Push Button. 4. Power LED. 5. User LEDs. 6. VGA Camera (OVM7690). 7. PICtail™ Connector. 8. Analog temperature sensor. Figure 1: Multimedia Expansion Board II Layout (Front) The underside of the MEB II includes these key features, as shown in Figure 2: 1. Regulated 5V and 3.3V power supply for powering the board via a 9-15V DC Adapter. 2. PIC32 Starter Kit connector (168-pin Hirose board-to-board connector). 3. 24-bit stereo audio codec (AK4953A). 4. Integrated 802.11bg wireless module (MRF24WG0MA). 5. Low-cost Bluetooth® HCI transceiver (BTM805). 6. EBI SRAM memory (IS61WV102416BLL). 7. microSD slot. 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-175 8. Analog accelerometer (ADXL325). Figure 2: Multimedia Expansion Board II Layout (Back) 3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations 3-176 4 Building Projects Help 4 MPLAB Harmony Help 4-177 4.1 Building Projects 4.1.1 Introduction This section describes the MPLAB X IDE projects that are provided to build binary (.a file) versions of key MPLAB Harmony libraries. Description The following MPLAB Harmony libraries are provided in prebuilt binary (“.a” file) format because source code is not released or to provide optimal performance for users of the free version of the compiler. The MPLAB X IDE projects used to build these libraries are provided so that you can rebuild these libraries with different build parameters, optimization settings, and/or debug symbols if desired. Note: Building these libraries with high optimization settings will require a fully licensed version of the necessary Microchip XC compiler. Build Projects Folder: “/build” Library Description framework/crypto MPLAB Harmony Encryption/Decryption Library framework/zlib MPLAB Harmony Compress/Decompression Library framework/math/dsp MPLAB Harmony Digital Signal Processing Library framework/math/libq MPLAB Harmony Fixed-point Math Library framework/peripheral MPLAB Harmony Peripheral Library Build Project 4.1.2 Release Notes MPLAB Harmony Version: v0.70b Building Projects: 0.70b Release Date: 18Nov2013 New This Release: Peripheral Libraries • Nothing to report in this release Known Issues: Peripheral Libraries • Build configurations were not created for all PIC32 devices. As a workaround, select any configuration and choose a different processor from the Project Properties dialog. This will require you to change the name of the output file to match the name of the selected processor. 4.1 Building Projects MPLAB Harmony Help Using the Build Projects 4-178 4.1.3 Using the Build Projects This section describes how to use the MPLAB Harmony build projects to generate binary (“.a” file) libraries that can be linked into your project. Description The following information describes how to use the MPLAB Harmony build projects to generate binary (“.a” file) libraries that can be linked into your project. Prerequisites To build MPLAB Harmony libraries, you must have the following installed on your development workstation: • MPLAB X IDE (v1.95 or higher) • MPLAB XC32 Compiler (v1.30 or higher) • Appropriate compiler license for your desired optimization settings Build Instructions The following general instructions apply to all MPLAB Harmony library build projects. Refer to the related “Libraries” section for additional information about building specific libraries. 1. Start MPLAB X IDE. 2. Open the desired build project. 3. Set it as the “main” project. 4.1 Building Projects MPLAB Harmony Help Using the Build Projects 4-179 4. Select the desired build configuration. Note: Different libraries provide different build configurations, depending on the set of possible choices that are relevant to that library. For example, the build project for the PIC32MX peripheral libraries (shown above) allows you to select the desired PIC32MX processor. Other libraries may allow you to choose the desired optimization level or feature set. Refer to the related “Libraries” section for information on the configurations provided by the build project for the library you want to build. 5. If required, select the desired processor (or other project settings, if desired). Note: Projects that provide processor-specific configurations will not require this step. a. Open the “Project Properties” dialog box. b. Select the desired processor. 4.1 Building Projects MPLAB Harmony Help Using the Build Projects 4-180 6. Build the library. 7. Copy the binary “.a” library file to your project folder. 8. Add the binary “.a” library file to your project. 4.1.4 Supported Libraries 4.1.4.1 Crypto Library This section describes MPLAB X IDE projects used to build the MPLAB Harmony Crypto libraries. Description The Crypto Library project is contained in the build/framework/crypto folder in the crypto.X project. The library contains functions for operations on blocks of data. Encryption/decryption operations can be done using AES, RSA, DES, Triple DES, and ECC. Authentication/hashing can be done using MD5, SHA-1, SHA-256, SHA-384, and SHA-512. Password-based key derivation can be done with HMAC. Compression and decompression can be done using Huffman Encoding. Random numbers can be created either one at a time or in a block. 4.1.4.2 Compression Library This section describes MPLAB X IDE projects used to build the MPLAB Harmony compression/decompression “zlib” libraries. Description The “zlib” libraries consists of routines for handling gzip (.gz) files, include compression and decompression. The library also contains functions that provide the Huffman compression available in the Crypto library. 4.1.4.3 DSP Math Library This section describes MPLAB X IDE projects used to build the MPLAB Harmony DSP math libraries. Description The DSP Math Library consists of routines that are optimized in assembly to take advantage of the microAptivTM core of the PIC32MZ devices. The library operates on fixed point integers, which are scaled to represent floating point numbers. Many functions are available in both 16-bit and 32-bit numerical formats. The library contains functions for mathematical operations on a vector (or array) of values, complex scalar values and matrixes. 4.1 Building Projects MPLAB Harmony Help Supported Libraries 4-181 Operations include add, subtract, multiply, power, data generation, and in the cases of vectors more complex functions including statistics. The DSP Math Library also contains a full set of digital filtering functions which include FIR and IIR primitives, as well as more complex architectures (e.g., cascade and parallel bi-quad structures). Finally the library contains a number of transform functions include FFT and inverse FFT, as well as a number of windowing functions. Some functions in the DSP Math Library require the use of the LIBQ Fixed Point Math library as well. In those cases the LIBQ library must also be installed with your project. Details on dependent functions are found in the DSP Math Library help file under the remarks section for that specific function. 4.1.4.4 Fixed-Point Math Library This section describes MPLAB X IDE projects used to build the MPLAB Harmony fixed-point math “libq” libraries. Description The Fixed-Point Math Library consists of routines in optimized assembly for performing advanced mathematical operations on a scalar. This is similar in construction to the floating point equivalent math.h file that is included with the compiler. All functions are performed using fixed-point integer operations and generally available in both high precision and low precision variants. Lower precision functions generally perform faster and may be suited for time critical operations. 4.1.4.5 Peripheral Libraries This section describes MPLAB X IDE projects used to build the MPLAB Harmony peripheral libraries. Description The MPLAB Harmony peripheral libraries are implemented almost entirely using C-language inline functions. This is done for efficiency so that the compiler can generate a few simple instructions in place of multiple layers of function calls when function parameters are passed as constants. However, if the project that uses the peripheral library is built with low optimization settings, the compiler may generate a function call instead of “inlining” the function implementation. Unfortunately, this will cause an “undefined symbol” error at link time if the linker cannot find an actual implementation of the function to which it can link the “call”. To satisfy the liker (and to provide optimized PLIB operation, even when low compiler optimization settings are used in your project), the MPLAB Harmony peripheral libraries must be prebuilt as ‘.a’ file, linkable libraries. The appropriate MPLAB X IDE peripheral library “.a” file for the processor in use must be added to the MPLAB X IDE project so that the linker can use them. Note: Prebuilt binary “.a” files are provided for all supported processors in the MPLAB Harmony installation in the following folder: /bin/framework/peripheral. The MPLAB Harmony peripheral library “.a” file build projects are provided so that you may rebuild the binary peripheral library “.a” files using any desired optimization settings. However, if you do this, you must have the appropriate xC compiler and you must copy the resultant “.a” file to your project folder and add it to your MPLAB X IDE project. (See the “Build Instructions” section for details of how to build the library.). Build Configurations Different MPLAB X IDE projects are provided for different processor families to build the peripheral libraries for MPLAB Harmony. Each project provides a set of MPLAB X IDE configurations, one for each supported processor. For example, the “mplab_pic32mx_plib.X” project provides configurations for each device in the PIC32MX family. To identify which devices are supported, open the MPLAB X IDE project that is named after the device family in which you are interested, select the MPLAB X IDE configuration named after the device you want to use, and look at the project properties to verify the device that is selected. 4.1 Building Projects MPLAB Harmony Help Supported Libraries 4-182 Key Configuration Options To build the peripheral library binary “.a” files, there are two key configuration options that must be defined, as follows: #define INLINE_API extern #define INLINE static inline These two configuration items are defined in the source file (“peripehral.c”), which then directly includes the peripheral library implementation headers. Note: This has already been done for you. This information is provided strictly for reference. During normal peripheral library use, both of these options are defined as “extern inline” so that the compiler can choose between generating a function call or generating inline code, directly in the calling function (as described above). However, to build the binary library “.a” files the peripheral library Application Program Interface (API) functions must be exposed as global “external” symbols. The “INLINE_API” attribute is placed as an attribute on all PLIB API function implementations. So, defining it as “extern” allows the compiler to expose these functions within the library “.a” file so that the linker can find them. The VREG and other “internal” functions prefixed by the “INLINE” attribute are then defined as “static inline” functions for efficiency. 4.1 Building Projects MPLAB Harmony Help Supported Libraries 4-183 5 Framework Help 5 MPLAB Harmony Help 5-184 5.1 Driver Library Help 5.1.1 Driver Library Overview A device driver provides a simple well-defined interface to a hardware peripheral that can be used without operating system support or that can be easily ported to a variety of operating systems. The basic driver operations allow an application to interact with a device, reading and writing data, as if it was a simple file. More specific operations are present on most drivers and the kind of specific operations available depends on the peripheral whose functionality is being exposed by the driver. A driver has the following fundamental responsibilities: 1. Providing a highly-abstracted interface to a peripheral 2. Controlling access to a peripheral 3. Managing the state of a peripheral The diagram below illustrates how a driver interacts with the other pieces of the system. • The application calls the well defined driver interface to use the services provided by the driver. • The driver calls various system services to perform the tasks that are possibly shared across other drivers. • The driver also calls the peripheral library of the peripheral that its abstracting the interface to. • Driver State machine can be invoked by the system task service (polling system) or the driver state machine can be invoked from an ISR. The driver provided the interfaces which can be broken down into the following two categories : ( is the abbreviation identifying the module) • System Operation - The interfaces for the system operation should be called by the system. Each driver can support all of the system interfaces, or it can choose to not support the optional system interfaces. The system interfaces are • DRV__Initialize - This routine initializes hardware for the index instance of the module, using the hardware initialization given data. It also initializes any internal data structures. The DRV__Status operation will return SYS_STATUS_READY when this operation has completed. Every driver module should define its own initialization 5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview 5-185 data structure type named “DRV__INIT”. This structure must be an extension of the SYS_MODULE_INIT structure (i.e. its first member must be the SYS_MODULE_INIT structure or equivalent). Any parameter that can change the power state of the module must be included in the data structure. Once the Initialize operation has been called, the Deinitialize operation must be called before the Initialize operation can be called again. • DRV__Reinitialize - This routine reinitializes and refreshes the hardware using the hardware initialization given data. The DRV__Status operation will return SYS_STATUS_READY when this operation has completed. It does not clear or reinitialize internal data structures (although it may change the value of a few appropriate data items necessary to manage the new hardware state) and it does not disconnect or interrupt any ongoing client operations.This operation can be used to change the power state of the peripheral the module manages. • DRV__Deinitialize - This routine de-initializes the index instance of the module, disabling its operation (and any hardware for driver modules).The DRV__Status operation will return SYS_STATUS_READY when this operation has completed. • DRV__Status - The Status operation can be used to determine when any of the other three module operations has completed. If the Status operation returns SYS_STATUS_BUSY, the previous operation has not yet completed. Once the Status operation returns “SYS_STATUS_READY”, any previous operations have completed. • The value of SYS_STATUS_READY is 1. Values between 1 and 10 are reserved for system defined “ready” states. A module may define module-specific “ready” or “run” states greater than or equal to 10 (SYS_STATUS_READY_EXTENDED). • The value of SYS_STATUS_ERROR is -1. Values between -1 and -10 are reserved for system-defined errors. A module may define module-specific error values of less than or equal to -10 (SYS_STATUS_ERROR_EXTENDED). • If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the deinitialize operation will need to be called, followed by the initialize operation to return to normal operations. (Remember to check the value returned by the Status routine after calling any of the module operations to find out when they have completed.) • DRV__Tasks - Used to maintain the driver’s state machine and implement its ISR. It is normally only called by the system’s tasks routine or by an Interrupt Service Routine (ISR). The usage model of the system interfaces is demonstrated in the diagram below: The system is also responsible for either calling the Tasks routine through an ISR or poll the Tasks routine in a polling environment. • Client Operation - The interfaces provided by the driver for client operation, can be called by the application. Each driver can provide a set of client interfaces, which supports the operation model of the peripheral that the driver is supporting. The client interfaces can include 5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview 5-186 • DRV__Open - This routine opens a driver for use by any client module and provides an “open-instance” handle that must be provided to any of the other driver operations to identify the caller and the instance of the driver/hardware module. • DRV__Close - This routine closes an opened-instance of a driver, invalidating the given handle. This routine is optional, if the driver is designed to never be closed. • DRV__ClientStatus - This routine provides the client, the status of the driver. • DRV__ - This is the basic format of a driver interface routine. Driver interface routines (other than the system module routines and the basic device driver routines) should follow this format. The general usage model of the client interfaces is demonstrated in the diagram below, each driver will document usage model specific to the driver in the driver help file. Driver Configuration A driver provides a set of configurations which can be divided into following categories: 1. Build Configuration Selection Configurations - The driver supports selecting the driver instance at build time (static configuration) or at run time (dynamic configuration). A driver also supports selecting the number of clients that can possibly connect to an hardware instance. All drivers will provide DRV__DRIVER_OBJECTS_NUMBER, when this configuration macro is defined driver is built in dynamic driver configuration, else it is built in static driver configuration. The number assigned to DRV__DRIVER_OBJECTS_NUMBER controls the maximum number of driver objects that can be used. If a driver supports multiple clients it will provide DRV__CLIENT_OBJECTS_NUMBER, when this configuration macro is defined driver is built to support multiple clients, else the driver is built to support single client. The number assigned to DRV__DRIVER_OBJECTS_NUMBER controls the maximum number of client objects that can be used. 2. Initialization Overrides - Initialization overrides are provided to enable configuration of the hardware statically and with low run time overhead. These override the parameters if also passed dynamically to Initialize or Reinitialize routine. 3. Other operational configurations - These can control the functionality of the driver or other setting of the driver that are required for support core or optional functionality. A driver allows the application to use the dynamic interface for all the above configuration when the application chooses the appropriate configurations at build time. This is the preferred method of usage for the drivers. As an exception, if the application wants to use multiple configurations in the same build for a driver type, or it needs to use multiple instances of the same driver type, it needs to directly use the static single - client configuration interfaces, or it needs to use the static multiple - client configuration interfaces. While using the driver the static single client driver configuration, the application and system can choose to ignore the SYS_MODULE_INDEX, SYS_MODULE_OBJ and DRV_HANDLE passed and returned to the driver and system interfaces. While using the driver the static multiple client driver configuration, the application and system can choose to ignore the 5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview 5-187 SYS_MODULE_INDEX and SYS_MODULE_OBJ passed and returned to the driver and system interfaces. 5.1.1.1 Data Types Enumerations Name Description DRV_CLIENT_STATUS Identifies the current status/state of a client's connection to a driver. DRV_IO_BUFFER_TYPES Identifies to which buffer a device operation will apply. DRV_IO_INTENT Identifies the intended usage of the device when it is opened. Types Name Description DRV_HANDLE Handle to an opened device driver. Description 5.1.1.1.1 DRV_CLIENT_STATUS Enumeration C typedef enum { DRV_CLIENT_STATUS_ERROR_EXTENDED = -10, DRV_CLIENT_STATUS_ERROR = -1, DRV_CLIENT_STATUS_CLOSED = 0, DRV_CLIENT_STATUS_BUSY = 1, DRV_CLIENT_STATUS_READY = 2, DRV_CLIENT_STATUS_READY_EXTENDED = 10 } DRV_CLIENT_STATUS; Description Driver Client Status This enumeration identifies the current status/state of a client's link to a driver. Members Members Description DRV_CLIENT_STATUS_ERROR_EXTENDED = -10 Indicates that a non-system defined error has occurred. DRV_CLIENT_STATUS_ERROR = -1 An un-specified error has occurred. DRV_CLIENT_STATUS_CLOSED = 0 An operation is currently in progress DRV_CLIENT_STATUS_BUSY = 1 An operation is currently in progress DRV_CLIENT_STATUS_READY = 2 Any previous operations have succeeded and the module is ready for additional operations DRV_CLIENT_STATUS_READY_EXTENDED = 10 Indicates that the module is in a non-system defined ready/run state. Remarks The enumeration used as the return type for the client-level status routines defined by each device driver or system module (for example, DRV_USART_ClientStatus) must be based on the values in this enumeration. 5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview 5-188 5.1.1.1.2 DRV_HANDLE Type C typedef uintptr_t DRV_HANDLE; Description Device Handle This handle identifies the open instance of a device driver. It must be passed to all other driver routines (except the initialization, deinitialization, or power routines) to identify the caller. Remarks Every application or module that wants to use a driver must first call the driver's open routine. This is the only routine that is absolutely required for every driver. If a driver is unable to allow an additional module to use it, it must then return the special value DRV_HANDLE_INVALID. Callers should check the handle returned for this value to ensure this value was not returned before attempting to call any other driver routines using the handle. 5.1.1.1.3 DRV_IO_BUFFER_TYPES Enumeration C typedef enum { DRV_IO_BUFFER_TYPE_NONE = 0x00, DRV_IO_BUFFER_TYPE_READ = 0x01, DRV_IO_BUFFER_TYPE_WRITE = 0x02, DRV_IO_BUFFER_TYPE_RW = DRV_IO_BUFFER_TYPE_READ|DRV_IO_BUFFER_TYPE_WRITE } DRV_IO_BUFFER_TYPES; Description Device Driver IO Buffer Identifier This enumeration identifies to which buffer (read, write, both, or neither) a device operation will apply. This is used for "flush" (or similar) operations. Members Members Description DRV_IO_BUFFER_TYPE_NONE = 0x00 Operation does not apply to any buffer DRV_IO_BUFFER_TYPE_READ = 0x01 Operation applies to read buffer DRV_IO_BUFFER_TYPE_WRITE = 0x02 Operation applies to write buffer DRV_IO_BUFFER_TYPE_RW = DRV_IO_BUFFER_TYPE_READ|DRV_IO_BUFFER_TYPE_WRITE Operation applies to both read and write buffers 5.1.1.1.4 DRV_IO_INTENT Enumeration C typedef enum { DRV_IO_INTENT_READ, DRV_IO_INTENT_WRITE, DRV_IO_INTENT_READWRITE, DRV_IO_INTENT_BLOCKING, DRV_IO_INTENT_NONBLOCKING, DRV_IO_INTENT_EXCLUSIVE, DRV_IO_INTENT_SHARED 5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview 5-189 } DRV_IO_INTENT; Description Device Driver I/O Intent This enumeration identifies the intended usage of the device when the caller opens the device. It identifies the desired behavior of the device driver for the following: • Blocking or non-blocking I/O behavior (do I/O calls such as read and write block until the operation is finished or do they return immediately and require the caller to call another routine to check the status of the operation) • Support reading and/or writing of data from/to the device • Identify the buffering behavior (sometimes called "double buffering" of the driver. Indicates if the driver should maintain its own read/write buffers and copy data to/from these buffers to/from the caller's buffers. • Identify the DMA behavior of the peripheral Members Members Description DRV_IO_INTENT_READ Read DRV_IO_INTENT_WRITE Write DRV_IO_INTENT_READWRITE Read and Write DRV_IO_INTENT_BLOCKING The driver will block and will return when the operation is complete DRV_IO_INTENT_NONBLOCKING The driver will return immediately DRV_IO_INTENT_EXCLUSIVE The driver will support only one client at a time DRV_IO_INTENT_SHARED The driver will support multiple clients at a time Remarks The buffer allocation method is not identified by this enumeration. Buffers can be allocated statically at build time, dynamically at run-time, or even allocated by the caller and passed to the driver for its own usage if a driver-specific routine is provided for such. This choice is left to the design of the individual driver and is considered part of its interface. These values can be considered "flags". One selection from each of the groups below can be ORed together to create the complete value passed to the driver's open routine. 5.1.1.2 Constants Macros Name Description DRV_CONFIG_NOT_SUPPORTED Not supported configuration. DRV_HANDLE_INVALID Invalid device handle. DRV_IO_ISBLOCKING Returns if the I/O intent provided is blocking DRV_IO_ISEXCLUSIVE Returns if the I/O intent provided is non-blocking. DRV_IO_ISNONBLOCKING Returns if the I/O intent provided is non-blocking. 5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview 5-190 Description 5.1.1.2.1 DRV_CONFIG_NOT_SUPPORTED Macro C #define DRV_CONFIG_NOT_SUPPORTED (((unsigned short) -1)) Description Not supported configuration If the configuration option is not supported on an instance of the peripheral, use this macro to equate to that configuration. This option should be listed as a possible value in the description of that configuration option. 5.1.1.2.2 DRV_HANDLE_INVALID Macro C #define DRV_HANDLE_INVALID (((DRV_HANDLE) -1)) Description Invalid Device Handle If a driver is unable to allow an additional module to use it, it must then return the special value DRV_HANDLE_INVALID. Callers should check the handle returned for this value to ensure this value was not returned before attempting to call any other driver routines using the handle. Remarks None. 5.1.1.2.3 DRV_IO_ISBLOCKING Macro C #define DRV_IO_ISBLOCKING(intent) (intent & DRV_IO_INTENT_BLOCKING) Description Device Driver Blocking Status Macro This macro returns if the I/O intent provided is blocking. Remarks None. 5.1.1.2.4 DRV_IO_ISEXCLUSIVE Macro C #define DRV_IO_ISEXCLUSIVE(intent) (intent & DRV_IO_INTENT_EXCLUSIVE) Description Device Driver Exclusive Status Macro This macro returns if the I/O intent provided is non-blocking. 5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview 5-191 Remarks None. 5.1.1.2.5 DRV_IO_ISNONBLOCKING Macro C #define DRV_IO_ISNONBLOCKING(intent) (intent & DRV_IO_INTENT_NONBLOCKING ) Description Device Driver Non Blocking Status Macro This macro returns if the I/ intent provided is non-blocking. Remarks None. 5.1.1.3 Files Files Name Description driver.h This file aggregates all of the driver library interface headers. driver_common.h This file defines the common macros and definitions used by the driver definition and implementation headers. Description 5.1.1.3.1 driver.h Driver Library Interface Header This file aggregates all of the driver library interface headers so client code only needs to include this one single header to obtain prototypes and definitions for the interfaces to all driver libraries. A device driver provides a simple well-defined interface to a hardware peripheral that can be used without operating system support or that can be easily ported to a variety of operating systems. A driver has the fundamental responsibilities: • Providing a highly-abstraced interface to a peripheral • Controlling access to a peripheral • Managing the state of a peripheral Remarks The directory in which this file resides should be added to the compiler's search path for header files. File Name drv.h Company Microchip Technology Inc. 5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview 5-192 5.1.1.3.2 driver_common.h Driver Common Header This file defines the common macros and definitions used by the driver definition and the implementation header. Remarks The directory in which this file resides should be added to the compiler's search path for header files. Enumerations Name Description DRV_CLIENT_STATUS Identifies the current status/state of a client's connection to a driver. DRV_IO_BUFFER_TYPES Identifies to which buffer a device operation will apply. DRV_IO_INTENT Identifies the intended usage of the device when it is opened. Macros Name Description DRV_CONFIG_NOT_SUPPORTED Not supported configuration. DRV_HANDLE_INVALID Invalid device handle. DRV_IO_ISBLOCKING Returns if the I/O intent provided is blocking DRV_IO_ISEXCLUSIVE Returns if the I/O intent provided is non-blocking. DRV_IO_ISNONBLOCKING Returns if the I/O intent provided is non-blocking. Types Name Description DRV_HANDLE Handle to an opened device driver. File Name drv_common.h Company Microchip Technology Inc. 5.1.2 ADC Driver Library 5.1.2.1 Introduction ADC Driver for Microchip Microcontrollers This Analog-to-Digital Converter (ADC) driver provides an interface to manage the ADC module on the Microchip family of microcontrollers. Description Overview An ADC is a vital part of any system that interfaces to real-world signals. While there are many techniques for analog-to-digital 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-193 conversion, the Microchip family of microcontrollers uses Successive Approximation as one of its primary techniques. 5.1.2.2 Release Notes MPLAB Harmony Version: v0.70b ADC Driver Library Version : 0.02a Release Date: 18Nov2013 New This Release: This is the first release of the library. The interface can change in the beta and\or 1.0 release. Known Issues: Nothing to report in this release. 5.1.2.3 SW License Agreement © 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED “AS IS.” MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 5.1.2.4 Using the Library This topic describes the basic architecture of the ADC Driver Library and provides information and examples on how to use it. Interface Header File: drv_adc.h The interface to the ADC Driver Library is defined in the "drv_adc.h" header file. Please refer to the MPLAB Harmony Overview for how the driver interacts with the framework. 5.1.2.4.1 Library Overview Refer to the section Driver Overview for how the driver operates in a system. The following table lists the interface section and its brief description. Section Description Configuring the Library Provides macros for configuring the system. It is required that the system configures the driver to build correctly by choosing appropriate configuration options as listed in this section. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-194 System Interaction Functions Provides system module interfaces, Device initialization, deinitialization, reinitialization and status functions. Client Core Configuration Functions Provides interfaces for core functionality of the driver. 5.1.2.4.2 Abstraction Model The ADC driver is modeled using the abstraction model, as shown in the following diagram. • DRV_ADC_InputsRegister allows selection of inputs • DRV_ADC_SamplesRead and DRV_ADC_SamplesReadLatest allow reading of the sample from the result buffer • DRV_ADC_Start and DRV_ADC_Stop will control the operation of the ADC 5.1.2.4.3 How the Library Works The library provides interfaces to support: • System Interaction • Client Core Functionality 5.1.2.4.3.1 System Initialization This section describes the system initialization and reinitialization settings for the ADC Peripheral Library. Description System Initialization and Reinitialization The system initialization and the reinitialization settings, effect only the instance of the peripheral that is being initialized or re-initialized. During system initialization configure each instance of the module with the following configuration settings that are supported by the specific ADC device hardware (refer to DRV_ADC_INIT) 1. Device requested power state: One of the system module power states. 2. Acquisition time: If the hardware supports this feature, configure this variable from DRV_ADC_ACQUISITION_TIME. 3. Voltage reference: If the hardware supports this feature, select the one from the available options(from DRV_ADC_VOLTAGE_REFERENCE). 4. Conversion clock: If the hardware supports this feature, select the conversion clock prescaler value (from DRV_ADC_CONVERSION_CLOCK_PRESCALER). 5. Conversion clock source: If the hardware supports this feature, select the conversion clock prescaler value (from DRV_ADC_CONVERSION_CLOCK_SOURCE). 6. Clock frequency: Peripheral clock frequency configured for the device. 7. Conversion trigger source: If the hardware supports this feature, select the conversion trigger source(from DRV_ADC_CONVERSION_TRIGGER_SOURCE). 8. Samples per interrupt: Configure the number of samples before to be generating interrupt(from 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-195 DRV_ADC_SAMPLES_PER_INTERRUPT). 9. Output data format: Select the output data format. 10. Interrupt source: Select the interrupt source. Example: Auto Sampling Mode #define MY_ADC_INSTANCE DRV_ADC_INDEX_0 SYS_MODULE_OBJ myAdcObj; DRV_ADC_INIT adcInitData; SYS_STATUS adcStatus; // Populate the adcInitData structure adcInitData.plibModuleId = ADC_ID_1; adcInitData.acquisitionTime = PLIB_ADC_ACQUISITION_TIME_20_TAD; adcInitData.voltageReference = PLIB_ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS; adcInitData.clockFrequency = 4000000; //4MHz adcInitData.conversionClock = PLIB_ADC_CONV_CLOCK_20_TCY; adcInitData.conversionClockSource = PLIB_ADC_CLOCK_SRC_SYSTEM_CLOCK; adcInitData.conversionTriggerSource = PLIB_ADC_CONVERSION_TRIGGER_INTERNAL_COUNT; adcInitData.dataOutputFormat = PLIB_ADC_OUTPUT_FORMAT_INTEGER_16BIT; adcInitData.initFlags = DRV_ADC_AUTO_SAMPLING; adcInitData.interruptSource= PLIB_INT_SOURCE_ADC_1; adcInitData.samplesPerInterrupt = PLIB_ADC_SAMPLE_PER_INTERRUPT_AT_EACH_SAMPLE; myAdcObj = DRV_ADC_Initialize(MY_ADC_INSTANCE, (SYS_MODULE_INIT*)&adcInitData); adcStatus = DRV_ADC_Status(myAdcObj); if (SYS_STATUS_BUSY == adcStatus) { // do something else and check back later } else if (SYS_STATUS_ERROR >= adcStatus) { // Handle error } 5.1.2.4.3.2 Client Core Functionality Core functionality provides a basic interface for the driver operation. Description General Client Operation Core functionality provides a basic interface for the driver operation. Applications using the timer core functionality, need to perform the following: 1. The system should have completed necessary initialization and DRV_ADC_Tasks should either be running in a polled environment, or in an interrupt environment. 2. Open the driver using DRV_ADC_Open (the timer driver supports exclusive access only). 3. Registers the inputs to be used by the clients using DRV_ADC_InputsRegister. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-196 4. Start the driver using DRV_ADC_Start. 5. Poll for the elapse status using DRV_ADC_SamplesAvailable, and then read the samples using either DRV_ADC_SamplesReadLatest or DRV_ADC_SamplesRead. 6. The client will be able to stop the started ADC instance using DRV_ADC_Stop at any point and will be able to close it using DRV_ADC_Close when it is no longer required. Example: DRV_HANDLE adcHandle; //Handle returned by DRV_ADC_Open function. uint16_t dataBuffer; //Buffer to which the data will be written. /* Open a new client. The handle returned by the this function should be used a passing parameter for all the specific client related operations. */ adcHandle = DRV_ADC_Open(MY_ADC_INSTANCE, DRV_IO_INTENT_NONBLOCKING); DRV_ADC_InputsRegister ( adcHandle ,PLIB_ADC_INPUT_AN1|PLIB_ADC_INPUT_AN2 ); /* ADC is not yet enabled. Enable it once the inputset is registered. Starts automatically since auto sample mode is enabled. */ DRV_ADC_Start(adcHandle); if ( DRV_ADC_SamplesAvailable(adcHandle) ) { DRV_ADC_SamplesReadLatest ( adcHandle, &dataBuffer, 1); /* Once the above function returns success, the data is in 'dataBuffer'. Application can use this data. */ } 5.1.2.4.3.3 Code Examples Example1 //PIC32/PIC24 in auto sampling , Polling mode #define MY_ADC_INSTANCE DRV_ADC_INDEX_0 DRV_HANDLE adcHandle; //Handle returned by DRV_ADC_Open function. uint16_t dataBuffer; //Buffer to which the data will be written. /* Open a new client. The handle returned by the this function should be used a passing parameter for all the specific client related operations. */ adcHandle = DRV_ADC_Open(MY_ADC_INSTANCE, DRV_IO_INTENT_NONBLOCKING); ipHandle = DRV_ADC_InputsRegister ( adcHandle ,inputSetConfig ); /* ADC is not yet enabled. Enable it once the inputset is registered. Starts automatically since auto sample mode is enabled. */ DRV_ADC_Start(adcHandle); while (DRV_ADC_SampleAvailable(adcHandle)) { DRV_ADC_InputSetRead ( adcHandle, &dataBuffer, 1); 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-197 /* Once the above function returns success, the data is in 'dataBuffer'. Application can use this data. */ } Example 2: //PIC32/PIC24 in Manual triggering , Polling mode #define MY_ADC_INSTANCE DRV_ADC_INDEX_0 int main() { SYS_MODULE_OBJ myAdcObj; //Object returned by DRV_ADC_Initialize function. DRV_ADC_INIT adcInitData; //Contains all the initialization values. DRV_HANDLE adcHandle; //Handle returned by DRV_ADC_Open function. DRV_ADC_INPUTSET_HANDLE ipHandle; //Handle returned by DRV_ADC_InputSetRegister function. DRV_ADC_INPUTSET_CONFIG inputSetConfig;//Contains all values to configure the inputset. uint16_t dataBuffer; //Buffer to which the data will be written. /* These initialization values should be based on the requirement of the application and the way it wants the hardware to be operating. Most of these values will be written directly to the hardware registers. */ adcInitData.plibModuleId = ADC_ID_1; adcInitData.acquisitionTime = PLIB_ADC_ACQUISITION_TIME_15_TAD; adcInitData.voltageReference = PLIB_ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS; adcInitData.clockFrequency = 4000000; //4MHz adcInitData.conversionClock = PLIB_ADC_CONV_CLOCK_5_TCY; adcInitData.conversionClockSource = PLIB_ADC_CLOCK_SRC_INTERNAL_RC; adcInitData.conversionTriggerSource = PLIB_ADC_CONVERSION_TRIGGER_INTERNAL_COUNT; adcInitData.dataOutputFormat = PLIB_ADC_OUTPUT_FORMAT_INTEGER_16BIT; adcInitData.interruptSource= PLIB_INT_SOURCE_ADC_1; adcInitData.samplesPerInterrupt = PLIB_ADC_SAMPLE_PER_INTERRUPT_AT_EACH_SAMPLE; myAdcObj = DRV_ADC_Initialize(MY_ADC_INSTANCE, (SYS_MODULE_INIT*)&adcInitData); /* Open a new client. The handle returned by the this function should be used a passing parameter for all the specific client related operations. */ adcHandle = DRV_ADC_Open(MY_ADC_INSTANCE, DRV_IO_INTENT_NONBLOCKING); /* Driver invokes the registered callback function every successful data read. Application can perform an action or do a state change in the callback */ inputSetConfig.callback = adcCallback; inputSetConfig.input = POTENTIOMETER_ANALOG_INPUT; inputSetConfig.errorTolerance = 10; inputSetConfig.samplingFrequency = 40000; ipHandle = DRV_ADC_InputSetRegister ( adcHandle ,inputSetConfig ); /* ADC is not yet enabled. Enable it once the inputset is registered. Starts automatically since auto sample mode is enabled. */ DRV_ADC_Start(adcHandle); while (1) { /* 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-198 This function can be either called in a sequential way or it could be called from a timer periodically */ triggerAdc(); DRV_HANDLE handle; DRV_ADC_Tasks (myAdcObj); DRV_ADC_InputSetRead ( adcHandle, &dataBuffer, 1); /* Once the above function returns success, the data is in 'dataBuffer'. Application can use this data. */ } } void adcCallback (void) { // Application can do something here } void triggerAdc(void) { DRV_ADC_OperationSetup(handle, DRV_ADC_START_SAMPLING); /* Give some delay between the two operations. */ for (i=0; i<100; i++); DRV_ADC_OperationSetup(handle, DRV_ADC_START_CONVERSION); } Example 3: //PIC32/PIC24 in auto sampling , Interrupt mode #define MY_ADC_INSTANCE DRV_ADC_INDEX_0 int main() { SYS_MODULE_OBJ myAdcObj; //Object returned by DRV_ADC_Initialize function. DRV_ADC_INIT adcInitData; //Contains all the initialization values. DRV_HANDLE adcHandle; //Handle returned by DRV_ADC_Open function. DRV_ADC_INPUTSET_HANDLE ipHandle; //Handle returned by DRV_ADC_InputSetRegister function. DRV_ADC_INPUTSET_CONFIG inputSetConfig;//Contains all values to configure the inputset. uint16_t dataBuffer; //Buffer to which the data will be written. /* These initialization values should be based on the requirement of the application and the way it wants the hardware to be operating. Most of these values will be written directly to the hardware registers. */ adcInitData.plibModuleId = ADC_ID_1; adcInitData.acquisitionTime = PLIB_ADC_ACQUISITION_TIME_15_TAD; adcInitData.voltageReference = PLIB_ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS; adcInitData.clockFrequency = 4000000; //4MHz adcInitData.conversionClock = PLIB_ADC_CONV_CLOCK_5_TCY; adcInitData.conversionClockSource = PLIB_ADC_CLOCK_SRC_INTERNAL_RC; adcInitData.conversionTriggerSource = PLIB_ADC_CONVERSION_TRIGGER_INTERNAL_COUNT; adcInitData.dataOutputFormat = PLIB_ADC_OUTPUT_FORMAT_INTEGER_16BIT; adcInitData.initFlags = DRV_ADC_AUTO_SAMPLING; adcInitData.interruptSource= PLIB_INT_SOURCE_ADC_1; adcInitData.samplesPerInterrupt = PLIB_ADC_SAMPLE_PER_INTERRUPT_AT_EACH_SAMPLE; 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-199 myAdcObj = DRV_ADC_Initialize(MY_ADC_INSTANCE, (SYS_MODULE_INIT*)&adcInitData); /* Open a new client. The handle returned by the this function should be used a passing parameter for all the specific client related operations. */ adcHandle = DRV_ADC_Open(MY_ADC_INSTANCE, DRV_IO_INTENT_NONBLOCKING); /* Driver invokes the registered callback function every successful data read. Application can perform an action or do a state change in the callback */ inputSetConfig.callback = adcCallback; inputSetConfig.input = POTENTIOMETER_ANALOG_INPUT; inputSetConfig.errorTolerance = 10; inputSetConfig.samplingFrequency = 40000; ipHandle = DRV_ADC_InputSetRegister ( adcHandle ,inputSetConfig ); /* ADC is not yet enabled. Enable it once the inputset is registered. Starts automatically since auto sample mode is enabled. */ DRV_ADC_Start(adcHandle); while (1) { /* Task function need not be called. Task function is registered as ISR in case of interrpt mode */ DRV_ADC_InputSetRead ( adcHandle, &dataBuffer, 1); /* Once the above function returns success, the data is in 'dataBuffer'. Application can use this data. */ } } void adcCallback (void) { // Application can do something here } // Do something else... } while(total < MY_BUFFER_SIZE); Example 4: //PIC32/PIC24 in Manual triggering , Interrupt mode #define MY_ADC_INSTANCE DRV_ADC_INDEX_0 int main() { SYS_MODULE_OBJ myAdcObj; //Object returned by DRV_ADC_Initialize function. DRV_ADC_INIT adcInitData; //Contains all the initialization values. DRV_HANDLE adcHandle; //Handle returned by DRV_ADC_Open function. DRV_ADC_INPUTSET_HANDLE ipHandle; //Handle returned by DRV_ADC_InputSetRegister function. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-200 DRV_ADC_INPUTSET_CONFIG inputSetConfig;//Contains all values to configure the inputset. uint16_t dataBuffer; //Buffer to which the data will be written. /* These initialization values should be based on the requirement of the application and the way it wants the hardware to be operating. Most of these values will be written directly to the hardware registers. */ adcInitData.plibModuleId = ADC_ID_1; adcInitData.acquisitionTime = PLIB_ADC_ACQUISITION_TIME_15_TAD; adcInitData.voltageReference = PLIB_ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS; adcInitData.clockFrequency = 4000000; //4MHz adcInitData.conversionClock = PLIB_ADC_CONV_CLOCK_5_TCY; adcInitData.conversionClockSource = PLIB_ADC_CLOCK_SRC_INTERNAL_RC; adcInitData.conversionTriggerSource = PLIB_ADC_CONVERSION_TRIGGER_INTERNAL_COUNT; adcInitData.dataOutputFormat = PLIB_ADC_OUTPUT_FORMAT_INTEGER_16BIT; adcInitData.interruptSource= PLIB_INT_SOURCE_ADC_1; adcInitData.samplesPerInterrupt = PLIB_ADC_SAMPLE_PER_INTERRUPT_AT_EACH_SAMPLE; myAdcObj = DRV_ADC_Initialize(MY_ADC_INSTANCE, (SYS_MODULE_INIT*)&adcInitData); /* Open a new client. The handle returned by the this function should be used a passing parameter for all the specific client related operations. */ adcHandle = DRV_ADC_Open(MY_ADC_INSTANCE, DRV_IO_INTENT_NONBLOCKING); /* Driver invokes the registered callback function every successful data read. Application can perform an action or do a state change in the callback */ inputSetConfig.callback = adcCallback; inputSetConfig.input = POTENTIOMETER_ANALOG_INPUT; inputSetConfig.errorTolerance = 10; inputSetConfig.samplingFrequency = 40000; ipHandle = DRV_ADC_InputSetRegister ( adcHandle ,inputSetConfig ); /* ADC is not yet enabled. Enable it once the inputset is registered. Starts automatically since auto sample mode is enabled. */ DRV_ADC_Start(adcHandle); while (1) { /* This function can be either called in a sequential way or it could be called from a timer periodically */ triggerAdc(); /* Task function need not be called. Task function is registered as ISR in case of interrpt mode */ DRV_ADC_InputSetRead ( adcHandle, &dataBuffer, 1); /* Once the above function returns success, the data is in 'dataBuffer'. Application can use this data. */ } 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-201 } void adcCallback (void) { // Application can do something here } void triggerAdc(void) { DRV_ADC_OperationSetup(handle, DRV_ADC_START_SAMPLING); /* Give some delay between the two operations. */ for (i=0; i<100; i++); DRV_ADC_OperationSetup(handle, DRV_ADC_START_CONVERSION); } 5.1.2.5 Configuring the Library The configuration of the ADC device driver is based on the file sys_config.h This header file contains the configuration selection for the ADC device driver build. Based on the selections made here and the system setup the ADC device driver will support or not selected features. These configuration settings will apply to all instances of the device driver. This header can be placed anywhere in the application specific folders and the path of this header needs to be presented to the include search for a successful build. Refer to the Applications Overview section for more details. 5.1.2.6 Building the Library Files Name Description drv_adc.c ADC Driver source file. drv_adc_client_multi.c ADC Driver multiple client implementations. drv_adc_client_single.c ADC Driver single client implementations. drv_adc_hw_dynamic.c ADC Driver build variant implementation for the dynamic driver. drv_adc_hw_static.c ADC Driver build variant implementation for the static driver. Description 5.1.2.6.1 drv_adc.c ADC Driver Source File This file implements the ADC Driver Interface routines. While building the driver from source, ALWAYS use this file in the build. File Name drv_adc.c Company Microchip Technology Inc. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-202 5.1.2.6.2 drv_adc_client_multi.c ADC Driver Multiple Client This file implements the functions for the multiple client support. While building the driver from source, use this file in the build when DRV_ADC_CLIENTS_NUMBER is defined in the system configuration or when DRV_ADC_INSTANCES_NUMBER is defined in the system configuration. File Name drv_adc_client_multi.c Company Microchip Technology Inc. 5.1.2.6.3 drv_adc_client_single.c ADC Driver Single Client This file implements the functions for the single client support While building the driver from source, use this file in the build when DRV_ADC_CLIENTS_NUMBER is not defined in system configuration. File Name drv_adc_client_single.c Company Microchip Technology Inc. 5.1.2.6.4 drv_adc_hw_dynamic.c ADC Driver Build Variant implementation for dynamic driver This file defines the build variant implementations for the dynamic driver. While building the driver from source, use this file in the build when DRV_ADC_INSTANCES_NUMBER is defined in the system configuration. File Name drv_adc_hw_dynamic.c Company Microchip Technology Inc. 5.1.2.6.5 drv_adc_hw_static.c ADC Driver build variant implementation for static driver This file defines the build variant implementations for the static driver. While building the driver from source, use this file in the build when DRV_ADC_INSTANCES_NUMBER is not defined in the system configuration. File Name drv_adc_hw_static.c Company Microchip Technology Inc. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-203 5.1.2.7 Library Interface Data Types and Constants Name Description DRV_ADC_CLIENT_STATUS Defines the client-specific status of the ADC driver. DRV_ADC_INIT Defines the data required to initialize or reinitialize the ADC driver. DRV_ADC_INIT_FLAGS Identifies the initialization flags of the ADC module. DRV_ADC_ACQUISITION_TIME Defines the acquisition time. DRV_ADC_ALTERNATE_INPUT_SAMPLING_ENABLE Enable the alternate input sampling feature of the ADC. DRV_ADC_ANALOG_INPUT Defines the analog input channel. DRV_ADC_AUTO_SAMPLING_ENABLE Rnable the suto-sampling feature of the ADC. DRV_ADC_CLIENTS_NUMBER Selects the miximum number of clients. DRV_ADC_CONVERSION_CLOCK_PRESCALER Defines the conversion clock. DRV_ADC_CONVERSION_CLOCK_SOURCE Defines the conversion clock source. DRV_ADC_CONVERSION_TRIGGER_SOURCE Defines the conversion trigger source. DRV_ADC_INDEX ADC static index selection. DRV_ADC_INDEX_0 ADC driver index definitions. DRV_ADC_INDEX_1 This is macro DRV_ADC_INDEX_1. DRV_ADC_INDEX_2 This is macro DRV_ADC_INDEX_2. DRV_ADC_INDEX_COUNT Number of valid ADC driver indices. DRV_ADC_INSTANCES_NUMBER Sets up the maximum number of hardware instances that can be supported. DRV_ADC_INTERNAL_BUFFER_SIZE Define the internal buffer size. DRV_ADC_INTERRUPT_MODE Controls operation of the driver in the interrupt or polled mode. DRV_ADC_INTERRUPT_SOURCE Defines the interrupt source of the static driver. DRV_ADC_PERIPHERAL_ID ADC PLIB ID Selection DRV_ADC_POWER_STATE Controls the power state of the ADC. DRV_ADC_RESULT_FORMAT Defines the data output format. DRV_ADC_SAMPLES_PER_INTERRUPT Define the sample per interrupt. DRV_ADC_STOP_ON_CONVERSION_ENABLE Enable the stop on conversion feature of the ADC. DRV_ADC_VOLTAGE_REFERENCE Defines the voltage reference. Client Core Configuration Functions Name Description DRV_ADC_ClientStatus Gets the current client-specific status the ADC driver. DRV_ADC_Close Closes an opened-instance of the ADC driver. DRV_ADC_InputsRegister Registers an input set with the driver for sampling. DRV_ADC_Open Opens the specified ADC driver instance and returns a handle to it. DRV_ADC_SamplesAvailable Identifies if any the ADC driver has any samples available to read. DRV_ADC_Start Starts the ADC driver sampling and converting analog to digital values. DRV_ADC_Stop Stops the ADC driver from sampling and converting analog to digital values. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-204 Other Functions Name Description DRV_ADC_SampleMaxGet Gets the max sample value. DRV_ADC_SampleMinGet Gets the min sample value. DRV_ADC_SamplesRead Reads the converted sample data from the ADC driver. DRV_ADC_SamplesReadLatest Reads the most recently converted sample data from the ADC driver. System Interaction Functions Name Description DRV_ADC_Deinitialize Deinitializes the specified instance of the ADC driver module. DRV_ADC_Initialize Initializes the ADC driver. DRV_ADC_Reinitialize Reinitializes the ADC instance for the specified module ID. DRV_ADC_Status Provides the current status of the ADC driver module. DRV_ADC_Tasks Maintains the driver's state machine and implements its ISR. Description 5.1.2.7.1 System Interaction Functions 5.1.2.7.1.1 DRV_ADC_Deinitialize Function C void DRV_ADC_Deinitialize( SYS_MODULE_OBJ object ); Description This function deinitializes the specified instance of the ADC driver module, disabling its operation (and any hardware). Invalidates all the internal data. Preconditions The DRV_ADC_Initialize function should have been called before calling this function. Parameters Parameters Description object Driver object handle, returned from DRV_ADC_Initialize Returns None. Remarks Once the Initialize operation has been called, the Deinitialize operation must be called before the Initialize operation can be called again. This function will NEVER block waiting for hardware. If the operation requires time to allow the hardware to complete, this will be reported by the DRV_ADC_Status operation. The system has to use DRV_ADC_Status to find out when the module is in the ready state. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-205 Example SYS_MODULE_OBJ object; // Returned from DRV_ADC_Initialize SYS_STATUS status; DRV_ADC_Deinitialize(object); status = DRV_ADC_Status(object); if (SYS_MODULE_DEINITIALIZED == status) { // Check again later if you need to know // when the driver is deinitialized. } 5.1.2.7.1.2 DRV_ADC_Initialize Function C SYS_MODULE_OBJ DRV_ADC_Initialize( const SYS_MODULE_INDEX drvIndex, const SYS_MODULE_INIT * const init ); Description This function initializes the ADC driver, making it ready for clients to open and use it. Preconditions None. Parameters Parameters Description drvIndex Index for the driver instance to be initialized init Pointer to a data structure containing any data necessary to initialize the driver. This pointer may be null if no data is required because static overrides have been provided. Returns If successful, returns a valid handle to a driver instance object. Otherwise, it returns SYS_MODULE_OBJ_INVALID. Remarks This function must be called before any other ADC function is called. This function should only be called once during system initialization unless DRV_ADC_Deinitialize is called to deinitialize the driver instance. This function will NEVER block for hardware access. If the operation requires time to allow the hardware to re-initialize, it will be reported by the DRV_ADC_Status operation. The system must use DRV_ADC_Status to find out when the driver is in the ready state. Build configuration options may be used to staticaly override options in the "init" sructure and will take precedance over initialization data passed using this function. Example DRV_ADC_INIT init; SYS_MODULE_OBJ objectHandle; // Populate the init structure init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL; init.adcID = ADC_ID_1; 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-206 init.initFlags = DRV_ADC_AUTO_SAMPLING; init.clockFrequency = 4000000; // 4MHz init.acquisitionTime = ADC_ACQUISITION_TIME_15_TAD; init.voltageReference = ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS; init.conversionClockPrescaler = ADC_CONV_CLOCK_5_TCY; init.conversionClockSource = ADC_CLOCK_SRC_INTERNAL_RC; init.conversionTriggerSource = ADC_CONVERSION_TRIGGER_INTERNAL_COUNT; init.samplesPerInterrupt = ADC_SAMPLE_PER_INTERRUPT_AT_EACH_SAMPLE; init.resultFormat = ADC_RESULT_FORMAT_INTEGER_16BIT; init.analogInput = ADC_INPUT_AN2 init.interruptSource = INT_SOURCE_ADC_1; // Initialize the ADC driver objectHandle = DRV_ADC_Initialize(DRV_ADC_INDEX_0, (SYS_MODULE_INIT*)&init); if (SYS_MODULE_OBJ_INVALID == objectHandle) { // Handle error } 5.1.2.7.1.3 DRV_ADC_Reinitialize Function C void DRV_ADC_Reinitialize( SYS_MODULE_OBJ object, const SYS_MODULE_INIT * const init ); Description This function reinitializes and refreshes the hardware for the index instance of the ADC module using the hardware initialization given data. It does not clear or reinitialize internal data structures (although it may change the value of a few appropriate data items necessary to manage the new hardware state). Preconditions The DRV_ADC_Initialize function should have been called before calling this function. Parameters Parameters Description object Driver object handle, returned from the DRV_ADC_Initialize Returns None. Example DRV_ADC_INIT init; SYS_MODULE_OBJ objectHandle; // Returned from DRV_ADC_Initialize SYS_STATUS adcStatus; // Populate the init structure init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL; init.adcID = ADC_ID_1; init.initFlags = DRV_ADC_AUTO_SAMPLING; init.clockFrequency = 4000000; // 4MHz init.acquisitionTime = ADC_ACQUISITION_TIME_15_TAD; init.voltageReference = ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS; init.conversionClockPrescaler = ADC_CONV_CLOCK_5_TCY; init.conversionClockSource = ADC_CLOCK_SRC_INTERNAL_RC; init.conversionTriggerSource = ADC_CONVERSION_TRIGGER_INTERNAL_COUNT; init.samplesPerInterrupt = ADC_SAMPLE_PER_INTERRUPT_AT_EACH_SAMPLE; init.resultFormat = ADC_RESULT_FORMAT_INTEGER_16BIT; init.analogInput = ADC_INPUT_AN2 init.interruptSource = INT_SOURCE_ADC_1; 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-207 // Reinitialize the ADC driver DRV_ADC_Reinitialize(objectHandle, (SYS_MODULE_INIT*)&init); // Check the status of the driver adcStatus = DRV_ADC_Status(myAdcObj); if (SYS_STATUS_BUSY == adcStatus) { // do something else and check back later } else if (SYS_STATUS_ERROR >= adcStatus) { // Handle error } Remarks: This function can be called multiple times to reinitialize the module. This operation can be used to refresh any supported hardware registers as specified by the initialization data or to change the power state of the module. This function will NEVER block for hardware access. If the operation requires time to allow the hardware to reinitialize, it will be reported by the DRV_ADC_Status operation. The system must use DRV_ADC_Status to find out when the driver is in the ready state. Build configuration options may be used to staticaly override options in the "init" sructure and will take precedance over initialization data passed using this function. 5.1.2.7.1.4 DRV_ADC_Status Function C SYS_STATUS DRV_ADC_Status( SYS_MODULE_OBJ object ); Description This function provides the current status of the ADC driver module. Preconditions The DRV_ADC_Initialize function must have been called before calling this function. Parameters Parameters Description object Driver object handle, returned from the DRV_ADC_Initialize Returns SYS_STATUS_READY - Indicates that the driver is busy with a previous system level operation and cannot start another Remarks Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new operations. SYS_STATUS_BUSY - Indicates that the driver is busy with a previous system level operation and cannot start another SYS_STATUS_ERROR - Indicates that the driver is in an error state Any value less than SYS_STATUS_ERROR is also an error state. SYS_MODULE_DEINITIALIZED - Indicates that the driver has been deinitialized This value is less than SYS_STATUS_ERROR 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-208 The this operation can be used to determine when any of the driver's module level operations has completed. If the status operation returns SYS_STATUS_BUSY, the a previous operation has not yet completed. Once the status operation returns SYS_STATUS_READY, any previous operations have completed. The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state. This function will NEVER block waiting for hardware. If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the deinitialize operation will need to be called, followed by the initialize operation to return to normal operations. Example SYS_MODULE_OBJ object; // Returned from DRV_TMR_Initialize SYS_STATUS status; status = DRV_ADC_Status(object); else if (SYS_STATUS_ERROR >= status) { // Handle error } 5.1.2.7.1.5 DRV_ADC_Tasks Function C void DRV_ADC_Tasks( SYS_MODULE_OBJ object ); Description This function is used to maintain the driver's internal state machine and implement its ISR for interrupt-driven implementations. Preconditions The DRV_ADC_Initialize function must have been called for the specified ADC driver instance. Parameters Parameters Description object Object handle for the specified driver instance (returned from DRV_ADC_Initialize) Returns None Remarks This function is normally not called directly by an application. It is called by the system's Tasks function (SYS_Tasks) or by the apropriate raw ISR. This function may excute in an ISR context and will never block or access any resources that may cause it to block. Example SYS_MODULE_OBJ object; // Returned from DRV_ADC_Initialize while (true) { DRV_ADC_Tasks (object); // Do other tasks } 5.1.2.7.2 Client Core Configuration Functions 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-209 5.1.2.7.2.1 DRV_ADC_ClientStatus Function C DRV_ADC_CLIENT_STATUS DRV_ADC_ClientStatus( DRV_HANDLE handle ); Description This function gets the client-specfic status of the ADC driver associated with the given handle. Preconditions The DRV_ADC_Initialize function must have been called. DRV_ADC_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open function Returns A DRV_ADC_CLIENT_STATUS value describing the current status of the driver. Remarks This function will not block for hardware access and will immediately return the current status. Example DRV_HANDLE handle; // Returned from DRV_ADC_Open DRV_ADC_CLIENT_STATUS status; status = DRV_ADC_ClientStatus(handle); if(DRV_ADC_CLIENT_STATUS_ERROR >= status) { // Handle the error } 5.1.2.7.2.2 DRV_ADC_Close Function C void DRV_ADC_Close( DRV_HANDLE handle ); Description This function closes an opened-instance of the ADC driver, invalidating the handle. Preconditions The DRV_ADC_Initialize function must have been called for the specified ADC driver instance. DRV_ADC_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open function Returns None 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-210 Remarks After calling this function, the handle passed in "handle" must not be used with any of the remaining driver functions. A new handle must be obtained by calling DRV_ADC_Open before the caller may use the driver again. If DRV_IO_INTENT_BLOCKING was requested and the driver was built appropriately to support blocking behavior call may block until the operation is complete. If DRV_IO_INTENT_NON_BLOCKING request the driver client can call the DRV_ADC_Status operation to find out when the module is in the ready state (the handle is no longer valid). Usually there is no need for the driver client to verify that the Close operation has completed. Example DRV_HANDLE handle; // Returned from DRV_ADC_Open DRV_ADC_Close(handle); 5.1.2.7.2.3 DRV_ADC_InputsRegister Function C void DRV_ADC_InputsRegister( DRV_HANDLE handle, uint32_t inputsMask ); Description This function registers an input set with the driver for sampling. Preconditions The DRV_ADC_Initialize function must have been called for the specified ADC device instance and the DRV_ADC_Status must have returned SYS_STATUS_READY. DRV_ADC_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open function inputsMask Mask bits recognising the various Analog Channels Returns None. Remarks None. Example DRV_HANDLE handle; // Returned from DRV_ADC_Open DRV_ADC_InputsRegister (handle, ADC_INPUT_AN2|ADC_INPUT_AN3); 5.1.2.7.2.4 DRV_ADC_Open Function C DRV_HANDLE DRV_ADC_Open( const SYS_MODULE_INDEX drvIndex, const DRV_IO_INTENT intent ); 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-211 Description This function opens the specified ADC driver instance and provides a handle that must be provided to all other client-level operations to identify the caller and the instance of the driver. Preconditions The DRV_ADC_Initialize function must have been called before calling this function. Parameters Parameters Description drvIndex Identifier for the object instance to be opened intent Zero or more of the values from the enumeration DRV_IO_INTENT "ORed" together to indicate the intended use of the driver Returns If successful, the function returns a valid open-instance handle (a number identifying both the caller and the module instance). If an error occurs, the return value is DRV_HANDLE_INVALID. Remarks The handle returned is valid until the DRV_ADC_Close function is called. This function will NEVER block waiting for hardware. If the DRV_IO_INTENT_BLOCKING is requested and the driver was built appropriately to support blocking behavior, other client-level operations may block waiting on hardware until they are complete. If DRV_IO_INTENT_NON_BLOCKING is requested the driver client can call the DRV_ADC_ClientStatus operation to find out when the module is in the ready state. If the requested intent flags are not supported, the function will return DRV_HANDLE_INVALID. Example DRV_HANDLE handle; handle = DRV_ADC_Open(DRV_ADC_INDEX_0, DRV_IO_INTENT_EXCLUSIVE); if (DRV_HANDLE_INVALID == handle) { // Unable to open the driver } 5.1.2.7.2.5 DRV_ADC_SamplesAvailable Function C bool DRV_ADC_SamplesAvailable( DRV_HANDLE handle ); Description This function identifies if any the ADC driver has any samples available to read. Preconditions The DRV_ADC_Initialize function must have been called. DRV_ADC_Open must have been called to obtain a valid opened device handle. The desired analog input set must have been selected by calling DRV_ADC_InputsRegister. DRV_ADC_Start must have been called to start the driver sampling and converting analog input samples to digital values. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-212 Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open function Returns • true - If one or more samples are available for the registered input set • false - If no samples are available Remarks None. Example DRV_HANDLE handle; // Returned from DRV_ADC_Open DRV_ADC_SAMPLE buffer; // An input set must have been registered and the ADC started. if (DRV_ADC_SamplesAvailable(handle)) { DRV_ADC_SamplesRead(handle, &buffer, sizeof(buffer)); } 5.1.2.7.2.6 DRV_ADC_Start Function C void DRV_ADC_Start( DRV_HANDLE handle ); Description This function starts the ADC driver sampling the selected analog inputs and converting the samples to digital values. Preconditions The DRV_ADC_Initialize function must have been called. DRV_ADC_Open must have been called to obtain a valid opened device handle. The desired analog input set must have been selected by calling DRV_ADC_InputsRegister. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open function Returns None. Remarks Call DRV_ADC_SamplesAvailable to find out when one or more samples is available. Example DRV_HANDLE handle; // Returned from DRV_ADC_Open // Use DRV_ADC_InputsRegister to register the desired inputs. DRV_ADC_Start(handle); 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-213 5.1.2.7.2.7 DRV_ADC_Stop Function C void DRV_ADC_Stop( DRV_HANDLE handle ); Description This function stops the ADC driver from sampling analog inputs and converting the samples to digital values. Preconditions The DRV_ADC_Initialize function must have been called. DRV_ADC_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open function Returns None. Remarks Call DRV_ADC_Start to restart sampling and conversion of analog inputs to digital values. Example DRV_HANDLE handle; // Returned from DRV_ADC_Open DRV_ADC_Stop(handle); 5.1.2.7.3 Other Functions 5.1.2.7.3.1 DRV_ADC_SampleMaxGet Function C ADC_SAMPLE DRV_ADC_SampleMaxGet( DRV_HANDLE handle ); Description This function returns the max sample value. Preconditions The DRV_ADC_Initialize function must have been called. DRV_ADC_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open function Returns Max sample value. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-214 Remarks None Example DRV_HANDLE handle; // Returned from DRV_ADC_Open ADC_SAMPLE maxValue, minValue; maxValue = DRV_ADC_SampleMaxGet(handle); minValue = DRV_ADC_SampleMinGet(handle); adcRange = maxValue - minValue; 5.1.2.7.3.2 DRV_ADC_SampleMinGet Function C ADC_SAMPLE DRV_ADC_SampleMinGet( DRV_HANDLE handle ); Description This function returns the min sample value. Preconditions The DRV_ADC_Initialize function must have been called. DRV_ADC_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open function Returns Min sample value. Remarks None Example DRV_HANDLE handle; // Returned from DRV_ADC_Open ADC_SAMPLE maxValue, minValue; maxValue = DRV_ADC_SampleMaxGet(handle); minValue = DRV_ADC_SampleMinGet(handle); adcRange = maxValue - minValue; 5.1.2.7.3.3 DRV_ADC_SamplesRead Function C unsigned short DRV_ADC_SamplesRead( DRV_HANDLE handle, ADC_SAMPLE * buffer, unsigned short bufferSize ); Description This function reads converted sample data from the ADC driver into the given buffer. How many samples depends on how many samples are available and on the relative sizes of the samples and the buffer passed in. Zero (0) samples are copied if the bufferSize is less than the size of a complete set of samples for the registered inputs. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-215 N sets of samples where the bufferSize / size of a complete set of samples = N, unless less than N samples are currently available. Then, the number of samples currently available are copied. Preconditions The DRV_ADC_Initialize function must have been called. DRV_ADC_Open must have been called to obtain a valid opened device handle. The desired analog input set must have been selected by calling DRV_ADC_InputsRegister. DRV_ADC_Start must have been called to start the driver sampling and converting analog input samples to digital values. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open function buffer A pointer to the buffer to where the sample data will be copied bufferSize Size of the buffer (in bytes) Returns Number of bytes of sample data copied to the specified buffer. Remarks The DRV_ADC_SamplesAvailable function can be used to determine if any sample data is available. Calling this function removes the samples from the driver's internal buffer queue of samples. Example DRV_HANDLE handle; // Returned from DRV_ADC_Open ADC_SAMPLE buffer; // An input set must have been registered and the ADC started. if (DRV_ADC_SamplesAvailable(handle)) { DRV_ADC_SamplesRead(handle, &buffer, sizeof(buffer)); } 5.1.2.7.3.4 DRV_ADC_SamplesReadLatest Function C unsigned short DRV_ADC_SamplesReadLatest( DRV_HANDLE handle, ADC_SAMPLE * buffer, unsigned short bufferSize ); Description This function reads only the most recenly converted sample data from the ADC driver into the given buffer. Only the data for a single set of samples for the registerd inputs is copied to the caller's buffer. If the buffer size is less than the size of a complete set of samples for the registerd inputs, no data is copied to the caller's buffer. Also, no sample data is copied to the caller's buffer if no sample data is currently available. Preconditions The DRV_ADC_Initialize function must have been called. DRV_ADC_Open must have been called to obtain a valid opened device handle. The desired analog input set must have been selected by calling DRV_ADC_InputsRegister. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-216 DRV_ADC_Start must have been called to start the driver sampling and converting analog input samples to digital values. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open function buffer A pointer to the buffer to where the sample data will be copied bufferSize Size of the buffer (in bytes) Returns Number of bytes of sample data copied to the specified buffer. Remarks The DRV_ADC_SamplesAvailable function can be used to determine if any sample data is available. This function does not remove any data from the driver's internal buffer queue of sample data. Example DRV_HANDLE handle; // Returned from DRV_ADC_Open ADC_SAMPLE buffer; // An input set must have been registered and the ADC started. if (DRV_ADC_SamplesAvailable(handle)) { DRV_ADC_SamplesReadLatest(handle, &buffer, sizeof(buffer)); } 5.1.2.7.4 Data Types and Constants 5.1.2.7.4.1 DRV_ADC_CLIENT_STATUS Enumeration C typedef enum { DRV_ADC_CLIENT_STATUS_STARTED, DRV_ADC_CLIENT_STATUS_STOPPED, DRV_ADC_CLIENT_STATUS_READY, DRV_ADC_CLIENT_STATUS_BUSY, DRV_ADC_CLIENT_STATUS_INVALID, DRV_ADC_CLIENT_STATUS_OVERFLOW, DRV_ADC_CLIENT_STATUS_BUFFER_TOO_SMALL } DRV_ADC_CLIENT_STATUS; Description ADC Client Status This enumeration defines the client-specific status codes of the ADC driver. Members Members Description DRV_ADC_CLIENT_STATUS_STARTED ADC Started DRV_ADC_CLIENT_STATUS_STOPPED stopped on error DRV_ADC_CLIENT_STATUS_READY Driver OK, ready for client operations DRV_ADC_CLIENT_STATUS_BUSY An operation is currently in progress DRV_ADC_CLIENT_STATUS_INVALID Client in an invalid (or un-opened) state DRV_ADC_CLIENT_STATUS_OVERFLOW Driver Overflowed 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-217 DRV_ADC_CLIENT_STATUS_BUFFER_TOO_SMALL Input Set Read Buffer Too Small Remarks Returned by the DRV_ADC_ClientStatus function. 5.1.2.7.4.2 DRV_ADC_INIT Structure C typedef struct { SYS_MODULE_INIT moduleInit; ADC_MODULE_ID adcId; DRV_ADC_INIT_FLAGS initFlags; uint32_t clockFrequency; ADC_ACQUISITION_TIME acquisitionTime; ADC_VOLTAGE_REFERENCE voltageReference; ADC_CONVERSION_CLOCK conversionClockPrescaler; ADC_CLOCK_SOURCE conversionClockSource; ADC_CONVERSION_TRIGGER_SOURCE conversionTriggerSource; ADC_SAMPLES_PER_INTERRUPT samplesPerInterrupt; ADC_RESULT_FORMAT resultFormat; ADC_INPUTS_POSITIVE analogInput; INT_SOURCE interruptSource; } DRV_ADC_INIT; Description ADC Driver Initialization Data This structure defines the data required to initialize or reinitialize the ADC driver. Members Members Description SYS_MODULE_INIT moduleInit; System module initialization ADC_MODULE_ID adcId; Identifies timer hardware module (PLIB-level) ID DRV_ADC_INIT_FLAGS initFlags; Initialization Flags uint32_t clockFrequency; Clock Frequency ADC_ACQUISITION_TIME acquisitionTime; Acquisition Time ADC_VOLTAGE_REFERENCE voltageReference; Voltage Reference Selection ADC_CONVERSION_CLOCK conversionClockPrescaler; Clock Setup for the Conversion ADC_CLOCK_SOURCE conversionClockSource; Clock Source for Conversion ADC_CONVERSION_TRIGGER_SOURCE conversionTriggerSource; Conversion Trigger Source ADC_SAMPLES_PER_INTERRUPT samplesPerInterrupt; Samples Per Interrupt valid values = 0- 15 ADC_RESULT_FORMAT resultFormat; Result Format ADC_INPUTS_POSITIVE analogInput; Input Channel to convert INT_SOURCE interruptSource; Interrupt Source for the module Remarks Not all init features are available for all devices. Refer to the specific data sheet to determine availability. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-218 5.1.2.7.4.3 DRV_ADC_INIT_FLAGS Enumeration C typedef enum { DRV_ADC_STOP_CONVERSION_ON_INTERRUPT, DRV_ADC_ALTERNATE_INPUT_SAMPLING, DRV_ADC_AUTO_SAMPLING, DRV_ADC_MANUAL_SAMPLING } DRV_ADC_INIT_FLAGS; Description ADC Initialization Flags This data type identifies the initialization flags of the ADC module. Members Members Description DRV_ADC_STOP_CONVERSION_ON_INTERRUPT Stops the conversion on the interrupt DRV_ADC_ALTERNATE_INPUT_SAMPLING Alternate Input Sampling DRV_ADC_AUTO_SAMPLING Begin sampling automaticaly after previous conversion DRV_ADC_MANUAL_SAMPLING Manual Sampling Remarks Not all modes are available on all devices. Refer to the specific data sheet to determine availability. 5.1.2.7.4.4 DRV_ADC_ACQUISITION_TIME Macro C #define DRV_ADC_ACQUISITION_TIME ADC_ACQUISITION_TIME_4_TAD Description ADC Acquisition Time This macro defines the acquistition time of the ADC driver. This provides static override of the dynamic selection of the acquisition time. If this macro is defined, this will be used for setting up the acquisition time and not the acquisition time value provided by DRV_ADC_INIT. Remarks None. 5.1.2.7.4.5 DRV_ADC_ALTERNATE_INPUT_SAMPLING_ENABLE Macro C #define DRV_ADC_ALTERNATE_INPUT_SAMPLING_ENABLE false Description ADC Alternate Input Sampling Enable This macro enables the alternate input sampling feature of the ADC. This macro can take the following values: • true - Enables the alternate Input sampling feature of the ADC • false - Disables the alternate Input sampling feature of the ADC • DRV_CONFIG_NOT_SUPPORTED - When the feature is not supported on the instance 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-219 Remarks None. 5.1.2.7.4.6 DRV_ADC_ANALOG_INPUT Macro C #define DRV_ADC_ANALOG_INPUT ADC_INPUT_AN2 Description ADC Analog input channel This macro defines the analog input channel for the ADC driver. This provides static override of the dynamic selection of the analog input. If this macro is defined, this will be used for setting up the analog input and not the analog input value provided by DRV_ADC_INIT. Remarks None. 5.1.2.7.4.7 DRV_ADC_AUTO_SAMPLING_ENABLE Macro C #define DRV_ADC_AUTO_SAMPLING_ENABLE true Description ADC Auto Sampling Enable This macro enables the auto-sampling feature of the ADC. This macro can take the following values: • true - Enables the auto-sampling feature of the ADC • false - Disables the auto-sampling feature of the ADC • DRV_CONFIG_NOT_SUPPORTED - When the feature is not supported on the instance Remarks None. 5.1.2.7.4.8 DRV_ADC_CLIENTS_NUMBER Macro C #define DRV_ADC_CLIENTS_NUMBER 1 Description ADC Maximum Number of Clients This definition selectd the maximum number of clients that the ADC driver can support at run time. Remarks None. 5.1.2.7.4.9 DRV_ADC_CONVERSION_CLOCK_PRESCALER Macro C #define DRV_ADC_CONVERSION_CLOCK_PRESCALER ADC_CONV_CLOCK_4_TCY 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-220 Description ADC Conversion Clock This macro defines the conversion clock for the ADC driver. This provides static override of the dynamic selection of the conversion clock. If this macro is defined, this will be used for setting up the conversion clock and not the conversion clock value provided by DRV_ADC_INIT. Remarks None. 5.1.2.7.4.10 DRV_ADC_CONVERSION_CLOCK_SOURCE Macro C #define DRV_ADC_CONVERSION_CLOCK_SOURCE ADC_CLOCK_SRC_SYSTEM_CLOCK Description ADC Conversion Clock Source This macro defines the conversion clock source for the ADC driver. This provides static override of the dynamic selection of the conversion clock source. If this macro is defined, this will be used for setting up the conversion clock source and not the conversion clock source value provided by DRV_ADC_INIT. Remarks None. 5.1.2.7.4.11 DRV_ADC_CONVERSION_TRIGGER_SOURCE Macro C #define DRV_ADC_CONVERSION_TRIGGER_SOURCE ADC_CONVERSION_TRIGGER_INTERNAL_COUNT Description Conversion Trigger Source This macro defines the conversion trigger source for the ADC driver. This provides static override of the dynamic selection of the conversion trigger source. If this macro is defined, this will be used for setting up the conversion trigger source and not the conversion trigger source value provided by DRV_ADC_INIT. Remarks None. 5.1.2.7.4.12 DRV_ADC_INDEX Macro C #define DRV_ADC_INDEX DRV_ADC_INDEX_0 Description ADC Static Index Selection ADC static index selection for the driver object reference. Remarks This index is required to make a reference to the driver object. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-221 5.1.2.7.4.13 DRV_ADC_INDEX_0 Macro C #define DRV_ADC_INDEX_0 0 Description Driver ADC Module Index Numbers These constants provide ADC driver index definitions. Remarks These constants should be used in place of hard-coded numeric literals. These values should be passed into the DRV_ADC_Initialize function to identify the driver instance in use. 5.1.2.7.4.14 DRV_ADC_INDEX_1 Macro C #define DRV_ADC_INDEX_1 1 Description This is macro DRV_ADC_INDEX_1. 5.1.2.7.4.15 DRV_ADC_INDEX_2 Macro C #define DRV_ADC_INDEX_2 2 Description This is macro DRV_ADC_INDEX_2. 5.1.2.7.4.16 DRV_ADC_INDEX_COUNT Macro C #define DRV_ADC_INDEX_COUNT _ADC_EXISTS Description Driver ADC Driver Module Index Count This constant identifies ADC driver index definitions. Remarks This constant should be used in place of hard-coded numeric literals. This value is device-specific. 5.1.2.7.4.17 DRV_ADC_INSTANCES_NUMBER Macro C #define DRV_ADC_INSTANCES_NUMBER 1 Description ADC hardware instance configuration This macro sets up the maximum number of hardware instances that can be supported. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-222 Remarks None. 5.1.2.7.4.18 DRV_ADC_INTERNAL_BUFFER_SIZE Macro C #define DRV_ADC_INTERNAL_BUFFER_SIZE 2 Description ADC Internal buffer size This macro defines the internal buffer size. Remarks None. 5.1.2.7.4.19 DRV_ADC_INTERRUPT_MODE Macro C #define DRV_ADC_INTERRUPT_MODE true Description ADC Interrupt And Polled Mode Operation Control This macro controls the operation of the driver in the interrupt mode of operation. The possible values of this macro are: • true - Select if interrupt mode of adc operation is desired • false - Select if polling mode of adc operation is desired Not defining this option to true or false will result in a build error. Remarks None. 5.1.2.7.4.20 DRV_ADC_INTERRUPT_SOURCE Macro C #define DRV_ADC_INTERRUPT_SOURCE PLIB_INT_SOURCE_ADC_1 Description ADC Interrupt Source Macro to define the interrupt source of the static driver. Remarks Refer to the Interrupt Peripheral Library document for more information on the PLIB_INT_SOURCE enumeration. 5.1.2.7.4.21 DRV_ADC_PERIPHERAL_ID Macro C #define DRV_ADC_PERIPHERAL_ID ADC_ID_1 Description ADC PLIB ID Selection 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-223 This macro selects the ADC PLIB ID Selection. This is an intialization override of the adcID member of the intialization configuration. Remarks None. 5.1.2.7.4.22 DRV_ADC_POWER_STATE Macro C #define DRV_ADC_POWER_STATE SYS_MODULE_POWER_IDLE_STOP Description ADC power state configuration This macro controls the power state of the ADC. Remarks This feature may not be available in the device or the ADC module selected. 5.1.2.7.4.23 DRV_ADC_RESULT_FORMAT Macro C #define DRV_ADC_RESULT_FORMAT ADC_RESULT_FORMAT_INTEGER_16BIT Description ADC Data Output Format This macro defines the data output format for the ADC driver. This provides static override of the dynamic selection of the data output format. If this macro is defined, this will be used for setting up the data output format and not the data output format value provided by DRV_ADC_INIT. Remarks None. 5.1.2.7.4.24 DRV_ADC_SAMPLES_PER_INTERRUPT Macro C #define DRV_ADC_SAMPLES_PER_INTERRUPT 2 Description Samples per Interrupt This macro defines the samples per interrupt of the ADC driver. This provides static override of the dynamic selection of the sample per interrupt. If this macro is defined, this will be used for setting up the samples per interrupt and not the samples per interrupt value provided by DRV_ADC_INIT. Remarks Select this size based on the device available and the number of samples that are required to form a set. 5.1.2.7.4.25 DRV_ADC_STOP_ON_CONVERSION_ENABLE Macro C #define DRV_ADC_STOP_ON_CONVERSION_ENABLE false 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-224 Description ADC Stop on conversion Enable This macro enables the stop on conversion feature of the ADC. This macro can take the following values: • true - Enables the ADC to stop on conversion • false - Disables the ADC to stop on conversion • DRV_CONFIG_NOT_SUPPORTED - When the feature is not supported on the instance Remarks None. 5.1.2.7.4.26 DRV_ADC_VOLTAGE_REFERENCE Macro C #define DRV_ADC_VOLTAGE_REFERENCE ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS Description ADC Voltage Reference This macro defines the voltage reference of the ADC driver. This provides static override of the dynamic selection of the voltage reference. If this macro is defined, this will be used for setting up the voltage reference and not the voltage reference value provided by DRV_ADC_INIT. Remarks None. 5.1.2.8 Files Files Name Description drv_adc.h ADC Driver interface definition. Description 5.1.2.8.1 drv_adc.h ADC Driver Interface Definition The ADC device driver provides a simple interface to manage the ADC modules on Microchip microcontrollers. This file defines the interface definition for the ADC driver. Enumerations Name Description DRV_ADC_CLIENT_STATUS Defines the client-specific status of the ADC driver. DRV_ADC_INIT_FLAGS Identifies the initialization flags of the ADC module. 5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library 5-225 Functions Name Description DRV_ADC_ClientStatus Gets the current client-specific status the ADC driver. DRV_ADC_Close Closes an opened-instance of the ADC driver. DRV_ADC_Deinitialize Deinitializes the specified instance of the ADC driver module. DRV_ADC_Initialize Initializes the ADC driver. DRV_ADC_InputsRegister Registers an input set with the driver for sampling. DRV_ADC_Open Opens the specified ADC driver instance and returns a handle to it. DRV_ADC_Reinitialize Reinitializes the ADC instance for the specified module ID. DRV_ADC_SampleMaxGet Gets the max sample value. DRV_ADC_SampleMinGet Gets the min sample value. DRV_ADC_SamplesAvailable Identifies if any the ADC driver has any samples available to read. DRV_ADC_SamplesRead Reads the converted sample data from the ADC driver. DRV_ADC_SamplesReadLatest Reads the most recently converted sample data from the ADC driver. DRV_ADC_Start Starts the ADC driver sampling and converting analog to digital values. DRV_ADC_Status Provides the current status of the ADC driver module. DRV_ADC_Stop Stops the ADC driver from sampling and converting analog to digital values. DRV_ADC_Tasks Maintains the driver's state machine and implements its ISR. Macros Name Description DRV_ADC_INDEX_0 ADC driver index definitions. DRV_ADC_INDEX_1 This is macro DRV_ADC_INDEX_1. DRV_ADC_INDEX_2 This is macro DRV_ADC_INDEX_2. DRV_ADC_INDEX_COUNT Number of valid ADC driver indices. Structures Name Description DRV_ADC_INIT Defines the data required to initialize or reinitialize the ADC driver. File Name drv_adc.h Company Microchip Technology Inc. 5.1.3 Ethernet MAC Driver Library 5.1.3.1 Introduction Ethernet (Media Access) Controller Driver Library for 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-226 Microchip Microcontrollers This library provides a driver-level abstraction of the on-chip Ethernet Controller found on many PIC32 devices. The "Host-To-Network" layer of a TCP/IP stack organization covers the Data Link and Physical Layers of the standard OSI stack. The Ethernet Controller provides the Data Link or Media Access Control Layer, in addition to other functions discussed below. An external Ethernet "PHY" provides the Physical layer, providing conversion between the digital and analog. Description The PIC32 Ethernet Controller is a bus master module that interfaces with an off-chip PHY in order to implement a complete Ethernet node in a system. The following are some of the key features of this module: • Supports 10/100 Ethernet • Full-Duplex and Half-Duplex operation • Broadcast, Multicast and Unicast packets • Manual and automatic flow control • Supports Auto-MDIX enabled PHYs • Reduced Media Independent Interface (RMII) and Media Independent Interface (MII) PHY data interfaces • Performance statistics metrics in hardware. • RAM descriptor based DMA operation for both receive and transmit path • Fully configurable interrupts • Configurable receive packet filtering using: • 64-bit Hash Table • 64-byte Pattern Match • Magic Packet™Filtering • Runt Packet Detection and Filtering • Supports Packet Payload Checksum calculation • CRC Check Support for the Serial Management Interface (SMI) (also known as the MIIM interface) is provided by the Ethernet PHY Driver Library. 5.1.3.2 Release Notes MPLAB Harmony Version: v0.70b Ethernet MAC Library Version : 7.10 Release Date: 18Nov2013 New This Release: This is the first release of the library. The interface can change in the beta and\or 1.0 release. Known Issues: Nothing to report in this release. 5.1.3.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-227 licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 5.1.3.4 Using the Library This topic describes the basic architecture of the Ethernet MAC Driver Library and provides information and examples on how to use it. Interface Header File: drv_ethmac.h The interface to the Ethernet MAC library is defined in the "drv_ethmac.h" header file. This file is included by the "drv_ethmac.h" file. Any C language source (.c) file that uses the Ethernet MAC Driver Library should include "drv.h". Library File: The Ethernet MAC Driver Library archive (.a) file is installed with MPLAB Harmony. Please refer to the MPLAB Harmony Overview for how the library interacts with the framework. 5.1.3.4.1 Abstraction Model The Ethernet Controller provides the modules needed to implement a 10/100 Mbps Ethernet node using an external Ethernet PHY chip. The PHY chip provides a digital-analog interface as part of the Physical Layer and the controller provides the Media Access Controller (MAC) layer above the PHY. As shown in Figure 1, the Ethernet Controller consists of the following modules: • Media Access Control (MAC) block: Responsible for implementing the MAC functions of the Ethernet IEEE 802.3 Specification • Flow Control (FC) block: Responsible for control of the transmission of PAUSE frames. (Reception of PAUSE frames is handled within the MAC.) • RX Filter (RXF) block: This module performs filtering on every receive packet to determine whether each packet should be accepted or rejected • TX DMA/TX Buffer Management Engine: The TX DMA and TX Buffer Management engines perform data transfers from the memory (using descriptor tables) to the MAC Transmit Interface • RX DMA/RX Buffer Management Engine: The RX DMA and RX Buffer Management engines transfer receive packets from the MAC to the memory (using descriptor tables) 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-228 Figure 1: Ethernet Controller Block Diagram For completeness, we also need to look at the interface diagram of a representative Ethernet PHY. As shown in Figure 2, the PHY has two interfaces, one for configuring and managing the PHY (SMI/MIIM) and another for transmit and receive data (RMII or MII). The SMI/MIIM interface is the responsibility of the Ethernet PHY Driver Library. When setting up the Ethernet PHY this library calls primitives from the Ethernet PHY Driver library. The RMII/MII interface is the responsibility of the Ethernet MAC Driver Library (this library). 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-229 Figure 2: Ethernet PHY Interfaces 5.1.3.4.2 Library Overview Refer to the section Driver Overview for how the driver operates in a system. The library interface routines are divided into various sub-sections, each of sub-section addresses one of the blocks or the overall operation of the Ethernet MAC Driver Library. Library Interface Section Description Client Level Functions PIC32MACOpen, PIC32MACClose, and PIC32MACSetup to support the TCP/IP Stack. Plus link status and power options. Get and Put Functions Get/Put functions for bytes, byte arrays, and Ethernet headers. Base Address and Buffer Size Functions Base address and sizes for buffers. Receive Functions Receive routines. Transmit Functions Transmit routines. Events Ethernet event support routines. Other Functions Checksum support, memory copying, version support. Data Types and Constants Typedefs and #defines. 5.1.3.4.3 MPLAB Harmony vs. Unified Stack Functions The following is a cross-reference linking MPLAB Harmony functions with functions from the legacy TCP/IP Stack: 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-230 MPLAB Harmony Function: MCHP_tcpip_unified Function: DRV_ETHMAC_BaseAddrTxGet DRV_ETHMAC_RxPacketDiscard DRV_ETHMAC_EventAck DRV_ETHMAC_EventDeInit DRV_ETHMAC_EventInit DRV_ETHMAC_EventNotifyClear DRV_ETHMAC_EventNotifyHandlerSet DRV_ETHMAC_EventNotifySet DRV_ETHMAC_EventPendingGet DRV_ETHMAC_ByteArrayGet DRV_ETHMAC_HeaderGet DRV_ETHMAC_IPBufferChecksumCalc DRV_ETHMAC_LinkCheck DRV_ETHMAC_MemoryCopyIsDone DRV_ETHMAC_PIC32MACClose DRV_ETHMAC_PIC32MACOpen DRV_ETHMAC_PIC32MACSetup DRV_ETHMAC_PIC32MACTeardown DRV_ETHMAC_PowerMode DRV_ETHMAC_ByteArrayPut DRV_ETHMAC_HeaderPut DRV_ETHMAC_ReadPointerBaseSet DRV_ETHMAC_ReadPointerSet DRV_ETHMAC_RxChecksumCalc DRV_ETHMAC_RxHashTableEntrySet DRV_ETHMAC_RxReadPointerGet DRV_ETHMAC_RxReadPointerSet DRV_ETHMAC_TxBufferFlush DRV_ETHMAC_TxIsReady DRV_ETHMAC_VersionGet DRV_ETHMAC_VersionStrGet DRV_ETHMAC_WritePointerSet PIC32MACGetTxBaseAddr PIC32MACDiscardRx PIC32MACEventAck PIC32MACEventDeInit PIC32MACEventInit PIC32TCPIP_MAC_EventNotifyClear PIC32MACEventSetNotifyHandler PIC32MACEventSetNotifyEvents PIC32MACEventGetPending PIC32MACGetArray PIC32MACGetHeader PIC32MACCalcIPBufferChecksum PIC32MACCheckLink PIC32MACIsMemCopyDone PIC32MACClose PIC32MACOpen PIC32MACInitialize PIC32MACDeinitialize PIC32MACPowerMode PIC32MACPutArray PIC32MACPutHeader PIC32MACSetBaseReadPtr PIC32MACSetReadPtr PIC32MACCalcRxChecksum PIC32MACSetRXHashTableEntry PIC32MACGetReadPtrInRx PIC32MACSetReadPtrInRx PIC32MACFlush PIC32MACIsTxReady -none- -nonePIC32MACSetWritePtr 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-231 MCHP_tcpip_unified Function MPLAB Harmony Function: PIC32MACCalcIPBufferChecksum PIC32MACCalcRxChecksum PIC32MACCheckLink PIC32MACDeinitialize PIC32MACDiscardRx PIC32MACEventAck PIC32MAC_EventNotifyClear PIC32MACEventDeInit PIC32MACEventGetPending PIC32MACEventInit PIC32MACEventSetNotifyEvents PIC32MACEventSetNotifyHandler PIC32MACFlush PIC32MACGetArray PIC32MACGetHeader PIC32MACGetReadPtrInRx PIC32MACGetTxBaseAddr PIC32MACIsMemCopyDone PIC32MACIsTxReady PIC32MACDeinitialize PIC32MACInitialize PIC32MACOpen PIC32MACClose PIC32MACPowerMode PIC32MACPutArray PIC32MACPutHeader PIC32MACSetBaseReadPtr PIC32MACSetRXHashTableEntry PIC32MACSetReadPtr PIC32MACSetReadPtrInRx PIC32MACSetWritePtr DRV_ETHMAC_IPBufferChecksumCalc DRV_ETHMAC_RxChecksumCalc DRV_ETHMAC_LinkCheck DRV_ETHMAC_PIC32MACTeardown DRV_ETHMAC_RxPacketDiscard DRV_ETHMAC_EventAck DRV_ETHMAC_EventNotifyClear DRV_ETHMAC_EventDeInit DRV_ETHMAC_EventPendingGet DRV_ETHMAC_EventInit DRV_ETHMAC_EventNotifySet DRV_ETHMAC_EventNotifyHandlerSet DRV_ETHMAC_TxBufferFlush DRV_ETHMAC_ByteArrayGet DRV_ETHMAC_HeaderGet DRV_ETHMAC_RxReadPointerGet DRV_ETHMAC_BaseAddrTxGet DRV_ETHMAC_MemoryCopyIsDone DRV_ETHMAC_TxIsReady DRV_ETHMAC_PIC32MACTeardown DRV_ETHMAC_PIC32MACSetup DRV_ETHMAC_PIC32MACOpen DRV_ETHMAC_PIC32MACClose DRV_ETHMAC_PowerMode DRV_ETHMAC_ByteArrayPut DRV_ETHMAC_HeaderPut DRV_ETHMAC_ReadPointerBaseSet DRV_ETHMAC_RxHashTableEntrySet DRV_ETHMAC_ReadPointerSet DRV_ETHMAC_RxReadPointerSet DRV_ETHMAC_WritePointerSet DRV_ETHMAC_VersionGet DRV_ETHMAC_VersionStrGet 5.1.3.4.4 Support for Legacy "Ethernet Controller Library" These routines (DRV_ETHMAC_Legacy*) provide MPLAB Harmony support for applications that use the "Ethernet Controller Library for Microchip PIC32MX Microcontrollers" that is installed with XC32 compilers. (See Microchip\xc32\v1.20\docs\pic32-lib-help\hlpETH.chm for information on this legacy support.) For some functions the argument list is the same, but for others the addition of an index value from the ETH_MODULE_ID enumeration has been added to make the function work from within the context of this MPLAB Harmony driver. 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-232 Legacy Controller Library MPLAB Harmony EthClose EthDescriptorGetBuffer EthDescriptorsPoolAdd EthDescriptorsPoolCleanUp EthDescriptorsPoolRemove EthEventsClr EthEventsEnableClr EthEventsEnableGet EthEventsEnableSet EthEventsEnableWrite EthEventsGet EthInit EthMACGetAddress EthMACOpen EthMACSetAddress EthMACSetMaxFrame EthRxAcknowledgeBuffer EthRxAcknowledgePacket EthRxBuffersAppend EthRxFiltersClr EthRxFiltersHTSet EthRxFiltersPMClr EthRxFiltersPMSet EthRxFiltersSet EthRxFiltersWrite EthRxGetBuffer EthRxGetPacket EthRxSetBufferSize EthStatRxAlgnErrCnt EthStatRxFcsErrCnt EthStatRxOkCnt EthStatRxOvflCnt EthStatTxMColCnt EthStatTxOkCnt EthStatTxSColCnt EthTxAcknowledgeBuffer EthTxAcknowledgePacket EthTxGetBufferStatus EthTxGetPacketStatus EthTxSendBuffer EthTxSendPacket DRV_ETHMAC_LegacyClose DRV_ETHMAC_LegacyDescriptorGetBuffer DRV_ETHMAC_LegacyDescriptorsPoolAdd DRV_ETHMAC_LegacyDescriptorsPoolCleanUp DRV_ETHMAC_LegacyDescriptorsPoolRemove PLIB_ETH_LegacyEventsClr PLIB_ETH_LegacyEventsEnableClr PLIB_ETH_LegacyEventsEnableGet PLIB_ETH_LegacyEventsEnableSet PLIB_ETH_LegacyEventsEnableWrite PLIB_ETH_LegacyEventsGet DRV_ETHMAC_LegacyInit PLIB_ETH_LegacyMACGetAddress DRV_ETHMAC_LegacyMACOpen PLIB_ETH_LegacyMACSetAddress PLIB_ETH_LegacyMACSetMaxFrame DRV_ETHMAC_LegacyRxAcknowledgeBuffer DRV_ETHMAC_LegacyRxAcknowledgePacket DRV_ETHMAC_LegacyRxBuffersAppend PLIB_ETH_LegacyRxFiltersClr PLIB_ETH_LegacyRxFiltersHTSet PLIB_ETH_LegacyRxFiltersPMClr PLIB_ETH_LegacyRxFiltersPMSet PLIB_ETH_LegacyRxFiltersSet PLIB_ETH_LegacyRxFiltersWrite DRV_ETHMAC_LegacyRxGetBuffer DRV_ETHMAC_LegacyRxGetPacket PLIB_ETH_LegacyRxSetBufferSize PLIB_ETH_LegacyStatRxAlgnErrCnt PLIB_ETH_LegacyStatRxFcsErrCnt PLIB_ETH_LegacyStatRxOkCnt PLIB_ETH_LegacyStatRxOvflCnt PLIB_ETH_LegacyStatTxMColCnt PLIB_ETH_LegacyStatTxOkCnt PLIB_ETH_LegacyStatTxSColCnt DRV_ETHMAC_LegacyTxAcknowledgeBuffer DRV_ETHMAC_LegacyTxAcknowledgePacket DRV_ETHMAC_LegacyTxGetBufferStatus DRV_ETHMAC_LegacyTxGetPacketStatus DRV_ETHMAC_LegacyTxSendBuffer DRV_ETHMAC_LegacyTxSendPacket 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-233 MAC Driver Function Legacy Controller Library DRV_ETHMAC_LegacyClose DRV_ETHMAC_LegacyDescriptorGetBuffer DRV_ETHMAC_LegacyDescriptorsPoolAdd DRV_ETHMAC_LegacyDescriptorsPoolCleanUp DRV_ETHMAC_LegacyDescriptorsPoolRemove DRV_ETHMAC_LegacyInit DRV_ETHMAC_LegacyMACOpen DRV_ETHMAC_LegacyRxAcknowledgeBuffer DRV_ETHMAC_LegacyRxAcknowledgePacket DRV_ETHMAC_LegacyRxBuffersAppend DRV_ETHMAC_LegacyRxGetBuffer DRV_ETHMAC_LegacyRxGetPacket DRV_ETHMAC_LegacyTxAcknowledgeBuffer DRV_ETHMAC_LegacyTxAcknowledgePacket DRV_ETHMAC_LegacyTxGetBufferStatus DRV_ETHMAC_LegacyTxGetPacketStatus DRV_ETHMAC_LegacyTxSendBuffer DRV_ETHMAC_LegacyTxSendPacket EthClose EthDescriptorGetBuffer EthDescriptorsPoolAdd EthDescriptorsPoolCleanUp EthDescriptorsPoolRemove EthInit EthMACOpen EthRxAcknowledgeBuffer EthRxAcknowledgePacket EthRxBuffersAppend EthRxGetBuffer EthRxGetPacket EthTxAcknowledgeBuffer EthTxAcknowledgePacket EthTxGetBufferStatus EthTxGetPacketStatus EthTxSendBuffer EthTxSendPacket 5.1.3.5 Configuring the Library Macros Name Description DRV_ETHMAC_CLIENTS_NUMBER Selects the maximum number of clients. DRV_ETHMAC_INDEX Ethernet MAC static index selection. DRV_ETHMAC_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be supported by the dynamic driver. DRV_ETHMAC_INTERRUPT_MODE Controls operation of the driver in the interrupt or polled mode. DRV_ETHMAC_INTERRUPT_SOURCE Defines an override of the interrupt source in case of static driver. DRV_ETHMAC_PERIPHERAL_ID Defines an override of the peripheral ID. DRV_ETHMAC_POWER_STATE Defines an override of the power state of the Ethernet MAC driver. Description The configuration of the Ethernet MAC Driver is based on the file sys_config.h This header file contains the configuration selection for the Ethernet MAC Driver. Based on the selections made, the Ethernet MAC Driver will support or not support selected features. These configuration settings will apply to all instances of the Ethernet MAC DRiver. This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a successful build. Refer to the Applications Overview section for more details. 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-234 5.1.3.5.1 DRV_ETHMAC_CLIENTS_NUMBER Macro C #define DRV_ETHMAC_CLIENTS_NUMBER 1 Description Ethernet MAC Maximum Number of Clients This definition select the maximum number of clients that the Ethernet MAC driver can support at run time. Not defining it means using a single client. Remarks None. 5.1.3.5.2 DRV_ETHMAC_INDEX Macro C #define DRV_ETHMAC_INDEX DRV_ETHMAC_INDEX_1 Description Ethernet MAC Static Index Selection This definition selects the Ethernet MAC static index for the driver object reference Remarks This index is required to make a reference to the driver object. 5.1.3.5.3 DRV_ETHMAC_INSTANCES_NUMBER Macro C #define DRV_ETHMAC_INSTANCES_NUMBER 1 Description Ethernet MAC hardware instance configuration This definition selects the maximum number of hardware instances that can be supported by the dynamic driver. Not defining it means using a static driver. Remarks None. 5.1.3.5.4 DRV_ETHMAC_INTERRUPT_MODE Macro C #define DRV_ETHMAC_INTERRUPT_MODE true Description Ethernet MAC Interrupt And Polled Mode Operation Control This macro controls the operation of the driver in the interrupt mode of operation. The possible values of this macro are: 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-235 • true - Select if interrupt mode of timer operation is desired • false - Select if polling mode of timer operation is desired Not defining this option to true or false will result in a build error. Remarks None. 5.1.3.5.5 DRV_ETHMAC_INTERRUPT_SOURCE Macro C #define DRV_ETHMAC_INTERRUPT_SOURCE INT_SOURCE_ETH_1 Description Ethernet MAC Interrupt Source Defines an override of the interrupt source in case of static driver. Remarks Refer to the INT PLIB document for more information on INT_SOURCE enumeration. 5.1.3.5.6 DRV_ETHMAC_PERIPHERAL_ID Macro C #define DRV_ETHMAC_PERIPHERAL_ID ETHMAC_ID_1 Description Ethernet MAC Peripheral ID Selection Defines an override of the peripheral ID, using macros. Remarks Some devices also support ETHMAC_ID_0 5.1.3.5.7 DRV_ETHMAC_POWER_STATE Macro C #define DRV_ETHMAC_POWER_STATE SYS_MODULE_POWER_IDLE_STOP Description Ethernet MAC power state configuration Defines an override of the power state of the Ethernet MAC driver. Remarks This feature may not be available in the device or the Ethernet MAC module selected. 5.1.3.6 Building the Library This section list the files that are available in the \src of the Ethernet MAC Driver. It lists which files need to be included in the 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-236 build based on either a hardware feature present on the board or configuration option selected by the system. 5.1.3.7 Library Interface Data Types and Constants Name Description ETH_CLOSE_FLAGS Defines the possible disable codes of Ethernet controller "DRV_ETHMAC_LegacyClose" call. ETH_LINK_STATUS Defines the possible status flags of Ethernet link. ETH_MODULE_STATUS Defines the possible status codes of the Ethernet controller. ETH_OPEN_FLAGS Supported open configuration flags for the Ethernet module (EthMACOpen). ETH_PAUSE_TYPE Defines the possible Ethernet MAC pause types. ETH_RESULT_CODE Defines the possible results of Ethernet operations that can succeed or fail ETHPHY_CONFIG_FLAGS flags for DRV_ETHPHY_Setup() call DRV_ETHMAC_INDEX_1 This is macro DRV_ETHMAC_INDEX_1. DRV_ETHPHY_INDEX_1 This is macro DRV_ETHPHY_INDEX_1. Client Level Functions Name Description DRV_ETHMAC_PIC32MACClose Closes a client instance of the PIC32 MAC Driver. DRV_ETHMAC_PIC32MACGetConfig Supports PIC32 Ethernet MAC by copying its configuration.. DRV_ETHMAC_PIC32MACLinkCheck Checks current link status. DRV_ETHMAC_PIC32MACOpen Opens a client instance of the PIC32 MAC Driver. DRV_ETHMAC_PIC32MACSetup Supports PIC32 Ethernet MAC setup. DRV_ETHMAC_PIC32MACTeardown Supports PIC32 Ethernet MAC Teardown (opposite of setup). Event Functions Name Description DRV_ETHMAC_PIC32MACEventAcknowledge This function acknowledges and re-enables processed events. Multiple events can be orr-ed together as they are processed together. The events acknowledged by this function should be the events that have been retrieved from the stack by calling DRV_ETHMAC_PIC32MACEventPendingGet() or have been passed to the user by the stack using the notification handler (PIC32MACEventSetNotifyHandler()) and have been processed and have to be re-enabled. DRV_ETHMAC_PIC32MACEventMaskSet Enables the MAC events. DRV_ETHMAC_PIC32MACEventPendingGet Returns the currently pending events. Other Functions Name Description DRV_ETHMAC_PIC32MACPowerMode Powers down the Ethernet MAC. DRV_ETHMAC_PIC32MACProcess MAC periodic processing function. Receive Functions Name Description DRV_ETHMAC_PIC32MACPacketRx A packet is returned if such a pending packet exists. DRV_ETHMAC_PIC32MACPacketTx A packet is submitted to the MAC driver for transmission. 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-237 Transmit Functions Name Description DRV_ETHMAC_PIC32MACRxFilterHashTableEntrySet Calculates a CRC-32 and sets the approriate bit in the ETHHTx registers Description 5.1.3.7.1 Client Level Functions 5.1.3.7.1.1 DRV_ETHMAC_PIC32MACClose Function C TCPIP_MAC_RES DRV_ETHMAC_PIC32MACClose( TCPIP_MAC_HANDLE hMac ); Description This function closes a client instance of the PIC32 MAC Driver. Preconditions DRV_ETHMAC_PIC32MACOpen should have been called. Parameters Parameters Description macId MAC idenfification, from the TCPIP_STACK_MODULE enumeration Returns TCPIP_MAC_RES_OK if initialization completed; otherwise, the error enumeration value. Example 5.1.3.7.1.2 DRV_ETHMAC_PIC32MACGetConfig Function C size_t DRV_ETHMAC_PIC32MACGetConfig( TCPIP_STACK_MODULE modId, void* configBuff, size_t buffSize, size_t* pConfigSize ); Description Supports PIC32 Ethernet MAC Teardown (opposite of Setup). Used by tcpip_module_manager. Preconditions Supports PIC32 Ethernet MAC by copying its configuration.. Parameters Parameters Description modId Module ID from TCPIP_STACK_MODULE enumeration, identifying MAC. configBuff Pointer to configuration buffer to be copied 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-238 buffSize Size of configuration buffer provided by configBuff pConfigSize Pointer to size of configuration buffer copied. Returns Size of configuration buffer copied. Remarks This function deinitializes the Eth controller, the MAC and the associated PHY. It should be called to be able to schedule any Eth transmit or receive operation. Example 5.1.3.7.1.3 DRV_ETHMAC_PIC32MACLinkCheck Function C bool DRV_ETHMAC_PIC32MACLinkCheck( TCPIP_MAC_HANDLE hMac ); Description This function checks the link status, performing a MAC reconfiguration if the link went up after being down. Preconditions None. Parameters Parameters Description hMac Ethernet MAC client handle Returns • true - If the link is up • false - If the link is not up Remarks If auto negotiation is enabled the MAC we may have to be reconfigured. Example 5.1.3.7.1.4 DRV_ETHMAC_PIC32MACOpen Function C TCPIP_MAC_HANDLE DRV_ETHMAC_PIC32MACOpen( TCPIP_STACK_MODULE macId ); Description This function opens a client instance of the PIC32 MAC Driver. Used by tcpip_module_manager. Preconditions DRV_ETHMAC_PIC32MACSetup should have been called. Parameters Parameters Description macId MAC idenfification, from the TCPIP_STACK_MODULE enumeration 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-239 Returns TCPIP_MAC_HANDLE - handle (pointer) to MAC client Example 5.1.3.7.1.5 DRV_ETHMAC_PIC32MACSetup Function C TCPIP_MAC_RES DRV_ETHMAC_PIC32MACSetup( TCPIP_MAC_MODULE_CTRL* const stackData, const TCPIP_MODULE_MAC_PIC32INT_CONFIG* initData ); Description This function supports setup of the PIC32 Ethernet MAC. Used by tcpip_module_manager. Preconditions DRV_ETHMAC_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description pStackData Pointer to stack data initData Pointer to initialization data Returns TCPIP_MAC_RES_OK if initialization completed; otherwise, error enumeration value. Remarks This function initializes the Ethernet controller, the MAC and the associated PHY. It should be called to be able to schedule any Ethernet transmit or receive operation. Example 5.1.3.7.1.6 DRV_ETHMAC_PIC32MACTeardown Function C TCPIP_MAC_RES DRV_ETHMAC_PIC32MACTeardown( const TCPIP_MAC_MODULE_CTRL* const stackData ); Description This function supports teardown of the PIC32 Ethernet MAC (opposite of setup). Used by tcpip_module_manager. Preconditions DRV_ETHMAC_PIC32MACSetup must have been called to setup the driver. Parameters Parameters Description pStackData Pointer to Stack Data Returns TCPIP_MAC_RES_OK if initialization completed, error enumeration value otherwise. 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-240 Remarks This function deinitializes the Ethernet controller, the MAC and the associated PHY. It should be called to be able to schedule any Ethernet transmit or receive operation. Example 5.1.3.7.2 Get and Put Functions 5.1.3.7.3 Base Address and Buffer Size Functions 5.1.3.7.4 Receive Functions 5.1.3.7.4.1 DRV_ETHMAC_PIC32MACPacketRx Function C TCPIP_MAC_PACKET* DRV_ETHMAC_PIC32MACPacketRx( TCPIP_MAC_HANDLE hMac, TCPIP_MAC_RES* pRes, const TCPIP_MAC_PACKET_RX_STAT** ppPktStat ); Description This is the MAC receive function. Once a pending packet is available in the MAC driver internal RX queues this function will dequeue the packet and hand it over to the MAC driver's client - i.e. the stack - for further processing. The flags for a RX packet have to be updated by the MAC driver: • TCPIP_MAC_PKT_FLAG_RX has to be set If the MAC supports it, it should set: • TCPIP_MAC_PKT_FLAG_UNICAST has to be set if that packet is a unicast packet • TCPIP_MAC_PKT_FLAG_BCAST has to be set if that packet is a broadcast packet • TCPIP_MAC_PKT_FLAG_MCAST has to be set if that packet is a multicast packet • TCPIP_MAC_PKT_FLAG_QUEUED has to be set • TCPIP_MAC_PKT_FLAG_SPLIT has to be set if the packet has multiple data segments Additional information about the packet is available by providing the pRes and ppPktStat fields. Preconditions DRV_ETHMAC_PIC32MACSetup() should have been called. Parameters Parameters Description hMac Ethernet MAC client handle pRes optional pointer to an address that will receive an additional result associated with the operation. Can be 0 if not needed. ppPktStat optional pointer to an address that will receive the received packet status. Note that this pointer cannot be used once the packet acknowledgement function was called. Can be 0 if not needed. 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-241 Returns a valid pointer to an available RX packet 0 if no packet pending/available Remarks The MAC driver dequeues and return to the caller just one single packet. Once the higher level layers in the stack are done with processing the RX packet, they have to call the corresponding packet acknowledgement function that tells the MAC driver that it can resume control of that packet. Once the stack modules are done processing the RX packets and the acknowledge function is called the MAC driver will reuse the RX packets. The MAC driver may use the DRV_ETHMAC_PIC32MACProcess() for obtaining new RX packets if needed. Example 5.1.3.7.4.2 DRV_ETHMAC_PIC32MACPacketTx Function C TCPIP_MAC_RES DRV_ETHMAC_PIC32MACPacketTx( TCPIP_MAC_HANDLE hMac, TCPIP_MAC_PACKET * ptrPacket ); Description This is the MAC transmit function. The MAC driver has to suport internal queueing! A packet is to be rejected only if it's not properly formatted. Otherwise it has to be scheduled for transmission in an internal queue! Once the packet is scheduled for transmission the MAC driver has to set the TCPIP_MAC_PKT_FLAG_QUEUED flag so that the stack is aware that this packet is under processing cnd cannot be modified! Once the packet is transmitted, the TCPIP_MAC_PKT_FLAG_QUEUED has to be cleared, the proper packet acknowledgement result (ackRes) has to be set and the packet acknowledgement function (ackFunc) has to be called. It is implementation dependant if all these steps are implemented as part of the ackFunc itself or as discrete steps. Preconditions DRV_ETHMAC_PIC32MACSetup() should have been called. Parameters Parameters Description hMac Ethernet MAC client handle ptrPacket pointer to a TCPIP_MAC_PACKET that's completely formatted and ready to be transmitted over the network Returns TCPIP_MAC_RES_OK if the packet transmitted, TCPIP_MAC_RES errocode for not properly formatted packets, etc. Example 5.1.3.7.5 Transmit Functions 5.1.3.7.5.1 DRV_ETHMAC_PIC32MACRxFilterHashTableEntrySet Function C TCPIP_MAC_RES DRV_ETHMAC_PIC32MACRxFilterHashTableEntrySet( 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-242 TCPIP_MAC_HANDLE hMac, TCPIP_MAC_ADDR* DestMACAddr ); Description This function salculates a CRC-32 using polynomial 0x4C11DB7 and then, using bits 28 through 23 of the CRC, sets the appropriate bit in the ETHHT0-ETHHT1 registers. Preconditions DRV_ETHMAC_PIC32MACSetup() should have been called. Parameters Parameters Description hMac Ethernet MAC client handle DestMACAddr 6-byte group destination MAC address to allow through the Hash Table Filter. If DestMACAddr is set to '0000 0000 0000', the hash table will be cleared of all entries and the filter will be disabled. Returns TCPIP_MAC_RES_OK if success, an eror code otherwise. Remarks Sets the appropriate bit in the ETHHT0/1 registers to allow packets sent to DestMACAddr to be received and enabled the Hash Table receive filter There is no way to individually unset destination MAC addresses from the hash table since it is possible to have a hash collision and therefore multiple MAC addresses relying on the same hash table bit. The stack would have to individually store each 6 byte MAC address to support this feature, which would waste a lot of RAM and be unnecessary in most applications. As a simple compromise, you can call DRV_ETHMAC_PIC32MACRxFilterHashTableEntrySet() using a 00-00-00-00-00-00 destination MAC address, which will clear the entire hash table and disable the hash table filter. This will allow you to then readd the necessary destination addresses. Example 5.1.3.7.6 Event Functions 5.1.3.7.6.1 DRV_ETHMAC_PIC32MACEventAcknowledge Function C bool DRV_ETHMAC_PIC32MACEventAcknowledge( TCPIP_MAC_HANDLE hMac, TCPIP_MAC_EVENT tcpAckEv ); Description This function acknowledges and re-enables processed events. Multiple events can be orr-ed together as they are processed together. The events acknowledged by this function should be the events that have been retrieved from the stack by calling DRV_ETHMAC_PIC32MACEventPendingGet() or have been passed to the user by the stack using the notification handler (PIC32MACEventSetNotifyHandler()) and have been processed and have to be re-enabled. Preconditions DRV_ETHMAC_PIC32MACSetup() should have been called. 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-243 Parameters Parameters Description hMac Ethernet MAC client handle tcpAckEv the events that the user processed and need to be re-enabled Returns true if events acknowledged false if no events to be acknowledged Remarks All events should be acknowledged, in order to be re-enabled. Some events are fatal errors and should not be acknowledged (TCPIP_MAC_EV_RX_BUSERR, TCPIP_MAC_EV_TX_BUSERR). Stack re-initialization is needed under such circumstances. Some events are just system/application behavior and they are intended only as simple info (TCPIP_MAC_EV_RX_OVFLOW, TCPIP_MAC_EV_RX_BUFNA, TCPIP_MAC_EV_TX_ABORT, TCPIP_MAC_EV_RX_ACT). The TCPIP_MAC_EV_RX_FWMARK and TCPIP_MAC_EV_RX_EWMARK events are part of the normal flow control operation (if auto flow control was enabled). They should be enabled alternatively, if needed. The events are persistent. They shouldn't be re-enabled unless they have been processed and the condition that generated them was removed. Re-enabling them immediately without proper processing will have dramatic effects on system performance. Example DRV_ETHMAC_PIC32MACEventAcknowledge( hMac, stackNewEvents ); 5.1.3.7.6.2 DRV_ETHMAC_PIC32MACEventMaskSet Function C bool DRV_ETHMAC_PIC32MACEventMaskSet( TCPIP_MAC_HANDLE hMac, TCPIP_MAC_EVENT macEvents, bool enable ); Description This function sets the enabled events. Multiple events can be orr-ed together. All events that are set will be added to the notification process. The old events will be disabled. The stack (or stack user) has to catch the events that are notified and process them: • The stack should process the TCPIP_MAC_EV_RX_PKTPEND/TCPIP_MAC_EV_RX_DONE, TCPIP_MAC_EV_TX_DONE transfer events • Process the specific condition and acknowledge them calling DRV_ETHMAC_PIC32MACEventAcknowledge() so that they can be re-enabled. Preconditions DRV_ETHMAC_PIC32MACSetup() should have been called. Parameters Parameters Description hMac Ethernet MAC client handle macEvMask events the user of the stack wants to add/delete for notification enable if true, the events will be enabled, else disabled 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-244 Returns always true, operation succeeded. Remarks The event notification system enables the user of the TCPIP stack to call into the stack for processing only when there are relevant events rather than being forced to periodically call from within a loop. If the notification events are nill the interrupt processing will be disabled. Otherwise the event notification will be enabled and the interrupts relating to the requested events will be enabled. Note that once an event has been caught by the stack ISR (and reported if a notification handler is in place) it will be disabled until the DRV_ETHMAC_PIC32MACEventAcknowledge() is called. Example DRV_ETHMAC_PIC32MACEventMaskSet( hMac, TCPIP_MAC_EV_RX_OVFLOW | TCPIP_MAC_EV_RX_BUFNA, true ); 5.1.3.7.6.3 DRV_ETHMAC_PIC32MACEventPendingGet Function C TCPIP_MAC_EVENT DRV_ETHMAC_PIC32MACEventPendingGet( TCPIP_MAC_HANDLE hMac ); Description This function returns the currently pending events belonging to a group. Multiple events can be orr-ed together as they accumulate. The stack should be called for processing whenever a stack managed event (TCPIP_MAC_EV_RX_PKTPEND, TCPIP_MAC_EV_TX_DONE) is present. The other, non critical events, may not be managed by the stack and passed to an user. They will have to be eventually acknowledged if re-enabling is needed. Preconditions DRV_ETHMAC_PIC32MACSetup should have been called. Parameters Parameters Description hMac parameter identifying the intended MAC client Returns The currently stack pending events. Remarks This is the preferred method to get the current pending MAC events. The stack maintains a proper image of the events from their occurrence to their acknowledgement. Even with a notification handler in place it's better to use this function to get the current pending events rather than using the events passed by the notification handler which could be stale. The events are persistent. They shouldn't be re-enabled unless they have been processed and the condition that generated them was removed. Re-enabling them immediately without proper processing will have dramatic effects on system performance. The returned value is just a momentary value. The pending events can change any time. Example TCPIP_MAC_EVENT currEvents = DRV_ETHMAC_PIC32MACEventPendingGet( hMac); 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-245 5.1.3.7.7 Library Functions 5.1.3.7.8 Other Functions 5.1.3.7.8.1 DRV_ETHMAC_PIC32MACPowerMode Function C bool DRV_ETHMAC_PIC32MACPowerMode( TCPIP_MAC_HANDLE hMac, TCPIP_MAC_POWER_MODE pwrMode ); Description This function powers down the Ethernet MAC. Preconditions None. Parameters Parameters Description hMac Ethernet MAC client handle pwrMode Power Mode (?) Returns None. Example 5.1.3.7.8.2 DRV_ETHMAC_PIC32MACProcess Function C TCPIP_MAC_RES DRV_ETHMAC_PIC32MACProcess( TCPIP_MAC_HANDLE hMac ); Description This is a function that allows for internal processing by the MAC driver. It is meant for processing that cannot be done from within ISR. Some of the processing that this is intended for: • the MAC driver can process its pending TX queues (although it should do that preferrably from within the TX ISR) • RX buffers replenishing. If the number of packets in the RX queue falls below a specified limit, the MAC driver can use this function to allocate some extra RX packets. Similarly, if there are too many allocated RX packets, the MAC driver can free some of them. Normally this function will be called in response to an TX and/or RX event signalled by the driver. This is specified by the MAC driver at initialization time using TCPIP_MAC_MODULE_CTRL. An alternative approach is that the MAC driver uses a system service to create a timer signal that will call the TCPIP_MAC_Process on a periodic basis. Preconditions DRV_ETHMAC_PIC32MACSetup() should have been called. 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-246 Parameters Parameters Description hMac Ethernet MAC client handle Returns TCPIP_MAC_RES_OK if all processing went on OK a TCPIP_MAC_RES error code if processing failed for some reason Remarks The MAC driver may use the DRV_ETHMAC_PIC32MACProcess() for obtaining new RX packets if needed. Example 5.1.3.7.9 Data Types and Constants 5.1.3.7.9.1 ETH_CLOSE_FLAGS Enumeration C typedef enum { ETH_CLOSE_GRACEFUL, ETH_CLOSE_DEFAULT = (0) } ETH_CLOSE_FLAGS; Description Ethernet Close Flags This enumeration defines the close capabilities of the Ethernet module. Members Members Description ETH_CLOSE_GRACEFUL Wait for the current TX/RX op to finish ETH_CLOSE_DEFAULT = (0) Default close options 5.1.3.7.9.2 ETH_LINK_STATUS Enumeration C typedef enum { ETH_LINK_ST_DOWN, ETH_LINK_ST_UP, ETH_LINK_ST_LP_NEG_UNABLE, ETH_LINK_ST_REMOTE_FAULT, ETH_LINK_ST_PDF, ETH_LINK_ST_LP_PAUSE, ETH_LINK_ST_LP_ASM_DIR, ETH_LINK_ST_NEG_TMO, ETH_LINK_ST_NEG_FATAL_ERR } ETH_LINK_STATUS; Description Ethernet Link Status Codes This enumeration defines the flags describing the status of the Ethernet link. 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-247 Members Members Description ETH_LINK_ST_DOWN No connection to the LinkPartner ETH_LINK_ST_UP Link is up ETH_LINK_ST_LP_NEG_UNABLE LP non negotiation able ETH_LINK_ST_REMOTE_FAULT LP fault during negotiation ETH_LINK_ST_PDF Parallel Detection Fault encountered (when ETH_LINK_ST_LP_NEG_UNABLE) ETH_LINK_ST_LP_PAUSE LP supports symmetric pause ETH_LINK_ST_LP_ASM_DIR LP supports asymmetric TX/RX pause operation ETH_LINK_ST_NEG_TMO LP not there ETH_LINK_ST_NEG_FATAL_ERR An unexpected fatal error occurred during the negotiation Remarks Multiple flags can be set. 5.1.3.7.9.3 ETH_MODULE_STATUS Enumeration C typedef enum { ETH_ST_RXBUSY, ETH_ST_TXBUSY, ETH_ST_BUSY } ETH_MODULE_STATUS; Description Ethernet Controller Status Codes This enumeration defines the flags describing the status of the Ethernet controller. Members Members Description ETH_ST_RXBUSY A packet is currently received ETH_ST_TXBUSY A packet is currently transmitted ETH_ST_BUSY Module is on or completing a transaction 5.1.3.7.9.4 ETH_OPEN_FLAGS Enumeration C typedef enum { ETH_OPEN_AUTO, ETH_OPEN_FDUPLEX, ETH_OPEN_HDUPLEX, ETH_OPEN_100, ETH_OPEN_10, ETH_OPEN_HUGE_PKTS, ETH_OPEN_MAC_LOOPBACK, ETH_OPEN_PHY_LOOPBACK, ETH_OPEN_MDIX_AUTO, ETH_OPEN_MDIX_NORM, ETH_OPEN_MDIX_SWAP, ETH_OPEN_RMII, ETH_OPEN_MII, ETH_OPEN_DEFAULT = (ETH_OPEN_AUTO|ETH_OPEN_FDUPLEX|ETH_OPEN_HDUPLEX| ETH_OPEN_100|ETH_OPEN_10|ETH_OPEN_MDIX_AUTO) 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-248 } ETH_OPEN_FLAGS; Description Ethernet Open Configuration Settings This enumeration defines the various configuration options for the Ethernet module. These values can be ORed together to create a configuration mask passed to the EthMACOpen routine. Members Members Description ETH_OPEN_AUTO Use auto negotiation. set the following flags to specify your choices ETH_OPEN_FDUPLEX Use full duplex or full duplex negotiation capability needed ETH_OPEN_HDUPLEX Use half duplex or half duplex negotiation capability needed ETH_OPEN_100 Use 100MBps or 100MBps negotiation capability needed ETH_OPEN_10 Use 10MBps or 10MBps negotiation capability needed ETH_OPEN_HUGE_PKTS Allow huge packets RX/TX ETH_OPEN_MAC_LOOPBACK Loopbacked at the MAC level ETH_OPEN_PHY_LOOPBACK When PHY is loopback-ed, negotiation will be disabled! ETH_OPEN_MDIX_AUTO Use Auto MDIX ETH_OPEN_MDIX_NORM Use normal MDIX when Auto MDIX disabled ETH_OPEN_MDIX_SWAP Use swapped MDIX when Auto MDIX disabled ETH_OPEN_RMII RMII connection ETH_OPEN_MII MII connection ETH_OPEN_DEFAULT = (ETH_OPEN_AUTO|ETH_OPEN_FDUPLEX|ETH_OPEN_HDUPLEX| ETH_OPEN_100|ETH_OPEN_10|ETH_OPEN_MDIX_AUTO) All capabilities default Remarks When Auto-negotiation is specified: • If multiple capability flags are set (ETH_OPEN_FDUPLEX, ETH_OPEN_HDUPLEX, ETH_OPEN_100, ETH_OPEN_10 ) they are all advertised as this link side capabilities. • If no setting is passed, the lowest one is taken, i.e., ETH_OPEN_HDUPLEX and ETH_OPEN_10. • Auto-MDIX requires Auto-Negotiation; ETH_OPEN_MDIX_NORM or ETH_OPEN_MDIX_SWAP setting irrelevant. When No Auto-negotiation is specified: • If multiple settings, the highest priority setting is taken, i.e. ETH_OPEN_FDUPLEX over ETH_OPEN_HDUPLEX and ETH_OPEN_100 over ETH_OPEN_10. • If no setting, the lowest setting is taken, i.e., ETH_OPEN_HDUPLEX and ETH_OPEN_10. • The MDIX is set based on the ETH_OPEN_MDIX_NORM/ETH_OPEN_MDIX_SWAP setting. 5.1.3.7.9.5 ETH_PAUSE_TYPE Enumeration C typedef enum { ETH_MAC_PAUSE_TYPE_NONE, ETH_MAC_PAUSE_TYPE_PAUSE, ETH_MAC_PAUSE_TYPE_ASM_DIR, 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-249 ETH_MAC_PAUSE_TYPE_EN_TX, ETH_MAC_PAUSE_TYPE_EN_RX, ETH_MAC_PAUSE_ALL = (ETH_MAC_PAUSE_TYPE_PAUSE|ETH_MAC_PAUSE_TYPE_ASM_DIR| ETH_MAC_PAUSE_TYPE_EN_TX|ETH_MAC_PAUSE_TYPE_EN_RX), ETH_MAC_PAUSE_CPBL_MASK = ETH_MAC_PAUSE_ALL } ETH_PAUSE_TYPE; Description Ethernet MAC Pause Types This enumeration defines the pause capabilities of the Ethernet MAC. Members Members Description ETH_MAC_PAUSE_TYPE_NONE No PAUSE capabilities ETH_MAC_PAUSE_TYPE_PAUSE Supports symmetric PAUSE ETH_MAC_PAUSE_TYPE_ASM_DIR Supports ASM_DIR ETH_MAC_PAUSE_TYPE_EN_TX Enable MAC TX pause support ETH_MAC_PAUSE_TYPE_EN_RX Enable MAC RX pause support ETH_MAC_PAUSE_ALL = (ETH_MAC_PAUSE_TYPE_PAUSE|ETH_MAC_PAUSE_TYPE_ASM_DIR| ETH_MAC_PAUSE_TYPE_EN_TX|ETH_MAC_PAUSE_TYPE_EN_RX) All types of pause ETH_MAC_PAUSE_CPBL_MASK = ETH_MAC_PAUSE_ALL All pause capabilities our MAC supports 5.1.3.7.9.6 ETH_RESULT_CODE Enumeration C typedef enum { ETH_RES_OK, ETH_RES_NO_PACKET, ETH_RES_PACKET_QUEUED, ETH_RES_OUT_OF_MEMORY, ETH_RES_NO_DESCRIPTORS, ETH_RES_USPACE_ERR, ETH_RES_RX_SIZE_ERR, ETH_RES_RX_PKT_SPLIT_ERR, ETH_RES_NEGOTIATION_UNABLE, ETH_RES_NEGOTIATION_INACTIVE, ETH_RES_NEGOTIATION_NOT_STARTED, ETH_RES_NEGOTIATION_ACTIVE, ETH_RES_NEGOTIATION_LINKDOWN, ETH_RES_DTCT_ERR, ETH_RES_CPBL_ERR, ETH_RES_CFG_ERR } ETH_RESULT_CODE; Description Ethernet Operation Result Codes This enumeration defines the possible results of any of the Ethernet library operations that have the possibilty of failing. This result should be checked to ensure that the operation achieved the desired result. Members Members Description ETH_RES_OK Everything ok ETH_RES_NO_PACKET No such packet exist ETH_RES_PACKET_QUEUED Packet is queued (not transmitted or received and not processed) 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-250 ETH_RES_OUT_OF_MEMORY Some memory allocation failed ETH_RES_NO_DESCRIPTORS Not enough descriptors available ETH_RES_USPACE_ERR We don't support user space buffers. ETH_RES_RX_SIZE_ERR The size of the receive buffers too small ETH_RES_RX_PKT_SPLIT_ERR A received packet spans more buffers/descriptors than supplied ETH_RES_NEGOTIATION_UNABLE No negotiation support ETH_RES_NEGOTIATION_INACTIVE No negotiation active ETH_RES_NEGOTIATION_NOT_STARTED Negotiation not started yet ETH_RES_NEGOTIATION_ACTIVE Negotiation active ETH_RES_NEGOTIATION_LINKDOWN Link down after negotiation, negotiation failed ETH_RES_DTCT_ERR No Phy was detected or it failed to respond to reset command ETH_RES_CPBL_ERR No match between the capabilities: the Phy supported and the open requested ones ETH_RES_CFG_ERR Hardware configuration doesn't match the requested open mode 5.1.3.7.9.7 ETHPHY_CONFIG_FLAGS Enumeration C typedef enum { ETH_PHY_CFG_RMII, ETH_PHY_CFG_MII, ETH_PHY_CFG_ALTERNATE, ETH_PHY_CFG_DEFAULT, ETH_PHY_CFG_AUTO } ETHPHY_CONFIG_FLAGS; Description flags for DRV_ETHPHY_Setup() call Members Members Description ETH_PHY_CFG_RMII RMII data interface in configuration fuses. ETH_PHY_CFG_MII MII data interface in configuration fuses. ETH_PHY_CFG_ALTERNATE Configuration fuses is ALT ETH_PHY_CFG_DEFAULT Configuration fuses is DEFAULT ETH_PHY_CFG_AUTO Use the fuses configuration to detect if you are RMII/MII and ALT/DEFAULT configuration 5.1.3.7.9.8 DRV_ETHMAC_INDEX_1 Macro C #define DRV_ETHMAC_INDEX_1 1 Description This is macro DRV_ETHMAC_INDEX_1. 5.1.3.7.9.9 DRV_ETHPHY_INDEX_1 Macro C #define DRV_ETHPHY_INDEX_1 1 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-251 Description This is macro DRV_ETHPHY_INDEX_1. 5.1.3.8 Files Files Name Description drv_ethernet_flags.h Ethernet driver configuration flags file. drv_ethmac.h Ethernet MAC device driver interface file. drv_ethmac_config.h Ethernet MAC driver configuration definitions template. Description 5.1.3.8.1 drv_ethernet_flags.h Ethernet Drivers Configuration Flags This file provides the definition of commonly-used configuration enumerations for use with the Ethernet PHY and Ethernet MAC Drivers. Enumerations Name Description ETH_CLOSE_FLAGS Defines the possible disable codes of Ethernet controller "DRV_ETHMAC_LegacyClose" call. ETH_LINK_STATUS Defines the possible status flags of Ethernet link. ETH_OPEN_FLAGS Supported open configuration flags for the Ethernet module (EthMACOpen). ETH_PAUSE_TYPE Defines the possible Ethernet MAC pause types. ETH_RESULT_CODE Defines the possible results of Ethernet operations that can succeed or fail ETHPHY_CONFIG_FLAGS flags for DRV_ETHPHY_Setup() call Company Microchip Technology Inc. FileName: drv_ethernet_flags.h 5.1.3.8.2 drv_ethmac.h Ethernet MAC Device Driver Interface The Ethernet MAC device driver provides a simple interface to manage the Ethernet peripheral. This file defines the interface definitions and prototypes for the Ethernet MAC driver. Enumerations Name Description ETH_MODULE_STATUS Defines the possible status codes of the Ethernet controller. 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-252 Functions Name Description DRV_ETHMAC_PIC32MACClose Closes a client instance of the PIC32 MAC Driver. DRV_ETHMAC_PIC32MACEventAcknowledge This function acknowledges and re-enables processed events. Multiple events can be orr-ed together as they are processed together. The events acknowledged by this function should be the events that have been retrieved from the stack by calling DRV_ETHMAC_PIC32MACEventPendingGet() or have been passed to the user by the stack using the notification handler (PIC32MACEventSetNotifyHandler()) and have been processed and have to be re-enabled. DRV_ETHMAC_PIC32MACEventMaskSet Enables the MAC events. DRV_ETHMAC_PIC32MACEventPendingGet Returns the currently pending events. DRV_ETHMAC_PIC32MACGetConfig Supports PIC32 Ethernet MAC by copying its configuration.. DRV_ETHMAC_PIC32MACLinkCheck Checks current link status. DRV_ETHMAC_PIC32MACOpen Opens a client instance of the PIC32 MAC Driver. DRV_ETHMAC_PIC32MACPacketRx A packet is returned if such a pending packet exists. DRV_ETHMAC_PIC32MACPacketTx A packet is submitted to the MAC driver for transmission. DRV_ETHMAC_PIC32MACPowerMode Powers down the Ethernet MAC. DRV_ETHMAC_PIC32MACProcess MAC periodic processing function. DRV_ETHMAC_PIC32MACRxFilterHashTableEntrySet Calculates a CRC-32 and sets the approriate bit in the ETHHTx registers DRV_ETHMAC_PIC32MACSetup Supports PIC32 Ethernet MAC setup. DRV_ETHMAC_PIC32MACTeardown Supports PIC32 Ethernet MAC Teardown (opposite of setup). Macros Name Description DRV_ETHMAC_INDEX_0 Ethernet driver index definitions. DRV_ETHMAC_INDEX_1 This is macro DRV_ETHMAC_INDEX_1. DRV_ETHMAC_INDEX_COUNT Number of valid Ethernet driver indices. Company Microchip Technology Inc. FileName: drv_ethmac.h 5.1.3.8.3 drv_ethmac_config.h ETHMAC Driver Configuration Definitions for the template version These definitions statically define the driver's mode of operation. Macros Name Description DRV_ETHMAC_CLIENTS_NUMBER Selects the maximum number of clients. DRV_ETHMAC_INDEX Ethernet MAC static index selection. 5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library 5-253 DRV_ETHMAC_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be supported by the dynamic driver. DRV_ETHMAC_INTERRUPT_MODE Controls operation of the driver in the interrupt or polled mode. DRV_ETHMAC_INTERRUPT_SOURCE Defines an override of the interrupt source in case of static driver. DRV_ETHMAC_PERIPHERAL_ID Defines an override of the peripheral ID. DRV_ETHMAC_POWER_STATE Defines an override of the power state of the Ethernet MAC driver. File Name drv_ethmac_config.h Company Microchip Technology Inc. 5.1.4 Ethernet PHY Driver Library 5.1.4.1 Introduction Ethernet PHY Driver Library for Microchip Microcontrollers This library provides a low-level abstraction of the Ethernet PHY Driver Library that is available on the Microchip family of microcontrollers with a convenient C language interface. It can be used to simplify low-level access to the module without the necessity of interacting directly with the module's registers, there by hiding differences from one microcontroller variant to another. Description This library provides a software abstraction for configuring external Ethernet PHY devices for use with the on-chip Ethernet Controller. 5.1.4.2 Release Notes MPLAB Harmony Version: v0.70b Ethernet PHY Driver Library Version : 7.10 Release Date: 18Nov2013 New This Release: This is the first release of the library. The interface can change in the beta and\or 1.0 release. Known Issues: Nothing to report in this release. 5.1.4.3 SW License Agreement (c) 2013 Microchip Technology Inc. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-254 Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 5.1.4.4 Using the Library This topic describes the basic architecture of the Ethernet PHY Driver Library and provides information and examples on how to use it. Interface Header File: drv_ethphy.h The interface to the Ethernet PHY Driver Library is defined in the "drv_ethphy.h" header file. This file is included by the "drv_ethphy.h" file. Any C language source (.c) file that uses the Ethernet PHY Driver Library should include "drv.h". Library File: The Ethernet PHY Driver Library archive (.a) file is installed with MPLAB Harmony. Please refer to the MPLAB Harmony Overview for how the library interacts with the framework. 5.1.4.4.1 Abstraction Model Overview To understand how this library works you must first understand how an external Ethernet PHY interfaces with the Ethernet Controller. As shown in Figure 1, the PHY has two interfaces, one for managing the PHY, known as the Serial Management Interface (SMI), for configuring the device and a second, known as the Reduced Media Independent Interface (RMII), for transmit and receive data. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-255 Figure 1: Typical External PHY Interface The block diagram also shows an interrupt signal (nINT) going to a external interrupt pin on the host device and signals going to on-board LEDs to show link state and link activity. The SMI interface is also known as the MII Management (MIIM) interface. This control interface is standardized for all PHY's by Clause 22 of the 802.3 standard. It provides up to 32 16-bit registers on the PHY. The table below provides a summary of all 32 registers. Consult the data sheet for the PHY device for the specific bit fields in each register. Register Address Register Name Register Type 0 Control Basic 1 Status Basic 2,3 PHY Identifier Extended 4 Auto-Negotiation Advertisement Extended 5 Auto-Negotiation Link Partner Base Page Ability Extended 6 Auto-Negotiation Expansion Extended 7 Auto-Negotiation Next Page Transmit Extended 8 Auto-Negotiation Link Partner Received Next Page Extended 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-256 9 MASTER-SLAVE Control Register Extended 10 MASTER-SLAVE Status Register Extended 11-14 Reserved Extended 15 Extended Status Reserved 16-31 Vendor Specific Extended 5.1.4.4.2 Library Overview The Ethernet PHY Driver Library is divided into the following sections: Library Interface Section Description System Level Functions Routines that integrate the driver into the MPLAB Harmony system Client Level Functions Open, Close, Link Status, Auto Negotiation SMI/MIIM Functions SMI/MIIM Management Interface External PHY Support Functions Provides the API for PHY support routines that the driver will call when setting up the PHY. The driver library provides support for 4 PHYs. Other Functions Functions that provide software version information. Data Types and Constants C language typedefs and enums used by this library. 5.1.4.4.3 MPLAB Harmony vs. the Unified TCP/IP Stack The following is a cross-reference of MPLAB Harmony functions and the equivalent Unified TCP/IP Stack function: 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-257 MPLAB Harmony Function: Unified Stack Function: DRV_ETHPHY_ClientStatus DRV_ETHPHY_Close DRV_ETHPHY_Deinitialize DRV_ETHPHY_HWConfigFlagsGet DRV_ETHPHY_Setup DRV_ETHPHY_Initialize DRV_ETHPHY_LinkScanRead DRV_ETHPHY_LinkScanStart DRV_ETHPHY_LinkScanStop DRV_ETHPHY_LinkStatusGet DRV_ETHPHY_NegotiationIsComplete DRV_ETHPHY_NegotiationResultGet DRV_ETHPHY_Open DRV_ETHPHY_Reinitialize DRV_ETHPHY_Reset DRV_ETHPHY_RestartNegotiation DRV_ETHPHY_SMIReadResultGet DRV_ETHPHY_SMIReadStart DRV_ETHPHY_SMIScanDataGet DRV_ETHPHY_SMIScanStart DRV_ETHPHY_SMIScanStatusGet DRV_ETHPHY_SMIScanStop DRV_ETHPHY_SMIWriteStart DRV_ETHPHY_SMIisBusy DRV_ETHPHY_Status DRV_ETHPHY_Tasks DRV_ETHPHY_VersionGet DRV_ETHPHY_VersionStrGet DRV_ETHPHY_SMIClockSet -none- -none- -noneEthPhyGetHwConfigFlags EthPhyInit -noneEthPhyScanLinkRead EthPhyScanLinkStart EthPhyScanLinkStop EthPhyGetLinkStatus EthPhyNegotiationComplete EthPhyGetNegotiationResult -none- -noneEthPhyReset EthPhyRestartNegotiation EthMIIMReadResult EthMIIMReadStart EthMIIMScanResult EthMIIMScanStart -none- -noneEthMIIMWriteStart -none- -none- -none- -none- -noneEthMIIMConfig 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-258 Unified Stack Function: MPLAB Harmony Function: EthMIIMConfig EthMIIMReadResult EthMIIMReadStart EthMIIMScanResult EthMIIMScanStart EthMIIMWriteStart EthPhyGetHwConfigFlags EthPhyGetLinkStatus EthPhyGetNegotiationResult EthPhyInit EthPhyNegotiationComplete EthPhyReset EthPhyRestartNegotiation EthPhyScanLinkRead EthPhyScanLinkStart EthPhyScanLinkStop -none- -none- -none- -none- -none- -none- -none- -none- -none- -none- -none- -none- -noneDRV_ETHPHY_SMIClockSet DRV_ETHPHY_SMIReadResultGet DRV_ETHPHY_SMIReadStart DRV_ETHPHY_SMIScanDataGet DRV_ETHPHY_SMIScanStart DRV_ETHPHY_SMIWriteStart DRV_ETHPHY_HWConfigFlagsGet DRV_ETHPHY_LinkStatusGet DRV_ETHPHY_NegotiationResultGet DRV_ETHPHY_Setup DRV_ETHPHY_NegotiationIsComplete DRV_ETHPHY_Reset DRV_ETHPHY_RestartNegotiation DRV_ETHPHY_LinkScanRead DRV_ETHPHY_LinkScanStart DRV_ETHPHY_LinkScanStop DRV_ETHPHY_ClientStatus DRV_ETHPHY_Close DRV_ETHPHY_Deinitialize DRV_ETHPHY_Initialize DRV_ETHPHY_Open DRV_ETHPHY_Reinitialize DRV_ETHPHY_SMIScanStatusGet DRV_ETHPHY_SMIScanStop DRV_ETHPHY_SMIisBusy DRV_ETHPHY_Status DRV_ETHPHY_Tasks DRV_ETHPHY_VersionGet DRV_ETHPHY_VersionStrGet 5.1.4.5 Configuring the Library Macros Name Description DRV_ETHPHY_CLIENTS_NUMBER Selects the miximum number of clients. DRV_ETHPHY_INDEX Ethernet PHY static index selection. DRV_ETHPHY_INDEX_0 Ethernet PHY driver index definitions. DRV_ETHPHY_INDEX_COUNT Number of valid Ethernet PHY driver indices. DRV_ETHPHY_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be supported by the dynamic driver. DRV_ETHPHY_PERIPHERAL_ID Defines an override of the peripheral ID. PHY_NEG_DONE_TMO negotiation complete timeout, ms. based on IEEE 802.3 Clause 28 Table 28-9 autoneg_wait_timer value (max 1s) PHY_NEG_INIT_TMO negotiation initiation timeout, ms. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-259 PHY_RESET_CLR_TMO reset self clear timeout, ms. IEEE 802.3 Clause 22 Table 22-7 and paragraph "22.2.4.1.1 Reset" (max 0.5s) TCPIP_IF_PIC32INT We have an internal PIC32 MAC Description The configuration of the Ethernet MAC Driver Library is based on the file sys_config.h This header file contains the configuration selection for the Ethernet MAC Driver Library. Based on the selections made, the Ethernet MAC Driver Library will support or not support selected features. These configuration settings will apply to all instances of the Ethernet MAC Driver Library. This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a successful build. Refer to the Applications Overview section for more details. 5.1.4.5.1 DRV_ETHPHY_CLIENTS_NUMBER Macro C #define DRV_ETHPHY_CLIENTS_NUMBER 1 Description Ethernet PHY Maximum Number of Clients This definition select the maximum number of clients that the Ethernet PHY driver can support at run time. Not defining it means using a single client. Remarks None. 5.1.4.5.2 DRV_ETHPHY_INDEX Macro C #define DRV_ETHPHY_INDEX DRV_ETHPHY_INDEX_1 Description Ethernet PHY Static Index Selection This definition selects the Ethernet PHY static index for the driver object reference. Remarks This index is required to make a reference to the driver object. 5.1.4.5.3 DRV_ETHPHY_INDEX_0 Macro C #define DRV_ETHPHY_INDEX_0 0 Description Ethernet PHY Driver Module Index Numbers These constants provide the Ethernet PHY driver index definitions. Remarks These constants should be used in place of hard-coded numeric literals. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-260 These values should be passed into the DRV_ETHPHY_Initialize and DRV_ETHPHY_Open routines to identify the driver instance in use. 5.1.4.5.4 DRV_ETHPHY_INDEX_COUNT Macro C #define DRV_ETHPHY_INDEX_COUNT 1 Description Ethernet PHY Driver Module Index Count This constant identifies the number of valid Ethernet PHY driver indices. Remarks This constant should be used in place of hard-coded numeric literals. This value is derived from part-specific header files defined as part of the peripheral libraries. 5.1.4.5.5 DRV_ETHPHY_INSTANCES_NUMBER Macro C #define DRV_ETHPHY_INSTANCES_NUMBER 1 Description Ethernet PHY hardware instance configuration This definition selects the maximum number of hardware instances that can be supported by the dynamic driver. Not defining it means using a static driver. Remarks None. 5.1.4.5.6 DRV_ETHPHY_PERIPHERAL_ID Macro C #define DRV_ETHPHY_PERIPHERAL_ID ETHPHY_ID_1 Description Ethernet PHY Peripheral ID Selection Defines an override of the peripheral ID, using macros. Remarks Some devices also support ETHPHY_ID_0 5.1.4.5.7 PHY_NEG_DONE_TMO Macro C #define PHY_NEG_DONE_TMO 2000 // negotiation complete timeout, ms. Description negotiation complete timeout, ms. based on IEEE 802.3 Clause 28 Table 28-9 autoneg_wait_timer value (max 1s) 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-261 5.1.4.5.8 PHY_NEG_INIT_TMO Macro C #define PHY_NEG_INIT_TMO 1 // negotiation initiation timeout, ms. Description negotiation initiation timeout, ms. 5.1.4.5.9 PHY_RESET_CLR_TMO Macro C #define PHY_RESET_CLR_TMO 500 // reset self clear timeout, ms. Description reset self clear timeout, ms. IEEE 802.3 Clause 22 Table 22-7 and paragraph "22.2.4.1.1 Reset" (max 0.5s) 5.1.4.5.10 TCPIP_IF_PIC32INT Macro C #define TCPIP_IF_PIC32INT Description We have an internal PIC32 MAC 5.1.4.6 Building the Library This section list the files that are available in the \src of the Ethernet PHY Driver. It lists which files need to be included in the build based on either a hardware feature present on the board or configuration option selected by the system. 5.1.4.7 Library Interface Data Types and Constants Name Description DRV_ETHPHY_CLIENT_STATUS Identifies the client-specific status of the Ethernet PHY driver. DRV_ETHPHY_INIT Contains all the data necessary to initialize the Ethernet PHY device. SMI_SCAN_DATA_STATUS Returns the status of the SMI of the Ethernet PHY. SYS_OBJ_HANDLE_INVALID This is macro SYS_OBJ_HANDLE_INVALID. SYS_OBJ_HANDLE_STATIC This is macro SYS_OBJ_HANDLE_STATIC. SYS_OBJ_HANDLE SYS_MODULE_OBJ is badly named. It should be SYS_MODULE_OBJ_HANDLE or something shorter. For brevity, it is renamed to SYS_OBJ_HANDLE. Client Level Functions Name Description DRV_ETHPHY_ClientStatus Gets the current client-specific status the Ethernet PHY driver. DRV_ETHPHY_Close Closes an opened instance of the Ethernet PHY driver. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-262 DRV_ETHPHY_HWConfigFlagsGet Returns the current Ethernet PHY hardware MII/RMII and ALTERNATE/DEFAULT configuration flags. DRV_ETHPHY_LinkScanRead Returns current link status. DRV_ETHPHY_LinkScanStart Starts an SMI scan of the link status. DRV_ETHPHY_LinkScanStop Stops the SMI scan of the link status. DRV_ETHPHY_LinkStatusGet Returns the current link status. DRV_ETHPHY_NegotiationIsComplete Returns the results of a previously initiated Ethernet PHY negotiation. DRV_ETHPHY_NegotiationResultGet Returns the link status after a completed negotiation. DRV_ETHPHY_Open Opens the specified Ethernet PHY driver instance and returns a handle to it. DRV_ETHPHY_Reset Immediately resets the Ethernet PHY. DRV_ETHPHY_RestartNegotiation Restarts auto-negotiation of the Ethernet PHY link. DRV_ETHPHY_Setup Initializes Ethernet PHY communication. External PHY Support Functions Name Description EXTPHY_MDIXCONFIGURE Configures the MDIX mode for the Ethernet PHY. EXTPHY_MIICONFIGURE Configures the Ethernet PHY in one of the MII/RMII operation modes. EXTPHY_SMIADDRESSGET Returns the SMI/MIIM address of the Ethernet PHY. EXTPHY_SMICLOCKGET Returns the SMI/MIIM maximum clock speed in Hz of the Ethernet PHY. Other Functions Name Description DRV_ETHPHY_VersionGet Gets the Ethernet PHY driver version in numerical format. DRV_ETHPHY_VersionStrGet Gets the Ethernet PHY driver version in string format. SMI/MIIM Functions Name Description DRV_ETHPHY_SMIClockSet Sets the SMI/MIIM interface clock. DRV_ETHPHY_SMIisBusy Returns a boolean 'true' if the SMI/MIIM interface is busy with a transaction. DRV_ETHPHY_SMIReadResultGet Gets the result of the SMI/MIIM register read. DRV_ETHPHY_SMIReadStart Initiates SMI/MIIM read transaction. DRV_ETHPHY_SMIScanDataGet Gets the latest SMI/MIIM scan data result. DRV_ETHPHY_SMIScanStart Starts the scan of the SMI/MIIM register. DRV_ETHPHY_SMIScanStatusGet Gets the status of the SMI/MIIM scan data. DRV_ETHPHY_SMIScanStop Stops the scan of the SMI/MIIM register. DRV_ETHPHY_SMIWriteStart Initiates a SMI/MIIM write transaction. System Level Functions Name Description DRV_ETHPHY_Deinitialize Deinitializes the specified instance of the Ethernet PHY driver module. DRV_ETHPHY_Initialize Initializes the Ethernet PHY driver. DRV_ETHPHY_Reinitialize Reinitializes the driver and refreshes any associated hardware settings. DRV_ETHPHY_Status Provides the current status of the Ethernet PHY driver module. DRV_ETHPHY_Tasks Maintains the driver's state machine and implements its ISR. Description This section describes the Application Programming Interface (API) functions of the Ethernet PHY Driver Library. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-263 Refer to each section for a detailed description. 5.1.4.7.1 System Level Functions 5.1.4.7.1.1 DRV_ETHPHY_Deinitialize Function C void DRV_ETHPHY_Deinitialize( SYS_OBJ_HANDLE object ); Description This function deinitializes the specified instance of the Ethernet PHY driver module, disabling its operation (and any hardware) and invalidates all of the internal data. Preconditions The DRV_ETHPHY_Initialize function must have been called before calling this routine and a valid SYS_OBJ_HANDLE must have been returned. Parameters Parameters Description object Driver object handle, returned from DRV_ETHPHY_Initialize Returns None. Remarks Once the Initialize operation has been called, the Deinitialize operation must be called before the Initialize operation can be called again. Example SYS_OBJ_HANDLE object; // Returned from DRV_ETHPHY_Initialize SYS_STATUS status; DRV_ETHPHY_Deinitialize(object); status = DRV_ETHPHY_Status(object); if (SYS_MODULE_DEINITIALIZED == status) { // Check again later if you need to know // when the driver is deinitialized. } 5.1.4.7.1.2 DRV_ETHPHY_Initialize Function C SYS_OBJ_HANDLE DRV_ETHPHY_Initialize( const SYS_MODULE_INDEX index, const SYS_MODULE_INIT * const init ); Description This function initializes the Ethernet PHY driver, making it ready for clients to open and use it. Preconditions None. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-264 Parameters Parameters Description drvIndex Index for the driver instance to be initialized init Pointer to a data structure containing any data necessary to initialize the driver. This pointer may be null if no data is required because static overrides have been provided. Returns If successful, returns a valid handle to a driver object. Otherwise, it returns SYS_OBJ_HANDLE_INVALID. The returned object must be passed as argument to DRV_ETHPHY_Reinitialize, DRV_ETHPHY_Deinitialize, DRV_ETHPHY_Tasks and DRV_ETHPHY_Status routines. Remarks This function must be called before any other Ethernet PHY routine is called. This function should only be called once during system initialization unless DRV_ETHPHY_Deinitialize is called to de-initialize the driver instance. Example DRV_ETHPHY_INIT init; SYS_OBJ_HANDLE objectHandle; // Populate the Ethernet PHY initialization structure init.phyId = ETHPHY_ID_0; // Populate the Ethernet PHY initialization structure init.phyId = ETHPHY_ID_2; init.sExtPHYFunctions.MyPHYMIIConfigure = &SMSC8720_MIIConfigure; init.sExtPHYFunctions.MyPHYMDIXConfigure = &SMSC8720_MDIXConfiguret; init.sExtPHYFunctions.MyPHYSMIAddressGet = &SMSC8720_SMIAddressGet; init.sExtPHYFunctions.MyPHYSMIClockGet = &SMSC8720_SMIClockGet; // Do something objectHandle = DRV_ETHPHY_Initialize(DRV_ETHPHY_INDEX_0, (SYS_MODULE_INIT*)&init); if (SYS_OBJ_HANDLE_INVALID == objectHandle) { // Handle error } 5.1.4.7.1.3 DRV_ETHPHY_Reinitialize Function C void DRV_ETHPHY_Reinitialize( SYS_OBJ_HANDLE object, const SYS_MODULE_INIT * const init ); Description This function reinitializes the driver and refreshes any associated hardware settings using the initialization data given, but it will not interrupt any ongoing operations. Preconditions The DRV_ETHPHY_Initialize function must have been called before calling this routine and a valid SYS_OBJ_HANDLE must have been returned. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-265 Parameters Parameters Description object Driver object handle, returned from the DRV_ETHPHY_Initialize routine init Pointer to the initialization data structure Returns None. Remarks This function can be called multiple times to reinitialize the module. This operation can be used to refresh any supported hardware registers as specified by the initialization data or to change the power state of the module. Example DRV_ETHPHY_INIT init; SYS_OBJ_HANDLE objectHandle; // Populate the Ethernet PHY initialization structure init.phyId = ETHPHY_ID_2; init.sExtPHYFunctions.MyPHYMIIConfigure = &SMSC8720_MIIConfigure; init.sExtPHYFunctions.MyPHYMDIXConfigure = &SMSC8720_MDIXConfiguret; init.sExtPHYFunctions.MyPHYSMIAddressGet = &SMSC8720_SMIAddressGet; init.sExtPHYFunctions.MyPHYSMIClockGet = &SMSC8720_SMIClockGet; DRV_ETHPHY_Reinitialize(objectHandle, (SYS_MODULE_INIT*)&init); phyStatus = DRV_ETHPHY_Status(objectHandle); if (SYS_STATUS_BUSY == phyStatus) { // Check again later to ensure the driver is ready } else if (SYS_STATUS_ERROR >= phyStatus) { // Handle error } 5.1.4.7.1.4 DRV_ETHPHY_Status Function C SYS_STATUS DRV_ETHPHY_Status( SYS_OBJ_HANDLE object ); Description This function provides the current status of the Ethernet PHY driver module. Preconditions The DRV_ETHPHY_Initialize function must have been called before calling this function. Parameters Parameters Description object Driver object handle, returned from DRV_ETHPHY_Initialize Returns SYS_STATUS_READY - Indicates that the driver is busy with a previous system level operation and cannot start another 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-266 Remarks Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new operations. SYS_STATUS_BUSY - Indicates that the driver is busy with a previous system level operation and cannot start another SYS_STATUS_ERROR - Indicates that the driver is in an error state Any value less than SYS_STATUS_ERROR is also an error state. SYS_MODULE_DEINITIALIZED - Indicates that the driver has been de-initialized This value is less than SYS_STATUS_ERROR. The this operation can be used to determine when any of the driver's module level operations has completed. If the status operation returns SYS_STATUS_BUSY, the a previous operation has not yet completed. Once the status operation returns SYS_STATUS_READY, any previous operations have completed. The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state. This function will NEVER block waiting for hardware. If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the deinitialize operation will need to be called, followed by the initialize operation to return to normal operations. Example SYS_OBJ_HANDLE object; // Returned from DRV_ETHPHY_Initialize SYS_STATUS status; status = DRV_ETHPHY_Status(object); else if (SYS_STATUS_ERROR >= status) { // Handle error } 5.1.4.7.1.5 DRV_ETHPHY_Tasks Function C void DRV_ETHPHY_Tasks( SYS_OBJ_HANDLE object ); Description This function is used to maintain the driver's internal state machine and implement its ISR for interrupt-driven implementations. Preconditions The DRV_ETHPHY_Initialize routine must have been called for the specified Ethernet PHY driver instance. Parameters Parameters Description object Object handle for the specified driver instance (returned from DRV_ETHPHY_Initialize) Returns None Remarks This function is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-267 apropriate raw ISR. This function may excute in an ISR context and will never block or access any resources that may cause it to block. Example SYS_OBJ_HANDLE object; // Returned from DRV_ETHPHY_Initialize while (true) { DRV_ETHPHY_Tasks (object); // Do other tasks } 5.1.4.7.2 Client Level Functions 5.1.4.7.2.1 DRV_ETHPHY_ClientStatus Function C DRV_ETHPHY_CLIENT_STATUS DRV_ETHPHY_ClientStatus( DRV_HANDLE handle ); Description This function gets the client-specfic status of the Ethernet PHY driver associated with the given handle. Preconditions The DRV_ETHPHY_Initialize routine must have been called. DRV_ETHPHY_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine Returns A DRV_ETHPHY_CLIENT_STATUS value describing the current status of the driver. Remarks This function will not block for hardware access and will immediately return the current status. Example DRV_HANDLE phyHandle; // Returned from DRV_ETHPHY_Open DRV_ETHPHY_CLIENT_STATUS phyClientStatus; phyClientStatus = DRV_ETHPHY_ClientStatus(phyHandle); if(DRV_ETHPHY_CLIENT_STATUS_ERROR >= phyClientStatus) { // Handle the error } 5.1.4.7.2.2 DRV_ETHPHY_Close Function C void DRV_ETHPHY_Close( DRV_HANDLE handle ); 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-268 Description This function closes an opened instance of the Ethernet PHY driver, invalidating the handle. Preconditions The DRV_ETHPHY_Initialize routine must have been called for the specified Ethernet PHY driver instance. DRV_ETHPHY_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open instance handle, returned from the driver's open routine Returns None Remarks After calling this routine, the handle passed in "handle" must not be used with any of the remaining driver routines. A new handle must be obtained by calling DRV_ETHPHY_Open before the caller may use the driver again. If DRV_IO_INTENT_BLOCKING was requested and the driver was built appropriately to support blocking behavior call may block until the operation is complete. If DRV_IO_INTENT_NON_BLOCKING request the driver client can call the DRV_ETHPHY_Status operation to find out when the module is in the ready state (the handle is no longer valid). Usually there is no need for the driver client to verify that the Close operation has completed. Example DRV_HANDLE handle; // Returned from DRV_ETHPHY_Open DRV_ETHPHY_Close(handle); 5.1.4.7.2.3 DRV_ETHPHY_HWConfigFlagsGet Function C ETHPHY_CONFIG_FLAGS DRV_ETHPHY_HWConfigFlagsGet( DRV_HANDLE handle ); Description This function returns the current Ethernet PHY hardware MII/RMII and ALTERNATE/DEFAULT configuration flags from the Device Configuration Fuse bits. Preconditions None. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) Returns Ethernet PHY configuration flag, see ETHPHY_CONFIG_FLAGS enumeration for bit values. Remarks Please note, 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-269 • ETHPHY_CONFIG_FLAGS DRV_ETHPHY_HWConfigFlagsGet( DRV_HANDLE handle ) replaces the legacy "Ethernet Controller Library" function: • eEthPhyCfgFlags EthPhyGetHwConfigFlags(void) Example 5.1.4.7.2.4 DRV_ETHPHY_LinkScanRead Function C ETH_LINK_STATUS DRV_ETHPHY_LinkScanRead( DRV_HANDLE handle ); Description This function returns the current link status. Preconditions DRV_ETHPHY_LinkScanStart must be called first. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) Returns Current link status, see ETH_LINK_STATUS enumeration. Remarks See also DRV_ETHPHY_LinkStatusGet. Please note, • ETH_LINK_STATUS DRV_ETHPHY_LinkScanRead( DRV_HANDLE handle ) replaces the legacy "Ethernet Controller Library" function: • eEthLinkStat EthPhyScanLinkRead(void) Example 5.1.4.7.2.5 DRV_ETHPHY_LinkScanStart Function C void DRV_ETHPHY_LinkScanStart( DRV_HANDLE handle ); Description This function starts an SMI scan of the link status. Preconditions Communication with the Ethernet PHY was already established. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-270 Returns None. Remarks This function starts an SMII scan of the Ethernet PHY link status register. It is a more efficient way of having access to the current link status, since the normal SMI frame read operation is slow. Please note, • void DRV_ETHPHY_LinkScanStart( DRV_HANDLE handle ) replaces the legacy "Ethernet Controller Library" function: • void EthPhyScanLinkStart(void) Example 5.1.4.7.2.6 DRV_ETHPHY_LinkScanStop Function C void DRV_ETHPHY_LinkScanStop( DRV_HANDLE handle ); Description This function stops the SMI scan of the ink status. Preconditions Communication with the Ethernet PHY was already established. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) Returns None. Remarks Please note, • void DRV_ETHPHY_LinkScanStop( DRV_HANDLE handle ) replaces the legacy "Ethernet Controller Library" function: • void EthPhyScanLinkStop(void) Example 5.1.4.7.2.7 DRV_ETHPHY_LinkStatusGet Function C ETH_LINK_STATUS DRV_ETHPHY_LinkStatusGet( DRV_HANDLE handle, bool refresh ); Description This function returns the urrent link status. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-271 Preconditions DRV_ETHPHY_Setup should have been called. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) refresh Boolean flag, true to specify that a double read is needed Returns Current link status, see ETH_LINK_STATUS enumeration. Remarks This function reads the Ethernet PHY to get current link status If refresh is specified then, if the link is down a second read will be performed to return the current link status. Please note, • ETH_LINK_STATUS DRV_ETHPHY_LinkStatusGet( DRV_HANDLE handle, bool refresh ) replaces the legacy "Ethernet Controller Library" function: • eEthLinkStat EthPhyGetLinkStatus(int refresh) Example 5.1.4.7.2.8 DRV_ETHPHY_NegotiationIsComplete Function C ETH_RESULT_CODE DRV_ETHPHY_NegotiationIsComplete( DRV_HANDLE handle, bool waitComplete ); Description This function returns the results of a previously initiated Ethernet PHY negotiation. Preconditions DRV_ETHPHY_Setup (and DRV_ETHPHY_RestartNegotiation) should have been called. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) waitComplete Boolean flag, true if wait for completion is required Returns ETH_RES_OK if negotiation is done, ETH_RES_NEGOTIATION_INACTIVE if no negotiation in progress, ETH_RES_NEGOTIATION_NOT_STARTED if negotiation not yet started yet (means tmo if waitComplete was requested), or ETH_RES_NEGOTIATION_ACTIVE if negotiation ongoing (means tmo if waitComplete was requested). Remarks See also DRV_ETHPHY_NegotiationResultGet. Please note, • ETH_RESULT_CODE DRV_ETHPHY_NegotiationIsComplete( DRV_HANDLE handle, bool waitComplete ) replaces the legacy "Ethernet Controller Library" function: 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-272 • eEthRes EthPhyNegotiationComplete(int waitComplete) Example 5.1.4.7.2.9 DRV_ETHPHY_NegotiationResultGet Function C ETH_LINK_STATUS DRV_ETHPHY_NegotiationResultGet( DRV_HANDLE handle, ETH_OPEN_FLAGS* pFlags, ETH_PAUSE_TYPE* pPauseType ); Description This function returns the link status after a completed negotiation. Preconditions DRV_ETHPHY_Setup, DRV_ETHPHY_RestartNegotiation, and DRV_ETHPHY_NegotiationIsComplete should have been called. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) pFlags Address to store the negotiation result pPauseType Address to store the pause type supported by the link partner Returns Link status after the (completed) negotiation, see ETH_LINK_STATUS enumeration. Remarks If no negotiation possible/active/failed, most likely the flags are invalid! Please note, • ETH_LINK_STATUS DRV_ETHPHY_NegotiationResultGet( DRV_HANDLE handle, ETH_OPEN_FLAGS* pFlags, ETH_PAUSE_TYPE* pPauseType ) replaces the legacy "Ethernet Controller Library" function: • eEthLinkStat EthPhyGetNegotiationResult(eEthOpenFlags* pFlags, eEthMacPauseType* pPauseType) Example 5.1.4.7.2.10 DRV_ETHPHY_Open Function C DRV_HANDLE DRV_ETHPHY_Open( const SYS_MODULE_INDEX drvIndex, const DRV_IO_INTENT intent ); Description This function opens the specified Ethernet PHY driver instance and provides a handle that must be provided to all other client-level operations to identify the caller and the instance of the driver. Preconditions The DRV_ETHPHY_Initialize function must have been called before calling this function. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-273 Parameters Parameters Description drvIndex Identifier for the object instance to be opened intent Zero or more of the values from the enumeration DRV_IO_INTENT ORed together to indicate the intended use of the driver Returns If successful, the routine returns a valid open-instance handle (a number identifying both the caller and the module instance). If an error occurs, the return value is DRV_HANDLE_INVALID. Remarks The handle returned is valid until the DRV_ETHPHY_Close routine is called. This function will NEVER block waiting for hardware. If the DRV_IO_INTENT_BLOCKING is requested and the driver was built appropriately to support blocking behavior, other client-level operations may block waiting on hardware until they are complete. If DRV_IO_INTENT_NON_BLOCKING is requested the driver client can call the DRV_ETHPHY_ClientStatus operation to find out when the module is in the ready state. If the requested intent flags are not supported, the function will return DRV_HANDLE_INVALID. Example DRV_HANDLE handle; handle = DRV_ETHPHY_Open(DRV_ETHPHY_INDEX_0, DRV_IO_INTENT_EXCLUSIVE); if (DRV_HANDLE_INVALID == handle) { // Unable to open the driver } 5.1.4.7.2.11 DRV_ETHPHY_Reset Function C bool DRV_ETHPHY_Reset( DRV_HANDLE handle, bool waitComplete ); Description This function immediately resets the Ethernet PHY, optionally waiting for a reset to complete. Preconditions Communication with the Ethernet PHY was already established. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) waitComplete boolean flag, if true the procedure will wait for reset to complete Returns True - If PHY reset procedure completed (or completion not required) False - Otherwise Remarks Please note, 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-274 • bool DRV_ETHPHY_Reset( DRV_HANDLE handle, bool waitComplete ) replaces the legacy "Ethernet Controller Library" function: • int EthPhyReset(int waitComplete) Example 5.1.4.7.2.12 DRV_ETHPHY_RestartNegotiation Function C void DRV_ETHPHY_RestartNegotiation( DRV_HANDLE handle ); Description This function restarts auto-negotiation of the Ethernet PHY link. Preconditions The Ethernet PHY should have been initialized with the proper duplex/speed mode. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) Returns None. Remarks Please note, • void DRV_ETHPHY_RestartNegotiation( DRV_HANDLE handle ) replaces the legacy "Ethernet Controller Library" function: • eEthRes EthPhyRestartNegotiation(void) Example 5.1.4.7.2.13 DRV_ETHPHY_Setup Function C ETH_RESULT_CODE DRV_ETHPHY_Setup( DRV_HANDLE handle, ETH_OPEN_FLAGS oFlags, ETHPHY_CONFIG_FLAGS cFlags, ETH_OPEN_FLAGS * pResFlags ); Description This function initializes the Ethernet PHY communication. It tries to detect the external Ethernet PHY, to read the capabilties and find a match with the requested features.Then it programs the Ethernet PHY accordingly. Preconditions DRV_ETHMAC_LegacyInit should have been called to initialize the Ethernet MAC. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-275 Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine oFlags The requested open flags cFlags Ethernet PHY MII/RMII configuration flags pResFlags Address to store the initialization results Returns ETH_RES_OK for success; otherwise, an error code. Remarks Please note, • ETH_RESULT_CODE DRV_ETHPHY_Setup( DRV_HANDLE handle, ETH_OPEN_FLAGS oFlags, ETHPHY_CONFIG_FLAGS cFlags, ETH_OPEN_FLAGS* pResFlags ) replaces the legacy "Ethernet Controller Library" function: • eEthRes EthPhyInit(eEthOpenFlags oFlags, eEthPhyCfgFlags cFlags, eEthOpenFlags* pResFlags) Example 5.1.4.7.3 SMI/MIIM Functions 5.1.4.7.3.1 DRV_ETHPHY_SMIClockSet Function C void DRV_ETHPHY_SMIClockSet( DRV_HANDLE handle, uint32_t hostClock, uint32_t maxSMIClock ); Description This function sets SMI/MIIM interface clock base on host clock and maximum supported SMI/MIIM interface clock speed. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) hostClock Host clock speed in Hz maxSMIClock Maximum supported SMI/MIIM clock speed in Hz Returns None. Remarks Please note, • void DRV_ETHPHY_SMIClockSet( DRV_HANDLE handle, uint16_t hostClock, uint16_t maxSMIClock ) replaces the legacy "Ethernet Controller Library" function: • void EthMIIMConfig(unsigned int hostClock, unsigned int miimClock) Example 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-276 5.1.4.7.3.2 DRV_ETHPHY_SMIisBusy Function C bool DRV_ETHPHY_SMIisBusy( DRV_HANDLE handle ); Description This function returns a boolean 'true' if the SMI/MIIM interface is busy with a transaction. Preconditions MyPHYSMIClockSet() called to setup SMI/MIIM clock. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) Returns • true - If the SMI/MIIM is busy • false - If the SMI/MIIM is not busy Example 5.1.4.7.3.3 DRV_ETHPHY_SMIReadResultGet Function C uint16_t DRV_ETHPHY_SMIReadResultGet( DRV_HANDLE handle ); Description This function gets the result of the SMI/MIIM register read. Preconditions MyPHYSMIClockSet was called to set up the SMI/MIIM clock and DRV_ETHPHY_SMIReadStart was called to initiate a SMI/MIIM register read. DRV_ETHPHY_SMIisBusy should return false. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) Returns Result of the SMI/MIIM register read previously scheduled. Remarks Please note, • uint16_t DRV_ETHPHY_SMIReadResultGet( DRV_HANDLE handle ) replaces the legacy "Ethernet Controller Library" function: • unsigned short EthMIIMReadResult ( void ) Example 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-277 5.1.4.7.3.4 DRV_ETHPHY_SMIReadStart Function C void DRV_ETHPHY_SMIReadStart( DRV_HANDLE handle, unsigned int rIx, unsigned int phyAdd ); Description This function initiates SMI/MIIM read transaction for a given PHY address and register. Preconditions MyPHYSMIClockSet was called to set up the SMI/MIIM clock. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) rIx PHY register to be accessed phyAdd Address of PHY to be accessed Returns None. Remarks Please note, • void DRV_ETHPHY_SMIReadStart( DRV_HANDLE handle, unsigned int rIx, unsigned int phyAdd ) replaces the legacy "Ethernet Controller Library" function: • void EthMIIMReadStart(unsigned int rIx, unsigned int phyAdd) Example 5.1.4.7.3.5 DRV_ETHPHY_SMIScanDataGet Function C uint16_t DRV_ETHPHY_SMIScanDataGet( DRV_HANDLE handle ); Description This functino gets the latest SMI/MIIM scan data result. Preconditions DRV_ETHPHY_SMIScanStart() has been called. DRV_ETHPHY_SMIScanStatusGet() should return SMI_SCAN_DATA_VALID. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) Returns Current scan result. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-278 Remarks Scan data status must be SMI_SCAN_DATA_VALID. Please note, • uint16_t DRV_ETHPHY_SMIScanDataGet( DRV_HANDLE handle ) replaces the legacy "Ethernet Controller Library" function: • unsigned short EthMIIMScanResult(void) Example 5.1.4.7.3.6 DRV_ETHPHY_SMIScanStart Function C void DRV_ETHPHY_SMIScanStart( DRV_HANDLE handle, unsigned int rIx, unsigned int phyAdd ); Description This function starts the scan of the SMI/MIIM register. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) rIx PHY register to be accessed, 0-31 phyAdd PHY address, 0-31 Returns None. Remarks Please note, • void DRV_ETHPHY_SMIScanStart( DRV_HANDLE handle, unsigned int rIx, unsigned int phyAdd ) replaces the legacy "Ethernet Controller Library" function: • void EthMIIMScanStart(unsigned int rIx, unsigned int phyAdd) Example 5.1.4.7.3.7 DRV_ETHPHY_SMIScanStatusGet Function C SMI_SCAN_DATA_STATUS DRV_ETHPHY_SMIScanStatusGet( DRV_HANDLE handle ); Description This function gets the status of the SMI/MIIM scan data. Preconditions DRV_ETHPHY_SMIScanStart() has been called. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-279 Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) Returns SMI_SCAN_DATA_NOTVALID or SMI_SCAN_DATA_VALID Remarks None. Example 5.1.4.7.3.8 DRV_ETHPHY_SMIScanStop Function C void DRV_ETHPHY_SMIScanStop( DRV_HANDLE handle ); Description This function stops the scan of the SMI/MIIM register. Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) Returns None. Remarks Stops a scan transaction on the SMI interface. Please note, • void DRV_ETHPHY_SMIScanStop( DRV_HANDLE handle ) replaces the legacy "Ethernet Controller Library" function: • void EthMIIMScanStop ( void ) Example 5.1.4.7.3.9 DRV_ETHPHY_SMIWriteStart Function C void DRV_ETHPHY_SMIWriteStart( DRV_HANDLE handle, unsigned int rIx, unsigned int phyAdd, uint16_t wData ); Description This function initiates SMI/MIIM write transaction for a given PHY address and register. Preconditions MyPHYSMIClockSet was called to set up the SMI/MIIM clock. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-280 Parameters Parameters Description handle Client's driver handle (returned from DRV_ETHPHY_Open) rIx PHY register to be accessed phyAdd Address of PHY to be accessed wData Data to be written Returns None. Remarks Please note, • void DRV_ETHPHY_SMIWriteStart( DRV_HANDLE handle, unsigned int rIx, unsigned int phyAdd, uint16_t wData ) replaces the legacy "Ethernet Controller Library" function: • void EthMIIMWriteStart(unsigned int rIx, unsigned int phyAdd, unsigned short wData) Example 5.1.4.7.4 External PHY Support Functions 5.1.4.7.4.1 EXTPHY_MDIXCONFIGURE Type C typedef ETH_RESULT_CODE (* EXTPHY_MDIXCONFIGURE)(DRV_HANDLE handle, ETH_OPEN_FLAGS oFlags); Description Pointer To Function: ETH_RESULT_CODE EXTPHY_MDIXConfigure( DRV_HANDLE handle, ETH_OPEN_FLAGS oFlags ) Configures the MDIX mode for the Ethernet PHY. Preconditions Communication to the PHY should have been established. Parameters Parameters Description handle Client's driver handle (returned from DRV_PHY_Open) oFlags Requested open flags: ETH_OPEN_MDIX_AUTO, ETH_OPEN_MDIX_NORM, or ETH_OPEN_MDIX_NORM | ETH_OPEN_MDIX_SWAP Returns ETH_RES_OK - if success; otherwise, ETH_RES_CFG_ERR. Remarks For some external PHYs, the MDIX configuration is set by pins on the device. In this case, the function will return ETH_RES_OK if the cFlags requests the already configured interface; otherwise, ETH_RES_CFG_ERR. 5.1.4.7.4.2 EXTPHY_MIICONFIGURE Type C typedef ETH_RESULT_CODE (* EXTPHY_MIICONFIGURE)(DRV_HANDLE handle, ETHPHY_CONFIG_FLAGS cFlags); 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-281 Description Pointer To Function: ETH_RESULT_CODE EXTPHY_MIIConfigure( DRV_HANDLE handle, ETHPHY_CONFIG_FLAGS cFlags ) Configures the Ethernet PHY in one of the MII/RMII operation modes. Preconditions Communication to the PHY should have been established. Parameters Parameters Description handle Client's driver handle (returned from DRV_PHY_Open) cFlags Requested configuration flags: ETH_PHY_CFG_RMII or ETH_PHY_CFG_MII Returns ETH_RES_OK - if success; otherwise, ETH_RES_CFG_ERR. Remarks For some external PHYs, the data interface is set by pins on the device or fuses in the host. In this case, the function will return ETH_RES_OK if the cFlags requests the already configured interface; otherwise, ETH_RES_CFG_ERR. 5.1.4.7.4.3 EXTPHY_SMIADDRESSGET Type C typedef unsigned int (* EXTPHY_SMIADDRESSGET)(DRV_HANDLE handle); Description Pointer To Function: uint16_t EXTPHY_SMIAddressGet( DRV_HANDLE handle ); Returns the SMI/MIIM address of the Ethernet PHY. Preconditions Communication to the PHY should have been established. Parameters Parameters Description handle Client's driver handle (returned from DRV_PHY_Open) Returns The SMI/MIIM Ethernet PHY address as an unsigned 16-bit integer. Remarks For some external PHYs, the MDIX configuration is set by pins on the device. In this case, the function will return ETH_RES_OK if the cFlags requests the already configured interface; otherwise, ETH_RES_CFG_ERR. 5.1.4.7.4.4 EXTPHY_SMICLOCKGET Type C typedef unsigned int (* EXTPHY_SMICLOCKGET)(DRV_HANDLE handle); Description Pointer to Function: uint16_t EXTPHY_SMIClockGet( DRV_HANDLE handle ); Returns the SMI/MIIM maximum clock speed in Hz of the Ethernet PHY. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-282 Preconditions Communication to the PHY should have been established. Parameters Parameters Description handle Client's driver handle (returned from DRV_PHY_Open) Returns The maximum SMI/MIIM clock speed as an unsigned 16-bit integer. Remarks For some external PHYs, the MDIX configuration is set by pins on the device. In this case, the function will return ETH_RES_OK if the cFlags requests the already configured interface; otherwise, ETH_RES_CFG_ERR. 5.1.4.7.5 Other Functions 5.1.4.7.5.1 DRV_ETHPHY_VersionGet Function C unsigned int DRV_ETHPHY_VersionGet( const SYS_MODULE_INDEX drvIndex ); Description This function gets the Ethernet PHY driver version. The version is encoded as major * 10000 + minor * 100 + patch. The stringed version can be obtained using DRV_ETHPHY_VersionStrGet() Preconditions None. Parameters Parameters Description drvIndex Identifier for the object instance to get the version for Returns Current driver version in numerical format. Remarks None. Example unsigned int version; version = DRV_ETHPHY_VersionGet( DRV_ETHPHY_INDEX_1 ); if(version < 110200) { // Do Something } 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-283 5.1.4.7.5.2 DRV_ETHPHY_VersionStrGet Function C char * DRV_ETHPHY_VersionStrGet( const SYS_MODULE_INDEX drvIndex ); Description This function gets the Ethernet PHY driver version. The version is returned as major.minor.path[type], where type is optional. The numerical version can be obtained using DRV_ETHPHY_VersionGet() Preconditions None. Parameters Parameters Description drvIndex Identifier for the object instance to get the version for. Returns Current Ethernet PHY driver version in the string format. Remarks None. Example char *version; version = DRV_ETHPHY_VersionStrGet( DRV_ETHPHY_INDEX_1 ); printf("%s", version); 5.1.4.7.6 Data Types and Constants 5.1.4.7.6.1 DRV_ETHPHY_CLIENT_STATUS Enumeration C typedef enum { DRV_ETHPHY_CLIENT_STATUS_ERROR, DRV_ETHPHY_CLIENT_STATUS_CLOSED, DRV_ETHPHY_CLIENT_STATUS_BUSY, DRV_ETHPHY_CLIENT_STATUS_READY } DRV_ETHPHY_CLIENT_STATUS; Description Ethernet PHY Driver Client Status This enumeration identifies the client-specific status of the Ethernet PHY driver. Members Members Description DRV_ETHPHY_CLIENT_STATUS_ERROR Unspecified error condition DRV_ETHPHY_CLIENT_STATUS_CLOSED Client is not open DRV_ETHPHY_CLIENT_STATUS_BUSY An operation is currently in progress DRV_ETHPHY_CLIENT_STATUS_READY Up and running, no operations running 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-284 Remarks None. 5.1.4.7.6.2 DRV_ETHPHY_INIT Structure C typedef struct { SYS_MODULE_INIT moduleInit; ETH_MODULE_ID ethphyId; EXTPHY_MIICONFIGURE MyPHYMIIConfigure; EXTPHY_MDIXCONFIGURE MyPHYMDIXConfigure; EXTPHY_SMIADDRESSGET MyPHYSMIAddressGet; EXTPHY_SMICLOCKGET MyPHYSMIClockGet; } DRV_ETHPHY_INIT; Description Ethernet PHY Device Driver Initialization Data This structure contains all the data necessary to initialize the Ethernet PHY device. Members Members Description SYS_MODULE_INIT moduleInit; System module initialization ETH_MODULE_ID ethphyId; Identifies peripheral (PLIB-level) ID EXTPHY_MIICONFIGURE MyPHYMIIConfigure; Select MII or RMII data interface EXTPHY_MDIXCONFIGURE MyPHYMDIXConfigure; AutoMDIX or Manual MDIX EXTPHY_SMIADDRESSGET MyPHYSMIAddressGet; Returns PHY's SMI Address EXTPHY_SMICLOCKGET MyPHYSMIClockGet; Returns PHY's clock speed Remarks A pointer to a structure of this format containing the desired initialization data must be passed into the DRV_ETHPHY_Initialize routine. 5.1.4.7.6.3 SMI_SCAN_DATA_STATUS Enumeration C typedef enum { SMI_SCAN_DATA_NOTVALID, SMI_SCAN_DATA_VALID } SMI_SCAN_DATA_STATUS; Description SMI Interface Scan Data Status Enumeration This enumeration returns the status of the SMI of the Ethernet PHY. Members Members Description SMI_SCAN_DATA_NOTVALID SMI interface ready for new scan/read/write SMI_SCAN_DATA_VALID SMI interface ready for new scan/read/write 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-285 Remarks None. 5.1.4.7.6.4 SYS_OBJ_HANDLE_INVALID Macro C #define SYS_OBJ_HANDLE_INVALID ( (SYS_OBJ_HANDLE) -1 ) Description This is macro SYS_OBJ_HANDLE_INVALID. 5.1.4.7.6.5 SYS_OBJ_HANDLE_STATIC Macro C #define SYS_OBJ_HANDLE_STATIC ( (SYS_OBJ_HANDLE) 0 ) Description This is macro SYS_OBJ_HANDLE_STATIC. 5.1.4.7.6.6 SYS_OBJ_HANDLE Type C typedef uintptr_t SYS_OBJ_HANDLE; Description SYS_MODULE_OBJ Rename SYS_MODULE_OBJ is badly named. It should be SYS_MODULE_OBJ_HANDLE or something shorter. For brevity, it is renamed to SYS_OBJ_HANDLE. Remarks None. 5.1.4.8 Files Files Name Description drv_ethphy.h Ethernet ETHPHY Device Driver Interface File drv_ethphy_config.h Ethernet PHY driver configuration definitions template. Description 5.1.4.8.1 drv_ethphy.h Ethernet ETHPHY Device Driver Interface The Ethernet ETHPHY device driver provides a simple interface to manage an Ethernet ETHPHY peripheral using MIIM (or SMI) interface. This file defines the interface definitions and prototypes for the Etherent ETHPHY driver. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-286 Enumerations Name Description DRV_ETHPHY_CLIENT_STATUS Identifies the client-specific status of the Ethernet PHY driver. SMI_SCAN_DATA_STATUS Returns the status of the SMI of the Ethernet PHY. Functions Name Description DRV_ETHPHY_ClientStatus Gets the current client-specific status the Ethernet PHY driver. DRV_ETHPHY_Close Closes an opened instance of the Ethernet PHY driver. DRV_ETHPHY_Deinitialize Deinitializes the specified instance of the Ethernet PHY driver module. DRV_ETHPHY_HWConfigFlagsGet Returns the current Ethernet PHY hardware MII/RMII and ALTERNATE/DEFAULT configuration flags. DRV_ETHPHY_Initialize Initializes the Ethernet PHY driver. DRV_ETHPHY_LinkScanRead Returns current link status. DRV_ETHPHY_LinkScanStart Starts an SMI scan of the link status. DRV_ETHPHY_LinkScanStop Stops the SMI scan of the link status. DRV_ETHPHY_LinkStatusGet Returns the current link status. DRV_ETHPHY_NegotiationIsComplete Returns the results of a previously initiated Ethernet PHY negotiation. DRV_ETHPHY_NegotiationResultGet Returns the link status after a completed negotiation. DRV_ETHPHY_Open Opens the specified Ethernet PHY driver instance and returns a handle to it. DRV_ETHPHY_Reinitialize Reinitializes the driver and refreshes any associated hardware settings. DRV_ETHPHY_Reset Immediately resets the Ethernet PHY. DRV_ETHPHY_RestartNegotiation Restarts auto-negotiation of the Ethernet PHY link. DRV_ETHPHY_Setup Initializes Ethernet PHY communication. DRV_ETHPHY_SMIClockSet Sets the SMI/MIIM interface clock. DRV_ETHPHY_SMIisBusy Returns a boolean 'true' if the SMI/MIIM interface is busy with a transaction. DRV_ETHPHY_SMIReadResultGet Gets the result of the SMI/MIIM register read. DRV_ETHPHY_SMIReadStart Initiates SMI/MIIM read transaction. DRV_ETHPHY_SMIScanDataGet Gets the latest SMI/MIIM scan data result. DRV_ETHPHY_SMIScanStart Starts the scan of the SMI/MIIM register. DRV_ETHPHY_SMIScanStatusGet Gets the status of the SMI/MIIM scan data. DRV_ETHPHY_SMIScanStop Stops the scan of the SMI/MIIM register. DRV_ETHPHY_SMIWriteStart Initiates a SMI/MIIM write transaction. DRV_ETHPHY_Status Provides the current status of the Ethernet PHY driver module. DRV_ETHPHY_Tasks Maintains the driver's state machine and implements its ISR. DRV_ETHPHY_VersionGet Gets the Ethernet PHY driver version in numerical format. DRV_ETHPHY_VersionStrGet Gets the Ethernet PHY driver version in string format. Macros Name Description DRV_ETHPHY_INDEX_0 Ethernet PHY driver index definitions. DRV_ETHPHY_INDEX_1 This is macro DRV_ETHPHY_INDEX_1. DRV_ETHPHY_INDEX_COUNT Number of valid Ethernet PHY driver indices. 5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library 5-287 Structures Name Description DRV_ETHPHY_INIT Contains all the data necessary to initialize the Ethernet PHY device. Types Name Description EXTPHY_MDIXCONFIGURE Configures the MDIX mode for the Ethernet PHY. EXTPHY_MIICONFIGURE Configures the Ethernet PHY in one of the MII/RMII operation modes. EXTPHY_SMIADDRESSGET Returns the SMI/MIIM address of the Ethernet PHY. EXTPHY_SMICLOCKGET Returns the SMI/MIIM maximum clock speed in Hz of the Ethernet PHY. Company Microchip Technology Incorported FileName: drv_ethphy.h 5.1.4.8.2 drv_ethphy_config.h Ethernet PHY Driver Configuration Definitions for the Template Version These definitions statically define the driver's mode of operation. Macros Name Description DRV_ETHPHY_CLIENTS_NUMBER Selects the miximum number of clients. DRV_ETHPHY_INDEX Ethernet PHY static index selection. DRV_ETHPHY_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be supported by the dynamic driver. DRV_ETHPHY_PERIPHERAL_ID Defines an override of the peripheral ID. PHY_NEG_DONE_TMO negotiation complete timeout, ms. based on IEEE 802.3 Clause 28 Table 28-9 autoneg_wait_timer value (max 1s) PHY_NEG_INIT_TMO negotiation initiation timeout, ms. PHY_RESET_CLR_TMO reset self clear timeout, ms. IEEE 802.3 Clause 22 Table 22-7 and paragraph "22.2.4.1.1 Reset" (max 0.5s) TCPIP_IF_PIC32INT We have an internal PIC32 MAC File Name drv_ethphy_config.h Company Microchip Technology Inc. 5.1.4.8.3 drv_ethernet_flags.h This file can be accessed through the following link: drv_ethernet_flags.h 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-288 5.1.5 Graphics (GFX) Driver Library 5.1.5.1 Introduction Graphics (GFX) Driver Library for Microchip Microcontrollers The Graphics (GFX) Driver Layer Library is the GFX library stack available for the Microchip family of microcontrollers. Description The MPLAB Harmony Graphics (GFX) Library is highly modular and is optimized for Microchip’s 32-bit microcontrollers. Additionally, the library is free for Microchip customers, easy to use, and has an open documented interface for new driver support, which requires creation of only one C file. 5.1.5.2 Release Notes MPLAB Harmony Version: v0.70b Graphics (GFX) Driver Layer Library Version : 4.00b Release Date: 18Nov2013 New This Release: This is the first release of the library. The interface can change in the beta and\or 1.0 release. Known Issues: Nothing to report in this release. 5.1.5.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-289 5.1.5.4 Using the Library 5.1.5.4.1 Abstraction Model The Graphics Driver Library structure consists of the following: • Application Layer – This is the program that utilizes the Graphics Driver Library • User Message Interface- This layer should be implemented by user to provide messages for the library • Graphics Object Layer – This layer renders the widgets controls such as button, slider, window, and so on • Graphics Primitives Layer – This layer implements the primitive drawing functions • Device Display Driver – This layer is dependent on the display device being used • Graphics Display Module – This is the display device being used The library provides two configurations (Blocking and Non-Blocking). For a Blocking configuration, all draw functions are blocking calls that delay the execution of program until rendering is done. For a Non-Blocking configuration, draw functions do not wait for the drawing completion and release control to the program. In this configuration, a draw function should be called repeatedly until the rendering of that particular draw function is complete. This allows efficient use of microcontroller CPU time since it can perform other tasks if the rendering is not yet done. 5.1.5.4.2 Library Overview This layer informs the GFX library on which graphics controller is being used along with the LCD. It takes input only from the primitive layer. This layer contains all the hardware specific functions the primitive layer needs to render primitives onto the LCD. Each driver contained in the GFX library has a build time structure associated with it that informs the primitive layer which hardware specific functions are available. Thus when the primitive layer calls a specific rendering task it gets passed a pointer from the driver of that task. If the task does not exist the driver passes back a NULL and the primitive layer and either render the primitive without hardware support or let the application know that this feature is not available. 5.1.5.5 Configuring the Library The configuration of the GFX driver is based on the file drv_gfx_config.h This header file contains the configuration selection for the GFX Driver. Based on the selections made, the GFX Driver will support or not support selected features. These configuration settings will apply to all instances of the GFX Driver. This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a successful build. Refer to the Applications Overview section for more details. The configuration of the GFX driver layer is mainly dependent on making sure the needed driver has the core driver functions inside of it. The main rendering one being a PixelPut type function for the GFX primitive layer. Once the GFX driver structure (GFX_DRV_DATA) is defined along with its primitive function rendering structure (GFX_DRV_FUNCTIONS) it can be used by the GFX primitive layer. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-290 5.1.5.6 Building the Library This section lists the files that are available in the /src folder of the GFX driver. It lists which files need to be included in the build based on either a hardware feature present on the board or a configuration option selected by the system. 5.1.5.7 Library Interface Data Types and Constants Name Description GFX_DRV_DATA Structure containing the driver graphics controller data. GFX_DRV_FUNCTIONS Structure containing the driver functions used by the primitive layer. LAYER_TYPE types of Layers supported by the GFX Library PAGE_TYPE types of pages supported by the GFX Library NUM_ALPHA_LEVELS Specific to device ALPHA_DELTA This is macro ALPHA_DELTA. GFX_CONFIG_DRIVER_COUNT This is macro GFX_CONFIG_DRIVER_COUNT. GFX_ALPHA_PARAMS This is type GFX_ALPHA_PARAMS. GFX_LAYER_PARAMS This is type GFX_LAYER_PARAMS. System Functions Name Description Percentage2Alpha DriverInterfaceInit This is function DriverInterfaceInit. Description All of the drivers in the GFX library must follow certain guidelines to be used by the GFX Primitve. These guidelines are defined in gfx_gol_display_driver.h The GFX primitve calls function pointers to reference a particular GFX driver function. If the function does not exist for a particular driver (ie Alpha Blending) then the driver defines the function as NULL at buildtime. The function structure for a driver file can be seen in "Basic Renderring Routines". 5.1.5.7.1 System Functions 5.1.5.7.1.1 Percentage2Alpha Function C inline uint8_t Percentage2Alpha( uint8_t alphaPercentage ); 5.1.5.7.1.2 DriverInterfaceInit Function C inline void DriverInterfaceInit( DRV_HANDLE * pmphandle, DRV_PMP_MODE_CONFIG * config ); 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-291 Description This is function DriverInterfaceInit. 5.1.5.7.2 Data Types and Constants 5.1.5.7.2.1 GFX_DRV_DATA Structure C typedef struct { uint16_t orientation; uint16_t horizontalResolution; uint16_t verticalResolution; uint16_t dataWidth; uint16_t horizontalPulseWidth; uint16_t horizontalBackPorch; uint16_t horizontalFrontPorch; uint16_t verticalPulseWidth; uint16_t verticalBackPorch; uint16_t verticalFrontPorch; uint8_t logicShift; enum { LCD_TFT = 1, LCD_MSTN, LCD_CSTN } LCDType; uint8_t colorType; uint8_t timingControl; GFX_DRV_FUNCTIONS PrimitiveFunction; uint8_t driverBusy; uint8_t ready; GFX_COLOR color; volatile uint8_t activePage; volatile uint8_t visualPage; } GFX_DRV_DATA; Description Structure: GFX_DRV_DATA Each driver in order to be registered with the primitive layer needs these values. they are mainly dependent on the chosen LCD. Members Members Description uint16_t orientation; Orientation of the display (given in degrees of 0,90,180,270) uint16_t horizontalResolution; Horizontal Resolution of the displayed orientation in Pixels uint16_t verticalResolution; Vertical resolution of the displayed orientation in pixels uint16_t horizontalPulseWidth; Horizontal Pulse Width of the LCD uint16_t horizontalBackPorch; Horizontal BackPorch of the LCD uint16_t horizontalFrontPorch; Horizontal FrontPorch of the LCD uint16_t verticalPulseWidth; Vertical Pulse width of the LCD uint16_t verticalBackPorch; Vertical BackPorch of the LCD uint16_t verticalFrontPorch; Vertical FrontPorch of the LCD uint8_t logicShift; Rising/Falling edge indicator of the LCD pixel clock 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-292 enum { LCD_TFT = 1, LCD_MSTN, LCD_CSTN } LCDType; LCD type uint8_t colorType; color depth (18BPP, 24BPP, 8BPP, palette) uint8_t timingControl; flag to GFX_DRV_FUNCTIONS PrimitiveFunction; List of Primitive Renderring functions available by the driver uint8_t driverBusy; Flag to indicate driver is currently busy uint8_t ready; Flag to indicate driver has been initialized and recognized by the primitive layer GFX_COLOR color; current Color set for the display driver volatile uint8_t activePage; current activepage set for the display driver volatile uint8_t visualPage; current visualPage set for the display driver 5.1.5.7.2.2 GFX_DRV_FUNCTIONS Structure C typedef struct { uint16_t (* PixelsPut)(short,short,uint16_t, uint16_t); uint16_t (* BarFill)(short,short,short,short); uint16_t* (* PixelArrayPut)(uint16_t*,short,short,uint16_t, uint16_t); uint16_t* (* PixelArrayGet)(uint16_t*,short,short,uint16_t); uint16_t (* PixelPut)(short,short); void (* ColorSet)(GFX_COLOR); void (* InstanceSet)(uint8_t); uint16_t (* PageSet)(uint8_t, uint8_t); uint16_t* (* Layer)(uint8_t, GFX_LAYER_PARAMS*); uint16_t (* PixelGet)(short,short); uint16_t* (* AlphaBlendWindow)(GFX_ALPHA_PARAMS*, uint16_t, uint16_t, uint8_t); } GFX_DRV_FUNCTIONS; Description Structure: GFX_DRV_FUNCTIONS This structure needs to be defined in the driver file to inform the primitive layer as to what functions are available. Members Members Description uint16_t (* PixelsPut)(short,short,uint16_t, uint16_t); This function sends pixels of an X,Y location to the LCD controller of a given count and linecount. uint16_t (* BarFill)(short,short,short,short); This function sends a 2D accelerated Bar command to the LCD controller uint16_t* (* PixelArrayPut)(uint16_t*,short,short,uint16_t, uint16_t); This function sends an array of pixels at an X,Y location to the LCD controller of a given count and linecount from a memory location. uint16_t* (* PixelArrayGet)(uint16_t*,short,short,uint16_t); This function gets an array of pixels at an X,Y location to the LCD controller of a given count and linecount from a memory location. uint16_t (* PixelPut)(short,short); This function sends a pixel of an X,Y location to the LCD controller. void (* ColorSet)(GFX_COLOR); This function sets the global color for the display driver void (* InstanceSet)(uint8_t); This function sets the global color for the display driver uint16_t (* PageSet)(uint8_t, uint8_t); See Primitive PageSet Defition uint16_t* (* Layer)(uint8_t, GFX_LAYER_PARAMS*); See Primitive Layer Definition uint16_t (* PixelGet)(short,short); This function gets a pixel of an X,Y location to the LCD controller. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-293 uint16_t* (* AlphaBlendWindow)(GFX_ALPHA_PARAMS*, uint16_t, uint16_t, uint8_t); See Primitive AlphaBlendWindow Definition 5.1.5.7.2.3 LAYER_TYPE Enumeration C typedef enum { PIP1 = 0, PIP2 } LAYER_TYPE; Description Enumeration: LAYER_TYPE 5.1.5.7.2.4 PAGE_TYPE Enumeration C typedef enum { ACTIVE_PAGE = 0, VISUAL_PAGE, BACKGROUND_PAGE, FOREGROUND_PAGE, DESTINATION_PAGE, TRANSITION_PAGE } PAGE_TYPE; Description Enumeration: PAGE_TYPE Members Members Description TRANSITION_PAGE Page that displays the transition 5.1.5.7.2.5 NUM_ALPHA_LEVELS Macro C #define NUM_ALPHA_LEVELS 0x20 // Specific to device Description Specific to device 5.1.5.7.2.6 ALPHA_DELTA Macro C #define ALPHA_DELTA ((NUM_ALPHA_LEVELS) << 5) Description This is macro ALPHA_DELTA. 5.1.5.7.2.7 GFX_CONFIG_DRIVER_COUNT Macro C #define GFX_CONFIG_DRIVER_COUNT 1 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-294 Description This is macro GFX_CONFIG_DRIVER_COUNT. 5.1.5.7.2.8 GFX_ALPHA_PARAMS Structure C typedef struct { uint8_t foregroundPage; short foregroundLeft; short foregroundTop; uint8_t backgroundPage; short backgroundLeft; short backgroundTop; uint8_t destinationPage; short destinationLeft; short destinationTop; uint8_t alpha; GFX_COLOR prevAlphaColor; } GFX_ALPHA_PARAMS; Description This is type GFX_ALPHA_PARAMS. 5.1.5.7.2.9 GFX_LAYER_PARAMS Structure C typedef struct { uint8_t type; uint8_t on; uint8_t page; short left; short top; uint16_t width; uint16_t height; short layerLeft; short layerTop; } GFX_LAYER_PARAMS; Description This is type GFX_LAYER_PARAMS. 5.1.5.8 Files Files Name Description drv_gfx_display.h GFX Display Driver definitions drv_gfx_config_template.h This is file drv_gfx_config_template.h. Description 5.1.5.8.1 drv_gfx_display.h GFX Display Driver definitions 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-295 This file describes the GFX Display Driver specific definitions. Enumerations Name Description LAYER_TYPE types of Layers supported by the GFX Library PAGE_TYPE types of pages supported by the GFX Library Files Name Description drv_gfx_lcc.h Interface for the graphics library where the primitives are renderred and sent to the graphics controller either external or internal drv_gfx_s1d13517.h Interface for the graphics library where the primitives are renderred and sent to the graphics controller either external or internal drv_gfx_ssd1926.h Interface for the graphics library where the primitives are renderred and sent to the graphics controller either external or internal Functions Name Description DriverInterfaceInit This is function DriverInterfaceInit. Percentage2Alpha Macros Name Description ALPHA_DELTA This is macro ALPHA_DELTA. GFX_CONFIG_DRIVER_COUNT This is macro GFX_CONFIG_DRIVER_COUNT. NUM_ALPHA_LEVELS Specific to device Structures Name Description GFX_ALPHA_PARAMS This is type GFX_ALPHA_PARAMS. GFX_DRV_DATA Structure containing the driver graphics controller data. GFX_DRV_FUNCTIONS Structure containing the driver functions used by the primitive layer. GFX_LAYER_PARAMS This is type GFX_LAYER_PARAMS. Company Microchip Technology Incorporated FileName: gfx_display_driver.h 5.1.5.8.1.1 drv_gfx_lcc.h None Enumerations Name Description DMA_ISR_TASK This is type DMA_ISR_TASK. LCC_TASK This is type LCC_TASK. Functions Name Description GFX_DRV_lcc_BrightnessSet Sets the brightness of the display backlight. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-296 GFX_DRV_lcc_Close closes an instance of the graphics controller GFX_DRV_lcc_Initialize resets LCD, initializes PMP GFX_DRV_lcc_Layer This is function GFX_DRV_lcc_Layer. GFX_DRV_lcc_Open opens an instance of the graphics controller GFX_DRV_lcc_PixelArrayGet gets an array of pixels of length count starting at *color GFX_DRV_lcc_PixelArrayPut outputs an array of pixels of length count starting at *color GFX_DRV_lcc_PixelPut outputs one pixel into the frame buffer at the x,y coordinate given GFX_DRV_lcc_PixelsPut outputs one pixel into the frame buffer at the x,y coordinate given GFX_DRV_lcc_SetColor Sets the color for the driver instance GFX_DRV_lcc_SetInstance Sets the instance for the driver GFX_DRV_lcc_SetPage This is function GFX_DRV_lcc_SetPage. GFX_DRV_lcc_Tasks Task machine that renders the driver calls for the graphics library it must be called peridically to output the contents of its circular buffer GFX_PRIM_SetPIPWindow This is function GFX_PRIM_SetPIPWindow. Macros Name Description GFX_DRV_lcc_COMMANDQUEUESIZE This is macro GFX_DRV_lcc_COMMANDQUEUESIZE. PIP_BUFFER This is macro PIP_BUFFER. USE_LCC_SCROLLING This is macro USE_LCC_SCROLLING. USE_PIP This is macro USE_PIP. Structures Name Description GFX_DRV_lcc_COMMAND Structure for the commands in the driver queue. File Name drv_gfx_lcc.h Company Microchip Technology Incorporated 5.1.5.8.1.2 drv_gfx_s1d13517.h None Functions Name Description GFX_DRV_S1D13517_AlphaBlendWindow SEE primitive layer alphablendWindow definition GFX_DRV_S1D13517_BrightnessSet Sets the brightness of the display backlight. GFX_DRV_S1D13517_Close closes an instance of the graphics controller GFX_DRV_S1D13517_GetReg returns graphics controller register value (byte access) GFX_DRV_S1D13517_Initialize resets LCD, initializes PMP GFX_DRV_S1D13517_Layer Updates a Layer depending on the layer parameters. GFX_DRV_S1D13517_Open opens an instance of the graphics controller GFX_DRV_S1D13517_PixelArrayPut outputs an array of pixels of length count starting at *color GFX_DRV_S1D13517_PixelPut outputs one pixel into the frame buffer at the x,y coordinate given GFX_DRV_S1D13517_PixelsPut outputs one pixel into the frame buffer at the x,y coordinate given 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-297 GFX_DRV_S1D13517_SetColor Sets the color for the driver instance GFX_DRV_S1D13517_SetInstance Sets the instance for the driver GFX_DRV_S1D13517_SetPage Sets the page of a certain page type GFX_DRV_S1D13517_SetReg updates graphics controller register value (byte access) GFX_DRV_S1D13517_Tasks Task machine that renders the driver calls for the graphics library it must be called peridically to output the contents of its circular buffer Structures Name Description GFX_DRV_S1D13517_COMMAND Structure for the commands in the driver queue. LAYER_REGISTERS This structure is used to describe layer registers. File Name S1D13517.h Company Microchip Technology Incorporated 5.1.5.8.1.3 drv_gfx_ssd1926.h None Functions Name Description GFX_DRV_SSD1926_BarFill Hardware accelerated barfill function GFX_DRV_SSD1926_BrightnessSet Sets the brightness of the display backlight. GFX_DRV_SSD1926_Busy Returns non-zero if LCD controller is busy (previous drawing operation is not completed). GFX_DRV_SSD1926_Close closes an instance of the graphics controller GFX_DRV_SSD1926_GetReg returns graphics controller register value (byte access) GFX_DRV_SSD1926_Initialize resets LCD, initializes PMP GFX_DRV_SSD1926_Open opens an instance of the graphics controller GFX_DRV_SSD1926_PixelArrayGet gets an array of pixels of length count starting at *color GFX_DRV_SSD1926_PixelArrayPut outputs an array of pixels of length count starting at *color GFX_DRV_SSD1926_PixelPut outputs one pixel into the frame buffer at the x,y coordinate given GFX_DRV_SSD1926_PixelsPut outputs one pixel into the frame buffer at the x,y coordinate given GFX_DRV_SSD1926_SetColor Sets the color for the driver instance GFX_DRV_SSD1926_SetInstance Sets the instance for the driver GFX_DRV_SSD1926_SetReg updates graphics controller register value (byte access) GFX_DRV_SSD1926_Tasks Task machine that renders the driver calls for the graphics library it must be called peridically to output the contents of its circular buffer Structures Name Description GFX_DRV_SSD1926_COMMAND Structure for the commands in the driver queue. GFX_DRV_SSD1926_TASK Structure for the task machine File Name SSD1926.h 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-298 Company Microchip Technology Incorporated 5.1.5.8.2 drv_gfx_config_template.h This is file drv_gfx_config_template.h. 5.1.5.9 Software Drivers 5.1.5.9.1 Low-Cost Controllerless (LCC) Graphics Driver Library 5.1.5.9.1.1 Introduction Low-Cost Controllerless Graphics Driver Library for Microchip Microcontrollers This library provides a low-level abstraction of the Low-Cost Controllerless Graphics Controller Driver Library that is available on the Microchip family of microcontrollers with a convenient C language interface. It can be used to simplify low-level access to the module without the necessity of interacting directly with the module's registers, there by hiding differences from one microcontroller variant to another. Description Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony. 5.1.5.9.1.2 Release Notes MPLAB Harmony Version: v0.70b Low-Cost Controllerless Graphics Driver Library Version : 4.00b Release Date: 18Nov2013 New This Release: This is the first release of the library. The interface can change in the beta and\or 1.0 release. Known Issues: DMA Channel 1 is non-configurable. The LCC driver will require DMA Channel 1 and not allow configuration via Harmony system services. 5.1.5.9.1.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-299 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 5.1.5.9.1.4 Using the Library This topic describes the basic architecture of the Low-Cost Controllerless (LCC) Graphics Driver Library and provides information and examples on how to use it. Interface Header File: gfx_drv_lcc.h The interface to the Low-Cost Controllerless (LCC) Graphics Driver library is defined in the "gfx_drv_lcc.h" header file. This file is included by the "gfx_drv_lcc.h" file. Any C language source (.c) file that uses the Low-Cost Controllerless (LCC) Graphics Driver Library should include "gfx_drv_lcc.h". Library File: The GFX Low-Cost Controller library archive (.a) file installed with MPLAB Harmony. Please refer to the MPLAB Harmony Overview for how the Low-Cost Controllerless (LCC) Graphics Driver Library interacts with the framework. 5.1.5.9.1.4.1 Library Overview Refer to the section Driver Overview for how the driver operates in a system. The library interface routines are divided into various sub-sections, each of sub-section addresses one of the blocks or the overall operation of the Low-Cost Controllerless (LCC) Graphics Controller Driver module. Library Interface Section Description Functions This section lists the API functions available in the library. 5.1.5.9.1.4.2 Abstraction Model This library provides the low-level abstraction of the Low-Cost Controllerless (LCC) Graphics Controller Driver module on the Microchip family of graphic display controllers with a convenient C language interface. This topic describes how that abstraction is modeled in the software and introduces the library interface. Description Low-Cost Controllerless (LCC) Graphics Controller Driver Abstraction Block Diagram Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony. 5.1.5.9.1.5 Configuring the Library The configuration of the Low-Cost Controllerless (LCC) Graphics Driver Library is based on the file system_config.h. This header file contains the configuration selection for the GFX Low-Cost Controller. Based on the selections made, the 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-300 Low-Cost Controllerless (LCC) Graphics Driver Library will support or not support selected features. These configuration settings will apply to all instances of the Low-Cost Controllerless (LCC) Graphics Driver Library. This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a successful build. Refer to the Applications Overview section for more details. 5.1.5.9.1.6 Building the Library This section list the files that are available in the \src of theLow-Cost Controllerless (LCC) Graphics Driver Library. It lists which files need to be included in the build based on either a hardware feature present on the board or configuration option selected by the system. • gfx_drv_lcc.c 5.1.5.9.1.7 Library Interface This section describes the Application Programming Interface (API) functions of the Low-Cost Controllerless (LCC) Graphics Driver Library. Refer to each section for a detailed description. 5.1.5.9.1.7.1 Functions Functions Name Description GFX_DRV_lcc_Close closes an instance of the graphics controller GFX_DRV_lcc_Initialize resets LCD, initializes PMP GFX_DRV_lcc_Open opens an instance of the graphics controller GFX_DRV_lcc_Tasks Task machine that renders the driver calls for the graphics library it must be called peridically to output the contents of its circular buffer GFX_DRV_lcc_BrightnessSet Sets the brightness of the display backlight. GFX_DRV_lcc_PixelArrayGet gets an array of pixels of length count starting at *color GFX_DRV_lcc_PixelArrayPut outputs an array of pixels of length count starting at *color GFX_DRV_lcc_PixelPut outputs one pixel into the frame buffer at the x,y coordinate given GFX_DRV_lcc_PixelsPut outputs one pixel into the frame buffer at the x,y coordinate given GFX_DRV_lcc_SetColor Sets the color for the driver instance GFX_DRV_lcc_SetInstance Sets the instance for the driver GFX_DRV_lcc_Layer This is function GFX_DRV_lcc_Layer. GFX_DRV_lcc_SetPage This is function GFX_DRV_lcc_SetPage. GFX_PRIM_SetPIPWindow This is function GFX_PRIM_SetPIPWindow. Description 5.1.5.9.1.7.1.1 GFX_DRV_lcc_Close Function C uint16_t GFX_DRV_lcc_Close( uint8_t instance ); 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-301 Description none Returns 0 - instance closed 2 - instance doesn't exist 3 - instance already closed 5.1.5.9.1.7.1.2 GFX_DRV_lcc_Initialize Function C uint16_t GFX_DRV_lcc_Initialize( uint8_t instance ); Description none Parameters Parameters Description instance driver instance Returns NULL - call not successful (PMP driver busy) !NULL - address of the display driver queue command 5.1.5.9.1.7.1.3 GFX_DRV_lcc_Open Function C uint16_t GFX_DRV_lcc_Open( uint8_t instance ); Description none Returns 1 - driver not initialied 2 - instance doesn't exist 3 - instance already open instance to driver when successful 5.1.5.9.1.7.1.4 GFX_DRV_lcc_Tasks Function C void GFX_DRV_lcc_Tasks(); 5.1.5.9.1.7.1.5 GFX_DRV_lcc_BrightnessSet Function C void GFX_DRV_lcc_BrightnessSet( uint8_t instance, uint16_t level ); Description none Parameters Parameters Description 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-302 5.1.5.9.1.7.1.6 GFX_DRV_lcc_PixelArrayGet Function C uint16_t* GFX_DRV_lcc_PixelArrayGet( uint16_t * color, short x, short y, uint16_t count ); Description none Parameters Parameters Description instance driver instance *color start of the array x x coordinate of the start point. y y coordinate of the end point. count number of pixels Returns NULL - call not successful (lcc driver busy) !NULL - address of the display driver queue command 5.1.5.9.1.7.1.7 GFX_DRV_lcc_PixelArrayPut Function C uint16_t* GFX_DRV_lcc_PixelArrayPut( uint16_t * color, short x, short y, uint16_t count, uint16_t lineCount ); Description none Parameters Parameters Description instance driver instance *color start of the array x x coordinate of the start point. y y coordinate of the end point. count number of pixels Returns NULL - call not successful !NULL - handle to the number of pixels remaining 5.1.5.9.1.7.1.8 GFX_DRV_lcc_PixelPut Function C uint16_t GFX_DRV_lcc_PixelPut( short x, 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-303 short y ); Description none Parameters Parameters Description x,y pixel coordinates Returns NULL - call not successful (lcc driver busy) !NULL - address of the display driver queue command 5.1.5.9.1.7.1.9 GFX_DRV_lcc_PixelsPut Function C uint16_t GFX_DRV_lcc_PixelsPut( short x, short y, uint16_t count, uint16_t lineCount ); Description none Parameters Parameters Description x,y pixel coordinates Returns NULL - call not successful (lcc driver busy) !NULL - address of the display driver queue command 5.1.5.9.1.7.1.10 GFX_DRV_lcc_SetColor Function C void GFX_DRV_lcc_SetColor( GFX_COLOR color ); Returns none 5.1.5.9.1.7.1.11 GFX_DRV_lcc_SetInstance Function C void GFX_DRV_lcc_SetInstance( uint8_t instance ); Returns none 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-304 5.1.5.9.1.7.1.12 GFX_DRV_lcc_Layer Function C uint16_t* GFX_DRV_lcc_Layer( uint8_t instance, GFX_LAYER_PARAMS* layer ); Description This is function GFX_DRV_lcc_Layer. 5.1.5.9.1.7.1.13 GFX_DRV_lcc_SetPage Function C uint16_t GFX_DRV_lcc_SetPage( uint8_t pageType, uint8_t page ); Description This is function GFX_DRV_lcc_SetPage. 5.1.5.9.1.7.1.14 GFX_PRIM_SetPIPWindow Function C void GFX_PRIM_SetPIPWindow( uint16_t left, uint16_t top, uint16_t hlength, uint16_t vlength, uint16_t pipx, uint16_t pipy ); Description This is function GFX_PRIM_SetPIPWindow. 5.1.5.9.1.7.2 Data Types and Constants Enumerations Name Description LCC_TASK This is type LCC_TASK. DMA_ISR_TASK This is type DMA_ISR_TASK. Macros Name Description USE_LCC_SCROLLING This is macro USE_LCC_SCROLLING. USE_PIP This is macro USE_PIP. PIP_BUFFER This is macro PIP_BUFFER. GFX_DRV_lcc_COMMANDQUEUESIZE This is macro GFX_DRV_lcc_COMMANDQUEUESIZE. Structures Name Description GFX_DRV_lcc_COMMAND Structure for the commands in the driver queue. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-305 Description 5.1.5.9.1.7.2.1 USE_LCC_SCROLLING Macro C #define USE_LCC_SCROLLING Description This is macro USE_LCC_SCROLLING. 5.1.5.9.1.7.2.2 USE_PIP Macro C #define USE_PIP Description This is macro USE_PIP. 5.1.5.9.1.7.2.3 GFX_DRV_lcc_COMMAND Structure C typedef struct { uint8_t instance; union { uint32_t Val; struct { uint8_t b0 : 1; uint8_t b1 : 1; uint8_t b2 : 1; uint8_t b3 : 1; uint8_t b4 : 1; uint8_t b5 : 1; uint8_t b6 : 1; uint8_t b7 : 1; uint8_t b8 : 1; uint8_t b9 : 1; uint8_t b10 : 1; uint8_t b11 : 1; uint8_t b12 : 1; uint8_t b13 : 1; uint8_t b14 : 1; uint8_t b15 : 1; uint8_t b16 : 1; uint8_t b17 : 1; uint8_t b18 : 1; uint8_t b19 : 1; uint8_t b20 : 1; uint8_t b21 : 1; uint8_t b22 : 1; uint8_t b23 : 1; uint8_t b24 : 1; uint8_t b25 : 1; uint8_t b26 : 1; uint8_t b27 : 1; uint8_t b28 : 1; uint8_t b29 : 1; uint8_t b30 : 1; uint8_t b31 : 1; } bits; 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-306 } address; uint16_t * array; uint16_t data; uint16_t count; uint16_t lineCount; uint8_t task; } GFX_DRV_lcc_COMMAND; Description Structure: GFX_DRV_lcc_COMMAND None 5.1.5.9.1.7.2.4 PIP_BUFFER Macro C #define PIP_BUFFER (3) Description This is macro PIP_BUFFER. 5.1.5.9.1.7.2.5 LCC_TASK Enumeration C typedef enum { UPDATE_CLOCK = 0, INITIALIZE, WAIT_TRANSMIT_PIXELS, FINISH_TRANSMIT_PIXELS, WAIT_TRANSMIT_ARRAY, FINISH_TRANSMIT_ARRAY, WAIT_RECEIVE, READ_RECEIVE, PUT_ARRAY, PUT_PIXELS, GET_PIXELS, COPY_PIXELS, PAGE, LAYERS } LCC_TASK; Description This is type LCC_TASK. 5.1.5.9.1.7.2.6 GFX_DRV_lcc_COMMANDQUEUESIZE Macro C #define GFX_DRV_lcc_COMMANDQUEUESIZE 480 Description This is macro GFX_DRV_lcc_COMMANDQUEUESIZE. 5.1.5.9.1.7.2.7 DMA_ISR_TASK Enumeration C typedef enum { ACTIVE_PERIOD = 0, BLANKING_PERIOD, FINISH_LINE, 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-307 OVERFLOW, PIP, SCROLL } DMA_ISR_TASK; Description This is type DMA_ISR_TASK. 5.1.5.9.1.8 Files Files Name Description 5.1.5.9.1.8.1 drv_gfx_lcc_config_template.h • Module for Microchip Graphics Library • This file contains compile time options for the Graphics Library. ******************************************************************* • FileName: GraphicsConfig.h • Dependencies: none • Processor: PIC24F, PIC24H, dsPIC, PIC32 • Compiler: C30 V3.00/C32 • Company: Microchip Technology, Inc. * • Software License Agreement * • Copyright © 2008 Microchip Technology Inc. All rights reserved. • Microchip licenses to you the right to use, modify, copy and distribute • Software only when embedded on a Microchip microcontroller or digital • signal controller, which is integrated into your product or third party • product (pursuant to the sublicense terms in the accompanying license • agreement). * • You should refer to the license agreement accompanying this Software • for additional information regarding your rights and obligations. * • SOFTWARE AND DOCUMENTATION ARE PROVIDED ?AS IS? WITHOUT WARRANTY OF ANY • KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY • OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR • PURPOSE. IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR • OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, • BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT • DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-308 • INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, • COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY • CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), • OR OTHER SIMILAR COSTS. * • Author Date Comment *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ • Anton Alkhimenok 10/28/2007 Initial Version • Pradeep Budagutta 10/28/2007 Display related defines • moved to DisplayConfig.h 5.1.5.10 Hardware Drivers 5.1.5.10.1 OTM2201A Graphics Controller Driver Library 5.1.5.10.1.1 Introduction OTM2201A Graphics Controller Driver Library for Microchip Microcontrollers This library provides a low-level abstraction of the OTM2201A Graphics Controller Driver Library that is available on the Microchip family of microcontrollers with a convenient C language interface. It can be used to simplify low-level access to the module without the necessity of interacting directly with the module's registers, there by hiding differences from one microcontroller variant to another. Description Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony. 5.1.5.10.1.2 Release Notes MPLAB Harmony Version: v0.70b OTM2201A Graphics Controller Driver Library Version : 4.00b Release Date: 18Nov2013 New This Release: This is the first release of the library. The interface can change in the beta and\or 1.0 release. Known Issues: Nothing to report in this release. 5.1.5.10.1.3 SW License Agreement (c) 2013 Microchip Technology Inc. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-309 Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 5.1.5.10.1.4 Using the Library This topic describes the basic architecture of the OTM2201A Graphics Controller Driver Library and provides information and examples on how to use it. Interface Header File: drv_gfx_otm2201a.h The interface to the OTM2201A Graphics Controller Driver library is defined in the "drv_gfx_otm2201a.h" header file. This file is included by the "gfx_primitive.h" file. Any C language source (.c) file that uses the OTM2201A Graphics Controller Driver library should include "gfx_primitive.h". Library File: The OTM2201A Graphics Controller Driver library archive (.a) file installed with MPLAB Harmony. Please refer to the MPLAB Harmony Overview for how the OTM2201A Graphics Controller Driver interacts with the framework. 5.1.5.10.1.4.1 Abstraction Model This library provides the low-level abstraction of the OTM2201A Graphics Controller Driver module on the Microchip family of microcontrollers with a convenient C language interface. This topic describes how that abstraction is modeled in the software and introduces the library interface. Description OTM2201A Graphics Controller Driver Abstraction Block Diagram Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony. 5.1.5.10.1.4.2 Library Overview Refer to the section Driver Overview for how the driver operates in a system. The library interface routines are divided into various sub-sections, each of sub-section addresses one of the blocks or the overall operation of the OTM2201 Graphics Controller Driver module. Library Interface Section Description Functions This section lists the API functions available in the library. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-310 5.1.5.10.1.5 Configuring the Driver Library The configuration of the OTM2201 Graphics Controller Driver is based on the file sys_config.h This header file contains the configuration selection for the OTM2201 Graphics Controller Driver. Based on the selections made, the OTM2201 Graphics Controller Driver will support or not support selected features. These configuration settings will apply to all instances of the OTM2201 Graphics Controller Driver. This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a successful build. Refer to the Applications Overview section for more details. 5.1.5.10.1.6 Building the Library This section list the files that are available in the \src of the OTM2201A Graphics Controller Driver. It lists which files need to be included in the build based on either a hardware feature present on the board or configuration option selected by the system. • drv_gfx_otm2201a.c 5.1.5.10.1.7 Library Interface This section describes the Application Programming Interface (API) functions of the OTM2201A Graphics Controller Driver Library. Refer to each section for a detailed description. 5.1.5.10.1.7.1 Functions Functions Name Description GFX_DRV_OTM2201A_AddressSet Sets the start GRAM address where pixel data to be written GFX_DRV_OTM2201A_BrightnessSet Sets the brightness of the display backlight. GFX_DRV_OTM2201A_Busy Returns non-zero value if LCD controller is busy (previous drawing operation is not completed). GFX_DRV_OTM2201A_Close Closes an instance of the graphics controller GFX_DRV_OTM2201A_ColorSet Sets the color for the driver instance GFX_DRV_OTM2201A_Initialize Intialize OTM2201A device GFX_DRV_OTM2201A_InstanceSet Sets the instance for the driver GFX_DRV_OTM2201A_Open Opens an instance of the graphics controller GFX_DRV_OTM2201A_PixelArrayGet Gets an array of pixels of length count into an array starting at *color GFX_DRV_OTM2201A_PixelArrayPut Outputs an array of pixels of length count starting at *color GFX_DRV_OTM2201A_PixelPut Outputs one pixel into the frame buffer at the x,y coordinate given GFX_DRV_OTM2201A_PixelsPut Outputs count number of pixels into the frame buffer from the given x,y coordinate. GFX_DRV_OTM2201A_RegGet Returns graphics controller register value (byte access) GFX_DRV_OTM2201A_RegSet Updates graphics controller register value (byte access) GFX_DRV_OTM2201A_Tasks Task machine that renders the driver calls for the graphics library it must be called peridically to output the contents of its circular buffer Description 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-311 5.1.5.10.1.7.1.1 GFX_DRV_OTM2201A_AddressSet Function C uint16_t GFX_DRV_OTM2201A_AddressSet( uint32_t address ); Description Address consists of Lower 8 bit at Register REG_RAM_ADDR_LOW and Higher 8 bit at Register REG_RAM_ADDR_HIGH Parameters Parameters Description address pixel address Returns DRV_OTM2201A_ERROR_PMP_WRITE - returns error during PMP Write, DRV_OTM2201A_ERROR_NO_ERROR - returns success without any error. 5.1.5.10.1.7.1.2 GFX_DRV_OTM2201A_BrightnessSet Function C void GFX_DRV_OTM2201A_BrightnessSet( uint8_t instance, uint16_t level ); Description Sets the brightness of the display backlight. Parameters Parameters Description instance instance of the driver level Brightness level. Valid values are 0 to 100. 0 = brightness level is zero or display is turned off. 100 = brightness level is maximum. Returns none 5.1.5.10.1.7.1.3 GFX_DRV_OTM2201A_Busy Function C uint16_t GFX_DRV_OTM2201A_Busy( uint8_t instance ); Description Returns non-zero value if LCD controller is busy (previous drawing operation is not completed). Parameters Parameters Description instance driver instance Returns DRV_OTM2201A_ERROR_DEVICE_BUSY - Device is busy, DRV_OTM2201A_ERROR_NO_ERROR - Success, driver is not 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-312 busy. 5.1.5.10.1.7.1.4 GFX_DRV_OTM2201A_Close Function C uint16_t GFX_DRV_OTM2201A_Close( uint8_t instance ); Description Closes an instance if instance exists and not already closed Parameters Parameters Description instance instance of the driver Returns DRV_OTM2201A_INSTANCE_CLOSED - instance closed, DRV_OTM2201A_INSTANCE_DOESNT_EXIST - instance doesn't exist, DRV_OTM2201A_INSTANCE_ALREADY_CLOSED - instance already closed. 5.1.5.10.1.7.1.5 GFX_DRV_OTM2201A_ColorSet Function C void GFX_DRV_OTM2201A_ColorSet( GFX_COLOR color ); Description Sets the color for the driver instance Parameters Parameters Description color 16 bit 565 format color value Returns none 5.1.5.10.1.7.1.6 GFX_DRV_OTM2201A_Initialize Function C uint16_t GFX_DRV_OTM2201A_Initialize( uint8_t instance ); Description Initialize OTM2201A device by initializing PMP interface, initializing command buffer for current instance initialize device registers Parameters Parameters Description instance driver instance Returns DRV_OTM2201A_ERROR_QUEUE_FULL - OTM2201A command queue is full, DRV_OTM2201A_ERROR_REG_GET - OTM2201A Error while reading register, DRV_OTM2201A_ERROR_REG_SET - OTM2201A Error while writing register, 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-313 DRV_OTM2201A_ERROR_DEVICE_BUSY - OTM2201A device is busy, DRV_OTM2201A_ERROR_NO_ERROR - Success without any error. 5.1.5.10.1.7.1.7 GFX_DRV_OTM2201A_InstanceSet Function C void GFX_DRV_OTM2201A_InstanceSet( uint8_t instance ); Description Sets the instance for the driver Parameters Parameters Description instance driver instance Returns none 5.1.5.10.1.7.1.8 GFX_DRV_OTM2201A_Open Function C uint16_t GFX_DRV_OTM2201A_Open( uint8_t instance ); Description Opens the instance of driver if instance is valid and not already opened Parameters Parameters Description instance instance of the driver Returns DRV_OTM2201A_NEW_INSTANCE_OPEN - driver not initialied, DRV_OTM2201A_INSTANCE_DOESNT_EXIST - instance doesn't exist, DRV_OTM2201A_INSTANCE_ALREADY_OPEN - instance already open. 5.1.5.10.1.7.1.9 GFX_DRV_OTM2201A_PixelArrayGet Function C uint16_t* GFX_DRV_OTM2201A_PixelArrayGet( uint16_t * color, short x, short y, uint16_t count ); Description Gets an array of pixels of length count into an array starting at *color Parameters Parameters Description color Pointer to array where color data is to be loaded 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-314 x pixel coordinate on x axis y pixel coordinate on y axis count count number of pixels Returns DRV_OTM2201A_ERROR_QUEUE_FULL - OTM2201A command queue is full, DRV_OTM2201A_ERROR_NO_ERROR - Success without any error. 5.1.5.10.1.7.1.10 GFX_DRV_OTM2201A_PixelArrayPut Function C uint16_t* GFX_DRV_OTM2201A_PixelArrayPut( uint16_t * color, short x, short y, uint16_t count, uint16_t lineCount ); Description Outputs an array of pixels of length count starting at *color Parameters Parameters Description color pointer to array of color of pixels x pixel coordinate on x axis. y pixel coordinate on y axis. count count number of pixels lineCount lineCount number of display lines Returns handle - handle to the number of pixels remaining, DRV_OTM2201A_ERROR_QUEUE_FULL - OTM2201A command queue is full. 5.1.5.10.1.7.1.11 GFX_DRV_OTM2201A_PixelPut Function C uint16_t GFX_DRV_OTM2201A_PixelPut( short x, short y ); Description Outputs one pixel into the frame buffer at the x,y coordinate given Parameters Parameters Description x pixel coordinate on x axis y pixel coordinate on y axis Returns DRV_OTM2201A_ERROR_QUEUE_FULL - OTM2201A command queue is full, DRV_OTM2201A_ERROR_NO_ERROR - Success without any error. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-315 5.1.5.10.1.7.1.12 GFX_DRV_OTM2201A_PixelsPut Function C uint16_t GFX_DRV_OTM2201A_PixelsPut( short x, short y, uint16_t count, uint16_t lineCount ); Description Outputs count number of pixels into the frame buffer from the given x,y coordinate. Parameters Parameters Description x pixel coordinate on x axis y pixel coordinate on y axis count count number of pixels lineCount lineCount number of display lines Returns DRV_OTM2201A_ERROR_QUEUE_FULL - OTM2201A command queue is full, DRV_OTM2201A_ERROR_NO_ERROR - Success without any error. 5.1.5.10.1.7.1.13 GFX_DRV_OTM2201A_RegGet Function C uint8_t GFX_DRV_OTM2201A_RegGet( uint16_t index, uint16_t * data ); Description Returns graphics controller register value (byte access) Parameters Parameters Description index register number *data array to store register data Returns DRV_OTM2201A_ERROR_PMP_WRITE - returns error during PMP Write, DRV_OTM2201A_ERROR_PMP_READ - returns error during PMP Read, DRV_OTM2201A_ERROR_NO_ERROR - returns success without any error. 5.1.5.10.1.7.1.14 GFX_DRV_OTM2201A_RegSet Function C uint16_t GFX_DRV_OTM2201A_RegSet( uint16_t index, uint16_t value, uint32_t repeatCount ); 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-316 Description This call can set "value" of the register accessed by its "index" and can repeat the same by number of times mentioned in "repeatCount" Parameters Parameters Description index register number value value to write to register repeatCount repeatCount number of times value is to be written to the register. Returns DRV_OTM2201A_ERROR_PMP_WRITE - returns error during PMP Write, DRV_OTM2201A_ERROR_NO_ERROR - returns success without any error. 5.1.5.10.1.7.1.15 GFX_DRV_OTM2201A_Tasks Function C void GFX_DRV_OTM2201A_Tasks(); Description Task machine that renders the driver calls for the graphics library it must be called peridically to output the contents of its circular buffer. 5.1.5.10.1.7.2 Data Types and Constants Enumerations Name Description OTM2201A_TASK Enumeration for command type. Structures Name Description GFX_DRV_OTM2201A_COMMAND Structure for the commands in the driver queue. Description 5.1.5.10.1.7.2.1 GFX_DRV_OTM2201A_COMMAND Structure C typedef struct { uint8_t instance; uint32_t address; uint16_t * array; uint16_t data; uint16_t count; uint16_t lineCount; OTM2201A_TASK task; } GFX_DRV_OTM2201A_COMMAND; Description Structure: GFX_DRV_OTM2201A_COMMAND Structure for the commands in the driver queue. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-317 Parameters Parameters Description instance instance of the driver address pixel address array pointer to array of pixel data data pixel color count count number of pixels in one line lineCount lineCount number of lines of display task Type of task (OTM2201A_TASK enum) 5.1.5.10.1.7.2.2 OTM2201A_TASK Enumeration C typedef enum { INITIALIZE = 0, BUSY, PUT_ARRAY, PUT_PIXELS } OTM2201A_TASK; Description Enum: OTM2201A_TASK Enumeration for command type. Parameters Parameters Description INITIALIZE driver initialization task BUSY driver busy task PUT_ARRAY driver put array task PUT_PIXELS driver put pixels task 5.1.5.10.1.7.3 Files Files Name Description drv_gfx_otm2201a.h Interface for the graphics library where the primitives are renderred and sent to the graphics controller either external or internal Description 5.1.5.10.1.7.3.1 drv_gfx_otm2201a.h None Enumerations Name Description OTM2201A_TASK Enumeration for command type. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-318 Functions Name Description GFX_DRV_OTM2201A_AddressSet Sets the start GRAM address where pixel data to be written GFX_DRV_OTM2201A_BrightnessSet Sets the brightness of the display backlight. GFX_DRV_OTM2201A_Busy Returns non-zero value if LCD controller is busy (previous drawing operation is not completed). GFX_DRV_OTM2201A_Close Closes an instance of the graphics controller GFX_DRV_OTM2201A_ColorSet Sets the color for the driver instance GFX_DRV_OTM2201A_Initialize Intialize OTM2201A device GFX_DRV_OTM2201A_InstanceSet Sets the instance for the driver GFX_DRV_OTM2201A_Open Opens an instance of the graphics controller GFX_DRV_OTM2201A_PixelArrayGet Gets an array of pixels of length count into an array starting at *color GFX_DRV_OTM2201A_PixelArrayPut Outputs an array of pixels of length count starting at *color GFX_DRV_OTM2201A_PixelPut Outputs one pixel into the frame buffer at the x,y coordinate given GFX_DRV_OTM2201A_PixelsPut Outputs count number of pixels into the frame buffer from the given x,y coordinate. GFX_DRV_OTM2201A_RegGet Returns graphics controller register value (byte access) GFX_DRV_OTM2201A_RegSet Updates graphics controller register value (byte access) GFX_DRV_OTM2201A_Tasks Task machine that renders the driver calls for the graphics library it must be called peridically to output the contents of its circular buffer Structures Name Description GFX_DRV_OTM2201A_COMMAND Structure for the commands in the driver queue. File Name drv_gfx_otm2201a.h Company Microchip Technology Incorporated 5.1.5.10.2 S1D13517 Graphics Controller Driver Library 5.1.5.10.2.1 Introduction S1D13517 Graphics Controller Driver Library for Microchip Microcontrollers This library provides a low-level abstraction of the S1D13517 Graphics Controller Driver Library that is available on the Microchip family of microcontrollers with a convenient C language interface. It can be used to simplify low-level access to the module without the necessity of interacting directly with the module's registers, there by hiding differences from one microcontroller variant to another. Description Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-319 5.1.5.10.2.2 Release Notes MPLAB Harmony Version: v0.70b S1D13517 Graphics Driver Library Version : 4.00b Release Date: 18Nov2013 New This Release: This is the first release of the library. The interface can change in the beta and\or 1.0 release. Known Issues: Nothing to report in this release. 5.1.5.10.2.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 5.1.5.10.2.4 Using the Library This topic describes the basic architecture of the S1D13517 Graphics Controller Driver Library and provides information and examples on how to use it. Interface Header File: gfx_drv_s1d13517.h The interface to the S1D13517 Graphics Controller Driver Library is defined in the "gfx_drv_s1d13517.h" header file. This file is included by the "gfx_drv_s1d13517.h" file. Any C language source (.c) file that uses the S1D13517 Graphics Controller Driver Library should include "gfx_drv_s1d13517.h". Library File: The S1D13517 Graphics Controller Driver Library archive (.a) file installed with MPLAB Harmony. Please refer to the MPLAB Harmony Overview for how the GFX S1D13517 Controller Driver interacts with the framework. 5.1.5.10.2.4.1 Abstraction Model This library provides the low-level abstraction of the S1D13517 Graphics Controller Driver module of the Microchip family of graphic display controllers with a convenient C language interface. This topic describes how that abstraction is modeled in the software and introduces the library interface. Description S1D13517 Graphics Controller Driver Abstraction Block Diagram 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-320 Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony. 5.1.5.10.2.4.2 Library Overview Refer to the section Driver Overview for how the driver operates in a system. The library interface routines are divided into various sub-sections, each of sub-section addresses one of the blocks or the overall operation of the S1D13517 Graphics Controller Driver module. Library Interface Section Description Functions This section lists the API functions available in the library. 5.1.5.10.2.5 Configuring the Library Macros Name Description USE_ANALOGCLOCK Enable Analog Clock Object. 5.1.5.10.2.5.1 USE_ANALOGCLOCK Macro C #define USE_ANALOGCLOCK Description Enable Analog Clock Object. 5.1.5.10.2.5.2 USE_BITMAP_FLASH Macro C #define USE_BITMAP_FLASH Description Similar to Font data bitmaps can also be placed in two locations. One is in FLASH memory and the other is from external memory. Definining one or both enables the support for bitmaps located in internal flash and external memory. Define this in GraphicsConfig.h • USE_BITMAP_FLASH - Images located in internal flash memory. • USE_BITMAP_EXTERNAL - Images located in external memory (including external memory mapped to EDS).. 5.1.5.10.2.5.3 USE_BUTTON Macro C #define USE_BUTTON Description Enable Button Object. 5.1.5.10.2.5.4 USE_CHART Macro C #define USE_CHART 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-321 Description This is macro USE_CHART. 5.1.5.10.2.5.5 USE_CHECKBOX Macro C #define USE_CHECKBOX Description Enable Checkbox Object. 5.1.5.10.2.5.6 USE_COMP_RLE Macro C #define USE_COMP_RLE Description • Overview: To enable support for DEFLATE compressed images for PutImage(). • When this macro is enabled, the PutImage() function will • be able to process images generated by the Graphics Resource • Converter (GRC) that are compressed using the DEFLATE algorithm. • PutImage() will need the IPU module of the Microchip Graphics • Module to decompress. Enable this feature only when the driver • features the IPU module (example: PIC24FJ2456DA210). • Define this in GraphicsConfig.h * ****************************************************************** #define USE_COMP_IPU 5.1.5.10.2.5.7 USE_CUSTOM Macro C #define USE_CUSTOM Description Enable Custom Control Object (an example to create customized Object). 5.1.5.10.2.5.8 USE_DIGITALMETER Macro C #define USE_DIGITALMETER Description Enable DigitalMeter Object. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-322 5.1.5.10.2.5.9 USE_EDITBOX Macro C #define USE_EDITBOX Description Enable Edit Box Object. 5.1.5.10.2.5.10 USE_FONT_FLASH Macro C #define USE_FONT_FLASH 5.1.5.10.2.5.11 USE_GOL Macro C #define USE_GOL Description Enable Graphics Object Layer. 5.1.5.10.2.5.12 USE_GRADIENT Macro C #define USE_GRADIENT Description To enable support for Gradient bars and bevel primitives. Define this in GraphicsConfig.h. 5.1.5.10.2.5.13 USE_GROUPBOX Macro C #define USE_GROUPBOX Description Enable Group Box Object. 5.1.5.10.2.5.14 USE_LISTBOX Macro C #define USE_LISTBOX Description Enable List Box Object. 5.1.5.10.2.5.15 USE_METER Macro C #define USE_METER Description Enable Meter Object. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-323 5.1.5.10.2.5.16 USE_MULTIBYTECHAR Macro C #define USE_MULTIBYTECHAR Description To enable support for unicode fonts, USE_MULTIBYTECHAR must be defined. This sets the XCHAR definition (0-2^16 range). See XCHAR for details. Define this in GraphicsConfig.h 5.1.5.10.2.5.17 USE_PICTURE Macro C #define USE_PICTURE Description Enable Picture Object. 5.1.5.10.2.5.18 USE_PROGRESSBAR Macro C #define USE_PROGRESSBAR Description Enable Progress Bar Object. 5.1.5.10.2.5.19 USE_RADIOBUTTON Macro C #define USE_RADIOBUTTON Description Enable Radio Button Object. 5.1.5.10.2.5.20 USE_ROUNDDIAL Macro C #define USE_ROUNDDIAL Description Enable Dial Object. 5.1.5.10.2.5.21 USE_SLIDER Macro C #define USE_SLIDER Description Enable Slider or Scroll Bar Object. 5.1.5.10.2.5.22 USE_STATICTEXT Macro C #define USE_STATICTEXT 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-324 Description Enable Static Text Object. 5.1.5.10.2.5.23 USE_TEXTENTRY Macro C #define USE_TEXTENTRY Description Enable TextEntry Object. 5.1.5.10.2.5.24 USE_TOUCHSCREEN Macro C #define USE_TOUCHSCREEN 5.1.5.10.2.5.25 USE_WINDOW Macro C #define USE_WINDOW Description Enable Window Object. 5.1.5.10.2.5.26 COLOR_DEPTH Macro C #define COLOR_DEPTH 16 Description Specifies the color depth used in the application defined in GraphicsConfig.h. 5.1.5.10.2.5.27 DRIVER_COUNT Macro C #define DRIVER_COUNT 1 Description • Overview: For XC16 or C30 builds only: When placing fonts in internal • data memory, there is a 32K limit for data space. The total • data should not exceed 32K. When this is unavoidable, the macro • USE_GFX_FONT_IN_PROGRAM_SECTION will relocate the font in • program space. This will remove the 32K restriction but at • the expense of slower access. • Define this in GraphicsConfig.h to enable the font to be • placed in program space. * ****************************************************************** #define USE_GFX_FONT_IN_PROGRAM_SECTION 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-325 5.1.5.10.2.5.28 GFX_free Macro C #define GFX_free(pObj) free(pObj) // Description When using Operating Systems (OS), define the OS specific malloc() and free() functions for compatibility with the OS based systems. Define these in GraphicsConfig.h 5.1.5.10.2.5.29 GFX_malloc Macro C #define GFX_malloc(size) malloc(size) Description When using Operating Systems (OS), define the OS specific malloc() and free() functions for compatibility with the OS based systems. Define these in GraphicsConfig.h 5.1.5.10.2.6 Building the Library This section list the files that are available in the \src of the S1D13517 Graphics Controller Driver Library. It lists which files need to be included in the build based on either a hardware feature present on the board or configuration option selected by the system. • drv_gfx_s1d13517.c 5.1.5.10.2.7 Library Interface This section describes the Application Programming Interface (API) functions of the S1D13517 Graphics Controller Driver Library. Refer to each section for a detailed description. 5.1.5.10.2.7.1 Functions Functions Name Description GFX_DRV_S1D13517_AlphaBlendWindow SEE primitive layer alphablendWindow definition GFX_DRV_S1D13517_BrightnessSet Sets the brightness of the display backlight. GFX_DRV_S1D13517_Close closes an instance of the graphics controller GFX_DRV_S1D13517_GetReg returns graphics controller register value (byte access) GFX_DRV_S1D13517_Initialize resets LCD, initializes PMP GFX_DRV_S1D13517_Layer Updates a Layer depending on the layer parameters. GFX_DRV_S1D13517_Open opens an instance of the graphics controller GFX_DRV_S1D13517_PixelArrayPut outputs an array of pixels of length count starting at *color GFX_DRV_S1D13517_PixelPut outputs one pixel into the frame buffer at the x,y coordinate given GFX_DRV_S1D13517_PixelsPut outputs one pixel into the frame buffer at the x,y coordinate given GFX_DRV_S1D13517_SetColor Sets the color for the driver instance GFX_DRV_S1D13517_SetInstance Sets the instance for the driver GFX_DRV_S1D13517_SetPage Sets the page of a certain page type GFX_DRV_S1D13517_SetReg updates graphics controller register value (byte access) 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-326 GFX_DRV_S1D13517_Tasks Task machine that renders the driver calls for the graphics library it must be called peridically to output the contents of its circular buffer Description 5.1.5.10.2.7.1.1 GFX_DRV_S1D13517_AlphaBlendWindow Function C uint16_t* GFX_DRV_S1D13517_AlphaBlendWindow( GFX_ALPHA_PARAMS* alphaParams, uint16_t width, uint16_t height, uint8_t alpha ); 5.1.5.10.2.7.1.2 GFX_DRV_S1D13517_BrightnessSet Function C void GFX_DRV_S1D13517_BrightnessSet( uint8_t instance, uint16_t level ); Description none Parameters Parameters Description 5.1.5.10.2.7.1.3 GFX_DRV_S1D13517_Close Function C uint16_t GFX_DRV_S1D13517_Close( uint8_t instance ); Description none Returns 0 - instance closed 2 - instance doesn't exist 3 - instance already closed 5.1.5.10.2.7.1.4 GFX_DRV_S1D13517_GetReg Function C uint8_t GFX_DRV_S1D13517_GetReg( uint8_t index ); Description none Parameters Parameters Description index register number 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-327 *data array to store data Returns 0 - when call was passed 5.1.5.10.2.7.1.5 GFX_DRV_S1D13517_Initialize Function C uint16_t GFX_DRV_S1D13517_Initialize( uint8_t instance ); Description none Parameters Parameters Description instance driver instance Returns NULL - call not successful (PMP driver busy) !NULL - address of the display driver queue command 5.1.5.10.2.7.1.6 GFX_DRV_S1D13517_Layer Function C uint16_t* GFX_DRV_S1D13517_Layer( uint8_t type, GFX_LAYER_PARAMS* layer ); Description none Parameters Parameters Description type layer type layer parameters for Layer function call Returns NULL - call not successful (PMP driver busy) !NULL - address of the display driver queue command 5.1.5.10.2.7.1.7 GFX_DRV_S1D13517_Open Function C uint16_t GFX_DRV_S1D13517_Open( uint8_t instance ); Description none Returns 1 - driver not initialied 2 - instance doesn't exist 3 - instance already open instance to driver when successful 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-328 5.1.5.10.2.7.1.8 GFX_DRV_S1D13517_PixelArrayPut Function C uint16_t* GFX_DRV_S1D13517_PixelArrayPut( uint16_t * color, short x, short y, uint16_t count, uint16_t lineCount ); Description none Parameters Parameters Description *color start of the array x x coordinate of the start point. y y coordinate of the end point. count number of pixels Returns NULL - call not successful (PMP driver busy) !NULL - address to the number of pixels yet to be serviced 5.1.5.10.2.7.1.9 GFX_DRV_S1D13517_PixelPut Function C uint16_t GFX_DRV_S1D13517_PixelPut( short x, short y ); Description none Parameters Parameters Description instance driver instance color color to output x,y pixel coordinates Returns NULL - call not successful (PMP driver busy) !NULL - address of the display driver queue command 5.1.5.10.2.7.1.10 GFX_DRV_S1D13517_PixelsPut Function C uint16_t GFX_DRV_S1D13517_PixelsPut( short x, short y, uint16_t count, uint16_t lineCount ); 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-329 Description none Parameters Parameters Description instance driver instance color color to output x,y pixel coordinates Returns NULL - call not successful (PMP driver busy) !NULL - address of the display driver queue command 5.1.5.10.2.7.1.11 GFX_DRV_S1D13517_SetColor Function C void GFX_DRV_S1D13517_SetColor( GFX_COLOR color ); Returns none 5.1.5.10.2.7.1.12 GFX_DRV_S1D13517_SetInstance Function C void GFX_DRV_S1D13517_SetInstance( uint8_t instance ); Returns none 5.1.5.10.2.7.1.13 GFX_DRV_S1D13517_SetPage Function C uint16_t GFX_DRV_S1D13517_SetPage( uint8_t pageType, uint8_t page ); Description none Parameters Parameters Description instance driver instance Returns NULL - call not successful (PMP driver busy) !NULL - address of the display driver queue command 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-330 5.1.5.10.2.7.1.14 GFX_DRV_S1D13517_SetReg Function C uint16_t GFX_DRV_S1D13517_SetReg( uint8_t index, uint8_t value ); Description none Parameters Parameters Description index register number value value to write to register Returns 1 - call was not passed 0 - call was passed 5.1.5.10.2.7.1.15 GFX_DRV_S1D13517_Tasks Function C void GFX_DRV_S1D13517_Tasks(); 5.1.5.10.2.7.2 S1D13517 Data Types and Constants Structures Name Description GFX_DRV_S1D13517_COMMAND Structure for the commands in the driver queue. LAYER_REGISTERS This structure is used to describe layer registers. Description 5.1.5.10.2.7.2.1 GFX_DRV_S1D13517_COMMAND Structure C typedef struct { uint8_t instance; short x; short y; uint16_t * array; uint16_t data; uint16_t count; uint16_t lineCount; uint8_t task; } GFX_DRV_S1D13517_COMMAND; Description Structure: GFX_DRV_S1D13517_COMMAND None 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-331 5.1.5.10.2.7.2.2 LAYER_REGISTERS Structure C typedef struct { uint8_t XStart; uint8_t XEnd; uint8_t YStart0; uint8_t YStart1; uint8_t YEnd0; uint8_t YEnd1; uint8_t StartAddress0; uint8_t StartAddress1; uint8_t StartAddress2; } LAYER_REGISTERS; Description This structure is used to describe layer registers. 5.1.5.10.2.8 Files Files Name Description 5.1.5.10.2.8.1 drv_gfx_s1d13517_config_template.h • Module for Microchip Graphics Library • This file contains compile time options for the Graphics Library. ******************************************************************* • FileName: GraphicsConfig.h • Dependencies: none • Processor: PIC24F, PIC24H, dsPIC, PIC32 • Compiler: C30 V3.00/C32 • Company: Microchip Technology, Inc. * • Software License Agreement * • Copyright © 2008 Microchip Technology Inc. All rights reserved. • Microchip licenses to you the right to use, modify, copy and distribute • Software only when embedded on a Microchip microcontroller or digital • signal controller, which is integrated into your product or third party • product (pursuant to the sublicense terms in the accompanying license • agreement). * • You should refer to the license agreement accompanying this Software • for additional information regarding your rights and obligations. * 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-332 • SOFTWARE AND DOCUMENTATION ARE PROVIDED ?AS IS? WITHOUT WARRANTY OF ANY • KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY • OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR • PURPOSE. IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR • OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, • BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT • DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, • INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, • COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY • CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), • OR OTHER SIMILAR COSTS. * • Author Date Comment *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ • Anton Alkhimenok 10/28/2007 Initial Version • Pradeep Budagutta 10/28/2007 Display related defines • moved to DisplayConfig.h 5.1.5.10.3 SSD1926 Graphics Controller Driver Library 5.1.5.10.3.1 Introduction SSD1926 Graphics Controller Driver Library for Microchip Microcontrollers This library provides a low-level abstraction of the SSD1926 Graphics Controller Driver Library that is available on the Microchip family of microcontrollers with a convenient C language interface. It can be used to simplify low-level access to the module without the necessity of interacting directly with the module's registers, there by hiding differences from one microcontroller variant to another. Description Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony. 5.1.5.10.3.2 Release Notes MPLAB Harmony Version: v0.70b SSD1926 Graphics Controller Driver Library Version : 4.00b Release Date: 18Nov2013 New This Release: This is the first release of the library. The interface can change in the beta and\or 1.0 release. Known Issues: Nothing to report in this release. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-333 5.1.5.10.3.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 5.1.5.10.3.4 Using the Library This topic describes the basic architecture of the SSD1926 Graphics Controller Driver Library and provides information and examples on how to use it. Interface Header File: drv_gfx_ssd1926.h The interface to the SSD1926 Graphics Controller Driver Library is defined in the "drv_gfx_ssd1926.h" header file. This file is included by the "gfx_primitive.h" file. Any C language source (.c) file that uses the SSD1926 Graphics Controller Driver Library should include "gfx_primitive.h". Library File: The SSD1926 Graphics Controller Driver Library archive (.a) file installed with MPLAB Harmony. Please refer to the MPLAB Harmony Overview for how the SSD1926 Graphics Controller Driver Library interacts with the framework. 5.1.5.10.3.4.1 Abstraction Model This library provides the low-level abstraction of the SSD1926 Graphics Controller Driver module of the Microchip family of graphic display controllers with a convenient C language interface. This topic describes how that abstraction is modeled in the software and introduces the library interface. Description SSD1926 Graphics Controller Driver Abstraction Block Diagram Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony. 5.1.5.10.3.4.2 Library Overview Refer to the section Driver Overview for how the driver operates in a system. The library interface routines are divided into various sub-sections, each of sub-section addresses one of the blocks or the overall operation of the SSD1926 Graphics Controller Driver module. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-334 Library Interface Section Description Functions This section lists the API functions available in the library. 5.1.5.10.3.5 Configuring the Library The configuration of the SSD1926 Graphics Controller Driver is based on the file system_config.h. This header file contains the configuration selection for the SSD1926 Graphics Controller Driver. Based on the selections made, the SSD1926 Graphics Controller Driver will support or not support selected features. These configuration settings will apply to all instances of the SSD1926 Graphics Controller Driver. This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a successful build. Refer to the Applications Overview section for more details. 5.1.5.10.3.6 Building the Library This section list the files that are available in the \src of the SSD1926 Graphics Controller Driver Library. It lists which files need to be included in the build based on either a hardware feature present on the board or configuration option selected by the system. • drv_gfx_ssd1926.c 5.1.5.10.3.7 Library Interface This section describes the Application Programming Interface (API) functions of the SSD1926 Graphics Controller Driver Library. Refer to each section for a detailed description. 5.1.5.10.3.7.1 Functions Functions Name Description GFX_DRV_SSD1926_BarFill Hardware accelerated barfill function GFX_DRV_SSD1926_BrightnessSet Sets the brightness of the display backlight. GFX_DRV_SSD1926_Busy Returns non-zero if LCD controller is busy (previous drawing operation is not completed). GFX_DRV_SSD1926_Close closes an instance of the graphics controller GFX_DRV_SSD1926_GetReg returns graphics controller register value (byte access) GFX_DRV_SSD1926_Initialize resets LCD, initializes PMP GFX_DRV_SSD1926_Open opens an instance of the graphics controller GFX_DRV_SSD1926_PixelArrayGet gets an array of pixels of length count starting at *color GFX_DRV_SSD1926_PixelArrayPut outputs an array of pixels of length count starting at *color GFX_DRV_SSD1926_PixelPut outputs one pixel into the frame buffer at the x,y coordinate given GFX_DRV_SSD1926_PixelsPut outputs one pixel into the frame buffer at the x,y coordinate given GFX_DRV_SSD1926_SetColor Sets the color for the driver instance GFX_DRV_SSD1926_SetInstance Sets the instance for the driver GFX_DRV_SSD1926_SetReg updates graphics controller register value (byte access) GFX_DRV_SSD1926_Tasks Task machine that renders the driver calls for the graphics library it must be called peridically to output the contents of its circular buffer 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-335 Description 5.1.5.10.3.7.1.1 GFX_DRV_SSD1926_BarFill Function C uint16_t GFX_DRV_SSD1926_BarFill( short left, short top, short right, short bottom ); Description see primitive BarFill Returns 1 - call not successful (PMP driver busy) 0 - call successful 5.1.5.10.3.7.1.2 GFX_DRV_SSD1926_BrightnessSet Function C void GFX_DRV_SSD1926_BrightnessSet( uint8_t instance, uint16_t level ); Description none Parameters Parameters Description 5.1.5.10.3.7.1.3 GFX_DRV_SSD1926_Busy Function C uint16_t GFX_DRV_SSD1926_Busy( uint8_t instance ); Description none Parameters Parameters Description instance driver instance Returns 1 - busy 0 - not busy 5.1.5.10.3.7.1.4 GFX_DRV_SSD1926_Close Function C uint16_t GFX_DRV_SSD1926_Close( uint8_t instance 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-336 ); Description none Returns 0 - instance closed 2 - instance doesn't exist 3 - instance already closed 5.1.5.10.3.7.1.5 GFX_DRV_SSD1926_GetReg Function C uint8_t GFX_DRV_SSD1926_GetReg( uint16_t index, uint8_t * data ); Description none Parameters Parameters Description index register number *data array to store data Returns 0 - when call was passed 5.1.5.10.3.7.1.6 GFX_DRV_SSD1926_Initialize Function C uint16_t GFX_DRV_SSD1926_Initialize( uint8_t instance ); Description none Parameters Parameters Description instance driver instance Returns 1 - call not successful (PMP driver busy) 0 - call successful 5.1.5.10.3.7.1.7 GFX_DRV_SSD1926_Open Function C uint16_t GFX_DRV_SSD1926_Open( uint8_t instance ); Description none 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-337 Returns 1 - driver not initialied 2 - instance doesn't exist 3 - instance already open instance to driver when successful 5.1.5.10.3.7.1.8 GFX_DRV_SSD1926_PixelArrayGet Function C uint16_t* GFX_DRV_SSD1926_PixelArrayGet( uint16_t * color, short x, short y, uint16_t count ); Description none Parameters Parameters Description instance driver instance *color start of the array x x coordinate of the start point. y y coordinate of the end point. count number of pixels Returns NULL - call not successful !NULL - address of the display driver queue command 5.1.5.10.3.7.1.9 GFX_DRV_SSD1926_PixelArrayPut Function C uint16_t* GFX_DRV_SSD1926_PixelArrayPut( uint16_t * color, short x, short y, uint16_t count, uint16_t lineCount ); Description none Parameters Parameters Description instance driver instance *color start of the array x x coordinate of the start point. y y coordinate of the end point. count number of pixels Returns NULL - call not successful !NULL - handle to the number of pixels remaining 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-338 5.1.5.10.3.7.1.10 GFX_DRV_SSD1926_PixelPut Function C uint16_t GFX_DRV_SSD1926_PixelPut( short x, short y ); Description none Parameters Parameters Description instance driver instance color color to output x,y pixel coordinates Returns NULL - call not successful !NULL - address of the display driver queue command 5.1.5.10.3.7.1.11 GFX_DRV_SSD1926_PixelsPut Function C uint16_t GFX_DRV_SSD1926_PixelsPut( short x, short y, uint16_t count, uint16_t lineCount ); Description none Parameters Parameters Description x,y pixel coordinates 5.1.5.10.3.7.1.12 GFX_DRV_SSD1926_SetColor Function C void GFX_DRV_SSD1926_SetColor( GFX_COLOR color ); Returns none 5.1.5.10.3.7.1.13 GFX_DRV_SSD1926_SetInstance Function C void GFX_DRV_SSD1926_SetInstance( uint8_t instance ); 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-339 Returns none 5.1.5.10.3.7.1.14 GFX_DRV_SSD1926_SetReg Function C uint16_t GFX_DRV_SSD1926_SetReg( uint16_t index, uint8_t value ); Description none Parameters Parameters Description index register number value value to write to register Returns 1 - call was not passed 0 - call was passed 5.1.5.10.3.7.1.15 GFX_DRV_SSD1926_Tasks Function C void GFX_DRV_SSD1926_Tasks(); 5.1.5.10.3.7.2 Data Types and Constants Structures Name Description GFX_DRV_SSD1926_COMMAND Structure for the commands in the driver queue. GFX_DRV_SSD1926_TASK Structure for the task machine Description 5.1.5.10.3.7.2.1 GFX_DRV_SSD1926_COMMAND Structure C typedef struct { uint8_t instance; uint32_t address; uint16_t * array; uint16_t data; uint16_t count; uint16_t lineCount; SSD1926_TASK task; } GFX_DRV_SSD1926_COMMAND; Description Structure: GFX_DRV_SSD1926_COMMAND None 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-340 Members Members Description uint32_t address; wether the task is complete or not 5.1.5.10.3.7.2.2 GFX_DRV_SSD1926_TASK Structure C typedef struct { uint8_t instance; uint32_t address; uint16_t color; uint8_t state; } GFX_DRV_SSD1926_TASK; Description Structure: GFX_DRV_SSD1926_TASK None 5.1.5.10.3.8 Files Files Name Description 5.1.5.10.3.8.1 drv_gfx_ssd1926_config_template.h • Module for Microchip Graphics Library • This file contains compile time options for the Graphics Library. ******************************************************************* • FileName: GraphicsConfig.h • Dependencies: none • Processor: PIC24F, PIC24H, dsPIC, PIC32 • Compiler: C30 V3.00/C32 • Company: Microchip Technology, Inc. * • Software License Agreement * • Copyright © 2008 Microchip Technology Inc. All rights reserved. • Microchip licenses to you the right to use, modify, copy and distribute • Software only when embedded on a Microchip microcontroller or digital • signal controller, which is integrated into your product or third party • product (pursuant to the sublicense terms in the accompanying license • agreement). * • You should refer to the license agreement accompanying this Software • for additional information regarding your rights and obligations. 5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library 5-341 * • SOFTWARE AND DOCUMENTATION ARE PROVIDED ?AS IS? WITHOUT WARRANTY OF ANY • KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY • OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR • PURPOSE. IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR • OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, • BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT • DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, • INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, • COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY • CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), • OR OTHER SIMILAR COSTS. * • Author Date Comment *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ • Anton Alkhimenok 10/28/2007 Initial Version • Pradeep Budagutta 10/28/2007 Display related defines • moved to DisplayConfig.h 5.1.6 Non-Volatile Memory (NVM) Driver Library 5.1.6.1 Introduction Non-Volatile Memory (NVM) Driver Library for Microchip Microcontrollers This library provides a low-level abstraction of the NVM Driver Library that is available on the Microchip family of microcontrollers with a convenient C language interface. It can be used to simplify low-level access to the module without the necessity of interacting directly with the module's registers, thereby hiding differences from one microcontroller variant to another. Description The functions provides in the NVM Driver Library also perform certain mandatory assembly language instructions specific for access and modification of memory, which are thus abstracted. Memory Devices for PIC Microcontrollers There are two primary forms of on-chip memory available for PIC microcontrollers: programmable Flash memory and data EEPROM memory. The access mechanism for both of these types are varied and different techniques are specified for the same.: 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-342 Flash Program Memory The Flash program memory is readable, writeable, and erasable during normal operation over the entire operating voltage range. A read from program memory is executed at one byte/word at a time depending on the width of the data bus. A write to the program memory is executed in either blocks of specific sizes or a single word depending on the type of processor used. An erase is performed in blocks. A bulk erase may be performed from user code depending on the type of processor supporting the operation. Writing or erasing program memory will cease instruction fetches until the operation is complete, restricting memory access, and therefore preventing code execution. This is controlled by an internal programming timer. There are three processor dependant methods for program memory modification. • Run-Time Self Programming (RTSP) • In-Circuit Serial Programming (ICSP) • EJTAG programming This section describes the RTSP techniques. 5.1.6.2 Release Notes MPLAB Harmony Version: v0.70b NVM Driver Library Version : 0.01 Release Date: 18Nov2013 New This Release: • Internal handling of erase feature for sector write function Known Issues: • Not tested by mapping the image to different parts of the memory 5.1.6.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED AS IS MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-343 5.1.6.4 Using the Library This topic describes the basic architecture of the NVM Driver Library and provides information and examples on how to use it. Interface Header File: drv_nvm.h The interface to the NVM Driver Library is defined in the "drv_nvm.h" header file. Any C language source (.c) file that uses the NVM Driver library should include "drv.h". Library File: The NVM Driver Library archive (.a) file installed with MPLAB Harmony. Please refer to the MPLAB Harmony Overview for how the driver interacts with the framework. 5.1.6.4.1 Abstraction Model This library provides a low-level abstraction of the NVM module on the Microchip family of microcontrollers with a convenient C language interface. This topic describes how that abstraction is modeled in software and introduces the library's interface. Description NVM Software Abstraction Block Diagram Note 1: This feature is not available on all devices. Refer to the specific device data sheet to determine availability. Abstraction Model The NVM peripheral library provides interface routines to interact with the blocks shown in the diagram. The Flash Status and Control Logic ensures that the Flash memory is configured appropriately for modification. It also provides the status of the different operations in progress as well as errors, if any. It also decides if the operation is for Flash program memory or the special device configuration registers. The Flash Read/Write block ensures that the user data is written to/read from the program memory holding latches. It provides a layer of abstraction over the sequence of processor-specific instructions that are required to access this data. Depending on the processor type either block or Word programming options area available. 5.1.6.4.2 Library Overview Refer to the section Driver Overview for how the driver operates in a system. The library interface routines are divided into various subsections, each of the sub-sections addresses one of the blocks or the 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-344 overall operation of the NVM module. Library Interface Section Description System Functions Provides system module interfaces, device initialization, deinitialization, reinitialization, tasks and status functions. Client Core Functions Provides open, close, status and other setup functions. Client Block Transfer Functions Provides buffered data operation functions available in the core configuration. Miscellaneous Functions Provides driver miscellaneous functions related to versions and others. 5.1.6.4.3 How the Library Works The library provides interfaces to support: • System Functionality • Client Functionality Note: Not all modes are available on all devices. Please refer to the specific device data sheet to determine the modes supported for your device. 5.1.6.4.3.1 System Initialization This section provides information for system initialization and reinitialization. Description System Initialization and Reinitialization The system performs the initialization and the reinitialization of the device driver with settings that affect only the instance of the device that is being initialized or reinitialized. During system initialization each instance of the NVM module would be initialized with the following configuration settings (either passed dynamically at run time using DRV_NVM_INIT or by using initialization overrides) that are supported by the specific NVM device hardware: • Device requested power state: One of the system module power states. For specific details please refer to the Data Types and Constants section. • The actual peripheral ID enumerated as the PLIB level module ID (e.g., NVM_ID_0) • Defining the respective interrupt sources for transmit (TX), receive (RX), and error interrupts The DRV_NVM_Initialize function returns an object handle of the type SYS_MODULE_OBJ. After this, the object handle returned by the initialize interface would be used by the other system interfaces, such as DRV_NVM_Reinitialize, DRV_NVM_Deinitialize, DRV_NVM_Status, and DRV_NVM_Tasks. Note: The system initialization and the reinitialization settings, only effect the instance of the peripheral that is being initialized or reinitialized. The SYS_MODULE_INDEX is passed to the DRV_NVM_Initialize function tol determine which type of memory is selected using: • DRV_NVM_INDEX_0 - FLASH Example: // This code snippet shows an example // of initializing the NVM Driver. DRV_NVM_INIT NVMInitData; SYS_MODULE_OBJ objectHandle; 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-345 NVMInitData.moduleInit.value = SYS_MODULE_POWER_RUN_FULL; NVMInitData.moduleId = NVM_ID_0; NVMInitData.flashInterruptSource = INT_SOURCE_FLASH_CONTROL; //usage of DRV_NVM_INDEX_0 indicates usage of flash realted APIs objectHandle = DRV_NVM_Initialize(DRV_NVM_INDEX_0, (SYS_MODULE_INIT*)NVMInitData); if (SYS_MODULE_OBJ_INVALID == objectHandle) { // Handle error } Tasks Routine The system will call DRV_NVM_Tasks, from system task service (in a polled environment) or DRV_NVM_Taskswill be called from the Interrupt Service Routine (ISR) of the NVM. 5.1.6.4.3.2 Client Access Operation This section provides information for general client operation. Description General Client Operation For the application to start using an instance of the module, it must call the DRV_NVM_Open function. This provides the configuration required to open the NVM instance for operation. If the driver is deinitialized using the function DRV_NVM_Deinitialize, the application must call the DRV_NVM_Open function again to set up the instance of the NVM. The function DRV_NVM_Open need not be called again if the system is reinitialized using the DRV_NVM_Reinitialize function. For the various options available for I/O INTENT please refer to the Data Types and Constants section. Example: DRV_HANDLE handle; handle = DRV_NVM_Open(DRV_NVM_INDEX_0, DRV_IO_INTENT_EXCLUSIVE); if (DRV_HANDLE_INVALID == handle) { // Unable to open the driver } 5.1.6.4.3.3 Client Basic Operation This section provides information for client basic functionality. Description An extremely basic interface for the driver operation is provided through client basic functionality. The NVM driver provides the word and row programming operations in the basic mode of operation. The type of memory on which these operations will be performed is provided as an index while initialization. The SYS_MODULE_INDEX is passed to the DRV_NVM_Initialize function to determine which type of memory is selected using: • DRV_NVM_INDEX_0 - FLASH Note: Not all devices support the word/row programming operations. It is the responsibility of the user to determine which devices support which mode of operation. The memory access method described in this document only refers to Real-Time Self-Programming (RTSP). Word Programming Operations Applications using the NVM word write functionality need to perform the following: 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-346 1. The system should have completed necessary initialization and DRV_NVM_Tasks should either be running in a polled environment, or in an interrupt environment. 2. Open the driver using DRV_NVM_Open with the necessary intent. 3. Provide the desired mode of operation using the operation mode. 4. Write a word using DRV_NVM_WriteWord. 5. The client will be able to close itself using the DRV_NVM_Close when required. DRV_HANDLE handle; // Returned from DRV_NVM_Open char myBuffer[MY_BUFFER_SIZE]; char* nvmAddr = BASE_ADDRESS_OF_NVM_TO_WRITE_TO DRV_NVM_OPERATION_STATUS myStatus = 0; myStatus = DRV_NVM_WriteWord( handle, myBuffer, nvmAddr); if(myStatus == DRV_NVM_STATUS_OPERATION_COMPLETE) { //Write successful } Applications using the NVM word erase functionality need to perform the following: 1. The system should have completed necessary initialization and DRV_NVM_Tasks should either be running in a polled environment, or in an interrupt environment. 2. Open the driver using DRV_NVM_Open with the necessary intent. 3. Provide the desired mode of operation using the operation mode. 4. Erase a word using DRV_NVM_EraseWord. 5. The client will be able to close itself using the DRV_NVM_Close when required. DRV_HANDLE handle; // Returned from DRV_NVM_Open char* nvmAddr = BASE_ADDRESS_OF_NVM_TO_ERASE_FROM DRV_NVM_OPERATION_STATUS myStatus = 0; myStatus = DRV_NVM_EraseWord( handle, myBuffer, nvmAddr); if(myStatus == DRV_NVM_STATUS_OPERATION_COMPLETE) { //Erase successful } Row Programming Operations Applications using the NVM row erase functionality needs to perform the following: 1. The system should have completed necessary initialization and DRV_NVM_Tasks should either be running in a polled environment, or in an interrupt environment. 2. Open the driver using DRV_NVM_Open with the necessary intent. 3. Provide the desired mode of operation using the operation mode. 4. Erase a word using DRV_NVM_EraseROW. 5. The client will be able to close itself using the DRV_NVM_Close when required. DRV_HANDLE handle; // Returned from DRV_NVM_Open char* nvmAddr = BASE_ADDRESS_OF_NVM_TO_ERASE_FROM DRV_NVM_OPERATION_STATUS myStatus = 0; myStatus = DRV_NVM_EraseROW( handle, nvmAddr); if(myStatus == DRV_NVM_STATUS_OPERATION_COMPLETE) { //Erase successful 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-347 } 5.1.6.4.3.4 Client Block Data Operation Client Block Data functionality provides advanced interface for the driver operation. These block data functions depend heavily on the block sizes and boundaries of individual devices and the APIs are responsible for keeping that information transparent from the application. These operations return the number of bytes of a successfully executed operation. Block Operations Applications using the NVM block write functionality need to perform the following: 1. The system should have completed necessary initialization and DRV_NVM_Tasks should either be running in a polled environment, or in an interrupt environment. 2. Open the driver using DRV_NVM_Open with the necessary intent. 3. Provide the desired mode of operation using the operation mode. 4. Provide the source and destination addresses and begin write using DRV_NVM_Write. 5. The client will be able to close itself using the DRV_NVM_Close when required. DRV_HANDLE handle; // Returned from DRV_NVM_Open char myBuffer[2 * DRV_NVM_ROW_SIZE]; // Destination address should be row aligned. char *destAddress = (char *)NVM_BASE_ADDRESS_TO_WRITE; unsigned int count = 2 * MY_BUFFER_SIZE; DRV_NVM_BUFFER_HANDLE bufferHandle; bufferHandle = DRV_NVM_Write(myNVMHandle, destAddress, &myBuffer[total], count); if(DRV_NVM_BUFFER_HANDLE_INVALID == bufferHandle) { // Do error handling here } // Wait till the buffer completes. This should not // be a while loop if a part of cooperative multi-tasking // routine. In that case, it should be invoked in task // state machine. while(DRV_NVM_BufferStatus(bufferHandle) != DRV_NVM_BUFFER_COMPLETED); Applications using the NVM block Read functionality need to perform the following: 1. The system should have completed necessary initialization and DRV_NVM_Tasks should either be running in a polled environment, or in an interrupt environment. 2. Open the driver using DRV_NVM_Open with the necessary intent. 3. Provide the desired mode of operation using the operation mode. 4. Provide the source and destination addresses and begin write using DRV_NVM_ReadBlock. 5. The client will be able to close itself using the DRV_NVM_Close when required. DRV_HANDLE handle; // Returned from DRV_NVM_Open char myBuffer[MY_BUFFER_SIZE]; char *srcAddress = NVM_BASE_ADDRESS_TO_READ_FROM; unsigned int count = MY_BUFFER_SIZE; DRV_NVM_BUFFER_HANDLE bufferHandle; bufferHandle = DRV_NVM_Read(myNVMHandle, &myBuffer[total], srcAddress, count); if(DRV_NVM_BUFFER_HANDLE_INVALID == bufferHandle) { // Do error handling here 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-348 } // Wait till the buffer completes. This should not // be a while loop if a part of cooperative multi-tasking // routine. In that case, it should be invoked in task // state machine. while(DRV_NVM_BufferStatus(bufferHandle) != DRV_NVM_BUFFER_COMPLETED); Internally, a buffer is maintained whose status can be obtained by calling API DRV_NVM_BufferStatus. 5.1.6.5 Configuring the Library Macros Name Description DRV_NVM_BUFFER_OBJECT_NUMBER Selects the maximum number of buffer objects DRV_NVM_CLIENTS_NUMBER Selects the maximum number of clients DRV_NVM_ERASE_SIZE Specifies the NVM Driver Erase Page Size in bytes. DRV_NVM_INSTANCES_NUMBER Selects the maximum number of Driver instances that can be supported by the dynamic driver. DRV_NVM_INTERRUPT_MODE Macro specifies operation of the driver to be in the interrupt mode or polled mode DRV_NVM_ROW_SIZE Specifies the NVM Driver Program Row Size in bytes. DRV_NVM_UNLOCK_KEY1 Specifies the NVM Driver Program Unlock Key 1 DRV_NVM_UNLOCK_KEY2 Specifies the NVM Driver Program Unlock Key 2 Description The configuration of the NVM Driver is based on the file sys_config.h This header file contains the configuration selection for the NVM Driver. Based on the selections made, the NVM Driver will support or not support selected features. These configuration settings will apply to all instances of the NVM Driver. This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a successful build. Refer to the Applications Overview section for more details. 5.1.6.5.1 DRV_NVM_BUFFER_OBJECT_NUMBER Macro C #define DRV_NVM_BUFFER_OBJECT_NUMBER 5 Description NVM Driver maximum number of buffer objects This definition selects the maximum number of buffer objects. This indirectly also specifies the queue depth. The NVM Driver can queue up DRV_NVM_BUFFER_OBJECT_NUMBER of read/write/erase requests before return a DRV_NVM_BUFFER_HANDLE_INVALID due to the queue being full. Increasing this number increases the RAM requirement of the driver. Remarks None. 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-349 5.1.6.5.2 DRV_NVM_CLIENTS_NUMBER Macro C #define DRV_NVM_CLIENTS_NUMBER 1 Description NVM maximum number of clients This definition selects the maximum number of clients that the NVM driver can supported at run time. Remarks None. 5.1.6.5.3 DRV_NVM_ERASE_SIZE Macro C #define DRV_NVM_ERASE_SIZE 4096 Description NVM Driver Erase Page Size. This definition specifies the NVM Driver Erase Page Size in bytes. This parameter is device specific and should be obtained from the device specific data sheet. The Erase Page Size is the minimum block size that can be erased in one erase operation. Remarks None. 5.1.6.5.4 DRV_NVM_INSTANCES_NUMBER Macro C #define DRV_NVM_INSTANCES_NUMBER 1 Description NVM Driver instance configuration This definition selects the maximum number of Driver instances that can be supported by the dynamic driver. In case of this driver, multiple instances of the driver could use the same hardware instance. Remarks None 5.1.6.5.5 DRV_NVM_INTERRUPT_MODE Macro C #define DRV_NVM_INTERRUPT_MODE false Description NVM interrupt and polled mode operation control This macro specifies operation of the driver to be in the interrupt mode or polled mode 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-350 • true - Select if interrupt mode of NVM operation is desired • false - Select if polling mode of NVM operation is desired Not defining this option to true or false will result in build error. Remarks None. 5.1.6.5.6 DRV_NVM_ROW_SIZE Macro C #define DRV_NVM_ROW_SIZE 512 Description NVM Driver Program Row Size. This definition specifies the NVM Driver Program Row Size in bytes. This parameter is device specific and should be obtained from the device specific data sheet. The Program Row Size is the minimum block size that can be programmed in one program operation. Remarks None. 5.1.6.5.7 DRV_NVM_UNLOCK_KEY1 Macro C #define DRV_NVM_UNLOCK_KEY1 0xAA996655 Description NVM Driver Program Unlock Key 1 This definition specifies the NVM Driver Program Unlock Key 1 parameter is device specific and should be obtained from the device specific data sheet. Remarks None. 5.1.6.5.8 DRV_NVM_UNLOCK_KEY2 Macro C #define DRV_NVM_UNLOCK_KEY2 0x556699AA Description NVM Driver Program Unlock Key 2 This definition specifies the NVM Driver Program Unlock Key 2 parameter is device specific and should be obtained from the device specific data sheet. Remarks None. 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-351 5.1.6.6 Building the Library This section list the files that are available in the \src of the NVM driver. It lists which files need to be included in the build based on either a hardware feature present on the board or configuration option selected by the system. 5.1.6.7 Library Interface Data Types and Constants Name Description DRV_NVM_BUFFER_HANDLE_INVALID This value defines the NVM Driver Buffer Invalid handle. DRV_NVM_INDEX_0 NVM driver index definitions DRV_NVM_INDEX_COUNT Number of valid NVM driver indices DRV_NVM_BUFFER_HANDLE This type defines the NVM Driver Buffer handle. DRV_NVM_BUFFER_STATUS Specifies the status of the buffer for the read, write and erase opeartions. DRV_NVM_CLIENT_STATUS Defines the client status DRV_NVM_INIT Defines the data required to initialize or reinitialize the NVM driver DRV_NVM_INDEX_1 This is macro DRV_NVM_INDEX_1. Client Block Data Functions Name Description DRV_NVM_Erase Erase the specified number of pages in flash memory. DRV_NVM_Read Reads a block of data from the specified address in memory. DRV_NVM_Tasks Maintains the driver's erase and write state machine and implements its ISR. DRV_NVM_Write Write a block of data to a specified address in memory. Client Core Functions Name Description DRV_NVM_ClientStatus Gets current client-specific status the NVM driver DRV_NVM_Close Closes an opened-instance of the NVM driver DRV_NVM_Open Opens the specified timer driver instance and returns a handle to it Miscellaneous Functions Name Description DRV_NVM_BufferStatus Gets the current status of the buffer. System Functions Name Description DRV_NVM_Deinitialize Deinitializes the specified instance of the NVM driver module DRV_NVM_Initialize Initializes the NVM instance for the specified driver index DRV_NVM_Status Gets the current status of the NVM driver module. Description This section describes the Application Programming Interface (API) functions of the NVM Driver Library. Refer to each section for a detailed description. 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-352 5.1.6.7.1 System Functions 5.1.6.7.1.1 DRV_NVM_Deinitialize Function C void DRV_NVM_Deinitialize( SYS_MODULE_OBJ object ); Description Deinitializes the specified instance of the NVM driver module, disabling its operation (and any hardware). Invalidates all the internal data. Preconditions Function DRV_NVM_Initialize should have been called before calling this function. Parameters Parameters Description object Driver object handle, returned from the DRV_NVM_Initialize routine Returns None. Remarks Once the Initialize operation has been called, the Deinitialize operation must be called before the Initialize operation can be called again. This routine will NEVER block waiting for hardware. If the operation requires time to allow the hardware to complete, this will be reported by the DRV_NVM_Status operation. The system has to use DRV_NVM_Status to find out when the module is in the ready state. Example // This code snippet shows an example // of deinitializng the driver. SYS_MODULE_OBJ object; // Returned from DRV_NVM_Initialize SYS_STATUS status; DRV_NVM_Deinitialize(object); status = DRV_NVM_Status(object); if (SYS_MODULE_DEINITIALIZED != status) { // Check again later if you need to know // when the driver is deinitialized. } 5.1.6.7.1.2 DRV_NVM_Initialize Function C SYS_MODULE_OBJ DRV_NVM_Initialize( const SYS_MODULE_INDEX index, const SYS_MODULE_INIT * const init ); 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-353 Description This routine initializes the NVM driver instance for the specified driver index, making it ready for clients to open and use it. Preconditions None. Parameters Parameters Description index Identifier for the instance to be initialized also the type of memory used init Pointer to a data structure containing any data necessary to initialize the driver. Returns If successful, returns a valid handle to a driver instance object. Otherwise, it returns SYS_MODULE_OBJ_INVALID. Remarks This routine must be called before any other NVM routine is called. This routine should only be called once during system initialization unless DRV_NVM_Deinitialize is called to de-initialize the driver instance. This routine will NEVER block for hardware access. If the operation requires time to allow the hardware to re-initialize, it will be reported by the DRV_NVM_Status operation. The system must use DRV_NVM_Status to find out when the driver is in the ready state. Build configuration options may be used to staticaly override options in the "init" sructure and will take precedance over initialization data passed using this routine. Example // This code snippet shows an example // of initializing the NVM Driver. DRV_NVM_INIT NVMInitData; SYS_MODULE_OBJ objectHandle; NVMInitData.moduleInit.value = SYS_MODULE_POWER_RUN_FULL; NVMInitData.moduleId = NVM_ID_0; NVMInitData.flashInterruptSource = INT_SOURCE_FLASH_CONTROL; //usage of DRV_NVM_INDEX_0 indicates usage of flash realted APIs objectHandle = DRV_NVM_Initialize(DRV_NVM_INDEX_0, (SYS_MODULE_INIT*)NVMInitData); if (SYS_MODULE_OBJ_INVALID == objectHandle) { // Handle error } 5.1.6.7.1.3 DRV_NVM_Status Function C SYS_STATUS DRV_NVM_Status( SYS_MODULE_OBJ object ); Description This routine provides the current status of the NVM driver module. Preconditions Function DRV_NVM_Initialize should have been called before calling this function. 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-354 Parameters Parameters Description object Driver object handle, returned from the DRV_NVM_Initialize routine Returns SYS_STATUS_READY - Indicates that the driver is ready and accept requests for new operations. Note Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new operations. SYS_STATUS_BUSY - Indicates that the driver is busy with a previous system level operation and cannot start another SYS_STATUS_ERROR - Indicates that the driver is in an error state Remarks Any value less than SYS_STATUS_ERROR is also an error state. SYS_MODULE_DEINITIALIZED - Indicates that the driver has been de-initialized This value is less than SYS_STATUS_ERROR The this operation can be used to determine when any of the driver's module level operations has completed. If the status operation returns SYS_STATUS_BUSY, the a previous operation has not yet completed. Once the status operation returns SYS_STATUS_READY, any previous operations have completed. The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state. This routine will NEVER block waiting for hardware. If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the deinitialize operation will need to be called, followed by the initialize operation to return to normal operations. Example SYS_MODULE_OBJ object; // Returned from DRV_NVM_Initialize SYS_STATUS NVMStatus; NVMStatus = DRV_NVM _Status(object); else if (SYS_STATUS_ERROR >= NVMStatus) { // Handle error } 5.1.6.7.2 Client Core Functions 5.1.6.7.2.1 DRV_NVM_ClientStatus Function C DRV_NVM_CLIENT_STATUS DRV_NVM_ClientStatus( const DRV_HANDLE handle ); Description This routine gets the client-specfic status of the NVM driver associated with the given handle. Preconditions The DRV_NVM_Initialize routine must have been called. DRV_NVM_Open must have been called to obtain a valid opened device handle. 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-355 Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine Returns A DRV_NVM_CLIENT_STATUS value describing the current status of the driver Remarks This routine will not block for hardware access and will immediately return the current status. Example DRV_HANDLE handle; // Returned from DRV_NVM_Open DRV_NVM_CLIENT_STATUS clientStatus; clientStatus = DRV_NVM_ClientStatus(handle); if(DRV_NVM_CLIENT_STATUS_ERROR >= clientStatus) { // Handle the error } 5.1.6.7.2.2 DRV_NVM_Close Function C void DRV_NVM_Close( const DRV_HANDLE handle ); Description This routine closes an opened-instance of the NVM driver, invalidating the handle. Preconditions The DRV_NVM_Initialize routine must have been called for the specified NVM driver instance. DRV_NVM_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine Returns None Remarks After calling this routine, the handle passed in "handle" must not be used with any of the remaining driver routines. A new handle must be obtained by calling DRV_NVM_Open before the caller may use the driver again. If DRV_IO_INTENT_BLOCKING was requested and the driver was built appropriately to support blocking behavior call may block until the operation is complete. If DRV_IO_INTENT_NON_BLOCKING request the driver client can call the DRV_NVM_Status operation to find out when the module is in the ready state (the handle is no longer valid). Usually there is no need for the driver client to verify that the Close operation has completed. Example DRV_HANDLE handle; // Returned from DRV_NVM_Open 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-356 DRV_NVM_Close(handle); 5.1.6.7.2.3 DRV_NVM_Open Function C DRV_HANDLE DRV_NVM_Open( const SYS_MODULE_INDEX index, const DRV_IO_INTENT ioIntent ); Description This routine opens the specified NVM driver instance and provides a handle that must be provided to all other client-level operations to identify the caller and the instance of the driver. Preconditions Function DRV_NVM_Initialize must have been called before calling this function. Parameters Parameters Description drvIndex Identifier for the object instance to be opened intent Zero or more of the values from the enumeration DRV_IO_INTENT "or'd" together to indicate the intended use of the driver Returns If successful, the routine returns a valid open-instance handle (a number identifying both the caller and the module instance). If an error occurs, the return value is DRV_HANDLE_INVALID. Remarks The handle returned is valid until the DRV_NVM_Close routine is called. This routine will NEVER block waiting for hardware. If the DRV_IO_INTENT_BLOCKING is requested and the driver was built appropriately to support blocking behavior, then other client-level operations may block waiting on hardware until they are complete. If DRV_IO_INTENT_NON_BLOCKING is requested the driver client can call the DRV_NVM_ClientStatus operation to find out when the module is in the ready state. If the requested intent flags are not supported, the routine will return DRV_HANDLE_INVALID. Example DRV_HANDLE handle; handle = DRV_NVM_Open(DRV_NVM_INDEX_0, DRV_IO_INTENT_EXCLUSIVE); if (DRV_HANDLE_INVALID == handle) { // Unable to open the driver } 5.1.6.7.3 Client Block Data Functions 5.1.6.7.3.1 DRV_NVM_Erase Function C DRV_NVM_BUFFER_HANDLE DRV_NVM_Erase( const DRV_HANDLE handle, 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-357 uint8_t * targetbuffer, const unsigned int numbytes ); Description This routine erases the specified number of pages in flash memory. It returns a buffer handle that can be queried by the DRV_NVM_BufferStatus() function to check for completion of the operation. The target address should be aligned on a DRV_NVM_PAGE_SIZE byte boundary. The number of bytes to write should be equal to or should be multiples of DRV_NVM_PAGE_SIZE. Preconditions The DRV_NVM_Initialize routine must have been called for the specified NVM driver instance. DRV_NVM_Open must have been called to obtain a valid opened device handle. DRV_IO_INTENT_READ or DRV_IO_INTENT_READWRITE must have been specified in the DRV_NVM_Open call. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine targetBuffer Start address in NVM memory from where the erase should begin. Should be aligned on a DRV_NVM_PAGE_SIZE byte boundary. numbytes Total number of pages to be erased expressed in bytes. This should be equal to or a multiple of DRV_NVM_PAGE_SIZE. Returns DRV_NVM_BUFFER_HANDLE_INVALID in case the operation was not successful. A valid handle otherwise. Remarks If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_NVM_Open routine and the driver was built to support blocking behavior the call will block until the operation is complete. If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_NVM_Open routine or the driver was built to only support non-blocking behavior the call will return immediately. Example // Returned from DRV_NVM_Open DRV_HANDLE handle; // Destination address should be row aligned. char *destAddress = (char *)NVM_BASE_ADDRESS_TO_ERASE; unsigned int count = 2 * DRV_NVM_PAGE_SIZE; DRV_NVM_BUFFER_HANDLE bufferHandle; bufferHandle = DRV_NVM_Write(myNVMHandle, destAddress, count); if(DRV_NVM_BUFFER_HANDLE_INVALID == bufferHandle) { // Do error handling here } // Wait till the buffer completes. This should not // be a while loop if a part of cooperative multi-tasking // routine. In that case, it should be invoked in task // state machine. while(DRV_NVM_BufferStatus(bufferHandle) != DRV_NVM_BUFFER_COMPLETED); 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-358 5.1.6.7.3.2 DRV_NVM_Read Function C DRV_NVM_BUFFER_HANDLE DRV_NVM_Read( const DRV_HANDLE handle, uint8_t * targetBuffer, uint8_t * srcAddress, const unsigned int numbytes ); Description This routine reads a block of data from the specified address in memory. It returns a buffer handle that can be queried by the DRV_NVM_BufferStatus() function to check for completion of the operation. Preconditions The DRV_NVM_Initialize routine must have been called for the specified NVM driver instance. DRV_NVM_Open must have been called to obtain a valid opened device handle. DRV_IO_INTENT_READ or DRV_IO_INTENT_READWRITE must have been specified in the DRV_NVM_Open call. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine targetBuffer Buffer into which the data read from the NVM instance will be placed. srcAddress The base address in NVM memory from data read should begin numbytes Total number of bytes that need to be read from the module instance (must be equal to or less than the size of the buffer) Returns DRV_NVM_BUFFER_HANDLE_INVALID in case the operation was not successful. A valid handle otherwise. Remarks If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_NVM_Open routine and the driver was built to support blocking behavior the call will block until the operation is complete. If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_NVM_Open routine or the driver was built to only support non-blocking behavior the call will return immediately, identifying how many bytes of data were actually copied into the client's buffer and the client must call DRV_NVM_Read again with adjusted parameters as shown in the example. Example DRV_HANDLE handle; // Returned from DRV_NVM_Open char myBuffer[MY_BUFFER_SIZE]; char *srcAddress = NVM_BASE_ADDRESS_TO_READ_FROM; unsigned int count = MY_BUFFER_SIZE; DRV_NVM_BUFFER_HANDLE bufferHandle; bufferHandle = DRV_NVM_Read(myNVMHandle, &myBuffer[total], srcAddress, count); if(DRV_NVM_BUFFER_HANDLE_INVALID == bufferHandle) { // Do error handling here } // Wait till the buffer completes. This should not // be a while loop if a part of cooperative multi-tasking // routine. In that case, it should be invoked in task // state machine. while(DRV_NVM_BufferStatus(bufferHandle) != DRV_NVM_BUFFER_COMPLETED); 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-359 5.1.6.7.3.3 DRV_NVM_Tasks Function C void DRV_NVM_Tasks( SYS_MODULE_OBJ object ); Description This routine is used to maintain the driver's internal write and erase state machine and implement its ISR for interrupt-driven implementations. Preconditions The DRV_NVM_Initialize routine must have been called for the specified NVM driver instance. Parameters Parameters Description object Object handle for the specified driver instance (returned from DRV_NVM_Initialize) Returns None. Remarks This routine is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the apropriate raw ISR. This routine may excute in an ISR context and will never block or access any resources that may cause it to block. Example SYS_MODULE_OBJ object; // Returned from DRV_NVM_Initialize while (true) { DRV_NVM_Tasks (object); // Do other tasks } 5.1.6.7.3.4 DRV_NVM_Write Function C DRV_NVM_BUFFER_HANDLE DRV_NVM_Write( DRV_HANDLE handle, uint8_t * destination, uint8_t * source, const unsigned int nBytes ); Description This routine writes a block of data to a specified address in memory. It returns a buffer handle that can be queried by the DRV_NVM_BufferStatus() function to check for completion of the operation. The contents of the source buffer should not be changed while the operation is in progress. The target address should be aligned on a DRV_NVM_ROW_SIZE byte boundary. The number of bytes to write should be equal to or should be multiples of DRV_NVM_ROW_SIZE. Preconditions The DRV_NVM_Initialize routine must have been called for the specified NVM driver instance. DRV_NVM_Open must have been called to obtain a valid opened device handle. 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-360 DRV_IO_INTENT_READ or DRV_IO_INTENT_READWRITE must have been specified in the DRV_NVM_Open call. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine targetBuffer Buffer in NVM memory where the data from srcAddress will be placed. Should be aligned on a DRV_NVM_ROW_SIZE byte boundary. srcAddress The source buffer containing data to programmed into NVM numbytes Total number of bytes that need to be written to the NVM. This should be equal to or a multiple of DRV_NVM_ROW_SIZE. Returns DRV_NVM_BUFFER_HANDLE_INVALID in case the operation was not successful. A valid handle otherwise. Remarks If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_NVM_Open routine and the driver was built to support blocking behavior the call will block until the operation is complete. If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_NVM_Open routine or the driver was built to only support non-blocking behavior the call will return immediately. Example DRV_HANDLE handle; // Returned from DRV_NVM_Open char myBuffer[2 * DRV_NVM_ROW_SIZE]; // Destination address should be row aligned. char *destAddress = (char *)NVM_BASE_ADDRESS_TO_WRITE; unsigned int count = 2 * MY_BUFFER_SIZE; DRV_NVM_BUFFER_HANDLE bufferHandle; bufferHandle = DRV_NVM_Write(myNVMHandle, destAddress, &myBuffer[total], count); if(DRV_NVM_BUFFER_HANDLE_INVALID == bufferHandle) { // Do error handling here } // Wait till the buffer completes. This should not // be a while loop if a part of cooperative multi-tasking // routine. In that case, it should be invoked in task // state machine. while(DRV_NVM_BufferStatus(bufferHandle) != DRV_NVM_BUFFER_COMPLETED); 5.1.6.7.4 Client Basic Functions 5.1.6.7.5 Miscellaneous Functions 5.1.6.7.5.1 DRV_NVM_BufferStatus Function C DRV_NVM_BUFFER_STATUS DRV_NVM_BufferStatus( DRV_HANDLE handle, const DRV_HANDLE bufferHandle ); 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-361 Description This routine gets the current status of the buffer. The application must use this routine in case a polling based implementation is desired. Preconditions The DRV_NVM_Initialize routine must have been called. DRV_NVM_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine Returns A DRV_NVM_BUFFER_STATUS value describing the current status of the buffer Remarks This routine will not block for hardware access and will immediately return the current status. Example DRV_HANDLE handle; // Returned from DRV_NVM_Open DRV_HANDLE bufferHandle; DRV_NVM_BUFFER_STATUS status; status = DRV_NVM_BufferStatus(handle, bufferHandle); if(status == DRV_NVM_BUFFER_COMPLETED) { // Operation Done } 5.1.6.7.6 Data Types and Constants 5.1.6.7.6.1 DRV_NVM_BUFFER_HANDLE_INVALID Macro C #define DRV_NVM_BUFFER_HANDLE_INVALID Description NVM Driver Buffer Invalid Handle This value defines the NVM Driver Buffer Invalid handle. This value is returned by read/write/erase routines when the desired operation could not be completed. Remarks None. 5.1.6.7.6.2 DRV_NVM_INDEX_0 Macro C #define DRV_NVM_INDEX_0 0 Description Driver NVM Module Index reference These constants provide NVM driver index definitions. 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-362 Remarks These constants should be used in place of hard-coded numeric literals. These values should be passed into the DRV_NVM_Initialize and DRV_NVM_Open routines to identify the driver instance in use. 5.1.6.7.6.3 DRV_NVM_INDEX_COUNT Macro C #define DRV_NVM_INDEX_COUNT 1 Description NVM Driver Module Index Count This constant identifies NVM driver index definitions. Remarks This constant should be used in place of hard-coded numeric literals. This value is part-specific. 5.1.6.7.6.4 DRV_NVM_BUFFER_HANDLE Type C typedef uintptr_t DRV_NVM_BUFFER_HANDLE; Description NVM Driver Buffer Handle This type defines the NVM Driver Buffer handle. Remarks None. 5.1.6.7.6.5 DRV_NVM_BUFFER_STATUS Enumeration C typedef enum { DRV_NVM_BUFFER_COMPLETED = 0, DRV_NVM_BUFFER_QUEUED = 1, DRV_NVM_BUFFER_IN_PROGRESS = 2, DRV_NVM_BUFFER_ERROR_UNKNOWN = -1 } DRV_NVM_BUFFER_STATUS; Description NVM Driver Buffer Status This type specifies the status of the buffer for the read, write and erase opeartions. Members Members Description DRV_NVM_BUFFER_COMPLETED = 0 Done OK and ready DRV_NVM_BUFFER_QUEUED = 1 Scheduled but not started DRV_NVM_BUFFER_IN_PROGRESS = 2 Currently being in transfer DRV_NVM_BUFFER_ERROR_UNKNOWN = -1 Unknown buffer 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-363 Remarks None. 5.1.6.7.6.6 DRV_NVM_CLIENT_STATUS Enumeration C typedef enum { DRV_NVM_CLIENT_STATUS_READY, DRV_NVM_CLIENT_STATUS_BUSY, DRV_NVM_WRITE_TERMINATED, DRV_NVM_ERASE_TERMINATED, DRV_NVM_LOW_VOLTAGE_ERROR, DRV_NVM_LOW_VOLTAGE_DETECT_ERROR, DRV_NVM_STATUS_INVALID } DRV_NVM_CLIENT_STATUS; Description NVM Client Status Defines the various client status codes. Members Members Description DRV_NVM_CLIENT_STATUS_READY Up and running, ready to start new operations DRV_NVM_CLIENT_STATUS_BUSY Operation in progress, unable to start a new one DRV_NVM_WRITE_TERMINATED Write operation terminated Occured DRV_NVM_ERASE_TERMINATED Erase operation terminated Occured DRV_NVM_LOW_VOLTAGE_ERROR Low voltage Error DRV_NVM_LOW_VOLTAGE_DETECT_ERROR Low voltage Error DRV_NVM_STATUS_INVALID Client Invalid Remarks None 5.1.6.7.6.7 DRV_NVM_INIT Structure C typedef struct { SYS_MODULE_INIT moduleInit; NVM_MODULE_ID nvmID; INT_SOURCE interruptSource; } DRV_NVM_INIT; Description NVM Driver Initialization Data This data type defines the data required to initialize or reinitialize the NVM driver. Members Members Description SYS_MODULE_INIT moduleInit; System module initialization NVM_MODULE_ID nvmID; Identifies NVM hardware module (PLIB-level) ID INT_SOURCE interruptSource; Interrupt Source for Write Interrupt 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-364 Remarks Not all the init features are available for all the microcontrollers 5.1.6.7.6.8 DRV_NVM_INDEX_1 Macro C #define DRV_NVM_INDEX_1 1 Description This is macro DRV_NVM_INDEX_1. 5.1.6.8 Files Files Name Description drv_nvm.h NVM Driver Interface Definition drv_nvm_config_template.h NVM driver configuration definitions template Description 5.1.6.8.1 drv_nvm.h NVM Driver Interface Definition The NVM device driver provides a simple interface to manage the NVM modules on Microchip microcontrollers. This file defines the interface definition for the NVM driver. Enumerations Name Description DRV_NVM_BUFFER_STATUS Specifies the status of the buffer for the read, write and erase opeartions. DRV_NVM_CLIENT_STATUS Defines the client status Functions Name Description DRV_NVM_BufferStatus Gets the current status of the buffer. DRV_NVM_ClientStatus Gets current client-specific status the NVM driver DRV_NVM_Close Closes an opened-instance of the NVM driver DRV_NVM_Deinitialize Deinitializes the specified instance of the NVM driver module DRV_NVM_Erase Erase the specified number of pages in flash memory. DRV_NVM_Initialize Initializes the NVM instance for the specified driver index DRV_NVM_Open Opens the specified timer driver instance and returns a handle to it DRV_NVM_Read Reads a block of data from the specified address in memory. DRV_NVM_Status Gets the current status of the NVM driver module. DRV_NVM_Tasks Maintains the driver's erase and write state machine and implements its ISR. DRV_NVM_Write Write a block of data to a specified address in memory. 5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library 5-365 Macros Name Description DRV_NVM_BUFFER_HANDLE_INVALID This value defines the NVM Driver Buffer Invalid handle. DRV_NVM_INDEX_0 NVM driver index definitions DRV_NVM_INDEX_1 This is macro DRV_NVM_INDEX_1. DRV_NVM_INDEX_COUNT Number of valid NVM driver indices Structures Name Description DRV_NVM_INIT Defines the data required to initialize or reinitialize the NVM driver Types Name Description DRV_NVM_BUFFER_HANDLE This type defines the NVM Driver Buffer handle. File Name drv_nvm.h Company Microchip Technology Incorported 5.1.6.8.2 drv_nvm_config_template.h NVM Driver Configuration Definitions for the template version These definitions statically define the driver's mode of operation. Macros Name Description DRV_NVM_BUFFER_OBJECT_NUMBER Selects the maximum number of buffer objects DRV_NVM_CLIENTS_NUMBER Selects the maximum number of clients DRV_NVM_ERASE_SIZE Specifies the NVM Driver Erase Page Size in bytes. DRV_NVM_INSTANCES_NUMBER Selects the maximum number of Driver instances that can be supported by the dynamic driver. DRV_NVM_INTERRUPT_MODE Macro specifies operation of the driver to be in the interrupt mode or polled mode DRV_NVM_ROW_SIZE Specifies the NVM Driver Program Row Size in bytes. DRV_NVM_UNLOCK_KEY1 Specifies the NVM Driver Program Unlock Key 1 DRV_NVM_UNLOCK_KEY2 Specifies the NVM Driver Program Unlock Key 2 File Name drv_NVM_config_template.h Company Microchip Technology Incorported 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-366 5.1.7 Parallel Master Port (PMP) Driver Library 5.1.7.1 Introduction PMP Driver Library for Microchip Microcontrollers This library provides an interface to manage the Parallel Master Port (PMP) module on Microchip family of microcontrollers in different modes of operation. Description The Parallel Master Port (PMP) is a parallel 8-bit/16-bit I/O module specifically designed to communicate with a wide variety of parallel devices such as communications peripherals, LCDs, external memory devices and microcontrollers. Because the interfaces to parallel peripherals vary significantly, the PMP module is highly configurable. The following figure shows a generic block diagram of the ways PMP module can be used: PMP module can be used in different modes. Master and Slave are the two modes which can further have sub-modes depending on the different microcontroller families. Master Mode: In master mode, the PMP module can provide a 8-bit or 16-bit data bus, up to 16 bits of address, and all the necessary control signals to operate a variety of external parallel devices such as memory devices, peripherals and slave microcontrollers. The PMP master modes provide a simple interface for reading and writing data, but not executing program instructions from external devices, such as SRAM or Flash memories. Slave Mode: Slave modes support 8-bit data only and the module control pins are automatically dedicated when this mode is selected. 5.1.7.2 Release Notes MPLAB Harmony Version: v0.70b PMP Driver Library Version : 0.01 Release Date: 18Nov2013 New This Release: This is the first release of the library. The interface can change in the beta and\or 1.0 release. 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-367 Known Issues: Nothing to report in this release. 5.1.7.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 5.1.7.4 Using the Library This topic describes the basic architecture of the PMP Driver Library and provides information and examples on how to use it. Interface Header File: drv_pmp.h The interface to the PMP Driver library is defined in the "drv_pmp.h" header file. This file is included by the "drv.h" file. Any C language source (.c) file that uses the PMP Driver Library should include "drv.h". Library File: The PMP Driver Library archive (.a) file installed with MPLAB Harmony. Please refer to the MPLAB Harmony Overview for how the driver interacts with the framework. 5.1.7.4.1 Abstraction Model This library provides a low-level abstraction of the Parallel Master Port (PMP) module on Microchip's microcontrollers with a convenient C language interface. This topic describes how that abstraction is modeled in software and introduces the library's interface. Description Hardware Abstraction Model Description The PMP module provides interface routines to interact with external peripherals such as LCD, EEPROM, Flash memory, etc., as shown in the following diagram. The diagram shows the PMP module acting as a master. The PMP module can be easily configured to act as a slave. The address and data lines can be multiplexed to suit the application. The address and data buffers are up to 2-byte (16-bit) buffers for data transmitted or received by the parallel interface to the PMP bus over the data and address lines synchronized with control logic including the read and write strobe. 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-368 PMP Hardware Abstraction Model Diagram The desired timing wait states to suit different peripheral timings can also be programmed using the PMP module. 5.1.7.4.2 Library Overview Refer to the section Driver Overview for how the driver operates in a system. The library interface routines are divided into various sub-sections, each sub-section addresses one of the blocks or the overall operation of the PMP module. Library Interface Section Description System Functions Provides system module interfaces, device initialization, deinitialization, re-initialization, tasks, and status functions. Client Interaction Functions Provides open, close, client status and client mode configuration functions. Client Transfer Functions Provides interface for data transfer in master and slave mode. Miscellaneous Provides driver miscellaneous functions, version identification functions etc. 5.1.7.4.3 How the Library Works This section describes how the PMP Driver Library operates. Description Before the driver is ready for use, its should be configured (compile time configuration). Refer to the Configuring the Library section for more details on how to configure the driver. There are few run-time configuration items that are done during initialization of the driver instance, and a few that are client-specific and are done using dedicated functions. To use the PMP Driver, initialization and client functions should be invoked in a specific sequence to ensure correct operation. The following is the sequence in which various routines should be called: 1. Call DRV_PMP_Init to initialize the PMP Driver. Note that this may be performed by the MPLAB Harmony system module. The DRV_PMP_Status function may be used to check the status of the initialization. 2. Once initialization for a particular driver instance is done, the client wanting to use the driver can open it using API DRV_PMP_Open. 3. The DRV_PMP_ModeConfig function should now be called, which will configure the driver for the exact mode of operation required by that client. 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-369 4. After configuring the mode, DRV_PMP_Write and/or DRV_PMP_Read can be called by the user application to Write/Read using the PMP module. Calling these functions does not start the PMP transfer immediately in non-interrupt mode. Instead, all of these transfer tasks are queued in an internal queue. Actual transfer starts only when the PMP Task function is called by the system/user. In interrupt mode, although transfer tasks are queued, the actual transfer starts immediately. 5. PMP Write and Read functions return an ID of that particular transfer, which should be saved by user to get the status of that transfer later. 6. The system will either call DRV_PMP_Tasks from the System Task Service (in a polled environment), or it will be called from interrupt service routine of the PMP. 7. At any time status of the transfer can be obtained by using DRV_PMP_TransferStatus. Note: Not all modes are available on all devices. Please refer to the specific device data sheet to determine the supported modes. 5.1.7.4.3.1 System Initialization This section describes initialization and reinitialization features. Description Initialization and Reinitialization The system performs the initialization and the reinitialization of the device driver with settings that affect only the instance of the device that is being initialized or reinitialized. During system initialization each instance of the PMP device will be initialized with the following configuration settings: Initialization member Description moduleInit System module initialization of the power state. pmpId PMP hardware module ID (peripheral library-level ID). stopInIdle Decide whether or not the module should be stopped in Idle mode. muxMode To select one of the different multiplexing modes possible for PMP module. inputBuffer Select the type of Input Buffer will be of TTL or Schmitt Trigger. polarity Select polarity of different PMP pins. ports Set the pins the user wants to use as port or PMP pins. The DRV_PMP_Initialize function returns an object handle of the type SYS_MODULE_OBJ. After this, the object handle returned by the initialize interface would be used by the other system interfaces, such as DRV_PMP_Reinitialize, DRV_PMP_Deinitialize, DRV_PMP_Status, and DRV_PMP_Tasks. Example for PMP Initialization Through the DRV_PMP_INIT Structure DRV_PMP_INIT init; SYS_MODULE_OBJ object; SYS_STATUS pmpStatus; // populate the PMP init configuration structure init.inputBuffer = PMP_INPUT_BUFFER_TTL; init.polarity.addressLatchPolarity = PMP_POLARITY_ACTIVE_HIGH; init.polarity.rwStrobePolarity = PMP_POLARITY_ACTIVE_LOW; init.polarity.writeEnableStrobePolarity = PMP_POLARITY_ACTIVE_LOW; init.polarity.chipselect1Polarity = PMP_POLARITY_ACTIVE_HIGH; init.polarity.chipselect2Polarity = PMP_POLARITY_ACTIVE_LOW; init.ports.addressPortsMask = PMP_PMA0_PORT | PMP_PMA1_PORT | PMP_PMA2_TO_PMA13_PORTS | PMP_PMA14_PORT; init.ports.readWriteStrobe = PORT_ENABLE; init.ports.writeEnableStrobe = PORT_ENABLE; 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-370 init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL; init.pmpID = PMP_ID_0; init.stopInIdle = false; init.muxMode = PMP_MUX_NONE; object = DRV_PMP_Initialize (DRV_PMP_INDEX_0, (SYS_MODULE_INIT *)&init); pmpStatus = DRV_PMP_Status(object); if ( SYS_STATUS_READY != pmpStatus) { // Handle error } Deinitialization Once the initialize operation has been called, the deinitialize operation must be called before the initialize operation can be called again. This routine may block if the driver is running in an OS environment that supports blocking operations and the driver requires system resources access. However, the function will never block for hardware PMP access. If the operation requires time to allow the hardware to complete, which will be reported by DRV_PMP_Status. Status PMP status is available to query the module state before, during and after initialization, deinitialization, and reinitialization. Tasks Routine The DRV_PMP_Tasks function will see the queue status and perform the task of transferring the data accordingly. In the Blocking mode when interrupts are disabled, it will finish one of the tasks completely (that means emptying one space in queue), and then return back. Whereas in Non-Blocking mode, it will return back just after starting one word (8-bit or 16-bit) of transfer (may not be emptying one space in the queue, as that task may not be completely finished). The DRV_PMP_Tasks function can be called in two ways: • By the system task service in a polled environment • By the interrupt service routine of the PMP in an interrupt-based system Example: Polling int main( void ) { SYS_MODULE_OBJ object; object = DRV_PMP_Initialize( DRV_PMP_INDEX_0, (SYS_MODULE_INIT *) &initConf ); if( SYS_STATUS_READY != DRV_PMP_Status( object ) ) return 0; while (1) { DRV_PMP_Tasks (object); } } Example: Interrupt int main( void ) { SYS_MODULE_OBJ object; object = DRV_PMP_Initialize( DRV_PMP_INDEX_0, (SYS_MODULE_INIT *) &initConf ); if( SYS_STATUS_READY != DRV_PMP_Status( object ) ) return 0; while (1); 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-371 } /* Sample interrupt routine not specific to any device family */ void ISR PMPInterrupt(void) { //Call the PMP Tasks routine DRV_PMP_Tasks(object); } Note: A PMP transfer in Blocking mode in an interrupt environment is not supported. 5.1.7.4.3.1.1 Transfer Operation This section describes transfer operation. Description Once the PMP Driver is open and configured for a client, it is set to start Reading/Writing through DRV_PMP_Read and DRV_PMP_Write. However, these functions will not directly start reading or writing. These will just put the relevant information in a queue in non-interrupt mode and return an ID that can be used later for checking the transfer status. In Interrupt mode, the Read/Write functions will trigger the transfer immediately after storing the transfer information in the queue. The user must use a buffer pointing to character for data values. The repeatCount parameter allows the user to repeatedly write the same nBytes of data into the slave devices. Example: unsigned char myReadBuffer[300], myWriteBuffer[100]; // has to be 'char' arrays uint32_t deviceAddress, nBytes, repeatCount, i; uint32_t writeID, readID; DRV_HANDLE handle; //initialize, open and configure the driver/client /* ... */ deviceAddress = 0x0206; nBytes = 100; repeatCount = 0x01; for (i=0; i= pmpStatus) { // Handle error } 5.1.7.7.1.4 DRV_PMP_Status Function C SYS_STATUS DRV_PMP_Status( const SYS_MODULE_OBJ pmpDriverObject ); Description This function provides the current status of the PMP driver module. Preconditions The DRV_PMP_Initialize function must have been called before calling this function. Parameters Parameters Description pmpDriverObject Driver object handle, returned from the DRV_PMP_Initialize routine Returns SYS_STATUS_READY - Indicates that the driver is busy with a previous system level operation and cannot start another Remarks Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new operations. SYS_STATUS_BUSY - Indicates that the driver is busy with a previous system level operation and cannot start another SYS_STATUS_ERROR - Indicates that the driver is in an error state 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-381 Any value less than SYS_STATUS_ERROR is also an error state. SYS_MODULE_DEINITIALIZED - Indicates that the driver has been deinitialized This value is less than SYS_STATUS_ERROR. This operation can be used to determine when any of the driver's module level operations has completed. If the status operation returns SYS_STATUS_BUSY, a previous operation has not yet completed. Once the status operation returns SYS_STATUS_READY, any previous operations have completed. The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state. This function will NEVER block waiting for hardware. If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the deinitialize operation will need to be called, followed by the initialize operation to return to normal operations. Example SYS_MODULE_OBJ pmpDriverObject; // Returned from DRV_PMP_Initialize SYS_STATUS status; status = DRV_PMP_Status(pmpDriverObject); else if (SYS_STATUS_ERROR >= status) { // Handle error } 5.1.7.7.1.5 DRV_PMP_Tasks Function C void DRV_PMP_Tasks( SYS_MODULE_OBJ pmpDriverObject ); Description This function is used to maintain the queue and execute the tasks stored in the queue. It resides in the ISR of the PMP for interrupt-driven implementations. Preconditions The DRV_PMP_Initialize function must have been called for the specified PMP driver instance. Parameters Parameters Description pmpDriverObject Object handle for the specified driver instance (returned from DRV_PMP_Initialize) Returns None. Remarks This function is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the appropriate raw ISR. This function may excute in an ISR context and will never block or access any resources that may cause it to block. Example SYS_MODULE_OBJ pmpDriverObject; // Returned from DRV_PMP_Initialize while (true) { 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-382 DRV_PMP_Tasks (pmpDriverObject); // Do other tasks } 5.1.7.7.2 Client Interaction Functions 5.1.7.7.2.1 DRV_PMP_ClientStatus Function C DRV_PMP_CLIENT_STATUS DRV_PMP_ClientStatus( DRV_HANDLE hClient ); Description This function gets the client-specfic status of the PMP driver associated with the specified handle. Preconditions The DRV_PMP_Initialize routine must have been called. DRV_PMP_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description hClient A valid open-instance handle, returned from the driver's open routine Returns A DRV_PMP_CLIENT_STATUS value describing the current status of the driver. Remarks This function will not block for hardware access and will immediately return the current status. Example DRV_HANDLE hClient; // Returned from DRV_PMP_Open DRV_PMP_CLIENT_STATUS pmpClientStatus; pmpClientStatus = DRV_PMP_ClientStatus(hClient); if(DRV_PMP_CLIENT_STATUS_ERROR >= pmpClientStatus) { // Handle the error } 5.1.7.7.2.2 DRV_PMP_Close Function C void DRV_PMP_Close( const DRV_HANDLE hClient ); Description This function closes an opened instance of the PMP driver, invalidating the handle. Preconditions The DRV_PMP_Initialize routine must have been called for the specified PMP driver instance. DRV_PMP_Open must have been called to obtain a valid opened device handle. 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-383 Parameters Parameters Description hClient A valid open instance handle, returned from the driver's open routine Returns None Remarks After calling this function, the handle passed in "handle" must not be used with any of the remaining driver routines. A new handle must be obtained by calling DRV_PMP_Open before the caller may use the driver again. If DRV_IO_INTENT_BLOCKING was requested and the driver was built appropriately to support blocking behavior call may block until the operation is complete. If DRV_IO_INTENT_NON_BLOCKING request the driver client can call the DRV_PMP_Status operation to find out when the module is in the ready state (the handle is no longer valid). Usually there is no need for the driver client to verify that the Close operation has completed. Example DRV_HANDLE hClient; // Returned from DRV_PMP_Open DRV_PMP_Close(hClient); 5.1.7.7.2.3 DRV_PMP_ModeConfig Function C void DRV_PMP_ModeConfig( DRV_HANDLE hClient, DRV_PMP_MODE_CONFIG config ); Description This function configures the modes for client in which it wants to operate. Different master-slave modes, 8/16 data bits selection, address increment/decrement, interrupt mode, wait states, etc., can be configured through this function. Preconditions Function DRV_PMP_Initialize must have been called. DRV_PMP_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description hClient Client handle obtained from DRV_PMP_Open API config Structure which will have all the required PMP modes configuration Returns None. Remarks This function will NEVER block waiting for hardware. If this API is called more than once for a particular client handle, previous config setting of that client will be overwritten. Example DRV_HANDLE hClient; DRV_PMP_MODE_CONFIG config; 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-384 config.chipSelect = PMCS1_AND_PMCS2_AS_CHIP_SELECT; config.endianMode = LITTLE_ENDIAN; config.incrementMode = PMP_ADDRESS_AUTO_INCREMENT; config.intMode = PMP_INTERRUPT_NONE; config.pmpMode = PMP_MASTER_READ_WRITE_STROBES_INDEPENDENT; config.portSize = PMP_DATA_SIZE_8_BITS; config.waitStates.dataHoldWait = PMP_DATA_HOLD_2; config.waitStates.dataWait = PMP_DATA_WAIT_THREE; config.waitStates.strobeWait = PMP_STROBE_WAIT_5; DRV_PMP_ModeConfig ( hClient, config ); 5.1.7.7.2.4 DRV_PMP_Open Function C DRV_HANDLE DRV_PMP_Open( const SYS_MODULE_INDEX index, const DRV_IO_INTENT intent ); Description This function opens the specified PMP driver instance and provides a handle that must be provided to all other client-level operations to identify the caller and the instance of the driver. Preconditions The DRV_PMP_Initialize function must have been called before calling this function. Parameters Parameters Description drvIndex Identifier for the object instance to be opened intent Zero or more of the values from the enumeration DRV_IO_INTENT ORed together to indicate the intended use of the driver Returns If successful, the function returns a valid open-instance handle (a number identifying both the caller and the module instance). If an error occurs, the return value is DRV_HANDLE_INVALID. Remarks The handle returned is valid until the DRV_PMP_Close routine is called. This function will NEVER block waiting for hardware. If the DRV_IO_INTENT_BLOCKING is requested and the driver was built appropriately to support blocking behavior, other client-level operations may block waiting on hardware until they are complete. If DRV_IO_INTENT_NON_BLOCKING is requested the driver client can call the DRV_PMP_ClientStatus operation to find out when the module is in the ready state. If the requested intent flags are not supported, the routine will return DRV_HANDLE_INVALID. Example DRV_HANDLE hClient; hClient = DRV_PMP_Open(DRV_PMP_INDEX_0, DRV_IO_INTENT_EXCLUSIVE); if (DRV_HANDLE_INVALID == hClient) { // Unable to open the driver } 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-385 5.1.7.7.2.5 DRV_PMP_Read Function C QUEUE_ELEMENT_OBJECT* DRV_PMP_Read( DRV_HANDLE hClient, uint32_t address, uint16_t* buffer, uint32_t nBytes ); Description This function reads the given number of data bytes from the given address of the external device to the MCU buffer through the selected PMP instance. This function should be used for all the master and slave modes. Proper configuration should be done using DRV_PMP_ModeConfig before calling this function. Preconditions The DRV_PMP_Initialize routine must have been called. DRV_PMP_Open must have been called to obtain a valid opened device handle. DRV_PMP_ModeConfig must have been called to configure the desired mode Parameters Parameters Description hClient A valid open-instance handle, returned from the driver's open routine address Starting address of the slave device from where data has to be read. It does not have any significance for legacy slave mode and buffer mode. In PMP enhanced slave mode i.e. addressable buffer slave mode, this parameter should be the buffer number to be used. buffer Pointer to the buffer into which the data read through the PMP instance will be placed. Even if only one word has to be tranferred, pointer should be used. nBytes Number of bytes that need to be read through the PMP instance Returns Returns the position number of the queue, where the data element was stored. Returns '0' when there is no place in the queue to store the data. Example DRV_HANDLE hClient; // Returned from DRV_PMP_Open uint32_t deviceAddress; uint32_t nBytes; unsigned char myBuffer[nBytes]; uint32_t transferID; transferID = DRV_PMP_Read ( hClient, deviceAddress, &myBuffer, nBytes); 5.1.7.7.2.6 DRV_PMP_Write Function C QUEUE_ELEMENT_OBJECT* DRV_PMP_Write( DRV_HANDLE* hClient, bool address, uint32_t * buffer, uint32_t nBytes, uint32_t repeatCount ); Description This function transfer the given number of data bytes from the MCU buffer location to the defined address of the external device 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-386 through the selected PMP instance. It repeats the operation n (=repeatCount) number of times as well. This function should be used for all the master and slave modes. Proper configuration should be done using DRV_PMP_ModeConfig before calling this function. Preconditions The DRV_PMP_Initialize routine must have been called. DRV_PMP_Open must have been called to obtain a valid opened device handle. DRV_PMP_ModeConfig must have been called to configure the desired mode. Parameters Parameters Description hClient A valid open-instance handle, returned from the driver's open routine address Starting address of the slave device where data has to be written. It does not have any significance for legacy slave mode and buffer mode. In PMP enhanced slave mode (i.e., addressable buffer slave mode), this parameter should be the buffer number to be used. buffer Pointer to MCU Buffer from which the data will be written through the PMP instance. even if only one word has to be tranferred, pointer should be used. nBytes Total number of bytes that need to be written through the PMP instance repeatCount Number of times the data set (nBytes of data) to be repetedly written. This value should be 0 if user does not want any repetation. If repeatCount is greater than 0, then after writing every nBytes of data, the buffer starts pointing to its first element. Ideally, PMP Address should be in auto increment/decrement mode for repeatCount greater than 0. Returns Returns a 32-bit ID with which status of the transfer can be checked later. Returns '0' when there is no place in the queue to store the data. Example DRV_HANDLE hClient; // Returned from DRV_PMP_Open uint32_t deviceAddress; uint32_t nBytes; unsigned char myBuffer[nBytes]; uint32_t repeatCount; uint32_t transferID; transferID = DRV_PMP_MasterWrite ( hClient, deviceAddress, &myBuffer, nBytes, repeatCount); 5.1.7.7.3 Client Transfer Functions 5.1.7.7.3.1 DRV_PMP_TransferStatus Function C DRV_PMP_TRANSFER_STATUS DRV_PMP_TransferStatus( QUEUE_ELEMENT_OBJECT* queueObject ); Description This function returns the status of a particular transfer whose ID has been specified as input. Parameters Parameters Description drvIndex Identifier for the object instance to be opened seqID A valid ID returned from read/write transfer functions 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-387 Returns A DRV_PMP_TRANSFER_STATUS value describing the current status of the transfer. Example uint32_8 seqID; DRV_PMP_TRANSFER_STATUS transferStatus; transferStatus = DRV_PMP_TransferStatus( DRV_PMP_INDEX_0, seqID); 5.1.7.7.4 Data Types and Constants 5.1.7.7.4.1 DRV_PMP_INDEX_COUNT Macro C #define DRV_PMP_INDEX_COUNT _PMP_EXISTS Description PMP Driver Module Index Count This constant identifies the number of valid PMP driver indices. Remarks The value of "_PMP_EXISTS" is derived from device-specific header files defined as part of the peripheral libraries. 5.1.7.7.4.2 DRV_PMP_CHIPX_STROBE_MODE Enumeration C typedef enum { PMP_RW_STROBE_WITH_ENABLE_STROBE, PMP_READ_AND_WRITE_STROBES } DRV_PMP_CHIPX_STROBE_MODE; Description PMP writeEnable/ReadWrite strobes This enumeration provides ReadWrite/WriteEnable Strobe definitions. Members Members Description PMP_RW_STROBE_WITH_ENABLE_STROBE One strobe for read/write and another for enable PMP_READ_AND_WRITE_STROBES Separate strobes for read and write operations 5.1.7.7.4.3 DRV_PMP_CLIENT_STATUS Enumeration C typedef enum { DRV_PMP_CLIENT_STATUS_INVALID, PMP_CLIENT_STATUS_CLOSED, DRV_PMP_CLIENT_STATUS_OPEN } DRV_PMP_CLIENT_STATUS; Description PMP Client Status This enumeration provides various client status possibilities. 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-388 5.1.7.7.4.4 DRV_PMP_ENDIAN_MODE Enumeration C typedef enum { LITTLE, BIG } DRV_PMP_ENDIAN_MODE; Description PMP Endian modes This enumeration holds the endian configuration options. Members Members Description LITTLE Little Endian BIG Big Endian 5.1.7.7.4.5 DRV_PMP_INDEX Enumeration C typedef enum { DRV_PMP_INDEX_0, DRV_PMP_INDEX_1 } DRV_PMP_INDEX; Description PMP Driver Module Index Numbers These constants provide PMP driver index definitions. Members Members Description DRV_PMP_INDEX_0 First PMP instance DRV_PMP_INDEX_1 Second PMP instance (not avaialble for now) Remarks These values should be passed into the DRV_PMP_Initialize and DRV_PMP_Open functions to identify the driver instance in use. 5.1.7.7.4.6 DRV_PMP_INIT Structure C typedef struct { SYS_MODULE_INIT moduleInit; PMP_MODULE_ID pmpID; bool stopInIdle; PMP_MUX_MODE muxMode; PMP_INPUT_BUFFER_TYPE inputBuffer; DRV_PMP_POLARITY_OBJECT polarity; DRV_PMP_PORTS ports; } DRV_PMP_INIT; Description PMP Driver Initialize Data 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-389 This data type defines data required to initialize or reinitialize the PMP driver. Members Members Description SYS_MODULE_INIT moduleInit; module power state info PMP_MODULE_ID pmpID; module PLIB ID bool stopInIdle; Stop in Idle enable PMP_MUX_MODE muxMode; MUX mode PMP_INPUT_BUFFER_TYPE inputBuffer; Input buffer type to be used DRV_PMP_POLARITY_OBJECT polarity; Polarity settings DRV_PMP_PORTS ports; PMP port settings Remarks Not all the initialization features are available for all devices. 5.1.7.7.4.7 DRV_PMP_MODE_CONFIG Structure C typedef struct { PMP_OPERATION_MODE pmpMode; PMP_INTERRUPT_MODE intMode; PMP_INCREMENT_MODE incrementMode; DRV_PMP_ENDIAN_MODE endianMode; PMP_DATA_SIZE portSize; DRV_PMP_WAIT_STATES waitStates; PMP_CHIPSELECT_FUNCTION chipSelect; } DRV_PMP_MODE_CONFIG; Description PMP modes configuration This data type controls the configuration of PMP modes. Members Members Description PMP_OPERATION_MODE pmpMode; PMP Usage Mode Type PMP_INTERRUPT_MODE intMode; Interrupt mode PMP_INCREMENT_MODE incrementMode; should be appropriately selected based on read/write requirements and operation mode setting */ address/buffer increment mode DRV_PMP_ENDIAN_MODE endianMode; it does not have any significance in PMP slave mode or 8bit data mode */ Endian modes PMP_DATA_SIZE portSize; Data Port Size DRV_PMP_WAIT_STATES waitStates; Wait states PMP_CHIPSELECT_FUNCTION chipSelect; use this when plib is fixed 5.1.7.7.4.8 DRV_PMP_POLARITY_OBJECT Structure C typedef struct { PMP_POLARITY_LEVEL addressLatchPolarity; PMP_POLARITY_LEVEL byteEnablePolarity; PMP_POLARITY_LEVEL rwStrobePolarity; PMP_POLARITY_LEVEL writeEnableStrobePolarity; 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-390 PMP_POLARITY_LEVEL chipselect1Polarity; PMP_POLARITY_LEVEL chipselect2Polarity; } DRV_PMP_POLARITY_OBJECT; Description PMP polarity object This structure holds the polarities of different entities to be configured. Members Members Description PMP_POLARITY_LEVEL addressLatchPolarity; Address latch polarity PMP_POLARITY_LEVEL byteEnablePolarity; ByteEnable port polarity PMP_POLARITY_LEVEL rwStrobePolarity; Read/Write strobe polarity PMP_POLARITY_LEVEL writeEnableStrobePolarity; Write/Enable strobe polarity PMP_POLARITY_LEVEL chipselect1Polarity; ChipSelect-1 Polarity PMP_POLARITY_LEVEL chipselect2Polarity; chipSelect-2 Polarity 5.1.7.7.4.9 DRV_PMP_PORT_CONTROL Enumeration C typedef enum { PORT_ENABLE, PORT_DISABLE } DRV_PMP_PORT_CONTROL; Description PMP port enable/disable. This enumeration provides port enable/disable values. Members Members Description PORT_ENABLE Enable the given port PORT_DISABLE Disable the given port 5.1.7.7.4.10 DRV_PMP_PORTS Structure C typedef struct { PMP_ADDRESS_PORT addressPortsMask; PMP_PMBE_PORT byteEnablePort; DRV_PMP_PORT_CONTROL readWriteStrobe; DRV_PMP_PORT_CONTROL writeEnableStrobe; } DRV_PMP_PORTS; Description PMP Ports This structure holds the ports (including the address ports) to be configured by the application to function as general purpose I/O (GPIO) or part of the PMP. 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-391 Members Members Description PMP_ADDRESS_PORT addressPortsMask; User needs to put the address lines which he wants to use in OR'd fashion */ Address ports PMP_PMBE_PORT byteEnablePort; Byte enable ports DRV_PMP_PORT_CONTROL readWriteStrobe; READ/WRITE Strobe PORT DRV_PMP_PORT_CONTROL writeEnableStrobe; WRITE/ENABLE strobe port 5.1.7.7.4.11 DRV_PMP_QUEUE_ELEMENT_OBJ Type C typedef struct _DRV_PMP_QUEUE_ELEMENT_OBJ DRV_PMP_QUEUE_ELEMENT_OBJ; Description PMP Driver Queue Element Object This defines the object structure for each queue element of PMP. This object gets created for every Read/Write operations APIs. Remarks None 5.1.7.7.4.12 DRV_PMP_TRANSFER_STATUS Enumeration C typedef enum { MASTER_8BIT_TRANSFER_IN_PROGRESS = PMP_DATA_SIZE_8_BITS, MASTER_16BIT_TRANSFER_IN_PROGRESS = PMP_DATA_SIZE_16_BITS, MASTER_8BIT_BUFFER_IN_PROGRESS, MASTER_16BIT_BUFFER_IN_PROGRESS, MASTER_8BIT_BUFFER_CONTINUE, QUEUED_BUT_PMP_TRANSFER_NOT_STARTED, PMP_TRANSFER_FINISHED } DRV_PMP_TRANSFER_STATUS; Description Queue Element Transfer Status This enumeration defines the PMP transfer status. 5.1.7.7.4.13 DRV_PMP_WAIT_STATES Structure C typedef struct { PMP_DATA_HOLD_STATES dataHoldWait; PMP_STROBE_WAIT_STATES strobeWait; PMP_DATA_WAIT_STATES dataWait; } DRV_PMP_WAIT_STATES; Description PMP wait states object This structure holds the different wait states to be configured. Refer to the PMP PLIB help document for the possible values and meaning of the different wait states. 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-392 Members Members Description PMP_DATA_HOLD_STATES dataHoldWait; data hold wait states PMP_STROBE_WAIT_STATES strobeWait; read/write strobe wait states PMP_DATA_WAIT_STATES dataWait; data wait strobe wait sates 5.1.7.7.4.14 QUEUE_ELEMENT_OBJECT Type C typedef struct _QUEUE_ELEMENT_OBJECT QUEUE_ELEMENT_OBJECT; Description Queue Element Object This defines the structure required for maintaining the queue element. Remarks None 5.1.7.7.4.15 MAX_NONBUFFERED_BYTE_COUNT Macro C #define MAX_NONBUFFERED_BYTE_COUNT 4 //After this number the PMP transfer should be polled to gurantee data trasnfer Description After this number the PMP transfer should be polled to gurantee data trasnfer 5.1.7.7.4.16 DRV_PMP_TRANSFER_TYPE Enumeration C typedef enum { ADDRESS, READ, WRITE, BUFFERED_WRITE } DRV_PMP_TRANSFER_TYPE; Description This is type DRV_PMP_TRANSFER_TYPE. Members Members Description ADDRESS PMP Address needs to be updated READ PMP Read Transfer WRITE PMP Write Transfer BUFFERED_WRITE PMP Array Write Transfer 5.1.7.7.5 Miscellaneous Functions 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-393 5.1.7.7.5.1 DRV_PMP_VersionGet Function C unsigned int DRV_PMP_VersionGet( const SYS_MODULE_INDEX drvIndex ); Description This function gets the PMP driver version. The version is encoded as major * 10000 + minor * 100 + patch. The stringed version can be obtained using DRV_PMP_VersionStrGet(). Preconditions None. Parameters Parameters Description drvIndex Identifier for the driver instance to get the version for Returns Current driver version in numerical format. Remarks None. Example unsigned int version; version = DRV_PMP_VersionGet( DRV_PMP_INDEX_0 ); if(version < 110200) { // Do Something } 5.1.7.7.5.2 DRV_PMP_VersionStrGet Function C char * DRV_PMP_VersionStrGet( const SYS_MODULE_INDEX drvIndex ); Description This function gets the PMP driver version. The version is returned as major.minor.path[type], where type is optional. The numerical version can be obtained using DRV_PMP_VersionGet(). Preconditions None. Parameters Parameters Description drvIndex Identifier for the driver instance to get the version for Returns Current PMP driver version in the string format. 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-394 Remarks None. Example char *version; version = DRV_PMP_VersionStrGet( DRV_PMP_INDEX_0 ); printf("%s", version); 5.1.7.8 Files Files Name Description drv_pmp.h Parallel Master Port (PMP) device driver interface file. drv_pmp_config.h PMP driver configuration definitions template Description 5.1.7.8.1 drv_pmp.h PMP Device Driver Interface The PMP device driver provides a simple interface to manage the Parallel Master and Slave ports. This file defines the interface definitions and prototypes for the PMP driver. Enumerations Name Description DRV_PMP_CHIPX_STROBE_MODE PMP writeEnable/ReadWrite strobes. DRV_PMP_CLIENT_STATUS PMP client status definitions. DRV_PMP_ENDIAN_MODE PMP endian modes. DRV_PMP_INDEX PMP driver index definitions. DRV_PMP_PORT_CONTROL PMP port enable/disable definitions. DRV_PMP_TRANSFER_STATUS Defines the PMP transfer status. DRV_PMP_TRANSFER_TYPE This is type DRV_PMP_TRANSFER_TYPE. Functions Name Description DRV_PMP_ClientStatus Gets the current client-specific status of the PMP driver. DRV_PMP_Close Closes an opened instance of the PMP driver. DRV_PMP_Deinitialize Deinitializes the specified instance of the PMP driver module DRV_PMP_Initialize Initializes the PMP driver. DRV_PMP_ModeConfig Configure the PMP modes. DRV_PMP_Open Opens the specified PMP driver instance and returns a handle to it. DRV_PMP_Read Read the data from external device. DRV_PMP_Reinitialize Reinitializes the driver and refreshes any associated hardware settings. DRV_PMP_Status Provides the current status of the PMP driver module. DRV_PMP_Tasks Maintains the driver's state machine and implements its ISR. 5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library 5-395 DRV_PMP_TransferStatus Returns the transfer status. DRV_PMP_VersionGet Gets the PMP driver version in numerical format. DRV_PMP_VersionStrGet Gets the PMP driver version in string format. DRV_PMP_Write Transfers the data from the MCU to the external device. Macros Name Description DRV_PMP_INDEX_COUNT Number of valid PMP driver indices. MAX_NONBUFFERED_BYTE_COUNT After this number the PMP transfer should be polled to gurantee data trasnfer Structures Name Description DRV_PMP_INIT Defines the PMP driver initialization data. DRV_PMP_MODE_CONFIG PMP modes configuration. DRV_PMP_POLARITY_OBJECT PMP polarity object. DRV_PMP_PORTS PMP port configuration. DRV_PMP_WAIT_STATES PMP wait states object. Types Name Description DRV_PMP_QUEUE_ELEMENT_OBJ Defines the object for PMP queue element. QUEUE_ELEMENT_OBJECT Defines the structure required for maintaining the queue element. Company Microchip Technology Inc. FileName: drv_pmp.h 5.1.7.8.2 drv_pmp_config.h PMP Driver Configuration Definitions for the Template Version These definitions statically define the driver's mode of operation. Macros Name Description DRV_PMP_CLIENTS_NUMBER Selects the maximum number of clients. DRV_PMP_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be supported by the dynamic driver. DRV_PMP_QUEUE_SIZE PMP queue size for different instances. File Name drv_pmp_config_template.h Company Microchip Technology Inc. 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-396 5.1.8 Secure Digital (SD) Card Driver Library 5.1.8.1 Introduction Secure Digital (SD) Card Driver Library for Microchip Microcontrollers The SD Card driver provides the necessary interfaces to interact with an SD card. It provides the necessary abstraction for the higher layer. Description A SD Card is a non-volatile memory (Flash memory) card designed to provide high-capacity memory in a small size. Its applications are like digital video camcorders, digital cameras, handheld computers, audio players and mobile phones. 5.1.8.2 Release Notes MPLAB Harmony Version: v0.70b SD Card Library Version : Release Date: 18Nov2013 New This Release: 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-397 • Non-blocking operation • Layered architecture • Interoperability Known Issues: • Tested only with SDHC cards (Card memory more than 2 GB) • CARD detection mechanism is not so fine-tuned • Card maximum Frequency detection is not automatic. Different cards will have specific specific frequency of operation and that needs to be set in system_config.h • Not tested the drivers operation with multiple SD cards • Timeout and driver reset on failure case is not implemented 5.1.8.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 5.1.8.4 Using the Library This topic describes the basic architecture of the SD Card Driver Library and provides information and examples on how to use it. Interface Header File: drv_sdcard.h The interface to the SD Card Driver library is defined in the "drv _sdcard.h" header file. This file is included by the "drv.h" file. Any C language source (.c) file that uses the SD Card Driver library should include "drv.h". Library File: The SD Card Driver library archive (.a) file installed with MPLAB Harmony. Please refer to the MPLAB Harmony Overview for how the Driver interacts with the framework. 5.1.8.4.1 Abstraction Model SD Card Driver Software Abstraction Block Diagram 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-398 • SD Card driver comes in the layer below the Partition Manager in MPLAB Harmony file system architecture. • It uses the SPI driver to interact with SD card. 5.1.8.4.2 Library Overview Refer to the section Driver Overview for how the driver operates in a system. The library interface routines are divided into various sub-sections, each of sub-section addresses one of the blocks or the overall operation of the SD Card module. Library Interface Section Description System Level Functions Includes functions for initialize the module. Client Level Functions Functions to open and close a client. Operation Functions Functions for read and write operations Module Information Functions Functions for information about the module. Version Information Functions Functions to get the software version. 5.1.8.4.3 How the Library Works Note: Not all modes are available on all devices. Please refer to the specific device data sheet to determine the supported modes. 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-399 5.1.8.5 Configuring the Library The configuration of the SD Card driver is based on the file sys_config.h This header file contains the configuration selection for the SD Card driver. Based on the selections made, the SD Card driver will support or not support selected features. These configuration settings will apply to all instances of the SD Card. This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a successful build. Refer to the Applications Overview section for more details. 5.1.8.6 Building the Library This section list the files that are available in the \src of the SD Card driver. It lists which files need to be included in the build based on either a hardware feature present on the board or configuration option selected by the system. 5.1.8.7 Library Interface Data Types and Constants Name Description DRV_SDCARD_INDEX_0 SD Card driver index definitions DRV_SDCARD_INDEX_COUNT Number of valid SD Card driver indices DRV_SDCARD_BUFFER_HANDLE Handle to a buffer added to the process queue. DRV_SDCARD_CLIENT_STATUS Identifies the client-specific status of the SD card driver DRV_SDCARD_INIT Contains all the data necessary to initialize the SD Card device SYS_MEDIA_EVENT Defines the buffer status SDCARD_MAX_LIMIT Maximum allowed SD card instances DRV_SDCARD_INDEX_1 This is macro DRV_SDCARD_INDEX_1. DRV_SDCARD_INDEX_2 This is macro DRV_SDCARD_INDEX_2. DRV_SDCARD_INDEX_3 This is macro DRV_SDCARD_INDEX_3. Client Level Functions Name Description DRV_SDCARD_ClientStatus Gets current client-specific status the SD Card driver DRV_SDCARD_Close Closes an opened-instance of the SD Card driver DRV_SDCARD_Open Opens the specified SD Card driver instance and returns a handle to it Module Information Functions Name Description DRV_SDCARD_SectorsCountGet Gets the number of sectors present in the selected SD card device. DRV_SDCARD_SectorSizeGet Gets the sector size of the selected SD card device. DRV_SDCARD_WriteProtectionIsEnabled Gets the status of write protection. Operation Functions Name Description DRV_SDCARD_SectorRead Reads data from the sectors of the SD card. DRV_SDCARD_SectorWrite Writes sector(s) of data to an SD card. 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-400 DRV_SDCARD_BufferStatusGet Gets the status of an an SD card operation (read/write) DRV_SDCARD_MediaStatusGet Gets the status of the device. System Level Functions Name Description DRV_SDCARD_Deinitialize Deinitializes the specified instance of the SD Card driver module DRV_SDCARD_Initialize Initializes the SD Card driver DRV_SDCARD_Reinitialize Reinitializes the driver and refreshes any associated hardware settings DRV_SDCARD_Status Provides the current status of the SD Card driver module DRV_SDCARD_Tasks Maintains the driver's state machine Version Information Functions Name Description DRV_SDCARD_VersionGet Gets SD card driver version in numerical format. DRV_SDCARD_VersionStrGet Gets SD card driver version in string format. Description This section describes the Application Programming Interface (API) functions of the SD Card Driver. Refer to each section for a detailed description. 5.1.8.7.1 System Level Functions 5.1.8.7.1.1 DRV_SDCARD_Deinitialize Function C void DRV_SDCARD_Deinitialize( SYS_MODULE_OBJ object ); Description Deinitializes the specified instance of the SD Card driver module, disabling its operation (and any hardware). Invalidates all the internal data. Preconditions Function DRV_SDCARD_Initialize must have been called before calling this routine and a valid SYS_MODULE_OBJ must have been returned. Parameters Parameters Description object Driver object handle, returned from the DRV_SDCARD_Initialize routine. Returns None. Remarks Once the Initialize operation has been called, the Deinitialize operation must be called before the Initialize operation can be called again. This routine will NEVER block waiting for hardware. If the operation requires time to allow the hardware to complete, this will be reported by the DRV_SDCARD_Status operation. The system has to use DRV_SDCARD_Status to find out when the module is 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-401 in the ready state. Example SYS_MODULE_OBJ object; // Returned from DRV_SDCARD_Initialize SYS_STATUS status; DRV_SDCARD_Deinitialize(object); status = DRV_SDCARD_Status(object); if (SYS_MODULE_UNINITIALIZED == status) { // Check again later if you need to know // when the driver is deinitialized. } 5.1.8.7.1.2 DRV_SDCARD_Initialize Function C SYS_MODULE_OBJ DRV_SDCARD_Initialize( const SYS_MODULE_INDEX index, const SYS_MODULE_INIT * const init ); Description This routine initializes the SD Card driver, making it ready for clients to open and use it. Preconditions None. Parameters Parameters Description drvIndex Index for the driver instance to be initialized init Pointer to a data structure containing any data necessary to initialize the driver. This pointer may be null if no data is required because static overrides have been provided. Returns If successful, returns a valid handle to a driver object. Otherwise, it returns SYS_MODULE_OBJ_INVALID. The returned object must be passed as argument to DRV_SDCARD_Reinitialize, DRV_SDCARD_Deinitialize, DRV_SDCARD_TaskRead, DRV_SDCARD_TaskWrite and DRV_SDCARD_Status routines. Remarks This routine must be called before any other SD Card routine is called. This routine should only be called once during system initialization unless DRV_SDCARD_Deinitialize is called to de-initialize the driver instance. This routine will NEVER block for hardware access. If the operation requires time to allow the hardware to re-initialize, it will be reported by the DRV_SDCARD_Status operation. The system must use DRV_SDCARD_Status to find out when the driver is in the ready state. Build configuration options may be used to statically override options in the "init" structure and will take precedence over initialization data passed using this routine. Example DRV_SDCARD_INIT init; SYS_MODULE_OBJ objectHandle; 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-402 // Populate the SD Card initialization structure init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL; init.baudRate = 100000; init.spiId = SPI_ID_1; // Do something objectHandle = DRV_SDCARD_Initialize(DRV_SDCARD_INDEX_0, (SYS_MODULE_INIT*)&init); if (SYS_MODULE_OBJ_INVALID == objectHandle) { // Handle error } 5.1.8.7.1.3 DRV_SDCARD_Reinitialize Function C void DRV_SDCARD_Reinitialize( SYS_MODULE_OBJ object, const SYS_MODULE_INIT * const init ); Description This routine reinitializes the driver and refreshes any associated hardware settings using the initialization data given, but it will not interrupt any ongoing operations. Preconditions Function DRV_SDCARD_Initialize must have been called before calling this routine and a valid SYS_MODULE_OBJ must have been returned. Parameters Parameters Description object Driver object handle, returned from the DRV_SDCARD_Initialize routine init Pointer to the initialization data structure Returns None Remarks This function can be called multiple times to reinitialize the module. This operation can be used to refresh any supported hardware registers as specified by the initialization data or to change the power state of the module. This routine will NEVER block for hardware access. If the operation requires time to allow the hardware to re-initialize, it will be reported by the DRV_SDCARD_Status operation. The system must use DRV_SDCARD_Status to find out when the driver is in the ready state. Build configuration options may be used to statically override options in the "init" structure and will take precedence over initialization data passed using this routine. Example DRV_SDCARD_INIT init; SYS_MODULE_OBJ objectHandle; // Populate the SD Card initialization structure init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL; init.baudRate = 100000; init.spiId = SPI_ID_1; 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-403 // Do something 5.1.8.7.1.4 DRV_SDCARD_Status Function C SYS_STATUS DRV_SDCARD_Status( SYS_MODULE_OBJ object ); Description This routine provides the current status of the SD Card driver module. Preconditions Function DRV_SDCARD_Initialize must have been called before calling this Parameters Parameters Description object Driver object handle, returned from the DRV_SDCARD_Initialize routine Returns SYS_STATUS_READY - Indicates that the driver is busy with a previous system level operation and cannot start another Note Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new operations. SYS_STATUS_BUSY - Indicates that the driver is busy with a previous system level operation and cannot start another SYS_STATUS_ERROR - Indicates that the driver is in an error state Remarks Any value less than SYS_STATUS_ERROR is also an error state. SYS_MODULE_DEINITIALIZED - Indicates that the driver has been de-initialized This value is less than SYS_STATUS_ERROR The this operation can be used to determine when any of the driver's module level operations has completed. If the status operation returns SYS_STATUS_BUSY, the a previous operation has not yet completed. Once the status operation returns SYS_STATUS_READY, any previous operations have completed. The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state. This routine will NEVER block waiting for hardware. If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the deinitialize operation will need to be called, followed by the initialize operation to return to normal operations. Example SYS_MODULE_OBJ object; // Returned from DRV_SDCARD_Initialize SYS_STATUS status; status = DRV_SDCARD_Status(object); else if (SYS_STATUS_ERROR >= status) { // Handle error } 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-404 5.1.8.7.1.5 DRV_SDCARD_Tasks Function C void DRV_SDCARD_Tasks( SYS_MODULE_OBJ object ); Description This routine is used to maintain the driver's internal state machine. Preconditions The DRV_SDCARD_Initialize routine must have been called for the specified SDCARD driver instance. Parameters Parameters Description object Object handle for the specified driver instance (returned from DRV_SDCARD_Initialize) Returns None Remarks This routine is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the appropriate raw ISR. This routine may execute in an ISR context and will never block or access any resources that may cause it to block. Example SYS_MODULE_OBJ object; // Returned from DRV_SDCARD_Initialize while (true) { DRV_SDCARD_Tasks (object); // Do other tasks } 5.1.8.7.2 Client Level Functions 5.1.8.7.2.1 DRV_SDCARD_ClientStatus Function C DRV_SDCARD_CLIENT_STATUS DRV_SDCARD_ClientStatus( DRV_HANDLE handle ); Description This routine gets the client-specific status of the SD Card driver associated with the given handle. Preconditions The DRV_SDCARD_Initialize routine must have been called. DRV_SDCARD_Open must have been called to obtain a valid opened device handle. 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-405 Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine Returns A DRV_SDCARD_CLIENT_STATUS value describing the current status of the driver Remarks This routine will not block for hardware access and will immediately return the current status. Example DRV_HANDLE sdcardHandle; // Returned from DRV_SDCARD_Open DRV_SDCARD_CLIENT_STATUS sdcardClientStatus; sdcardClientStatus = DRV_SDCARD_ClientStatus ( sdcardHandle ); if ( DRV_SDCARD_CLIENT_STATUS_ERROR >= sdcardClientStatus ) { // Handle the error } 5.1.8.7.2.2 DRV_SDCARD_Close Function C void DRV_SDCARD_Close( DRV_HANDLE handle ); Description This routine closes an opened-instance of the SD Card driver, invalidating the handle. Preconditions The DRV_SDCARD_Initialize routine must have been called for the specified SD Card driver instance. DRV_SDCARD_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine Returns None Remarks After calling this routine, the handle passed in "handle" must not be used with any of the remaining driver routines. A new handle must be obtained by calling DRV_SDCARD_Open before the caller may use the driver again. If DRV_IO_INTENT_BLOCKING was requested and the driver was built appropriately to support blocking behavior call may block until the operation is complete. If DRV_IO_INTENT_NON_BLOCKING request the driver client can call the DRV_SDCARD_Status operation to find out when the module is in the ready state (the handle is no longer valid). Usually there is no need for the driver client to verify that the Close operation has completed. Example DRV_HANDLE handle; // Returned from DRV_SDCARD_Open 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-406 DRV_SDCARD_Close ( handle ); 5.1.8.7.2.3 DRV_SDCARD_Open Function C DRV_HANDLE DRV_SDCARD_Open( const SYS_MODULE_INDEX drvIndex, const DRV_IO_INTENT intent ); Description This routine opens the specified SD Card driver instance and provides a handle that must be provided to all other client-level operations to identify the caller and the instance of the driver. Preconditions Function DRV_SDCARD_Initialize must have been called before calling this function. Parameters Parameters Description drvIndex Identifier for the object instance to be opened intent Zero or more of the values from the enumeration DRV_IO_INTENT "or'd" together to indicate the intended use of the driver Returns If successful, the routine returns a valid open-instance handle (a number identifying both the caller and the module instance). If an error occurs, the return value is DRV_HANDLE_INVALID. Remarks The handle returned is valid until the DRV_SDCARD_Close routine is called. This routine will NEVER block waiting for hardware. If the DRV_IO_INTENT_BLOCKING is requested and the driver was built appropriately to support blocking behavior, then other client-level operations may block waiting on hardware until they are complete. If DRV_IO_INTENT_NON_BLOCKING is requested the driver client can call the DRV_SDCARD_ClientStatus operation to find out when the module is in the ready state. If the requested intent flags are not supported, the routine will return DRV_HANDLE_INVALID. Example DRV_HANDLE handle; handle = DRV_SDCARD_Open ( DRV_SDCARD_INDEX_0, DRV_IO_INTENT_EXCLUSIVE ); if ( DRV_HANDLE_INVALID == handle ) { // Unable to open the driver } 5.1.8.7.3 Operation Functions 5.1.8.7.3.1 DRV_SDCARD_SectorRead Function C SYS_FS_MEDIA_BUFFER_HANDLE DRV_SDCARD_SectorRead( 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-407 DRV_HANDLE handle, uint8_t * buffer, uint32_t sector_addr, uint32_t sectorCount ); Description This function reads data from the sectors of the SD card starting from the sector address and stores it in the location pointed by 'buffer'. Preconditions The DRV_SDCARD_Initialize routine must have been called. DRV_SDCARD_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine sector_addr The address of the sector on the card. sectorCount Number of sectors to be read. buffer The buffer where the retrieved data will be stored. If buffer is NULL, do not store the data anywhere. Returns SYS_FS_MEDIA_BUFFER_HANDLE - Buffer handle. Remarks This routine will not block for hardware access and will immediately return the current status. Example SYS_FS_MEDIA_BUFFER_HANDLE bufferHandle; bufferHandle = DRV_SDCARD_SectorRead ( handle, ,readData //buffer , 20 // Sector , 1 // Number of Sectors ); 5.1.8.7.3.2 DRV_SDCARD_SectorWrite Function C SYS_FS_MEDIA_BUFFER_HANDLE DRV_SDCARD_SectorWrite( DRV_HANDLE handle, uint32_t sector_addr, uint8_t * buffer, uint32_t sectorCount ); Description This function writes sector(s) of data (512 bytes) of data from the location pointed to by 'buffer' to the specified sector of the SD card. Preconditions The DRV_SDCARD_Initialize routine must have been called. DRV_SDCARD_Open must have been called to obtain a valid opened device handle. 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-408 Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine sector_addr The address of the sector on the card. buffer The buffer with the data to write. Returns SYS_FS_MEDIA_BUFFER_HANDLE - Buffer handle. Remarks The card expects the address field in the command packet to be a byte address. The sector_addr value is converted to a byte address by shifting it left nine times (multiplying by 512). Example SYS_FS_MEDIA_BUFFER_HANDLE bufferHandle; bufferHandle = DRV_SDCARD_SectorWrite ( handle, ,readData //buffer , 20 // Sector , 1 // Number of Sectors ); 5.1.8.7.3.3 DRV_SDCARD_BufferStatusGet Function C SYS_FS_MEDIA_BUFFER_STATUS DRV_SDCARD_BufferStatusGet( DRV_HANDLE handle, SYS_FS_MEDIA_BUFFER_HANDLE bufferHandle ); Description This function gets the status of an an SD card operation (read/write). To be called only after a read or write is scheduled. Preconditions The DRV_SDCARD_Initialize routine must have been called. DRV_SDCARD_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine bufferHandle Handle returned by a 'sector write' or a 'sector read' function. Returns SYS_FS_MEDIA_BUFFER_STATUS - Buffer status. Remarks None. Example int globalState = 0; SYS_FS_MEDIA_BUFFER_HANDLE bufferHandle; switch (globalState) { case 0: 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-409 bufferHandle = SYS_FS_MEDIA_MANAGER_SectorWrite ( handle, ,readData //buffer , 20 // Sector , 1 // Number of Sectors ); globalState++; break; case 1: if ( SYS_FS_MEDIA_MANAGER_BufferStatusGet(handle, bufferHandle) == SYS_FS_MEDIA_BUFFER_COMPLETED) { //Write complete } break; 5.1.8.7.3.4 DRV_SDCARD_MediaStatusGet Function C SYS_FS_MEDIA_STATUS DRV_SDCARD_MediaStatusGet( DRV_HANDLE handle ); Description This function gets the status of the device ( attached/detached ). Preconditions The DRV_SDCARD_Initialize routine must have been called. DRV_SDCARD_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine Returns SYS_FS_MEDIA_STATUS - Status of the device. Remarks None. Example DRV_HANDLE sdcardHandle; // Returned from DRV_SDCARD_Open if( DRV_SDCARD_MediaStatusGet ( handle ) == SYS_FS_MEDIA_ATTACHED ) { //Device is attached } 5.1.8.7.4 Module Information Functions 5.1.8.7.4.1 DRV_SDCARD_SectorsCountGet Function C uint32_t DRV_SDCARD_SectorsCountGet( DRV_HANDLE handle ); 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-410 Description This function gets the number of sectors present in the selected SD card device. Preconditions The DRV_SDCARD_Initialize routine must have been called. DRV_SDCARD_Open must have been called to obtain a valid opened device handle. SD Card must have been detected and initialized by the task routine. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine Returns The number of a sectors in the selected SD Card. Remarks This routine will not block for hardware access and will immediately return the current status. Example DRV_HANDLE sdcardHandle; // Returned from DRV_SDCARD_Open DRV_SDCARD_CLIENT_STATUS sdcardClientStatus; bool status; 5.1.8.7.4.2 DRV_SDCARD_SectorSizeGet Function C uint32_t DRV_SDCARD_SectorSizeGet( DRV_HANDLE handle ); Description This function gets the card's sector size. Preconditions The DRV_SDCARD_Initialize routine must have been called. DRV_SDCARD_Open must have been called to obtain a valid opened device handle. SD Card must have been detected and initialized by the task routine. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine Returns The size of a sector in the selected SD Card. Remarks This routine will not block for hardware access and will immediately return the current status. Example DRV_HANDLE sdcardHandle; // Returned from DRV_SDCARD_Open DRV_SDCARD_CLIENT_STATUS sdcardClientStatus; bool status; 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-411 5.1.8.7.4.3 DRV_SDCARD_WriteProtectionIsEnabled Function C bool DRV_SDCARD_WriteProtectionIsEnabled( DRV_HANDLE handle ); Description This function returns 'true' if the write protection for the card is enabled. Preconditions The DRV_SDCARD_Initialize routine must have been called. DRV_SDCARD_Open must have been called to obtain a valid opened device handle. SD Card must have been detected and initialized by the task routine. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine Returns true - Write protection is enabled. false - Write protection is disabled. Remarks This routine will not block for hardware access and will immediately return the current status. Example DRV_HANDLE sdcardHandle; // Returned from DRV_SDCARD_Open bool writeProtectStatus; //Call DRV_SDCARD_Open writeProtectStatus = DRV_SDCARD_WriteProtectionIsEnabled(sdcardHandle); 5.1.8.7.5 Version Information Functions 5.1.8.7.5.1 DRV_SDCARD_VersionGet Function C unsigned int DRV_SDCARD_VersionGet( const SYS_MODULE_INDEX drvIndex ); Description This routine gets the SD card driver version. The version is encoded as major * 10000 + minor * 100 + patch. The stringized version can be obtained using DRV_SDCARD_VersionStrGet() Preconditions None. Parameters Parameters Description drvIndex Identifier for the object instance to get the version for. 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-412 Returns Current driver version in numerical format. Remarks None. Example unsigned int version; version = DRV_SDCARD_VersionGet( DRV_SDCARD_INDEX_1 ); if(version < 110200) { // Do Something } 5.1.8.7.5.2 DRV_SDCARD_VersionStrGet Function C char* DRV_SDCARD_VersionStrGet( const SYS_MODULE_INDEX drvIndex ); Description This routine gets the SD card driver version. The version is returned as major.minor.path[type], where type is optional. The numerical version can be obtained using DRV_SDCARD_VersionGet() Preconditions None. Parameters Parameters Description drvIndex Identifier for the object instance to get the version for. Returns Current SD card driver version in the string format. Remarks None. Example char *version; version = DRV_SDCARD_VersionStrGet( DRV_SDCARD_INDEX_1 ); printf("%s", version); 5.1.8.7.6 Data Types and Constants 5.1.8.7.6.1 DRV_SDCARD_INDEX_0 Macro C #define DRV_SDCARD_INDEX_0 0 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-413 Description SD Card Driver Module Index Numbers These constants provide SD Card driver index definitions. Remarks These constants should be used in place of hard-coded numeric literals. These values should be passed into the DRV_SDCARD_Initialize and DRV_SDCARD_Open routines to identify the driver instance in use. 5.1.8.7.6.2 DRV_SDCARD_INDEX_COUNT Macro C #define DRV_SDCARD_INDEX_COUNT DRV_SDCARD_INDEX_MAX Description SD Card Driver Module Index Count This constant identifies number of valid SD Card driver indices. Remarks This constant should be used in place of hard-coded numeric literals. This value is derived from part-specific header files defined as part of the peripheral libraries. 5.1.8.7.6.3 DRV_SDCARD_BUFFER_HANDLE Type C typedef uintptr_t DRV_SDCARD_BUFFER_HANDLE; Description SD Card Buffer Handle This handle identifies the a buffer in the queue(read or write). 5.1.8.7.6.4 DRV_SDCARD_CLIENT_STATUS Enumeration C typedef enum { DRV_SDCARD_CLIENT_STATUS_INVALID, DRV_SDCARD_CLIENT_STATUS_ERROR, DRV_SDCARD_CLIENT_STATUS_CLOSED, DRV_SDCARD_CLIENT_STATUS_BUSY, DRV_SDCARD_CLIENT_STATUS_READY, DRV_SDCARD_CLIENT_STATUS_STOPPED } DRV_SDCARD_CLIENT_STATUS; Description SD Card Driver Client Status This enumeration identifies the client-specific status of the SD card driver. Members Members Description DRV_SDCARD_CLIENT_STATUS_INVALID Client in an invalid state 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-414 DRV_SDCARD_CLIENT_STATUS_ERROR Unspecified error condition DRV_SDCARD_CLIENT_STATUS_CLOSED Client is not open DRV_SDCARD_CLIENT_STATUS_BUSY An operation is currently in progress DRV_SDCARD_CLIENT_STATUS_READY Up and running, no operations running DRV_SDCARD_CLIENT_STATUS_STOPPED SD Card stopped (not running), but ready to accept commands Remarks None. 5.1.8.7.6.5 DRV_SDCARD_INIT Type C typedef struct _DRV_SDCARD_INIT DRV_SDCARD_INIT; Description SD Card Device Driver Initialization Data This structure contains all the data necessary to initialize the SD Card device. Remarks A pointer to a structure of this format containing the desired initialization data must be passed into the DRV_SDCARD_Initialize routine. 5.1.8.7.6.6 SYS_MEDIA_EVENT Enumeration C typedef enum { SYS_MEDIA_EVENT_SDCARD_ATTACHED, SYS_MEDIA_EVENT_SDCARD_DETACHED } SYS_MEDIA_EVENT; Description SD Card Buffer Status Defines the states that an SD Card buffer can be in during its lifetime Members Members Description SYS_MEDIA_EVENT_SDCARD_ATTACHED The media event is SD Card attach SYS_MEDIA_EVENT_SDCARD_DETACHED The media event is SD Card detach Remarks As buffers may have a limited life span, so too have the associated handles and status info. Once a buffer transfer is completed (and possibly notified and acknowledged) it will be discarded. The status of a discarded buffer is no longer maintained by the driver. 5.1.8.7.6.7 SDCARD_MAX_LIMIT Macro C #define SDCARD_MAX_LIMIT 2 Description SD Card Driver Maximum allowed limit 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-415 This constant identifies number of valid SD Card driver indices. Remarks This constant should be used in place of hard-coded numeric literals. This value is derived from part-specific header files defined as part of the peripheral libraries. 5.1.8.7.6.8 DRV_SDCARD_INDEX_1 Macro C #define DRV_SDCARD_INDEX_1 1 Description This is macro DRV_SDCARD_INDEX_1. 5.1.8.7.6.9 DRV_SDCARD_INDEX_2 Macro C #define DRV_SDCARD_INDEX_2 2 Description This is macro DRV_SDCARD_INDEX_2. 5.1.8.7.6.10 DRV_SDCARD_INDEX_3 Macro C #define DRV_SDCARD_INDEX_3 3 Description This is macro DRV_SDCARD_INDEX_3. 5.1.8.8 Files Files Name Description drv_sdcard.h SD Card Device Driver Interface File Description 5.1.8.8.1 drv_sdcard.h SD Card Device Driver Interface The SD Card device driver provides a simple interface to manage the "SD Card" peripheral. This file defines the interface definitions and prototypes for the SD Card driver. Enumerations Name Description DRV_SDCARD_CLIENT_STATUS Identifies the client-specific status of the SD card driver SYS_MEDIA_EVENT Defines the buffer status 5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library 5-416 Functions Name Description DRV_SDCARD_BufferStatusGet Gets the status of an an SD card operation (read/write) DRV_SDCARD_ClientStatus Gets current client-specific status the SD Card driver DRV_SDCARD_Close Closes an opened-instance of the SD Card driver DRV_SDCARD_Deinitialize Deinitializes the specified instance of the SD Card driver module DRV_SDCARD_Initialize Initializes the SD Card driver DRV_SDCARD_MediaStatusGet Gets the status of the device. DRV_SDCARD_Open Opens the specified SD Card driver instance and returns a handle to it DRV_SDCARD_Reinitialize Reinitializes the driver and refreshes any associated hardware settings DRV_SDCARD_SectorRead Reads data from the sectors of the SD card. DRV_SDCARD_SectorsCountGet Gets the number of sectors present in the selected SD card device. DRV_SDCARD_SectorSizeGet Gets the sector size of the selected SD card device. DRV_SDCARD_SectorWrite Writes sector(s) of data to an SD card. DRV_SDCARD_Status Provides the current status of the SD Card driver module DRV_SDCARD_Tasks Maintains the driver's state machine DRV_SDCARD_VersionGet Gets SD card driver version in numerical format. DRV_SDCARD_VersionStrGet Gets SD card driver version in string format. DRV_SDCARD_WriteProtectionIsEnabled Gets the status of write protection. Macros Name Description DRV_SDCARD_INDEX_0 SD Card driver index definitions DRV_SDCARD_INDEX_1 This is macro DRV_SDCARD_INDEX_1. DRV_SDCARD_INDEX_2 This is macro DRV_SDCARD_INDEX_2. DRV_SDCARD_INDEX_3 This is macro DRV_SDCARD_INDEX_3. DRV_SDCARD_INDEX_COUNT Number of valid SD Card driver indices SDCARD_MAX_LIMIT Maximum allowed SD card instances Types Name Description DRV_SDCARD_BUFFER_HANDLE Handle to a buffer added to the process queue. DRV_SDCARD_INIT Contains all the data necessary to initialize the SD Card device Company Microchip Technology Incorporated FileName: drv_sdcard.h 5.1.9 SPI Driver Library 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-417 5.1.9.1 Introduction SPI Driver Library for Microchip Microcontrollers This library provides an interface to manage the Serial Peripheral Interface (SPI) module on the Microchip family of microcontrollers in different modes of operation. Description Overview The SPI module is a full duplex synchronous serial interface useful for communicating with other peripherals or microcontrollers in master/slave relationship and it can transfer data over short distances at high speeds. The peripheral devices may be serial EEPROMs, shift registers, display drivers, analog-to-digital converters, etc. The SPI module is compatible with Motorola’s SPI and SIOP interfaces. During data transfer devices can work either in master or in Slave mode. The source of synchronization is the system clock, which is generated by the master. The SPI module allows to connect one or more slave devices to a single master device via the same bus. The SPI serial interface consists of four pins, which are further sub-divided into data and control lines: Data lines: • MOSI – Master Data Output, Slave Data Input • MISO – Master Data Input, Slave Data Output Control lines: • SCLK – Serial Clock • /SS – Slave Select (no addressing) SPI Master-Slave Relationship The SPI module can be configured to operate using 2, 3 or 4 pins. In the 3-pin mode, slave select line is not used. In the 2-pin mode, both MOSI and SS lines are not used. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-418 Note: Third-party trademarks are property of their respective owners. 5.1.9.2 Release Notes MPLAB Harmony Version: v0.70b SPI Driver Library Version : 0.01 Release Date: 18Nov2013 New This Release: • Configurable baud rate at client level • Interoperability Known Issues: • Does not work in the Slave mode of operation • DMA is not supported 5.1.9.3 SW License Agreement (c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED AS IS MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 5.1.9.4 Using the Library This topic describes the basic architecture of the SPI Driver Library and provides information and examples on how to use it. Interface Header File: drv_spi.h The interface to the SPI Driver library is defined in the "drv_spi.h" header file. Any C language source (.c) file that uses the SPI Driver library should include this header. Library File: The SPI Driver library archive (.a) file installed with MPLAB Harmony. Please refer to the MPLAB Harmony Overview for how the Driver interacts with the framework. 5.1.9.4.1 Abstraction Model Different types of SPIs are available on Microchip microcontrollers. Some have an internal buffer mechanism and some do not. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-419 The buffer depth varies across part families. The SPI driver abstracts out these differences and provides a unified model for data transfer across different types of SPIs available. Both transmitter and receiver provides a buffer in the driver which transmits and receives data to/from the hardware. The SPI driver provides a set of interfaces to perform the read and the write. The diagrams below illustrates the model used by the SPI driver for transmitter and receiver. Receiver Abstraction Model Transmitter Abstraction Model 5.1.9.4.2 Library Overview Refer to the section Driver Overview for how the driver operates in a system. The library interface routines are divided into various subsections, each of the sub section addresses one of the blocks or the overall operation of the SPI module. Library Interface Section Description System Interaction Functions Provides system module interfaces, device initialization, deinitialization, reinitialization, tasks and status functions. Client Setup Functions Provides open, close, status and other setup functions. Chip Selects Provides chip select functions available in the configuration. Client Data Transfer - Core Provides core data transfer functions available in the configuration. [Standard/Single buffer transfer] 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-420 Client Data Transfer - Advanced Provides advanced data transfer functions available in the configuration. [Enhanced/Multi buffer transfers] Miscellaneous Provides driver miscellaneous functions, data transfer status function, version identification functions etc. 5.1.9.4.3 How the Library Works The library provides interfaces to support: • System Functionality • Client Functionality Note: Not all modes are available on all microcontrollers, please refer to the specific device data sheet to the modes that are supported for your device. 5.1.9.4.3.1 System Access System Initialization and Re-initialization The system performs the initialization and the re-initialization of the device driver with settings that affect only the instance of the device that is being initialized or re-initialized. During system initialization each instance of the SPI module would be initialized with the following configuration settings (either passed dynamically at run time using DRV_SPI_INIT or by using Initialization Overrides) that are supported by the specific SPI device hardware: • Device requested power state: one of the System Module Power States. For specific details please refer to the Data Types section in this guide • The actual peripheral ID enumerated as the PLIB level module ID. e.g SPI_ID_2. • Defining the respective interrupt sources for Tx, Rx, and Error Interrupt. The DRV_SPI_Initialize API returns an object handle of the type SYS_MODULE_OBJ. There on, the object handle returned by the Initialize interface would be used by the other system interfaces like DRV_SPI_Reinitialize, DRV_SPI_Deinitialize, DRV_SPI_Status and DRV_SPI_Tasks. Note:The system initialization and the re-initialization settings, only effect the instance of the peripheral that is being initialized or re-initialized. Example: DRV_SPI_INIT spiInitData; SYS_MODULE_OBJ objectHandle; spiInitData.moduleInit.value = SYS_MODULE_POWER_RUN_FULL; spiInitData.spiId = SPI_ID_1; spiInitData.spiMode = DRV_SPI_MODE_MASTER; spiInitData.spiProtocolType = DRV_SPI_PROTOCOL_TYPE_STANDARD; spiInitData.commWidth = SPI_COMMUNICATION_8BIT_WIDE; spiInitData.baudRate = 5000; spiInitData.bufferType = DRV_SPI_BUFFER_TYPE_STANDARD; spiInitData.inputSamplePhase = SPI_INPUT_SAMPLING_PHASE_IN_MIDDLE; spiInitData.clockMode = DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE; spiInitData.txInterruptSource = INT_SOURCE_SPI_1_TRANSMIT; // INT_SOURCE_SPI_1_EVENT spiInitData.rxInterruptSource = INT_SOURCE_SPI_1_RECEIVE; // INT_SOURCE_SPI_1_EVENT spiInitData.errInterruptSource = INT_SOURCE_SPI_1_ERROR; spiInitData.pinConfig.sdiPin = PIN_6; // RPI38 spiInitData.pinConfig.sdoPin = PIN_10; // RP21 spiInitData.pinConfig.sckPin = PIN_11; // RP26 objectHandle = DRV_SPI_Initialize(DRV_SPI_INDEX_1, (SYS_MODULE_INIT*)&spiInitData); 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-421 if (SYS_MODULE_OBJ_INVALID == objectHandle) { // Handle error } Tasks Routine The system will either call DRV_SPI_Tasks, from System Task Service (in a polled environment) or DRV_SPI_Tasks will be called from interrupt service routine of the SPI. 5.1.9.4.3.2 Client Access General Client Operation For the application to start using an instance of the module, it must call the DRV_SPI_Open function. This provides the configuration required to open the SPI instance for operation. If the driver is de-initialized using the function DRV_SPI_Deinitialize, the application must call the DRV_SPI_Open function again to setup the instance of the SPI. The function DRV_SPI_Open need not be called again if the system is re-initialized using the DRV_SPI_Reinitialize function. For the various options available for IO INTENT please refer to the Data Types section in this guide. Example: DRV_HANDLE handle; // Configure the instance DRV_SPI_INDEX_1 with the configuration handle = DRV_SPI_Open(DRV_SPI_INDEX_1, DRV_IO_INTENT_READWRITE); if(handle == DRV_HANDLE_INVALID) { // Client cannot open the instance. } Communication Setup: Communication entities like the SPI modes, input clock frequency, baud rates, clock mode, ports setup etc. can be configured with the help of the driver function DRV_SPI_CommunicationSetup. This is a mandatory setup before doing any data transfer. The callback function registered during the communication setup gets called after a successful data transfer. Example: DRV_HANDLE handle; // Returned from DRV_SPI_Open DRV_SPI_COMM_CONFIG config; // Populate the communication setup configuration structure config.spiMode = DRV_SPI_MODE_MASTER; config.baudRate = 5000; config.inputSamplePhase = SPI_INPUT_SAMPLING_PHASE_IN_MIDDLE; config.clockMode = DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE; config.callback = &callBackFunction; // callback registered DRV_SPI_CommunicationSetup( handle, &config ); Chip Select Control: User can control the chip/slave select signals using the driver APIs DRV_SPI_ChipSelectActivate and DRV_SPI_ChipSelectDeactivate with appropriate parameters. Example: // Activates/Enables Slave Select connected to Port A, bit 1 DRV_SPI_ChipSelectActivate( handle, PORT_CHANNEL_A, PORTS_BIT_POS_1 ); ... ... ... // Deactivates/Disables Slave Select connected to Port A, bit 1 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-422 DRV_SPI_ChipSelectDeactivate( handle, PORT_CHANNEL_A, PORTS_BIT_POS_1 ); 5.1.9.4.3.3 Cient Transfer - Core Client basic functionality provides a extremely basic interface for the driver operation. This client transfer mechanism needs to be used for the devices which support the 'Standard' SPI mode of operation [Single Buffer]. This mechanism needs to be repeated in case of buffer based data transfers for transferring multi bytes/words. The diagram below illustrates the byte/word model used for the data transfer. Note: It is not necessary to close and re-open the client between multiple transfers. Client Byte/Word transfer Functionality Application using the SPI byte/word functionality, needs to perform the following: 1. The system should have completed necessary initialization and the DRV_SPI_Tasks should either be running in polled 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-423 environment, or in an interrupt environment. 2. Open the driver using DRV_SPI_Open with the necessary intent 3. Setup the communication using the driver function DRV_SPI_CommunicationSetup 4. Enable/activate the slave using the function DRV_SPI_ChipSelectActivate 5. Put/Write a byte using DRV_SPI_Put, dummy byte in case of read only 6. Check for the current transfer status using DRV_SPI_TransferStatus until the transfer is in progress DRV_SPI_TRANSFER_STATUS_IN_PROGRESS, call the DRV_SPI_Tasks in case of a polled environment until the transfer is success 7. Get/Read the dummy/valid data using the function DRV_SPI_Get 8. Repeat from step 5 till 7 to handle buffer transmission and reception using standard mode 9. Disable/deactivate the slave using the function DRV_SPI_ChipSelectDeactivate 10. The client will be able to close the driver using the DRV_SPI_Close when required. Example: DRV_HANDLE handle; // Returned from DRV_SPI_Open SPI_BUFFER myBuffer[MY_BUFFER_SIZE]; unsigned int numBytes; DRV_SPI_COMM_CONFIG config; // Pre-initialize myBuffer with MY_BUFFER_SIZE bytes of valid data. while( 1 ) { switch( state ) { case APP_STATE_INIT: /* Initialize the SPI Driver */ object = DRV_SPI_Initialize( sysIndex, ( SYS_MODULE_INIT * )&initConf ); /* Check for the System Status */ if( SYS_STATUS_READY != DRV_SPI_Status( object ) ) return 0; /* Open the Driver */ clHandle = DRV_SPI_Open( sysIndex, DRV_IO_INTENT_EXCLUSIVE ); /* Check for the Client Open Status */ if( DRV_SPI_CLIENT_STATUS_READY != DRV_SPI_ClientStatus( clHandle ) ) return 0; /* Set up the communication medium */ DRV_SPI_CommunicationSetup( clHandle, &commConf ); /* Update the state to transfer data */ state = APP_STATE_DATA_PUT; break; case APP_STATE_DATA_PUT: /* Enable/Activate the CS */ DRV_SPI_ChipSelectActivate( handle, PORT_CHANNEL_A, PORTS_BIT_POS_1 ); /* Initiate the data transfer */ DRV_SPI_Put( clHandle, myBuffer[i++] ); /* Deactivates/Disables CS */ DRV_SPI_ChipSelectDeactivate( handle, PORT_CHANNEL_A, PORTS_BIT_POS_1 ); /* Update the state to status check */ state = APP_STATE_STATUS_CHECK; break; case APP_STATE_STATUS_CHECK: 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-424 /* Check for the successful data transfer */ if( DRV_SPI_TRANSFER_STATUS_IN_PROGRESS & DRV_SPI_TransferStatus( clHandle ) ) { DRV_SPI_Tasks (object); /* Stay here until the data transfer is executed */ state = APP_STATE_STATUS_CHECK; } else { /* Data transfer was successfull, get the data */ state = APP_STATE_DATA_GET; } break; case APP_STATE_DATA_GET: /* Read the data from the peripheral */ rxd_data = DRV_SPI_Get( clHandle ); /* Restart the process by jumping to the beginning state */ state = APP_STATE_DATA_PUT; break; default: break; } } Note: 'bufferType' attribute of the initialization structure or the configuration macro 'DRV_SPI_BUFFER_USAGE_TYPE' needs to be updated as DRV_SPI_BUFFER_TYPE_STANDARD 5.1.9.4.3.4 Client Transfer - Advanced Client basic functionality provides a extremely basic interface for the driver operation. This client transfer mechanism needs to be used for the devices which support the 'Enhanced' SPI mode of operation [Internal FIFO or buffer]. The diagram below illustrates the buffer model used for the data transfer. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-425 Note: It is not necessary to close and re-open the client between multiple transfers. Client Byte/Word transfer Functionality Application using the SPI byte/word functionality, needs to perform the following: 1. The system should have completed necessary initialization and the DRV_SPI_Tasks should either be running in polled environment, or in an interrupt environment. 2. Open the driver using DRV_SPI_Open with the necessary intent 3. Setup the communication using the driver function DRV_SPI_CommunicationSetup 4. Enable/activate the slave using the function DRV_SPI_ChipSelectActivate 5. Put/Write a byte using DRV_SPI_PutBuffer, dummy byte in case of read only 6. Check for the current transfer status using DRV_SPI_TransferStatus until the transfer is in progress DRV_SPI_TRANSFER_STATUS_IN_PROGRESS, call the DRV_SPI_Tasks in case of a polled environment until the transfer is success 7. Get/Read the dummy/valid data using the function DRV_SPI_GetBuffer 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-426 8. Repeat from step 5 till 7 to handle multi buffer transmission and reception using enhanced mode 9. Disable/deactivate the slave using the function DRV_SPI_ChipSelectDeactivate 10. The client will be able to close the driver using the DRV_SPI_Close when required. Example: DRV_HANDLE handle; // Returned from DRV_SPI_Open SPI_DATA_TYPE tx_buffer[DRV_SPI_BUFFER_SIZE] = { 0x0001, 0x0001, 0x0001, 0x0001 }; SPI_DATA_TYPE rx_buffer[DRV_SPI_BUFFER_SIZE]; unsigned int numBytes; DRV_SPI_COMM_CONFIG config; // Pre-initialize tx_buffer with DRV_SPI_BUFFER_SIZE bytes of valid data. while( 1 ) { switch( state ) { case APP_STATE_INIT: /* Initialize the SPI Driver */ object = DRV_SPI_Initialize( sysIndex, ( SYS_MODULE_INIT * )&initConf ); /* Check for the System Status */ if( SYS_STATUS_READY != DRV_SPI_Status( object ) ) return 0; /* Open the Driver */ clHandle = DRV_SPI_Open( sysIndex, DRV_IO_INTENT_EXCLUSIVE ); /* Check for the Client Open Status */ if( DRV_SPI_CLIENT_STATUS_READY != DRV_SPI_ClientStatus( clHandle ) ) return 0; /* Set up the communication medium */ DRV_SPI_CommunicationSetup( clHandle, &commConf ); /* Update the state to transfer data */ state = APP_STATE_BUFFER_PUT; break; case APP_STATE_BUFFER_PUT: /* Initiate the data transfer */ DRV_SPI_PutBuffer( clHandle, &tx_buffer, sizeof( tx_buffer )/2 ); /* Update the state to status check */ state = APP_STATE_BUFFER_CHECK; break; case APP_STATE_BUFFER_CHECK: /* Check for the successful data transfer */ if( DRV_SPI_TRANSFER_STATUS_IN_PROGRESS & DRV_SPI_TransferStatus( clHandle ) ) { DRV_SPI_Tasks (object); /* Stay here until the data transfer is executed */ state = APP_STATE_BUFFER_CHECK; } else { /* Data transfer was successfull, get the data */ state = APP_STATE_BUFFER_GET; } break; case APP_STATE_BUFFER_GET: /* Read the data from the peripheral */ DRV_SPI_GetBuffer( clHandle, &rx_buffer, sizeof( rx_buffer )/2 ); 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-427 /* Restart the process by jumping to the beginning state */ state = APP_STATE_BUFFER_PUT; break; default: break; } } Note: 'bufferType' attribute of the initialization structure or the configuration macro 'DRV_SPI_BUFFER_USAGE_TYPE' needs to be updated as DRV_SPI_BUFFER_TYPE_ENHANCED 5.1.9.5 Configuring the Library The configuration of the SPI driver is based on the file sys_config.h This header file contains the configuration selection for the SPI driver. Based on the selections made, the SPI driver will support or not support selected features. These configuration settings will apply to all instances of the SPI driver. This header can be placed anywhere, the path of this header needs to be present in the include search path for a successful build. Refer to the Applications Overview section for more details. 5.1.9.5.1 Client Configuration 5.1.9.5.2 System Configuration 5.1.9.5.3 Miscellaneous Configuration 5.1.9.6 Building the Library This section list the files that are available in the \src of the SPI driver. It lists which files need to be included in the build based on either a hardware feature present on the board or configuration option selected by the system. 5.1.9.7 Library Interface Data Types and Constants Name Description DRV_SPI_BAUD_RATE Controls the baud rate value of the SPI driver. DRV_SPI_BAUD_RATE_CLOCK Selects the SPI baud rate clock. DRV_SPI_BUFFER_HANDLE_INVALID Definition of an invalid buffer handle. DRV_SPI_BUFFER_SIZE This is macro DRV_SPI_BUFFER_SIZE. DRV_SPI_BUFFER_USAGE_TYPE Controls the buffer type of the SPI driver. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-428 DRV_SPI_CLIENTS_NUMBER Selects the miximum number of clients. DRV_SPI_CLOCK_OPERATION_MODE Controls the clock mode of the SPI driver. DRV_SPI_COMMUNICATION_WIDTH Controls the communication width of the SPI driver. DRV_SPI_FRAME_SYNC_PULSE_COUNT Selects the SPI frame sync pulse count. DRV_SPI_FRAME_SYNC_PULSE_DIRECTION Selects the SPI frame sync pulse direction. DRV_SPI_FRAME_SYNC_PULSE_EDGE Selects the SPI frame sync pulse edge. DRV_SPI_FRAME_SYNC_PULSE_POLARITY Selects the SPI frame sync pulse polarity. DRV_SPI_FRAME_SYNC_PULSE_WIDTH Selects the SPI frame sync pulse width. DRV_SPI_INDEX SPI static index selection. DRV_SPI_INDEX_0 SPI driver index definitions. DRV_SPI_INDEX_COUNT Number of valid SPI driver indices. DRV_SPI_INPUT_SAMPLE_PHASE Selects the SPI input sample phase. DRV_SPI_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be supported by the dynamic driver . DRV_SPI_INTERRUPT_MODE Controls operation of the driver in the interrupt or polled mode. DRV_SPI_INTERRUPT_SOURCE_ERROR Defines the error interrupt source in case of static driver DRV_SPI_INTERRUPT_SOURCE_RX Defines the receive interrupt source in case of static driver. DRV_SPI_INTERRUPT_SOURCE_TX Defines the transmit/receive or transmit alone interrupt source in case of static driver. DRV_SPI_PERIPHERAL_ID SPI peripheral ID selection. DRV_SPI_PORTS_REMAP_USAGE Selects the SPI pins remap. DRV_SPI_POWER_STATE Controls the power state of the SPI driver. DRV_SPI_PROTOCOL Controls the protocol type of the SPI driver. DRV_SPI_USAGE_MODE Controls the usage mode of the SPI driver. DRV_SPI_BUFFER_EVENT Identifies the possible events that can result from a buffer add request. DRV_SPI_BUFFER_EVENT_HANDLER Pointer to a SPI Driver Buffer Event handler function DRV_SPI_BUFFER_HANDLE Handle identifying a read or write buffer passed to the driver. DRV_SPI_BUFFER_TYPE Identifies the various buffer types of the SPI module. DRV_SPI_CLIENT_SETUP Defines the data required to initialize an SPI client. DRV_SPI_CLOCK_MODE Identifies the various clock modes of the SPI module. DRV_SPI_INIT Defines the data required to initialize or reinitialize the SPI driver DRV_SPI_MODE Identifies the various usage modes of the SPI module. DRV_SPI_PROTOCOL_TYPE Identifies the various protocols of the SPI module. Client Setup Functions Name Description DRV_SPI_BufferStatus Returns the transmitter and receiver transfer status. DRV_SPI_ClientSetup Initializes a client. DRV_SPI_Close Closes an opened instance of the SPI driver DRV_SPI_Open Opens the specified SPI driver instance and returns a handle to it. Miscellaneous Functions Name Description DRV_SPI_BufferAddRead Registers a buffer for a read operation. Actual transfer will happen in the Task function. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-429 DRV_SPI_BufferAddWrite Registers a buffer for a read operation. Actual transfer will happen in the Task function. DRV_SPI_BufferAddWriteRead Registers a buffer for a read operation. Actual transfer will happen in the Task function. DRV_SPI_VersionGet Gets the SPI driver version in numerical format. DRV_SPI_VersionStrGet Gets the SPI driver version in string format. DRV_SPI_INDEX_1 This is macro DRV_SPI_INDEX_1. DRV_SPI_INDEX_2 This is macro DRV_SPI_INDEX_2. DRV_SPI_INDEX_3 This is macro DRV_SPI_INDEX_3. DRV_SPI_INDEX_4 This is macro DRV_SPI_INDEX_4. DRV_SPI_INDEX_5 This is macro DRV_SPI_INDEX_5. DRV_SPI_RX_FIFO_INTERRUPT_MODE This is macro DRV_SPI_RX_FIFO_INTERRUPT_MODE. DRV_SPI_TX_FIFO_INTERRUPT_MODE This is macro DRV_SPI_TX_FIFO_INTERRUPT_MODE. System Interaction Functions Name Description DRV_SPI_Deinitialize De-initializes the specified instance of the SPI driver module. DRV_SPI_Initialize Initializes the SPI driver. DRV_SPI_Status Provides the current status of the SPI driver module. DRV_SPI_Tasks Maintains the driver's state machine and implements its ISR. DRV_SPI_Read Gets/Reads byte(s) from SPI. The function will wait until the specified number of bytes is received. DRV_SPI_Write Writes the data to SPI. The function will wait until all the bytes are transmitted. Description This section describes the API functions of the SPI driver library. Refer to each section for a detailed description. 5.1.9.7.1 System Interaction Functions 5.1.9.7.1.1 DRV_SPI_Deinitialize Function C void DRV_SPI_Deinitialize( SYS_MODULE_OBJ object ); Description De-initializes the specified instance of the SPI driver module, disabling its operation (and any hardware) and invalidates all of the internal data. Preconditions Function DRV_SPI_Initialize must have been called before calling this routine and a valid SYS_MODULE_OBJ must have been returned. Parameters Parameters Description object Driver object handle, returned from DRV_SPI_Initialize 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-430 Returns None. Remarks Once the Initialize operation has been called, the De-initialize operation must be called before the Initialize operation can be called again. This function will NEVER block waiting for hardware. If the operation requires time to allow the hardware to complete, this will be reported by the DRV_SPI_Status operation. The system has to use DRV_SPI_Status to find out when the module is in the ready state. Example SYS_MODULE_OBJ object; // Returned from DRV_SPI_Initialize SYS_STATUS status; DRV_SPI_Deinitialize ( object ); status = DRV_SPI_Status( object ); if( SYS_MODULE_UNINITIALIZED == status ) { // Check again later if you need to know // when the driver is de-initialized. } 5.1.9.7.1.2 DRV_SPI_Initialize Function C SYS_MODULE_OBJ DRV_SPI_Initialize( const SYS_MODULE_INDEX index, const SYS_MODULE_INIT * const init ); Description This function initializes the SPI driver, making it ready for clients to open and use. Preconditions None. Parameters Parameters Description drvIndex Index for the driver instance to be initialized init Pointer to a data structure containing any data necessary to initialize the driver. This pointer may be null if no data is required because static overrides have been provided. Returns If successful, a valid handle to a driver object is returned. Otherwise, it returns SYS_MODULE_OBJ_INVALID. The returned object must be passed as an argument to the DRV_SPI_Reinitialize, DRV_SPI_Deinitialize, DRV_SPI_Tasks, and DRV_SPI_Status functions. Remarks This function must be called before any other SPI routine is called. This function should only be called once during system initialization unless DRV_SPI_Deinitialize is called to de-initialize the driver instance. This function will NEVER block for hardware access. If the operation requires time to allow the hardware to reinitialize, it will be 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-431 reported by the DRV_SPI_Status operation. The system must use DRV_SPI_Status to find out when the driver is in the ready state. Build configuration options may be used to statically override options in the "init" structure and will take precedence over initialization data passed using this function. Example DRV_SPI_INIT init; SYS_MODULE_OBJ objectHandle; // Populate the SPI initialization structure init.spiId = SPI_ID_1; init.spiMode = DRV_SPI_MODE_MASTER; init.spiProtocolType = DRV_SPI_PROTOCOL_TYPE_STANDARD; init.commWidth = SPI_COMMUNICATION_8BIT_WIDE; init.baudRate = 5000; init.bufferType = DRV_SPI_BUFFER_TYPE_STANDARD; init.inputSamplePhase = SPI_INPUT_SAMPLING_PHASE_IN_MIDDLE; init.clockMode = DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE; init.txInterruptSource = INT_SOURCE_SPI_1_TRANSMIT; // INT_SOURCE_SPI_1_EVENT init.rxInterruptSource = INT_SOURCE_SPI_1_RECEIVE; // INT_SOURCE_SPI_1_EVENT init.errInterruptSource = INT_SOURCE_SPI_1_ERROR; // Do something objectHandle = DRV_SPI_Initialize( DRV_SPI_INDEX_0, (SYS_MODULE_INIT*)&init ); if( SYS_MODULE_OBJ_INVALID == objectHandle ) { // Handle error } 5.1.9.7.1.3 DRV_SPI_Status Function C SYS_STATUS DRV_SPI_Status( SYS_MODULE_OBJ object ); Description This function provides the current status of the SPI driver module. Preconditions The DRV_SPI_Initialize function must have been called before calling this function. Parameters Parameters Description object Driver object handle, returned from DRV_SPI_Initialize Returns SYS_STATUS_READY - Indicates that the driver is busy with a previous system level operation and cannot start another Remarks Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new operations. SYS_MODULE_DEINITIALIZED - Indicates that the driver has been de-initialized This value is less than SYS_STATUS_ERROR. This function can be used to determine when any of the driver's module level operations has completed. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-432 If the status operation returns SYS_STATUS_BUSY, the previous operation has not yet completed. Once the status operation returns SYS_STATUS_READY, any previous operations have completed. The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state. This function will NEVER block waiting for hardware. If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the de-initialize operation will need to be called, followed by the initialize operation to return to normal operations. Example SYS_MODULE_OBJ object; // Returned from DRV_SPI_Initialize SYS_STATUS status; status = DRV_SPI_Status( object ); if( SYS_STATUS_READY != status ) { // Handle error } 5.1.9.7.1.4 DRV_SPI_Tasks Function C void DRV_SPI_Tasks( SYS_MODULE_OBJ object ); Description This routine is used to maintain the driver's internal state machine and implement its transmit ISR for interrupt-driven implementations. In polling mode, this function should be called from the SYS_Tasks() function. In interrupt mode, this function should be called in the transmit interrupt service routine of the USART that is associated with this USART driver hardware instance. Preconditions The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance. Parameters Parameters Description object Object handle for the specified driver instance (returned from DRV_SPI_Initialize) Returns None. Remarks This function is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the appropriate raw ISR. This function may execute in an ISR context and will never block or access any resources that may cause it to block. Example SYS_MODULE_OBJ object; // Returned from DRV_SPI_Initialize while( true ) { DRV_SPI_Tasks ( object ); // Do other tasks } 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-433 5.1.9.7.1.5 DRV_SPI_Read Function C size_t DRV_SPI_Read( DRV_HANDLE handle, void* buffer, size_t noOfBytes ); Description This function gets/reads byte(s) from SPI. The function will wait until the specified number of bytes is received. Preconditions The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance. DRV_SPI_Open must have been called to obtain a valid opened device handle. DRV_IO_INTENT_READ or DRV_IO_INTENT_READWRITE must have been specified in the DRV_SPI_Open call. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine buffer Buffer to which the data should be written to. noOfBytes Number of bytes to be received. Returns The number of bytes read. Remarks If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_SPI_Open function and the driver was built to support blocking behavior the call will block until the operation is complete. If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_SPI_Open function or the driver was built to only support non-blocking behavior the call will return immediately. If data is not available, a zero ('0') value will be returned and an underrun error status will be captured. To ensure that valid data is returned, the caller must first check the return value to DRV_SPI_BufferStatus, as shown in the example. Example DRV_HANDLE handle; // Returned from DRV_SPI_Open SPI_DATA_TYPE myBuffer[MY_BUFFER_SIZE]; unsigned int numberOfBytesRead; numberOfBytesRead = DRV_SPI_Read ( handle, myBuffer, 10 ); if ( numberOfBytesWritten == 0 ) { // Check for the error... } 5.1.9.7.1.6 DRV_SPI_Write Function C size_t DRV_SPI_Write( DRV_HANDLE handle, void* buffer, size_t noOfBytes ); 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-434 Description This function Writes the data to SPI. The function will wait until all the bytes are transmitted. Preconditions The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance. DRV_SPI_Open must have been called to obtain a valid opened device handle. DRV_IO_INTENT_WRITE or DRV_IO_INTENT_READWRITE must have been specified in the DRV_SPI_Open call. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine buffer Buffer which contains the data. noOfBytes Number of bytes to be transmitted. Returns The number of bytes written. Remarks If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_SPI_Open function and the driver was built to support blocking behavior the call will block until the operation is complete. If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_SPI_Open function or the driver was built to only support non-blocking behavior the call will return immediately. If the driver was not able to accept the data, an overrun error status will be captured. To ensure that the driver is ready to accept data, the caller must first check the return value to DRV_SPI_BufferStatus, as shown in the example. Example DRV_HANDLE handle; // Returned from DRV_SPI_Open SPI_DATA_TYPE myBuffer[MY_BUFFER_SIZE];//fill the data unsigned int numberOfBytesWritten; numberOfBytesWritten = DRV_SPI_Write ( handle, myBuffer, 10 ); if ( numberOfBytesWritten == 0 ) { // Check the error... } 5.1.9.7.2 Client Setup Functions 5.1.9.7.2.1 DRV_SPI_BufferStatus Function C DRV_SPI_BUFFER_EVENT DRV_SPI_BufferStatus( DRV_SPI_BUFFER_HANDLE bufferHandle ); Description This returns the transmitter and receiver transfer status. Preconditions The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance. DRV_SPI_Open must have been called to obtain a valid opened device handle. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-435 Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine Returns A DRV_SPI_BUFFER_STATUS value describing the current status of the transfer. Remarks The returned status may contain a value with more than one of the bits specified in the DRV_SPI_BUFFER_STATUS enumeration set. The caller should perform an AND with the bit of interest and verify if the result is non-zero (as shown in the example) to verify the desired status bit. Example DRV_HANDLE handle; // Returned from DRV_SPI_Open if( DRV_SPI_BUFFER_STATUS_SUCCESS & DRV_SPI_BufferStatus( handle ) ) { // All transmitter data has been sent. } 5.1.9.7.2.2 DRV_SPI_ClientSetup Function C void DRV_SPI_ClientSetup( DRV_HANDLE handle, const DRV_SPI_CLIENT_SETUP * const clientSetup ); Description This function sets up the device communication parameters. Using this API user can have configurations like chip select and baud rate specific to a client. The driver will be able to switch the between clients dynamically. 'DRV_SPI_CLIENT_SPECIFIC_CONTROL' must be defined in 'system_config.h'. This function is only useful for instance which has got multiple slaves. Preconditions The DRV_SPI_Initialize routine must have been called. DRV_SPI_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open instance handle, returned from the driver's open routine clientSetup Communication parameters identified by DRV_SPI_CLIENT_SETUP Returns None Remarks This is an optional call. It is necessary only two clients using needs different configurations. Example DRV_HANDLE handle; // Returned from DRV_SPI_Open DRV_SPI_CLIENT_SETUP clientSetup; // Populate the communication setup configuration structure 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-436 clientSetup.baudRate = 5000; clientSetup.inputSamplePhase = SPI_INPUT_SAMPLING_PHASE_IN_MIDDLE; clientSetup.clockMode = DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE; clientSetup.callback = &callBackFunction; // callback registered DRV_SPI_ClientSetup ( handle, &clientSetup ); 5.1.9.7.2.3 DRV_SPI_Close Function C void DRV_SPI_Close( DRV_HANDLE handle ); Description This function closes an opened instance of the SPI driver, invalidating the handle. Preconditions The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance. DRV_SPI_Open must have been called to obtain a valid opened device handle. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine Returns None Remarks After calling this routine, the handle passed in "handle" must not be used with any of the remaining driver routines. A new handle must be obtained by calling DRV_USART_Open before the caller may use the driver again. This function is thread safe in a RTOS application. Usually there is no need for the driver client to verify that the Close operation has completed. Example DRV_HANDLE handle; // Returned from DRV_SPI_Open DRV_SPI_Close ( handle ); 5.1.9.7.2.4 DRV_SPI_Open Function C DRV_HANDLE DRV_SPI_Open( const SYS_MODULE_INDEX drvIndex, const DRV_IO_INTENT intent ); Description This routine opens the specified USART driver instance and provides a handle that must be provided to all other client-level operations to identify the caller and the instance of the driver. The ioIntent parameter defines how the client interacts with this driver instance. The DRV_IO_INTENT_BLOCKING and DRV_IO_INTENT_NONBLOCKING ioIntent options additionally affect the behavior of the DRV_USART_Read() and DRV_USART_Write() functions. If the ioIntent is DRV_IO_INTENT_NONBLOCKING, then these function will not block even if the required amount of data could not be processed. If the ioIntent is DRV_IO_INTENT_BLOCKING, these functions will block till the required amount of data is processed. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-437 If ioIntent is DRV_IO_INTENT_READ, the client will only be read from the driver. If ioIntent is DRV_IO_INTENT_WRITE, the client will only be able to write to the driver. If the ioIntent in DRV_IO_INTENT_READWRITE, the client will be able to do both, read and write. Specifying a DRV_IO_INTENT_EXCLUSIVE will cause the driver to provide exclusive access to this client. The driver cannot be opened by any other client. Preconditions The DRV_SPI_Initialize function must have been called before calling this function. Parameters Parameters Description drvIndex Identifier for the object instance to be opened intent Zero or more of the values from the enumeration DRV_IO_INTENT ORed together to indicate the intended use of the driver Returns If successful, the routine returns a valid open-instance handle (a number identifying both the caller and the module instance). If an error occurs, the return value is DRV_HANDLE_INVALID. Error can occur • if the number of client objects allocated via DRV_USART_CLIENTS_NUMBER is insufficient. • if the client is trying to open the driver but driver has been opened exclusively by another client. • if the driver hardware instance being opened is not initialized or is invalid. Remarks The handle returned is valid until the DRV_USART_Close routine is called. This routine will NEVER block waiting for hardware.If the requested intent flags are not supported, the routine will return DRV_HANDLE_INVALID. This function is thread safe in a RTOS application. It should not be called in an ISR. Example DRV_HANDLE handle; handle = DRV_SPI_Open( DRV_SPI_INDEX_0, DRV_IO_INTENT_EXCLUSIVE ); if( DRV_HANDLE_INVALID == handle ) { // Unable to open the driver } 5.1.9.7.3 Miscellaneous Functions 5.1.9.7.3.1 DRV_SPI_BufferAddRead Function C DRV_SPI_BUFFER_HANDLE DRV_SPI_BufferAddRead( DRV_HANDLE handle, void * rxBuffer, size_t size ); 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-438 Description Registers a buffer for a read operation. Actual transfer will happen in the Task function. The status of this operation can be monitored using DRV_SPI_BufferStatus function. Preconditions The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance. DRV_SPI_Open must have been called to obtain a valid opened device handle. DRV_IO_INTENT_WRITE or DRV_IO_INTENT_READWRITE must have been specified in the DRV_SPI_Open call. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine rxBuffer The buffer to which the data should be written to. size Number of bytes to be read. Returns None. Remarks If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_SPI_Open function and the driver was built to support blocking behavior the call will block until the operation is complete. If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_SPI_Open function or the driver was built to only support non-blocking behavior the call will return immediately. If the driver was not able to accept the data, an overrun error status will be captured. To ensure that the driver is ready to accept data, the caller must first check the return value to DRV_SPI_BufferStatus, as shown in the example. Example DRV_HANDLE handle; // Returned from DRV_SPI_Open SPI_DATA_TYPE myBuffer[MY_BUFFER_SIZE]; // PUT API returns data in any case, upto the user to use it DRV_SPI_BufferAddRead( handle, myBuffer, 10 ); if( DRV_SPI_BUFFER_STATUS_SUCCESS & DRV_SPI_BufferStatus( handle ) ) { // All transmitter data has been sent. } 5.1.9.7.3.2 DRV_SPI_BufferAddWrite Function C DRV_SPI_BUFFER_HANDLE DRV_SPI_BufferAddWrite( DRV_HANDLE handle, void * txBuffer, size_t size ); Description Registers a buffer for a read operation. Actual transfer will happen in the Task function. The status of this operation can be monitored using DRV_SPI_BufferStatus function. Preconditions The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-439 DRV_SPI_Open must have been called to obtain a valid opened device handle. DRV_IO_INTENT_WRITE or DRV_IO_INTENT_READWRITE must have been specified in the DRV_SPI_Open call. Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine rxBuffer The buffer to which the data should be written to. size Number of bytes to be read. Returns None. Remarks If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_SPI_Open function and the driver was built to support blocking behavior the call will block until the operation is complete. If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_SPI_Open function or the driver was built to only support non-blocking behavior the call will return immediately. If the driver was not able to accept the data, an overrun error status will be captured. To ensure that the driver is ready to accept data, the caller must first check the return value to DRV_SPI_BufferStatus, as shown in the example. Example DRV_HANDLE handle; // Returned from DRV_SPI_Open SPI_DATA_TYPE myBuffer[MY_BUFFER_SIZE]; unsigned int numBytes; // Pre-initialize myBuffer with MY_BUFFER_SIZE bytes of valid data. numBytes = 0; // PUT API returns data in any case, upto the user to use it DRV_SPI_BufferAddRead( handle, myBuffer, 10 ); if( DRV_SPI_BUFFER_STATUS_SUCCESS & DRV_SPI_BufferStatus( handle ) ) { // All transmitter data has been sent. } 5.1.9.7.3.3 DRV_SPI_BufferAddWriteRead Function C DRV_SPI_BUFFER_HANDLE DRV_SPI_BufferAddWriteRead( DRV_HANDLE handle, void * txBuffer, void * rxBuffer, size_t size ); Description Registers a buffer for a read operation. Actual transfer will happen in the Task function. The status of this operation can be monitored using DRV_SPI_BufferStatus function. Preconditions The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance. DRV_SPI_Open must have been called to obtain a valid opened device handle. DRV_IO_INTENT_WRITE or DRV_IO_INTENT_READWRITE must have been specified in the DRV_SPI_Open call. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-440 Parameters Parameters Description handle A valid open-instance handle, returned from the driver's open routine rxBuffer The buffer to which the data should be written to. size Number of bytes to be read. Returns None. Remarks If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_SPI_Open function and the driver was built to support blocking behavior the call will block until the operation is complete. If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_SPI_Open function or the driver was built to only support non-blocking behavior the call will return immediately. If the driver was not able to accept the data, an overrun error status will be captured. To ensure that the driver is ready to accept data, the caller must first check the return value to DRV_SPI_BufferStatus, as shown in the example. Example DRV_HANDLE handle; // Returned from DRV_SPI_Open SPI_DATA_TYPE myBuffer[MY_BUFFER_SIZE]; unsigned int numBytes; // Pre-initialize myBuffer with MY_BUFFER_SIZE bytes of valid data. numBytes = 0; // PUT API returns data in any case, upto the user to use it DRV_SPI_BufferAddWriteRead( handle, myTxBuffer, myRxBuffer, 10 ); if( DRV_SPI_BUFFER_STATUS_SUCCESS & DRV_SPI_BufferStatus( handle ) ) { // All transmitter data has been sent. } 5.1.9.7.3.4 DRV_SPI_VersionGet Function C unsigned int DRV_SPI_VersionGet( const SYS_MODULE_INDEX drvIndex ); Description This function gets the SPI driver version. The version is encoded as major * 10000 + minor * 100 + patch. The stringed version can be obtained using DRV_SPI_VersionStrGet. Preconditions None. Parameters Parameters Description drvIndex Identifier for the object instance to get the version for Returns Current driver version in numerical format. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-441 Remarks None. Example unsigned int version; version = DRV_SPI_VersionGet( DRV_SPI_INDEX_0 ); if(version < 110200) { // Do Something } 5.1.9.7.3.5 DRV_SPI_VersionStrGet Function C char * DRV_SPI_VersionStrGet( const SYS_MODULE_INDEX drvIndex ); Description This function gets the SPI driver version. The version is returned as major.minor.path[type], where type is optional. The numerical version can be obtained using DRV_SPI_VersionGet. Preconditions None. Parameters Parameters Description drvIndex Identifier for the object instance to get the version for Returns Current the SPI driver version in the string format. Remarks None. Example char *version; version = DRV_SPI_VersionStrGet( DRV_SPI_INDEX_0 ); printf("%s", version); 5.1.9.7.3.6 DRV_SPI_INDEX_1 Macro C #define DRV_SPI_INDEX_1 1 Description This is macro DRV_SPI_INDEX_1. 5.1.9.7.3.7 DRV_SPI_INDEX_2 Macro C #define DRV_SPI_INDEX_2 2 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-442 Description This is macro DRV_SPI_INDEX_2. 5.1.9.7.3.8 DRV_SPI_INDEX_3 Macro C #define DRV_SPI_INDEX_3 3 Description This is macro DRV_SPI_INDEX_3. 5.1.9.7.3.9 DRV_SPI_INDEX_4 Macro C #define DRV_SPI_INDEX_4 4 Description This is macro DRV_SPI_INDEX_4. 5.1.9.7.3.10 DRV_SPI_INDEX_5 Macro C #define DRV_SPI_INDEX_5 5 Description This is macro DRV_SPI_INDEX_5. 5.1.9.7.3.11 DRV_SPI_RX_FIFO_INTERRUPT_MODE Macro C #define DRV_SPI_RX_FIFO_INTERRUPT_MODE SPI_FIFO_INTERRUPT_WHEN_RECEIVE_BUFFER_IS_FULL Description This is macro DRV_SPI_RX_FIFO_INTERRUPT_MODE. 5.1.9.7.3.12 DRV_SPI_TX_FIFO_INTERRUPT_MODE Macro C #define DRV_SPI_TX_FIFO_INTERRUPT_MODE SPI_FIFO_INTERRUPT_WHEN_TRANSMISSION_IS_COMPLETE Description This is macro DRV_SPI_TX_FIFO_INTERRUPT_MODE. 5.1.9.7.4 Data Types and Constants 5.1.9.7.4.1 DRV_SPI_BAUD_RATE Macro C #define DRV_SPI_BAUD_RATE 8000000 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-443 Description SPI baud rate value configuration This macro controls the baud rate value of the SPI driver. Remarks None. 5.1.9.7.4.2 DRV_SPI_BAUD_RATE_CLOCK Macro C #define DRV_SPI_BAUD_RATE_CLOCK SPI_BAUD_RATE_CLOCK_MCLK Description SPI baud rate clock selection This macro selects the SPI baud rate clock. Remarks None. 5.1.9.7.4.3 DRV_SPI_BUFFER_HANDLE_INVALID Macro C #define DRV_SPI_BUFFER_HANDLE_INVALID ((DRV_SPI_BUFFER_HANDLE)(-1)) Description SPI Driver Invalid Buffer Handle This is the definition of an invalid buffer handle. An invalid buffer handle is returned by DRV_SPI_BufferAddRead() and DRV_SPI_BufferAddWrite() function if the buffer add request was not successful. Remarks None 5.1.9.7.4.4 DRV_SPI_BUFFER_SIZE Macro C #define DRV_SPI_BUFFER_SIZE 8 Description This is macro DRV_SPI_BUFFER_SIZE. 5.1.9.7.4.5 DRV_SPI_BUFFER_USAGE_TYPE Macro C #define DRV_SPI_BUFFER_USAGE_TYPE DRV_SPI_BUFFER_TYPE_STANDARD Description SPI buffer type configuration This macro controls the buffer type of the SPI driver. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-444 Remarks None. 5.1.9.7.4.6 DRV_SPI_CLIENTS_NUMBER Macro C #define DRV_SPI_CLIENTS_NUMBER 1 Description SPI maximum number of clients This definition selects the maximum number of clients that the SPI driver can support at run time. Remarks None. 5.1.9.7.4.7 DRV_SPI_CLOCK_OPERATION_MODE Macro C #define DRV_SPI_CLOCK_OPERATION_MODE DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE Description SPI clock mode configuration This macro controls the clock mode of the SPI driver. Remarks None. 5.1.9.7.4.8 DRV_SPI_COMMUNICATION_WIDTH Macro C #define DRV_SPI_COMMUNICATION_WIDTH SPI_COMMUNICATION_8BIT_WIDE Description SPI communication width configuration This macro controls the communication width of the SPI driver. Remarks None. 5.1.9.7.4.9 DRV_SPI_FRAME_SYNC_PULSE_COUNT Macro C #define DRV_SPI_FRAME_SYNC_PULSE_COUNT SPI_FRAME_SYNC_PULSE_16_CHAR Description SPI frame sync pulse count selection This macro selects the SPI frame sync pulse count. Remarks None. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-445 5.1.9.7.4.10 DRV_SPI_FRAME_SYNC_PULSE_DIRECTION Macro C #define DRV_SPI_FRAME_SYNC_PULSE_DIRECTION SPI_FRAME_PULSE_DIRECTION_INPUT Description SPI frame sync pulse direction selection This macro selects the SPI frame sync pulse direction. Remarks None. 5.1.9.7.4.11 DRV_SPI_FRAME_SYNC_PULSE_EDGE Macro C #define DRV_SPI_FRAME_SYNC_PULSE_EDGE SPI_FRAME_PULSE_EDGE_PRECEDES_FIRST_CLOCK Description SPI frame sync pulse edge selection This macro selects the SPI frame sync pulse edge. Remarks None. 5.1.9.7.4.12 DRV_SPI_FRAME_SYNC_PULSE_POLARITY Macro C #define DRV_SPI_FRAME_SYNC_PULSE_POLARITY SPI_FRAME_PULSE_POLARITY_ACTIVE_HIGH Description SPI frame sync pulse polarity selection This macro selects the SPI frame sync pulse polarity. Remarks None. 5.1.9.7.4.13 DRV_SPI_FRAME_SYNC_PULSE_WIDTH Macro C #define DRV_SPI_FRAME_SYNC_PULSE_WIDTH SPI_FRAME_PULSE_WIDTH_TO_ONE_WORD Description SPI frame sync pulse width selection This macro selects the SPI frame sync pulse width. Remarks None. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-446 5.1.9.7.4.14 DRV_SPI_INDEX Macro C #define DRV_SPI_INDEX DRV_SPI_INDEX_2 Description SPI static index selection This definition selects the SPI static index for the driver object reference. Remarks This index is required to make a reference to the driver object. 5.1.9.7.4.15 DRV_SPI_INDEX_0 Macro C #define DRV_SPI_INDEX_0 0 Description SPI Driver Module Index Numbers These constants provide the SPI driver index definitions. Remarks These constants should be used in place of hard-coded numeric literals. These values should be passed into the DRV_SPI_Initialize and DRV_SPI_Open functions to identify the driver instance in use. 5.1.9.7.4.16 DRV_SPI_INDEX_COUNT Macro C #define DRV_SPI_INDEX_COUNT SPI_NUMBER_OF_MODULES Description SPI Driver Module Index Count This constant identifies the number of valid SPI driver indices. Remarks This constant should be used in place of hard-coded numeric literals. This value is derived from device-specific header files defined as part of the peripheral libraries. 5.1.9.7.4.17 DRV_SPI_INPUT_SAMPLE_PHASE Macro C #define DRV_SPI_INPUT_SAMPLE_PHASE SPI_INPUT_SAMPLING_PHASE_IN_MIDDLE Description SPI input sample phase selection This macro selects the SPI input sample phase. Remarks None. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-447 5.1.9.7.4.18 DRV_SPI_INSTANCES_NUMBER Macro C #define DRV_SPI_INSTANCES_NUMBER 1 Description SPI hardware instance configuration This definition selects the maximum number of hardware instances that can be supported by the dynamic driver. Remarks None. 5.1.9.7.4.19 DRV_SPI_INTERRUPT_MODE Macro C #define DRV_SPI_INTERRUPT_MODE false Description SPI interrupt and polled mode operation control This macro controls the operation of the driver in the interrupt mode of operation. The possible values of this macro are: • true - Select if interrupt mode of SPI operation is desired • false - Select if polling mode of SPI operation is desired Not defining this option to true or false will result in build error. Remarks None. 5.1.9.7.4.20 DRV_SPI_INTERRUPT_SOURCE_ERROR Macro C #define DRV_SPI_INTERRUPT_SOURCE_ERROR INT_SOURCE_SPI_1_ERROR Description SPI error interrupt source Macro to define the error interrupt source in case of static driver. Remarks Refer to the INT PLIB document for more information on INT_SOURCE enumeration 5.1.9.7.4.21 DRV_SPI_INTERRUPT_SOURCE_RX Macro C #define DRV_SPI_INTERRUPT_SOURCE_RX INT_SOURCE_SPI_1_EVENT Description SPI receive interrupt source This macro defines the receive interrupt source of the static driver. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-448 Remarks Refer to the Interrupt Peripheral Library documentation for more information on INT_SOURCE enumeration. This should be specified in case the device does not have a dedicated receive interrupt source. 5.1.9.7.4.22 DRV_SPI_INTERRUPT_SOURCE_TX Macro C #define DRV_SPI_INTERRUPT_SOURCE_TX INT_SOURCE_SPI_1_EVENT Description SPI transmit/receive or transmit alone interrupt source This macro defines the transmit/receive or transmit alone interrupt source of the static driver. Remarks Refer to the Interrupt Peripheral Library documentation for more information on the INT_SOURCE enumeration. Some devices have a single interrupt source for both transmit and receive communication, while some have a dedicated transmit interrupt source. These are handled through the DRV_SPI_INTERRUPT_SOURCE configuration switch. 5.1.9.7.4.23 DRV_SPI_PERIPHERAL_ID Macro C #define DRV_SPI_PERIPHERAL_ID SPI_ID_1 Description SPI peripheral ID selection This macro selects the SPI peripheral ID selection. This is an intialization override of the spiID member of the intialization configuration. Remarks Some devices also support SPI_ID_0. 5.1.9.7.4.24 DRV_SPI_PORTS_REMAP_USAGE Macro C #define DRV_SPI_PORTS_REMAP_USAGE false Description SPI pins remap selection This macro selects the SPI pins remap. The possible values of this macro are: • true - Remap is required • false - Remap is not required Remarks None. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-449 5.1.9.7.4.25 DRV_SPI_POWER_STATE Macro C #define DRV_SPI_POWER_STATE SYS_MODULE_POWER_IDLE_STOP Description SPI power state configuration This macro controls the power state of the SPI driver. Remarks This feature may not be available in the device or the SPI module selected. 5.1.9.7.4.26 DRV_SPI_PROTOCOL Macro C #define DRV_SPI_PROTOCOL DRV_SPI_PROTOCOL_TYPE_STANDARD Description SPI protocol type configuration This macro controls the protocol type of the SPI driver. Remarks None. 5.1.9.7.4.27 DRV_SPI_USAGE_MODE Macro C #define DRV_SPI_USAGE_MODE DRV_SPI_MODE_MASTER Description SPI usage mode configuration This macro controls the usage mode of the SPI driver. Remarks None. 5.1.9.7.4.28 DRV_SPI_BUFFER_EVENT Enumeration C typedef enum { DRV_SPI_BUFFER_EVENT_PENDING, DRV_SPI_BUFFER_EVENT_COMPLETE, DRV_SPI_BUFFER_EVENT_ERROR } DRV_SPI_BUFFER_EVENT; Description SPI Driver Buffer Events This enumeration identifies the possible events that can result from a buffer add request caused by the client calling either the DRV_NVM_BufferAddRead or DRV_NVM_BufferAddWrite functions. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-450 Members Members Description DRV_SPI_BUFFER_EVENT_PENDING Buffer is pending to get processed DRV_SPI_BUFFER_EVENT_COMPLETE All data from or to the buffer was transferred successfully. DRV_SPI_BUFFER_EVENT_ERROR There was an error while processing the buffer transfer request. Remarks One of these values is passed in the "event" parameter of the event handling callback function that the client registered with the driver by calling the DRV_NVM_BufferEventHandlerSet function when a buffer transfer request is completed. 5.1.9.7.4.29 DRV_SPI_BUFFER_EVENT_HANDLER Type C typedef void (* DRV_SPI_BUFFER_EVENT_HANDLER)(DRV_SPI_BUFFER_EVENT event, DRV_SPI_BUFFER_HANDLE bufferHandle, uintptr_t context); Description SPI Driver Buffer Event Handler Function Pointer This data type defines the required function signature for the SPI driver buffer event handling callback function. A client must register a pointer to a buffer event handling function who's function signature (parameter and return value types) match the types specified by this function pointer in order to receive buffer related event calls back from the driver. The parameters and return values and return value are described here and a partial example implementation is provided. Parameters Parameters Description event Identifies the type of event bufferHandle Handle identifying the buffer to which the vent relates context Value identifying the context of the application that registered the event handling function. Returns None. Remarks If the event is DRV_SPI_BUFFER_EVENT_COMPLETE, it means that the data was transferred successfully. If the event is DRV_SPI_BUFFER_EVENT_ERROR, it means that the data was not transferred successfully. The bufferHandle parameter contains the buffer handle of the buffer that failed. The context parameter contains the a handle to the client context, provided at the time the event handling function was registered using the DRV_SPI_BufferEventHandlerSet function. This context handle value is passed back to the client as the "context" parameter. It can be any value necessary to identify the client context or instance (such as a pointer to the client's data) instance of the client that made the buffer add request. The event handler function executes in an interrupt context when the driver is configured for interrupt mode operation. It is recommended of the application to not perform process intensive operations with in this function. Example void APP_MyBufferEventHandler( DRV_SPI_BUFFER_EVENT event, DRV_SPI_BUFFER_HANDLE bufferHandle, uintptr_t context ) { 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-451 MY_APP_DATA_STRUCT pAppData = (MY_APP_DATA_STRUCT) context; switch(event) { case DRV_SPI_BUFFER_EVENT_COMPLETE: // Handle the completed buffer. break; case DRV_SPI_BUFFER_EVENT_ERROR: default: // Handle error. break; } } 5.1.9.7.4.30 DRV_SPI_BUFFER_HANDLE Type C typedef uintptr_t DRV_SPI_BUFFER_HANDLE; Description SPI Driver Buffer Handle A buffer handle value is returned by a call to the DRV_SPI_BufferAddRead()/ DRV_SPI_BufferAddWriteor DRV_SPI_BufferAddReadWrite() functions. This handle is associated with the buffer passed into the function and it allows the application to track the completion of the data from (or into) that buffer. The buffer handle value returned from the "buffer add" function is returned back to the client by the "callback" function registered with the driver. The buffer handle assigned to a client request expires when the client has been notified of the completion of the buffer transfer (after event handler function that notifies the client returns) or after the buffer has been retired by the driver if no event handler callback was set. Remarks None 5.1.9.7.4.31 DRV_SPI_BUFFER_TYPE Enumeration C typedef enum { DRV_SPI_BUFFER_TYPE_STANDARD, DRV_SPI_BUFFER_TYPE_ENHANCED } DRV_SPI_BUFFER_TYPE; Description SPI Buffer Type Selection This enumeration identifies the various buffer types of the SPI module. Members Members Description DRV_SPI_BUFFER_TYPE_STANDARD SPI Buffer Type Standard DRV_SPI_BUFFER_TYPE_ENHANCED SPI Enhanced Buffer Type Remarks None. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-452 5.1.9.7.4.32 DRV_SPI_CLIENT_SETUP Type C typedef struct _DRV_SPI_CLIENT_SETUP DRV_SPI_CLIENT_SETUP; Description SPI Client Initialization Data This structure lists the elements needed to set up an SPI client. Used by the function DRV_SPI_ClientSetup function. This data type defines the data required to initialize an SPI client. Remarks None. 5.1.9.7.4.33 DRV_SPI_CLOCK_MODE Enumeration C typedef enum { DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE, DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_FALL, DRV_SPI_CLOCK_MODE_IDLE_HIGH_EDGE_FALL, DRV_SPI_CLOCK_MODE_IDLE_HIGH_EDGE_RISE } DRV_SPI_CLOCK_MODE; Description SPI Clock Mode Selection This enumeration identifies the various clock modes of the SPI module. Members Members Description DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE SPI Clock Mode 0 - Idle State Low & Sampling on Rising Edge DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_FALL SPI Clock Mode 1 - Idle State Low & Sampling on Falling Edge DRV_SPI_CLOCK_MODE_IDLE_HIGH_EDGE_FALL SPI Clock Mode 2 - Idle State High & Sampling on Falling Edge DRV_SPI_CLOCK_MODE_IDLE_HIGH_EDGE_RISE SPI Clock Mode 3 - Idle State High & Sampling on Rising Edge Remarks None. 5.1.9.7.4.34 DRV_SPI_INIT Type C typedef struct _DRV_SPI_INIT DRV_SPI_INIT; Description SPI Driver Initialization Data This data type defines the data required to initialize or reinitialize the SPI driver. If the driver is built statically, the members of this data structure are statically over-ridden by static override definitions in the system_config.h file. Remarks None. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-453 5.1.9.7.4.35 DRV_SPI_MODE Enumeration C typedef enum { DRV_SPI_MODE_MASTER, DRV_SPI_MODE_SLAVE } DRV_SPI_MODE; Description SPI Usage Modes Enumeration This enumeration identifies the various usage modes of the SPI module. Members Members Description DRV_SPI_MODE_MASTER SPI Mode Master DRV_SPI_MODE_SLAVE SPI Mode Slave Remarks None. 5.1.9.7.4.36 DRV_SPI_PROTOCOL_TYPE Enumeration C typedef enum { DRV_SPI_PROTOCOL_TYPE_STANDARD, DRV_SPI_PROTOCOL_TYPE_FRAMED, DRV_SPI_PROTOCOL_TYPE_AUDIO } DRV_SPI_PROTOCOL_TYPE; Description SPI Protocols Enumeration This enumeration identifies the various protocols of the SPI module. Members Members Description DRV_SPI_PROTOCOL_TYPE_STANDARD SPI Protocol Type Standard DRV_SPI_PROTOCOL_TYPE_FRAMED SPI Protocol Type Framed DRV_SPI_PROTOCOL_TYPE_AUDIO SPi Protocol Type Audio Remarks None. 5.1.9.8 Files Files Name Description drv_spi.h SPI device driver interface file. drv_spi_config_template.h SPI Driver configuration definitions template. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-454 Description 5.1.9.8.1 drv_spi.h SPI Driver Interface The SPI driver provides a simple interface to manage the SPI module. This file defines the interface definitions and prototypes for the SPI driver. Enumerations Name Description DRV_SPI_BUFFER_EVENT Identifies the possible events that can result from a buffer add request. DRV_SPI_BUFFER_TYPE Identifies the various buffer types of the SPI module. DRV_SPI_CLOCK_MODE Identifies the various clock modes of the SPI module. DRV_SPI_MODE Identifies the various usage modes of the SPI module. DRV_SPI_PROTOCOL_TYPE Identifies the various protocols of the SPI module. Functions Name Description DRV_SPI_BufferAddRead Registers a buffer for a read operation. Actual transfer will happen in the Task function. DRV_SPI_BufferAddWrite Registers a buffer for a read operation. Actual transfer will happen in the Task function. DRV_SPI_BufferAddWriteRead Registers a buffer for a read operation. Actual transfer will happen in the Task function. DRV_SPI_BufferStatus Returns the transmitter and receiver transfer status. DRV_SPI_ClientSetup Initializes a client. DRV_SPI_Close Closes an opened instance of the SPI driver DRV_SPI_Deinitialize De-initializes the specified instance of the SPI driver module. DRV_SPI_Initialize Initializes the SPI driver. DRV_SPI_Open Opens the specified SPI driver instance and returns a handle to it. DRV_SPI_Read Gets/Reads byte(s) from SPI. The function will wait until the specified number of bytes is received. DRV_SPI_Status Provides the current status of the SPI driver module. DRV_SPI_Tasks Maintains the driver's state machine and implements its ISR. DRV_SPI_VersionGet Gets the SPI driver version in numerical format. DRV_SPI_VersionStrGet Gets the SPI driver version in string format. DRV_SPI_Write Writes the data to SPI. The function will wait until all the bytes are transmitted. Macros Name Description DRV_SPI_BUFFER_HANDLE_INVALID Definition of an invalid buffer handle. DRV_SPI_INDEX_0 SPI driver index definitions. DRV_SPI_INDEX_1 This is macro DRV_SPI_INDEX_1. DRV_SPI_INDEX_2 This is macro DRV_SPI_INDEX_2. DRV_SPI_INDEX_3 This is macro DRV_SPI_INDEX_3. DRV_SPI_INDEX_4 This is macro DRV_SPI_INDEX_4. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-455 DRV_SPI_INDEX_5 This is macro DRV_SPI_INDEX_5. DRV_SPI_INDEX_COUNT Number of valid SPI driver indices. Types Name Description DRV_SPI_BUFFER_EVENT_HANDLER Pointer to a SPI Driver Buffer Event handler function DRV_SPI_BUFFER_HANDLE Handle identifying a read or write buffer passed to the driver. DRV_SPI_CLIENT_SETUP Defines the data required to initialize an SPI client. DRV_SPI_INIT Defines the data required to initialize or reinitialize the SPI driver File Name drv_spi.h Company Microchip Technology Inc. 5.1.9.8.2 drv_spi_config_template.h SPI Driver Configuration Definitions for the Template Version These definitions statically define the driver's mode of operation. Macros Name Description DRV_SPI_BAUD_RATE Controls the baud rate value of the SPI driver. DRV_SPI_BAUD_RATE_CLOCK Selects the SPI baud rate clock. DRV_SPI_BUFFER_SIZE This is macro DRV_SPI_BUFFER_SIZE. DRV_SPI_BUFFER_USAGE_TYPE Controls the buffer type of the SPI driver. DRV_SPI_CLIENTS_NUMBER Selects the miximum number of clients. DRV_SPI_CLOCK_OPERATION_MODE Controls the clock mode of the SPI driver. DRV_SPI_COMMUNICATION_WIDTH Controls the communication width of the SPI driver. DRV_SPI_FRAME_SYNC_PULSE_COUNT Selects the SPI frame sync pulse count. DRV_SPI_FRAME_SYNC_PULSE_DIRECTION Selects the SPI frame sync pulse direction. DRV_SPI_FRAME_SYNC_PULSE_EDGE Selects the SPI frame sync pulse edge. DRV_SPI_FRAME_SYNC_PULSE_POLARITY Selects the SPI frame sync pulse polarity. DRV_SPI_FRAME_SYNC_PULSE_WIDTH Selects the SPI frame sync pulse width. DRV_SPI_INDEX SPI static index selection. DRV_SPI_INPUT_SAMPLE_PHASE Selects the SPI input sample phase. DRV_SPI_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be supported by the dynamic driver . DRV_SPI_INTERRUPT_MODE Controls operation of the driver in the interrupt or polled mode. DRV_SPI_INTERRUPT_SOURCE_ERROR Defines the error interrupt source in case of static driver DRV_SPI_INTERRUPT_SOURCE_RX Defines the receive interrupt source in case of static driver. DRV_SPI_INTERRUPT_SOURCE_TX Defines the transmit/receive or transmit alone interrupt source in case of static driver. DRV_SPI_PERIPHERAL_ID SPI peripheral ID selection. DRV_SPI_PORTS_REMAP_USAGE Selects the SPI pins remap. DRV_SPI_POWER_STATE Controls the power state of the SPI driver. 5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library 5-456 DRV_SPI_PROTOCOL Controls the protocol type of the SPI driver. DRV_SPI_RX_FIFO_INTERRUPT_MODE This is macro DRV_SPI_RX_FIFO_INTERRUPT_MODE. DRV_SPI_TX_FIFO_INTERRUPT_MODE This is macro DRV_SPI_TX_FIFO_INTERRUPT_MODE. DRV_SPI_USAGE_MODE Controls the usage mode of the SPI driver. File Name drv_spi_config_template.h Company Microchip Technology Inc. 5.1.10 Timer Driver Library 5.1.10.1 Introduction Timer Driver Library for Microchip Microcontrollers This library provides an interface to manage the Timer module on the Microchip family of microcontrollers during different modes of operation. Description Overview Timers are useful for generating accurate time based periodic interrupts for software application or real time operating systems. Other uses include counting external pulses or accurate timing measurement of external events using the timer's gate functions and accurate hardware delays. Please refer to the the Data Sheet for the part that is being used. Note: Trademarks and Intellectual Property are property of their respective owners. Customers are responsible for obtaining appropriate licensing or rights before using this software. 5.1.10.2 Release Notes MPLAB Harmony Version: v0.70b Timer Driver Library Version : 0.02 Alpha Release Date: 18Nov2013 New This Release: This is the first release of the library. The interface can change in the beta and\or 1.0 release. Known Issues: Nothing to report in this release. 5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library 5-457 5.1.10.3 SW License Agreement © 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved. SOFTWARE IS PROVIDED “AS IS.” MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER SIMILAR COSTS. To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have paid directly to Microchip to use this software. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. 5.1.10.4 Using the Library This topic describes the basic architecture of the Timer Driver Library and provides information and examples on how to use it. Interface Header File: drv_tmr.h The interface to the Timer Driver Library is defined in the "drv_tmr.h" header file. Please refer to the MPLAB Harmony Overview for how the driver interacts with the framework. 5.1.10.4.1 Abstraction Model Microchip devices have two type of timers: • Period-Match - When the counting timer matches the configured period, this timer is said to complete one iteration and an interrupt is set • Overflow - When the counting timer overflows/rolls over, interrupt is set and restarts from its previously set counter value. In this case, the preset period value would be the maximum possible count value. The Timer Driver abstracts this difference and provides a unified model for both of these types of timers. Description Abstraction Model The abstraction model of the Timer Driver is explained in the following diagram: 5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library 5-458 The core functionality of the Timer allows access to both the counter and the period values. The unified model allows user not to worry about whether the Timer currently being used is a overflow or period match-based. The user simply updates the period and the driver automatically takes care of adjusting the respective Timer's periodicity. In case a user needs any modification into the counter's initial value (i.e., to adjust for any errors in periodicity), they are allowed to do so using the counter control interfaces. 5.1.10.4.2 Library Overview Refer to the section Driver Overview for how the driver operates in a system. The table below lists the interface section and its brief description. Library Interface Section Description Configuration Provides macros for configuring the system. It is required that the system configures the driver to build correctly by choosing appropriate configuration options as listed in this section. These macros enable different features or modes of the timer peripheral. System Interaction Functions Provides interfaces to system layer to initialize, deinitialize and reinitialize the module. This section also describes functions to query the status of the module. Core Functions Provides interfaces for core functionality of the driver. Alarm Functions Provides interfaces to handle alarm features, if alarm functionality is enabled. Period Functions Provides interfaces to control the periodicity of the timers. Counter Control Functions Provides interfaces to update the counter values. Miscellaneous Functions Provides interfaces to get the version information, timer tick and operating frequencies. 5.1.10.4.3 How the Library Works The library provides interfaces to support: • System Interaction • Sync Mode Setup • Period Modification • Counter Modification • Client Core Functionality • Client Alarm Functionality (optional function, enabled using configuration options) • Other Optional Functionality (enabled using configuration options) Note: Any code segment pertaining to the driver interfaces will work for both the static or dynamic configurations. It is not necessary to modify the code to move from one configuration to the other (i.e., from static or dynamic or static-multi). 5.1.10.4.3.1 System Interaction This section describes Timer initialization and reinitialization. 5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library 5-459 Description Initialization and Reinitialization The system performs the initialization and the reinitialization of the device driver with settings that affect only the instance of the device that is being initialized or re-initialized. During system initialization, each instance of the Timer module will be initialized with the following configuration settings (either passed dynamically at run time using DRV_TMR_INIT or by using initialization overrides) that are supported by the specific Timer module hardware: Initialization member Configuration Name Description moduleInit DRV_TMR_POWER_STATE System module initialization of the power state. tmrId DRV_TMR_PERIPHERAL_ID Timer hardware module ID (peripheral library-level ID). clockSource DRV_TMR_CLOCK_SOURCE Clock Source Selection, Enables either the internal or the external clock, using one of the possible values from TMR_CLOCK_SOURCE. timerPeriod DRV_TMR_TIMER_PERIOD Timer period value. prescale DRV_TMR_PRESCALE Sets up the prescaler, using one of the possible values from TMR_PRESCALE. sourceEdge DRV_TMR_SOURCE_EDGE Source edge selection, if supported by the hardware, selects either the rising or falling edge, using one of the possible values from TMR_CLOCK_SOURCE_EDGE. postscale DRV_TMR_POSTSCALE Sets up the postscaler, if supported by the hardware, using one of the possible values from TMR_POSTSCALE. syncMode DRV_TMR_SYNCHRONIZATION_MODE Selects the operation mode of the instance using one of the possible values from DRV_TMR_SYNC_MODE. interruptSource DRV_TMR_INTERRUPT_SOURCE Interrupt source identifier for the Timer module being initialized, which is available from the respective device's processor headers. The DRV_TMR_Initialize function returns an object handle of the type SYS_MODULE_OBJ. After this, the object handle returned by the Initialize interface would be used by the other system interfaces like DRV_TMR_Reinitialize, DRV_TMR_Deinitialize, DRV_TMR_Status and DRV_TMR_Tasks. Example: Timer Initialization Through DRV_TMR_INIT DRV_TMR_INIT init; SYS_MODULE_OBJ object; SYS_STATUS tmrStatus; // populate the TMR init configuration structure init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL; init.tmrId = TMR_ID_2; init.clockSource = TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK; init.prescale = TMR_PRESCALE_TX_VALUE_256; init.syncMode = DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL; init.interruptSource = INT_SOURCE_TIMER_2; init.timerPeriod = 0xABCD; object = DRV_TMR_Initialize (DRV_TMR_INDEX_0, (SYS_MODULE_INIT *)&init); tmrStatus = DRV_TMR_Status(object); if ( SYS_STATUS_READY != tmrStatus) { // Handle error } 5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library 5-460 Example: Timer initialization Through Configuration Source file: SYS_MODULE_OBJ object; SYS_STATUS tmrStatus; int main( void ) { object = DRV_TMR_Initialize (DRV_TMR_INDEX_0, (SYS_MODULE_INIT *)NULL); tmrStatus = DRV_TMR_Status(object); if ( SYS_STATUS_READY != tmrStatus) { // Handle error } } Configuration file: sys_config.h #define DRV_TMR_POWER_STATE SYS_MODULE_POWER_RUN_FULL #define DRV_TMR_PERIPHERAL_ID TMR_ID_3 // TMR_MODULE_ID #define DRV_TMR_CLOCK_SOURCE TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK #define DRV_TMR_PRESCALE TMR_PRESCALE_TX_VALUE_256 #define DRV_TMR_SYNCHRONIZATION_MODE DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL #define DRV_TMR_INTERRUPT_SOURCE INT_SOURCE_TIMER_3 #define DRV_TMR_TIMER_PERIOD 0x0000F424 // 200ms Deinitialization Once the Initialize operation has been called, the Deinitialize operation must be called before the iIitialize operation can be called again.This routine may block if the driver is running in an OS environment that supports blocking operations and the driver requires system resources access. However, the routine will never block for hardware Timer access. If the operation requires time to allow the hardware to complete, this will be reported by the DRV_TMR_Status operation. Status Timer status is available to query the module state before, during, and after initialization, deinitialization, and reinitialization. Tasks Routine The interface DRV_TMR_Tasks can be called in two ways: • By the system task service in a polled environment • By the interrupt service routine of the timer in an interrupt based system Example: Polling int main( void ) { SYS_MODULE_OBJ object; object = DRV_TMR_Initialize( DRV_TMR_INDEX_0, (SYS_MODULE_INIT *) &initConf ); if( SYS_STATUS_READY != DRV_TMR_Status( object ) ) return 0; while (1) { DRV_TMR_Tasks (object); } } Example: Interrupt int main( void ) { 5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library 5-461 SYS_MODULE_OBJ object; object = DRV_TMR_Initialize( DRV_TMR_INDEX_0, (SYS_MODULE_INIT *) &initConf ); if( SYS_STATUS_READY != DRV_TMR_Status( object ) ) return 0; while (1); } /* Sample interrupt routine not specific to any device family */ void ISR T1Interrupt(void) { //Call the Timer Tasks routine DRV_TMR_Tasks(object); } 5.1.10.4.3.2 Client Interaction This section describer general client operation. Description General Client Operation For the application to begin using an instance of the Timer module, it must call the DRV_TMR_Open function. This provides the configuration required to open the Timer instance for operation. If the driver is deinitialized using the function DRV_TMR_Deinitialize, the application must call the DRV_TMR_Open function again to set up the instance of the Timer. The function DRV_TMR_Open need not be called again if the system is reinitialized using the DRV_TMR_Reinitialize function. The Timer Driver supports only the 'DRV_IO_INTENT_EXCLUSIVE' IO_INTENT. Example: DRV_HANDLE handle; // Configure the instance DRV_TMR_INDEX_1 with the configuration handle = DRV_TMR_Open(DRV_TMR_INDEX_1, DRV_IO_INTENT_EXCLUSIVE); if( handle == DRV_HANDLE_INVALID ) { // Client cannot open the instance. } The function DRV_TMR_Close closes an already opened instance of the Timer Driver, invalidating the handle. DRV_TMR_Open must have been called to obtain a valid opened device handle. Example: DRV_HANDLE handle; // Configure the instance DRV_TMR_INDEX_1 with the configuration handle = DRV_TMR_Open(DRV_TMR_INDEX_1, DRV_IO_INTENT_EXCLUSIVE); /*...*/ DRV_TMR_Close( handle ); The client has the option to check the status through the interface DRV_TMR_ClientStatus. Example: DRV_HANDLE handle; // Configure the instance DRV_TMR_INDEX_1 with the configuration handle = DRV_TMR_Open(DRV_TMR_INDEX_1, DRV_IO_INTENT_EXCLUSIVE); 5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library 5-462 if ( DRV_TMR_CLIENT_STATUS_READY != DRV_TMR_ClientStatus( handle ) ) return 0; 5.1.10.4.3.3 Sync Mode Selection This section describes the Sync mode selection process. Description Sync Mode Selection The Timer Driver can operate in various modes as described below. They can be changed using DRV_TMR_SyncModeSet, and the current mode being using by the Timer can be retrieved using DRV_TMR_SyncModeGet/ DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL - Synchronous Internal Clock Counter • This mode can be used to provide the following capabilities: • Create elapsed time measurements • Create time delays • Create periodic timer interrupts • The input clock to the Timer is provided from the internal system clock • The Timer increments in the effective delta time specified by the prescaler and the selected source clock DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL_GATED - Synchronous Internal Gated Counter • In this mode, the operation is dependent on an external signal applied to a pin assigned as a gate. When the gate signal remains high, the Timer increments. When the gate signal goes low, the operation terminates. • Input clock to the timer is provided from the internal system clock • The Timer increments in the effective delta time specified by the prescaler and the selected source clock • Gated Timer mode is not possible when the Timer is set to use external clock source DRV_TMR_SYNC_MODE_SYNCHRONOUS_EXTERNAL_WITHOUT_CLKSYNC - Synchronous External Clock Counter • The Synchronous External Clock Counter operation provides the following capabilities: • Counting periodic or non-periodic pulses • Uses the external clock as the time base for Timers • The selected Timer increments on every rising edge of the clock input on the TxCK pin DRV_TMR_SYNC_MODE_SYNCHRONOUS_EXTERNAL_WITH_CLKSYNC - Synchronous External Clock Counter • The clock source for the Timer is provided externally • The selected Timer increments on every rising edge of the input on the TxCK pin • External Clock sync is enabled to operate in the Synchronous mode DRV_TMR_SYNC_MODE_ASYNCHRONOUS_EXTERNAL_WITHOUT_CLKSYNC - Asynchronous External Clock Counter • The Asynchronous Timer operation provides the following capabilities: • The Timer can operate during Sleep mode and can generate an interrupt on a period register match that will wake the processor from Sleep or Idle modes. • The Timer can be clocked from the secondary oscillator for real-time clock applications • The clock source for the Timer is provided externally • The selected Timer increments on every rising edge of the clock input on the TxCK pin • Synchronization with the external clock is disabled DRV_TMR_SYNC_MODE_ASYNCHRONOUS_EXTERNAL_WITH_CLKSYNC - Asynchronous External Clock Counter 5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library 5-463 • The clock source for the Timer is provided externally • The selected Timer increments on every rising edge of the clock input on the TxCK pin • Synchronization with the external clock is enabled Changing the Sync Mode Perform the following steps before changing the sync mode. Preconditions: DRV_TMR_Open should have been called before calling this function and should have returned a valid handle. 1. Stop the TMR module using DRV_TMR_Stop. 2. Change the sync mode using DRV_TMR_SyncModeSet. 3. Update the counter using DRV_TMR_Counter[8Bit/16Bit/32Bit]Set, if applicable. 4. Start the TMR module using DRV_TMR_Start. Example: DRV_HANDLE handle; /* Open the client */ handle = DRV_TMR_Open( DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE ); /* Stop the timer */ DRV_TMR_Stop( handle ); /* Change the sync mode */ DRV_TMR_SyncModeSet( handle, DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL ); /* Re-start the timer */ DRV_TMR_Start( handle ); Note: Not all modes are supported by all the Timer modules. Please refer the specific device data sheet to determine the supported modes for your device. 5.1.10.4.3.4 Period Modification This section describes Period modification for the different types of Timers (i.e., 8-/16-/32-bit). Description These set of functions help modify the Timer periodicity at the client level, regardless of whether it is an overflow or a period match-based Timer. This interface can be used to alter the already set periodicity at the system level interface DRV_TMR_Initialize. Period Modification Periodicity for the type of Timer (8-/16-/32-bit) can be controlled as follows: • 8-bit timer periodicity can be modified using DRV_TMR_Period8BitSet and the current period value can be obtained using DRV_TMR_Period8BitGet • 16-bit timer periodicity can be modified using DRV_TMR_Period16BitSet and the current period value can be obtained using DRV_TMR_Period16BitGet • 32-bit timer periodicity can be modified using DRV_TMR_Period32BitSet and the current period value can be obtained using DRV_TMR_Period32BitGet Example: DRV_HANDLE handle; /* Open the client */ handle = DRV_TMR_Open( DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE ); /* ... */ 5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library 5-464 /* Update the new period */ DRV_TMR_Period16BitSet( handle, 0x0000