Section II. Hardware Abstraction Layer



Similar documents
1. Overview of Nios II Embedded Development

1. Overview of Nios II Embedded Development

2. Developing Nios II Software

Nios II Software Developer s Handbook

2. Getting Started with the Graphical User Interface

8. Exception Handling

Nios II Classic Software Developer s Handbook

13. Publishing Component Information to Embedded Software

Guidelines for Developing a Nios II HAL Device Driver

Digitale Signalverarbeitung mit FPGA (DSF) Soft Core Prozessor NIOS II Stand Mai Jens Onno Krah

8. Hardware Acceleration and Coprocessing

Nios II IDE Help System

A. Using the Nios II Integrated Development Environment

Using the NicheStack TCP/IP Stack - Nios II Edition Tutorial

Freescale Semiconductor, I

Remote Configuration Over Ethernet with the Nios II Processor

8. MicroC/OS-II Real-Time Operating System

!!! Technical Notes : The One-click Installation & The AXIS Internet Dynamic DNS Service. Table of contents

System Calls and Standard I/O

VxWorks Guest OS Programmer's Guide for Hypervisor 1.1, 6.8. VxWorks GUEST OS PROGRAMMER'S GUIDE FOR HYPERVISOR

Using Nios II Floating-Point Custom Instructions Tutorial

Von der Hardware zur Software in FPGAs mit Embedded Prozessoren. Alexander Hahn Senior Field Application Engineer Lattice Semiconductor

MPLAB Harmony System Service Libraries Help

7. Mentor Graphics PCB Design Tools Support

EE8205: Embedded Computer System Electrical and Computer Engineering, Ryerson University. Multitasking ARM-Applications with uvision and RTX

SKP16C62P Tutorial 1 Software Development Process using HEW. Renesas Technology America Inc.

Application Note: AN00121 Using XMOS TCP/IP Library for UDP-based Networking

VOIP Project: System Design

ENGI E1112 Departmental Project Report: Computer Science/Computer Engineering

Comparing RTOS to Infinite Loop Designs

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Exceptions in MIPS. know the exception mechanism in MIPS be able to write a simple exception handler for a MIPS machine

DS-5 ARM. Using the Debugger. Version 5.7. Copyright 2010, 2011 ARM. All rights reserved. ARM DUI 0446G (ID092311)

ADL User Guide for Open AT V4.10

Notes and terms of conditions. Vendor shall note the following terms and conditions/ information before they submit their quote.

A Design of Video Acquisition and Transmission Based on ARM. Ziqiang Hao a, Hongzuo Li b

Selection Criteria for ZigBee Development Kits

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Red Hat Linux Internals

Linux Driver Devices. Why, When, Which, How?

The Advanced JTAG Bridge. Nathan Yawn 05/12/09

XMOS Programming Guide

Keil C51 Cross Compiler

Adapting the PowerPC 403 ROM Monitor Software for a 512Kb Flash Device

Using C to Access Data Stored in Program Space Memory on the TMS320C24x DSP

A FRAMEWORK FOR AUTOMATIC FUNCTION POINT COUNTING

Real Time Programming: Concepts

DS-5 ARM. Using the Debugger. Version Copyright ARM. All rights reserved. ARM DUI 0446M (ID120712)

FIXED INCOME ATTRIBUTION

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Call Tracking & Google Analytics Integration

Chapter 6, The Operating System Machine Level

UG103.8 APPLICATION DEVELOPMENT FUNDAMENTALS: TOOLS

Operating Systems 4 th Class

Getting Started with Embedded System Development using MicroBlaze processor & Spartan-3A FPGAs. MicroBlaze

December 2002, ver. 1.0 Application Note 285. This document describes the Excalibur web server demonstration design and includes the following topics:

A performance analysis of EtherCAT and PROFINET IRT

How To Understand How A Process Works In Unix (Shell) (Shell Shell) (Program) (Unix) (For A Non-Program) And (Shell).Orgode) (Powerpoint) (Permanent) (Processes

Operating System Manual. Realtime Communication System for netx. Kernel API Function Reference.

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

1 Abstract Data Types Information Hiding

The C Programming Language course syllabus associate level

Software Development Environment

Using the CoreSight ITM for debug and testing in RTX applications

AN 589: Using the Design Security Feature in Cyclone III LS Devices

Automatic Logging of Operating System Effects to Guide Application-Level Architecture Simulation

4. Nios II Command-Line Tools

RN-131-PICTAIL & RN-171-PICTAIL Evaluation Boards

Real-Time Systems Prof. Dr. Rajib Mall Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

THE MODELING AND CALCULATION OF SOUND RADIATION FROM FACILITIES WITH GAS FLOWED PIPES INTRODUCTION

Application Note: AN00141 xcore-xa - Application Development

Chapter 1 Lesson 3 Hardware Elements in the Embedded Systems Chapter-1L03: "Embedded Systems - ", Raj Kamal, Publs.: McGraw-Hill Education

An Introduction To Simple Scheduling (Primarily targeted at Arduino Platform)

10/100/1000Mbps Ethernet MAC with Protocol Acceleration MAC-NET Core with Avalon Interface

AN1229. Class B Safety Software Library for PIC MCUs and dspic DSCs OVERVIEW OF THE IEC STANDARD INTRODUCTION

Example of Standard API

Jorix kernel: real-time scheduling

Serial Communications

ECE487/587 Embedded Systems Laboratory Lab 3: Multiple Device Input/Output Programming

White Paper. Real-time Capabilities for Linux SGI REACT Real-Time for Linux

The Windows NT Device Driver Book: A Guide for Programmers

Altera SoC Embedded Design Suite User Guide

Beam Loss Monitor Software Guide

Implementation of Web-Server Using Altera DE2-70 FPGA Development Kit

Introduction to Embedded Systems. Software Update Problem

Chapter 3: Operating-System Structures. Common System Components

Block 3 Size 0 KB 0 KB 16KB 32KB. Start Address N/A N/A F4000H F0000H. Start Address FA000H F8000H F8000H F8000H. Block 2 Size 8KB 16KB 16KB 16KB

Going Linux on Massive Multicore

Designing a Home Alarm using the UML. And implementing it using C++ and VxWorks

S12XE IPLL Calculator

Programing the Microprocessor in C Microprocessor System Design and Interfacing ECE 362

Applying the Benefits of Network on a Chip Architecture to FPGA System Design

R&S AFQ100A, R&S AFQ100B I/Q Modulation Generator Supplement

The programming language C. sws1 1

Using the TASKING Software Platform for AURIX

Introducing the Adafruit Bluefruit LE Sniffer

Gigabit Ethernet Packet Capture. User s Guide

Combinational-Circuit Building Blocks

Chapter 3: Operating-System Structures. System Components Operating System Services System Calls System Programs System Structure Virtual Machines

Transcription:

Section II. Hardware Abstraction Layer This section describes the Nios II hardware abstraction layer (HAL). It includes the ollowing chapters: Chapter 5, Overview o the Hardware Abstraction Layer Chapter 6, Developing Programs Using the Hardware Abstraction Layer Chapter 7, Developing Device Drivers or the Hardware Abstraction Layer March 2009 Altera Corporation Nios II Sotware Developer s Handbook

II 2 Section II: Hardware Abstraction Layer Nios II Sotware Developer s Handbook March 2009 Altera Corporation

5. Overview o the Hardware Abstraction Layer NII52003-9.0.0 Introduction This chapter introduces the hardware abstraction layer (HAL) or the Nios II processor. This chapter contains the ollowing sections: Getting Started on page 5 1 HAL Architecture on page 5 2 Supported Peripherals on page 5 4 The HAL is a lightweight runtime environment that provides a simple device driver interace or programs to communicate with the underlying hardware. The HAL application program interace (API) is integrated with the ANSI C standard library. The HAL API allows you to access devices and iles using amiliar C library unctions, such as print(), open(), write(), etc. The HAL serves as a device driver package or Nios II processor systems, providing a consistent interace to the peripherals in your system. Tight integration between SOPC Builder and the Nios II sotware development tools automates the construction o a HAL instance or your hardware. Ater SOPC Builder generates a hardware system, the Nios II integrated development environment (IDE) or the Nios II sotware build tools can generate a custom HAL board support package (BSP) to match the hardware coniguration. Changes in the hardware coniguration automatically propagate to the HAL device driver coniguration, preventing changes in the underlying hardware rom creating bugs. HAL device driver abstraction provides a clear distinction between application and device driver sotware. This driver abstraction promotes reusable application code that is resistant to changes in the underlying hardware. In addition, the HAL standard makes it straightorward to write drivers or new hardware peripherals that are consistent with existing peripheral drivers. Getting Started The easiest way to get started using the HAL is to perorm the tutorials provided with the Nios II IDE. In the process o creating a new project in the Nios II IDE, you also create a HAL BSP. You need not create or copy HAL iles, and you need not edit any o the HAL source code. The Nios II IDE generates the HAL BSP or you. In the Nios II sotware build tools command-line sotware build tools low, you can create an example BSP based on the HAL using one o the create-this-bsp scripts supplied with the Nios II embedded design suite. You must base the HAL on a speciic SOPC Builder system. An SOPC Builder system is a Nios II processor core integrated with peripherals and memory (which is generated by SOPC Builder). I you do not have a custom SOPC Builder system, you can base your project on an Altera-provided example hardware system. In act, you can irst start developing projects targeting an Altera Nios development board, and later re-target the project to a custom board. You can easily change the target SOPC Builder system later. March 2009 Altera Corporation Nios II Sotware Developer s Handbook

5 2 Chapter 5: Overview o the Hardware Abstraction Layer HAL Architecture For inormation about creating a new project with the Nios II IDE, reer to the Nios II Integrated Development Environment chapter o the Nios II Sotware Developer s Handbook, or to the Nios II IDE help system. For inormation about creating a new project with the Nios II sotware build tools, reer to the Introduction to the Nios II Sotware Build Tools chapter o the Nios II Sotware Developer s Handbook. More inormation about creating a Nios II IDE project is available in the Nios II IDE help system. HAL Architecture This section describes the undamental elements o the HAL architecture. Services The HAL provides the ollowing services: Integration with the newlib ANSI C standard library Provides the amiliar C standard library unctions Device drivers Provides access to each device in the system The HAL API Provides a consistent, standard interace to HAL services, such as device access, interrupt handling, and alarm acilities System initialization Perorms initialization tasks or the processor and the runtime environment beore main() Device initialization Instantiates and initializes each device in the system beore main() runs Figure 5 1 shows the layers o a HAL-based system, rom the hardware level up to a user program. Figure 5 1. The Layers o a HAL-Based System User Program C Standard Library HAL API Device Driver Device Driver... Device Driver Nios II Processor System Hardware Nios II Sotware Developer s Handbook March 2009 Altera Corporation

Chapter 5: Overview o the Hardware Abstraction Layer 5 3 HAL Architecture Applications versus Drivers Application developers are responsible or writing the system s main() routine, among other routines. Applications interact with system resources either through the C standard library, or through the HAL API. Device driver developers are responsible or making device resources available to application developers. Device drivers communicate directly with hardware through low-level hardware-access macros. For urther details about the HAL, reer to the ollowing chapters: The Developing Programs Using the Hardware Abstraction Layer chapter o the Nios II Sotware Developer s Handbook describes how to take advantage o the HAL to write programs without considering the underlying hardware. The Developing Device Drivers or the Hardware Abstraction Layer chapter o the Nios II Sotware Developer s Handbook describes how to communicate directly with hardware and how to make hardware resources available with the HAL API. Generic Device Models The HAL provides generic device models or classes o peripherals ound in embedded systems, such as timers, Ethernet MAC/PHY chips, and I/O peripherals that transmit character data. The generic device models are at the core o the HAL s power. The generic device models allow you to write programs using a consistent API, regardless o the underlying hardware. Device Model Classes The HAL provides models or the ollowing classes o devices: Character-mode devices Hardware peripherals that send and/or receive characters serially, such as a UART. Timer devices Hardware peripherals that count clock ticks and can generate periodic interrupt requests. File subsystems A mechanism or accessing iles stored in physical device(s). Depending on the internal implementation, the ile subsystem driver might access the underlying device(s) directly or use a separate device driver. For example, you can write a lash ile subsystem driver that accesses lash using the HAL API or lash memory devices. Ethernet devices Devices that provide access to an Ethernet connection or a networking stack such as the Altera-provided NicheStack TCP/IP Stack - Nios II Edition. You need a networking stack to use an ethernet device. Direct memory access (DMA) devices Peripherals that perorm bulk data transactions rom a data source to a destination. Sources and destinations can be memory or another device, such as an Ethernet connection. Flash memory devices Nonvolatile memory devices that use a special programming protocol to store data. March 2009 Altera Corporation Nios II Sotware Developer s Handbook

5 4 Chapter 5: Overview o the Hardware Abstraction Layer Supported Hardware C Standard Library Newlib Supported Hardware Nios II Processor Core Support Supported Peripherals Beneits to Application Developers The HAL deines a set o unctions that you use to initialize and access each class o device. The API is consistent, regardless o the underlying implementation o the device hardware. For example, to access character-mode devices and ile subsystems, you can use the C standard library unctions, such as print() and open(). For application developers, you need not write low-level routines just to establish basic communication with the hardware or these classes o peripherals. Beneits to Device Driver Developers Each device model deines a set o driver unctions necessary to manipulate the particular class o device. I you are writing drivers or a new peripheral, you need only provide this set o driver unctions. As a result, your driver development task is predeined and well documented. In addition, you can use existing HAL unctions and applications to access the device, which saves sotware development eort. The HAL calls driver unctions to access hardware. Application programmers call the ANSI C or HAL API to access hardware, rather than calling your driver routines directly. Thereore, the usage o your driver is already documented as part o the HAL API. The HAL integrates the ANSI C standard library in its runtime environment. The HAL uses newlib, an open-source implementation o the C standard library. newlib is a C library or use on embedded systems, making it a perect match or the HAL and the Nios II processor. newlib licensing does not require you to release your source code or pay royalties or projects based on newlib. The ANSI C standard library is well documented. Perhaps the most well-known reerence is The C Programming Language by B. Kernighan and D. Ritchie, published by Prentice Hall and available in over 20 languages. Redhat also provides online documentation or newlib at http://sources.redhat.com/newlib. This section summarizes Nios II HAL support or Nios II hardware. The Nios II HAL supports all available Nios II processor core implementations. Altera provides many peripherals or use in Nios II processor systems. Most Altera peripherals provide HAL device drivers that allow you to access the hardware with the HAL API. The ollowing Altera peripherals provide ull HAL support: Character mode devices UART core JTAG UART core LCD 16207 display controller Nios II Sotware Developer s Handbook March 2009 Altera Corporation

Chapter 5: Overview o the Hardware Abstraction Layer 5 5 Supported Hardware Flash memory devices Common lash interace compliant lash chips Altera s erasable programmable conigurable serial (EPCS) serial coniguration device controller File subsystems Altera host based ile system Altera read-only zip ile system Timer devices Timer core DMA devices DMA controller core Scatter-gather DMA controller core Ethernet devices Triple Speed Ethernet MegaCore unction LAN91C111 Ethernet MAC/PHY Controller The LAN91C111 and Triple Speed Ethernet components require the MicroC/OS-II runtime environment. For more inormation, reer to the Ethernet and the NicheStack TCP/IP Stack - Nios II Edition chapter o the Nios II Sotware Developer s Handbook. Third-party vendors oer additional peripherals not listed here. For a list o other peripherals available or the Nios II processor, visit the Embedded Sotware page o the Altera website. All peripherals (both rom Altera and third party vendors) must provide a header ile that deines the peripheral s low-level interace to hardware. Thereore, all peripherals support the HAL to some extent. However, some peripherals might not provide device drivers. I drivers are not available, use only the deinitions provided in the header iles to access the hardware. Do not use unnamed constants, such as hard-coded addresses, to access a peripheral. Inevitably, certain peripherals have hardware-speciic eatures with usage requirements that do not map well to a general-purpose API. The HAL handles hardware-speciic requirements by providing the UNIX-style ioctl() unction. Because the hardware eatures depend on the peripheral, the ioctl() options are documented in the description or each peripheral. Some peripherals provide dedicated accessor unctions that are not based on the HAL generic device models. For example, Altera provides a general-purpose parallel I/O (PIO) core or use with the Nios II processor system. The PIO peripheral does not it in any class o generic device models provided by the HAL, and so it provides a header ile and a ew dedicated accessor unctions only. For complete details regarding sotware support or a peripheral, reer to the peripheral s description. For urther details about Altera-provided peripherals, reer to Volume 5: Embedded Peripherals o the Quartus II Handbook. March 2009 Altera Corporation Nios II Sotware Developer s Handbook

5 6 Chapter 5: Overview o the Hardware Abstraction Layer Reerenced Documents MPU Support MMU Support The HAL does not include explicit support or the optional memory protection unit (MPU) hardware. However, it does support an advanced exception handler that can handle Nios II MPU exceptions. For details about handling MPU and other advanced exceptions, reer to the Exception Handling chapter o the Nios II Sotware Developer s Handbook. For details about the MPU hardware implementation, reer to the Programming Model chapter o the Nios II Processor Reerence Handbook. The HAL does not support the optional memory management unit (MMU) hardware. To use the MMU, you need to implement a ull-eatured operating system. For details about the Nios II MMU, reer to the Programming Model chapter o the Nios II Processor Reerence Handbook. Reerenced Documents Document Revision History This chapter reerences the ollowing documents: Nios II Integrated Development Environment chapter o the Nios II Sotware Developer s Handbook Introduction to the Nios II Sotware Build Tools chapter o the Nios II Sotware Developer s Handbook Developing Programs Using the Hardware Abstraction Layer chapter o the Nios II Sotware Developer s Handbook Developing Device Drivers or the Hardware Abstraction Layer chapter o the Nios II Sotware Developer s Handbook Exception Handling chapter o the Nios II Sotware Developer s Handbook Ethernet and the NicheStack TCP/IP Stack - Nios II Edition chapter o the Nios II Sotware Developer s Handbook Programming Model chapter o the Nios II Processor Reerence Handbook Volume 5: Embedded Peripherals o the Quartus II Handbook The Embedded Sotware page o the Altera website Table 5 1 shows the revision history or this document. Nios II Sotware Developer s Handbook March 2009 Altera Corporation

Chapter 5: Overview o the Hardware Abstraction Layer 5 7 Document Revision History Table 5 1. Document Revision History Date & Document Version Changes Made Summary o Changes March 2009 v9.0.0 Reorganized and updated inormation and terminology to clariy role o Nios II sotware build tools. Corrected minor typographical errors. May 2008 No change rom previous release. v8.0.0 October 2007 v7.2.0 May 2007 v7.1.0 March 2007 v7.0.0 November 2006 v6.1.0 May 2006 v6.0.0 October 2005 v5.1.0 May 2005 v5.0.0 May 2004 v1.0 No change rom previous release. Scatter-gather DMA core Triple-speed Ethernet MAC Reer to HAL generation with Nios II sotware build tools. Added table o contents to Introduction section. Added Reerenced Documents section. No change rom previous release. NicheStack TCP/IP Stack - Nios II Edition No change rom previous release. No change rom previous release. No change rom previous release. Initial Release. Scatter-gather DMA core Triple-speed Ethernet MAC Nios II sotware build tools March 2009 Altera Corporation Nios II Sotware Developer s Handbook

5 8 Chapter 5: Overview o the Hardware Abstraction Layer Document Revision History Nios II Sotware Developer s Handbook March 2009 Altera Corporation

6. Developing Programs Using the Hardware Abstraction Layer NII52004-9.0.0 Introduction This chapter discusses how to develop programs or the Nios II processor based on the Altera hardware abstraction layer (HAL). This chapter contains the ollowing sections: The Nios II Project Structure on page 6 2 The system.h System Description File on page 6 4 Data Widths and the HAL Type Deinitions on page 6 5 UNIX-Style Interace on page 6 5 File System on page 6 6 Using Character-Mode Devices on page 6 8 Using File Subsystems on page 6 15 Using Timer Devices on page 6 15 Using Flash Devices on page 6 19 Using DMA Devices on page 6 24 Reducing Code Footprint on page 6 29 Boot Sequence and Entry Point on page 6 36 Memory Usage on page 6 38 Working with HAL Source Files on page 6 43 Using the HAL in an IDE Project on page 6 44 The application program interace (API) or HAL-based systems is readily accessible to sotware developers who are new to the Nios II processor. Programs based on the HAL use the ANSI C standard library unctions and runtime environment, and access hardware resources with the HAL API s generic device models. The HAL API largely conorms to the amiliar ANSI C standard library unctions, though the ANSI C standard library is separate rom the HAL. The close integration o the ANSI C standard library and the HAL makes it possible to develop useul programs that never call the HAL unctions directly. For example, you can manipulate character mode devices and iles using the ANSI C standard library I/O unctions, such as print() and scan(). This document does not cover the ANSI C standard library. An excellent reerence is The C Programming Language, Second Edition, by Brian Kernighan and Dennis M. Ritchie (Prentice-Hall). March 2009 Altera Corporation Nios II Sotware Developer s Handbook

6 2 Chapter 6: Developing Programs Using the Hardware Abstraction Layer The Nios II Project Structure Nios II Development Flows HAL BSP Settings The Nios II Embedded Design Suite (EDS) provides two distinct development lows or creating Nios II programs. You can work entirely in the Nios II integrated development environment (IDE), or you can use the Nios II sotware build tools in command-line and scripted environments. Every Nios II board support package (BSP) has settings that determine the BSP s characteristics. For example, HAL BSPs have settings to identiy the hardware components associated with standard devices such as stdout. Deining and manipulating BSP settings is an important part o Nios II project creation. How you manipulate BSP settings depends on the development low you use. In the command-line sotware build tools low, you manipulate BSP settings with command-line options or Tcl scripts. For details about how to control BSP settings, reer to one or more o the ollowing documents: For the Nios II IDE development low, reer to the Nios II IDE help system. For the Nios II command-line sotware build tools development low, reer to the Using the Nios II Sotware Build Tools chapter o the Nios II Sotware Developer s Handbook. For detailed descriptions o available BSP settings, reer to the Nios II Sotware Build Tools Reerence chapter o the Nios II Sotware Developer s Handbook. Many HAL settings are relected in the system.h ile, which provides a helpul reerence or details about your BSP. For inormation about system.h, reer to The system.h System Description File on page 6 4. 1 Do not edit system.h. The Nios II EDS provides tools to manipulate system settings. The Nios II Project Structure The creation and management o sotware projects based on the HAL is integrated tightly with the Nios II sotware build tools. This section discusses the Nios II projects as a basis or understanding the HAL. Figure 6 1 shows the blocks o a Nios II program with emphasis on how the HAL BSP its in. The label or each block describes what or who generated that block, and an arrow points to each block s dependency. Nios II Sotware Developer s Handbook March 2009 Altera Corporation

Chapter 6: Developing Programs Using the Hardware Abstraction Layer 6 3 The Nios II Project Structure Figure 6 1. The Nios II HAL Project Structure Nios II Program Based on HAL Application Project Also known as: Your program, or user project Deined by:.c,.h,.s,.s iles Created by: You HAL BSP Project Deined by: Nios II BSP settings Created by: Nios II IDE or Nios II command line tools SOPC Builder System Also known as: Nios II processor system, or the hardware Deined by:.sopcino ile Created by: SOPC Builder Every HAL-based Nios II program consists o two Nios II projects, as shown in Figure 6 1. Your application-speciic code is contained in one project (the user application project), and it depends on a separate BSP project (the HAL BSP). The application project contains all the code you develop. The executable image or your program ultimately results rom building both projects. In the Nios II IDE low, the Nios II IDE creates the HAL BSP project when you create your application project. In the Nios II command-line sotware build tools low, you create the BSP using nios2-bsp or a related tool. The HAL BSP project contains all inormation needed to interace your program to the hardware. The HAL drivers relevant to your SOPC Builder system are incorporated in the BSP project. The BSP project depends on the SOPC Builder system, deined by an SOPC Builder system (.sopcino) ile.the Nios II sotware build tools can keep your BSP up-to-date with the SOPC Builder system. This project dependency structure isolates your program rom changes to the underlying hardware, and you can develop and debug code without concern about whether your program matches the target hardware. When you rebuild a BSP, the Nios II sotware build tools can update it to match the hardware. You control whether and when these updates occur. For details about how the sotware build tools keep your BSP up-to-date with your hardware system, reer to the Using the Nios II Sotware Build Tools chapter o the Nios II Sotware Developer s Handbook. In summary, when your program is based on a HAL BSP, you can always keep it synchronized with the target hardware by simply rebuilding your sotware. March 2009 Altera Corporation Nios II Sotware Developer s Handbook

6 4 Chapter 6: Developing Programs Using the Hardware Abstraction Layer The system.h System Description File The system.h System Description File The system.h ile provides a complete sotware description o the Nios II system hardware. Not all inormation in system.h is useul to you as a programmer, and it is rarely necessary to include it explicitly in your C source iles. Nonetheless, system.h holds the answer to the question, What hardware is present in this system? The system.h ile describes each peripheral in the system and provides the ollowing details: The hardware coniguration o the peripheral The base address The interrupt request (IRQ) priority (i any) A symbolic name or the peripheral Both Nios II development lows generate the system.h ile or HAL BSP projects. The contents o system.h depend on both the hardware coniguration and the HAL BSP properties. 1 Do not edit system.h. Both development lows provide tools to manipulate system settings. For details about how to control BSP settings, reer to HAL BSP Settings on page 6 2. The code in Example 6 1 rom a system.h ile shows some o the hardware coniguration options this ile deines. Example 6 1. Excerpts rom a system.h File /* * sys_clk_timer coniguration * */ #deine SYS_CLK_TIMER_NAME "/dev/sys_clk_timer" #deine SYS_CLK_TIMER_TYPE "altera_avalon_timer" #deine SYS_CLK_TIMER_BASE 0x00920800 #deine SYS_CLK_TIMER_IRQ 0 #deine SYS_CLK_TIMER_ALWAYS_RUN 0 #deine SYS_CLK_TIMER_FIXED_PERIOD 0 /* * jtag_uart coniguration * */ #deine JTAG_UART_NAME "/dev/jtag_uart" #deine JTAG_UART_TYPE "altera_avalon_jtag_uart" #deine JTAG_UART_BASE 0x00920820 #deine JTAG_UART_IRQ 1 Nios II Sotware Developer s Handbook March 2009 Altera Corporation

Chapter 6: Developing Programs Using the Hardware Abstraction Layer 6 5 Data Widths and the HAL Type Deinitions Data Widths and the HAL Type Deinitions For embedded processors such as the Nios II processor, it is oten important to know the exact width and precision o data. Because the ANSI C data types do not explicitly deine data width, the HAL uses a set o standard type deinitions instead. The ANSI C types are supported, but their data widths are dependent on the compiler s convention. The header ile alt_types.h deines the HAL type deinitions; Table 6 1 shows the HAL type deinitions. Table 6 1. The HAL Type Deinitions Type alt_8 alt_u8 alt_16 alt_u16 alt_32 alt_u32 alt_64 alt_u64 Signed 8-bit integer. Unsigned 8-bit integer. Signed 16-bit integer. Unsigned 16-bit integer. Signed 32-bit integer. Unsigned 32-bit integer. Signed 64-bit integer. Unsigned 64-bit integer. Meaning Table 6 2 shows the data widths that the Altera-provided GNU tool-chain uses. Table 6 2. GNU Toolchain Data Widths Type char short long int 8 bits. 16 bits. 32 bits. 32 bits. Meaning UNIX-Style Interace The HAL API provides a number o UNIX-style unctions. The UNIX-style unctions provide a amiliar development environment or new Nios II programmers, and can ease the task o porting existing code to run in the HAL environment. The HAL uses these unctions primarily to provide the system interace or the ANSI C standard library. For example, the unctions perorm device access required by the C library unctions deined in stdio.h. The ollowing list contains all o the available UNIX-style unctions: _exit() close() stat() getpid() gettimeoday() March 2009 Altera Corporation Nios II Sotware Developer s Handbook

6 6 Chapter 6: Developing Programs Using the Hardware Abstraction Layer File System ioctl() isatty() kill() lseek() open() read() sbrk() settimeoday() stat() usleep() wait() write() The most commonly used unctions are those that relate to ile I/O. Reer to File System on page 6 6. File System For details about the use o these unctions, reer to the HAL API Reerence chapter o the Nios II Sotware Developer s Handbook. The HAL provides inrastructure or UNIX-style ile access. You can use this inrastructure to build a ile system on any storage devices available in your hardware. For an example, reer to the Read-Only Zip File System chapter o the Nios II Sotware Developer s Handbook. You can access iles in a HAL-based ile system by using either the C standard library ile I/O unctions in the newlib C library (or example open(), close(), and read()), or using the UNIX-style ile I/O provided by the HAL. The HAL provides the ollowing UNIX-style unctions or ile manipulation: close() stat() ioctl() isatty() lseek() open() read() stat() write() Nios II Sotware Developer s Handbook March 2009 Altera Corporation

Chapter 6: Developing Programs Using the Hardware Abstraction Layer 6 7 File System For more inormation about these unctions, reer to the HAL API Reerence chapter o the Nios II Sotware Developer s Handbook. The HAL registers a ile subsystem as a mount point in the global HAL ile system. Attempts to access iles below that mount point are directed to the ile subsystem. For example, i a read-only zip ile subsystem (zips) is mounted as /mount/zips0, the zips ile subsystem handles calls to open() or /mount/zips0/myile. There is no concept o a current directory. Sotware must access all iles using absolute paths. The HAL ile inrastructure also allows you to manipulate character mode devices with UNIX-style path names. The HAL registers character mode devices as nodes in the HAL ile system. By convention, system.h deines the name o a device node as the preix /dev/ plus the name assigned to the hardware component in SOPC builder. For example, a UART peripheral uart1 in SOPC builder is /dev/uart1 in system.h. The code in Example 6 2 reads characters rom a read-only zip ile subsystem rozips that is registered as a node in the HAL ile system. The standard header iles stdio.h, stdde.h, and stdlib.h are installed with the HAL. Example 6 2. Reading Characters rom a File Subsystem #include <stdio.h> #include <stdde.h> #include <stdlib.h> #deine BUF_SIZE (10) int main(void) { FILE* p; char buer[buf_size]; p = open ("/mount/rozips/test", "r"); { print ("Cannot open ile.\n"); exit (1); } i (p == NULL) read (buer, BUF_SIZE, 1, p); close (p); return 0; } For more inormation about the use o these unctions, reer to the newlib C library documentation installed with the Nios II EDS. On the Windows Start menu, click Programs > Altera > Nios II > Nios II Documentation. March 2009 Altera Corporation Nios II Sotware Developer s Handbook

6 8 Chapter 6: Developing Programs Using the Hardware Abstraction Layer Using Character-Mode Devices Using Character-Mode Devices A character-mode device is a hardware peripheral that sends and/or receives characters serially. A common example is the UART. Character mode devices are registered as nodes in the HAL ile system. In general, a program associates a ile descriptor to a device s name, and then writes and reads characters to or rom the ile using the ANSI C ile operations deined in ile.h. The HAL also supports the concept o standard input, standard output, and standard error, allowing programs to call the stdio.h I/O unctions. Standard Input, Standard Output and Standard Error Using standard input (stdin), standard output (stdout), and standard error (stderr) is the easiest way to implement simple console I/O. The HAL manages stdin, stdout, and stderr behind the scenes, which allows you to send and receive characters through these channels without explicitly managing ile descriptors. For example, the HAL directs the output o print() to standard out, and perror() to standard error. You associate each channel to a speciic hardware device by manipulating BSP settings. The code in Example 6 3 shows the classic Hello World program. This program sends characters to whatever device is associated with stdout when the program is compiled. Example 6 3. Hello World #include <stdio.h> int main () { print ("Hello world!"); return 0; } When using the UNIX-style API, you can use the ile descriptors stdin, stdout, and stderr, deined in unistd.h, to access, respectively, the standard in, standard out, and standard error character I/O streams. unistd.h is installed with the Nios II EDS as part o the newlib C library package. General Access to Character Mode Devices Accessing a character-mode device other than stdin, stdout, or stderr is as easy as opening and writing to a ile. The code in Example 6 4 writes a message to a UART called uart1. Nios II Sotware Developer s Handbook March 2009 Altera Corporation

Chapter 6: Developing Programs Using the Hardware Abstraction Layer 6 9 Using Character-Mode Devices Example 6 4. Writing Characters to a UART #include <stdio.h> #include <string.h> int main (void) { char* msg = "hello world"; FILE* p; } p = open ("/dev/uart1", "w"); i (p!=null) { print(p, "%s",msg); close (p); } return 0; C++ Streams /dev/null HAL-based systems can use the C++ streams API or manipulating iles rom C++. All systems include the device /dev/null. Writing to /dev/null has no eect, and all data is discarded. /dev/null is used or sae I/O redirection during system startup. This device can also be useul or applications that wish to sink unwanted data. This device is purely a sotware construct. It does not relate to any physical hardware device in the system. Lightweight Character-Mode I/O Altera Logging Functions The HAL oers several methods o reducing the code ootprint o character-mode device drivers. For details, reer to Reducing Code Footprint on page 6 29. The Altera logging unctions provide a separate channel or sending logging and debugging inormation to a character-mode device, supplementing stdout and stderr. The Altera logging inormation can be printed in response to several conditions. Altera logging can be enabled and disabled independently o any normal stdio output, making it a powerul debugging tool. When Altera logging is enabled, your sotware can print extra messages to a speciied port with HAL unction calls. The logging port, speciied in the BSP, can be a UART or a JTAG UART device. In its deault coniguration, Altera logging prints out boot messages, which trace each step o the boot process. 1 Avoid setting the Altera logging device to the device used or stdout or stderr. I Altera logging output is sent to stdout or stderr, the logging output might appear interleaved with the stdout or stderr output March 2009 Altera Corporation Nios II Sotware Developer s Handbook

6 10 Chapter 6: Developing Programs Using the Hardware Abstraction Layer Using Character-Mode Devices Several logging options are available, controlled by C preprocessor symbols. You can also choose to add custom logging messages. 1 Altera logging changes system behavior. The logging implementation is designed to be as simple as possible, loading characters directly to the transmit register. It can have a negative impact on sotware perormance. Altera logging unctions are conditionally compiled. When logging is disabled, it has no impact on code ootprint or perormance. 1 The Altera reduced device drivers do not support Altera logging. Enabling Altera Logging The Nios II sotware build tools have a setting to enable Altera logging. The setting is called hal.log_port. It is similar to hal.stdout, hal.stdin, and hal.stderr. To enable Altera logging, you set hal.log_port to a JTAG UART or a UART device. The setting allows the HAL to send log messages to the speciied device when a logging macro is invoked. When Altera logging is enabled, the Nios II sotware build tools deine ALT_LOG_ENABLE in public.mk to enable log messages. The build tools also set the ALT_LOG_PORT_TYPE and ALT_LOG_PORT_BASE values in system.h to point to the speciied device. When Altera logging is enabled without special options, the HAL prints out boot messages to the selected port. For typical sotware that uses the standard alt_main.c (such as the Hello World sotware example), the messages appear as in Example 6 5. Example 6 5. Deault Boot Logging Output [crt0.s] Inst & Data Cache Initialized. [crt0.s] Setting up stack and global pointers. [crt0.s] Clearing BSS [crt0.s] Calling alt_main. [alt_main.c] Entering alt_main, calling alt_irq_init. [alt_main.c] Done alt_irq_init, calling alt_os_init. [alt_main.c] Done OS Init, calling alt_sem_create. [alt_main.c] Calling alt_sys_init. [alt_main.c] Done alt_sys_init. Redirecting IO. [alt_main.c] Calling C++ constructors. [alt_main.c] Calling main. [alt_exit.c] Entering _exit() unction. [alt_exit.c] Exit code rom main was 0. [alt_exit.c] Calling ALT_OS_STOP(). [alt_exit.c] Calling ALT_SIM_HALT(). [alt_exit.c] Spinning orever. 1 A write operation to the Altera logging device stalls in ALT_LOG_PRINTF() until the characters are read rom the Altera logging device's output buer. To ensure that the Nios II application completes initialization, run the nios2-terminal command rom the Nios II command shell to accept the Altera logging output. Nios II Sotware Developer s Handbook March 2009 Altera Corporation

Chapter 6: Developing Programs Using the Hardware Abstraction Layer 6 11 Using Character-Mode Devices Extra Logging Options In addition to the deault boot messages, logging options are incorporated in Altera logging. Each option is controlled by a C preprocessor symbol. The details o each option are outlined in Table 6 3. Table 6 3. Altera Logging Options (Part 1 o 2) Name Description System clock log Purpose Prints out a message rom the system clock interrupt handler at a speciied interval. This indicates that the system is still running. The deault interval is every 1 second. Preprocessor ALT_LOG_SYS_CLK_ON_FLAG_SETTING symbol Modiiers The system clock log has two modiiers, providing two dierent ways to speciy the logging interval. ALT_LOG_SYS_CLK_INTERVAL Speciies the logging interval in system clock ticks. The deault is <clock ticks per second>, that is, one second. ALT_LOG_SYS_CLK_INTERVAL_MULTIPLIER Speciies the logging interval in seconds. The deault is 1. When you modiy ALT_LOG_SYS_CLK_INTERVAL_MULTIPLIER, ALT_LOG_SYS_CLK_INTERVAL is recalculated. Sample Output System Clock On 0 System Clock On 1 Write echo Purpose Every time alt_write() is called (normally, whenever characters are sent to stdout), the irst <n> characters are echoed to a logging message. The message starts with the string "Write Echo:". <n> is speciied with ALT_LOG_WRITE_ECHO_LEN. The deault is 15 characters. Preprocessor ALT_LOG_WRITE_ON_FLAG_SETTING symbol Modiiers ALT_LOG_WRITE_ECHO_LEN Number o characters to echo. Deault is 15. Sample Output Write Echo: Hello rom Nio JTAG startup log Purpose At JTAG UART driver initialization, print out a line with the number o characters in the sotware transmit buer ollowed by the JTAG UART control register contents. The number o characters, preaced by the string "SW CirBu", might be negative, because it is computed as (<tail_pointer> - <head_pointer>) on a circular buer. For more inormation about the JTAG UART control register ields, reer to the O-Chip Interace Peripherals section in Volume 5: Embedded Peripherals o the Quartus II Handbook. Preprocessor ALT_LOG_JTAG_UART_STARTUP_INFO_ON_FLAG_SETTING symbol Modiiers None Sample Output JTAG Startup Ino: SW CirBu = 0, HW FIFO wspace=64 AC=0 WI=0 RI=0 WE=0 RE=1 March 2009 Altera Corporation Nios II Sotware Developer s Handbook

6 12 Chapter 6: Developing Programs Using the Hardware Abstraction Layer Using Character-Mode Devices Table 6 3. Altera Logging Options (Part 2 o 2) Name JTAG interval log Purpose Creates an alarm object to print out the same JTAG UART inormation as the JTAG startup log, but at a repeated interval. Deault interval is 0.1 second, or 10 messages a second. Preprocessor ALT_LOG_JTAG_UART_ALARM_ON_FLAG_SETTING symbol Modiiers The JTAG interval log has two modiiers, providing two dierent ways to speciy the logging interval. ALT_LOG_JTAG_UART_TICKS Logging interval in ticks. Deault is <ticks_per_second> / 10. JTAG interrupt service routine (ISR) log Sample Output Purpose Preprocessor symbol Modiiers Sample Output ALT_LOG_JTAG_UART_TICKS_DIVISOR Speciies the number o logs per second. The deault is 10. When you modiy ALT_LOG_JTAG_UART_TICKS_DIVISOR, ALT_LOG_JTAG_UART_TICKS is recalculated. JTAG Alarm: SW CirBu = 0, HW FIFO wspace=45 AC=0 WI=0 RI=0 WE=0 RE=1 Prints out a message every time the JTAG UART near-empty interrupt triggers. Message contains the same JTAG UART inormation as in the JTAG startup log. ALT_LOG_JTAG_UART_ISR_ON_FLAG_SETTING None Description JTAG IRQ: SW CirBu = -20, HW FIFO wspace=64 AC=0 WI=1 RI=0 WE=1 RE=1 Boot log Purpose Prints out messages tracing the sotware boot process. The boot log is turned on by deault when Altera logging is enabled. Preprocessor ALT_LOG_BOOT_ON_FLAG_SETTING symbol Modiiers None Sample Output Reer to Enabling Altera Logging on page 6 10. Setting a preprocessor lag to 1 enables the corresponding option. Any value other than 1 disables the option. Several options have modiiers, which are additional preprocessor symbols controlling details o how the options work. For example, the system clock log s modiiers control the logging interval. Option modiiers are also listed in Table 6 3. An option s modiiers are meaningul only when the option is enabled. Nios II Sotware Developer s Handbook March 2009 Altera Corporation

Chapter 6: Developing Programs Using the Hardware Abstraction Layer 6 13 Using Character-Mode Devices Logging Levels An additional preprocessor symbol, ALT_LOG_FLAGS, can be set to provide some grouping or the extra logging options. ALT_LOG_FLAGS implements logging levels based on perormance impact. With higher logging levels, the Altera logging options take more processor time. ALT_LOG_FLAGS levels are deined in Table 6 4 Table 6 4. Altera Logging Levels Because each logging option is controlled by an independent preprocessor symbol, individual options in the logging levels can be overridden. Example: Creating a BSP with Logging Example 6 6 creates a HAL BSP with Altera logging enabled and the ollowing options in addition to the deault boot log: Logging Level Logging 0 Boot log (deault) 1 Level 0 plus system clock log and JTAG startup log 2 Level 1 plus JTAG interval log and write echo 3 Level 2 plus JTAG ISR log -1 Silent mode No Altera logging Note to Table 6 4: (1) You can use logging level -1 to turn o logging without changing the program ootprint. The logging code is still present in your executable image, as determined by other logging options chosen. This is useul when you wish to switch the log output on or o without disturbing the memory map. System clock log JTAG startup log JTAG interval log, logging twice a second No write echo Example 6 6. BSP With Logging nios2-bsp hal my_bsp../my_hardware.sopcino \ --set hal.log_port uart1 \ --set hal.make.bsp_clags_user_lags \ -DALT_LOG_FLAGS=2 \ -DALT_LOG_WRITE_ON_FLAG_SETTING=0 \ -DALT_LOG_JTAG_UART_TICKS_DIVISOR=2r The -DALT_LOG_FLAGS=2 argument adds -DALT_LOG_FLAGS=2 to the ALT_CPP_FLAGS make variable in public.mk. Custom Logging Messages You can add custom messages that are sent to the Altera logging device. To deine a custom message, include the header ile alt_log_print.h in your C source ile as ollows: #include "sys/alt_log_print.h" Then use the ollowing macro unction: ALT_LOG_PRINTF(const char *ormat,...) March 2009 Altera Corporation Nios II Sotware Developer s Handbook

6 14 Chapter 6: Developing Programs Using the Hardware Abstraction Layer Using Character-Mode Devices This C preprocessor macro is a pared-down version o print(). The ormat argument supports most print() options. It supports %c, %d, %I, %o, %s, %u, %x, and %X, as well as some precision and spacing modiiers, such as %-9.3o. It does not support loating point ormats, such as % or %g. This unction is not compiled i Altera logging is not enabled. I you want your custom logging message be controlled by Altera logging preprocessor options, use the appropriate Altera logging option preprocessor lags rom Table 6 4, or Table 6 3 on page 6 11. Example 6 7 illustrates two ways to implement logging options with custom logging messages. Example 6 7. Using Preprocessor Flags /* The ollowing example prints "Level 2 logging message" i logging is set to level 2 or higher */ #i ( ALT_LOG_FLAGS >= 2 ) ALT_LOG_PRINTF ( "Level 2 logging message" ); #endi /* The ollowing example prints "Boot logging message" i boot logging is turned on */ #i ( ALT_LOG_BOOT_ON_FLAG_SETTING == 1) ALT_LOG_PRINTF ( "Boot logging message" ); #endi Altera Logging Files Table 6 5 lists HAL source iles which implement Altera logging unctions. Table 6 5. HAL Implementation Files or Altera Logging Location (1) components/altera_hal/hal/inc/sys/ components/altera_hal/hal/src/ components/altera_nios2/hal/src/ Note to Table 6 5: (1) All ile locations are relative to $SOPC_KIT_NIOS2. File Name alt_log_print.h alt_log_print.c alt_log_macro.s Table 6 6 lists HAL source iles which use Altera logging unctions. These iles implement the logging options listed in table Table 6 3 on page 6 11. They also serve as examples o logging usage. Nios II Sotware Developer s Handbook March 2009 Altera Corporation

Chapter 6: Developing Programs Using the Hardware Abstraction Layer 6 15 Using File Subsystems Table 6 6. HAL Example Files or Altera Logging Location (1) components/altera_avalon_jtag_uart/hal/src/ components/altera_avalon_timer/hal/src/ components/altera_hal/hal/src/ components/altera_hal/hal/src/ components/altera_hal/hal/src/ components/altera_nios2/hal/src/ Note to Table 6 6: (1) All ile locations are relative to $SOPC_KIT_NIOS2. File Name altera_avalon_jtag_uart.c altera_avalon_timer_sc.c alt_exit.c alt_main.c alt_write.c crt0.s Using File Subsystems The HAL generic device model or ile subsystems allows access to data stored in an associated storage device using the C standard library ile I/O unctions. For example, the Altera read-only zip ile system provides read-only access to a ile system stored in lash memory. A ile subsystem is responsible or managing all ile I/O access beneath a given mount point. For example, i a ile subsystem is registered with the mount point /mnt/ rozips, all ile access beneath this directory, such as open("/mnt/rozips/ myile", "r"), is directed to that ile subsystem. As with character mode devices, you can manipulate iles in a ile subsystem using the C ile I/O unctions deined in ile.h, such as open() and read(). For more inormation about the use o these unctions, reer to the newlib C library documentation installed with the Nios II EDS. On the Windows Start menu, click Programs > Altera > Nios II <version> > Nios II EDS <version> Documentation. Using Timer Devices Timer devices are hardware peripherals that count clock ticks and can generate periodic interrupt requests. You can use a timer device to provide a number o time-related acilities, such as the HAL system clock, alarms, the time-o-day, and time measurement. To use the timer acilities, the Nios II processor system must include a timer peripheral in hardware. The HAL API provides two types o timer device drivers: System clock driver This type o driver supports alarms, such as you would use in a scheduler. Timestamp driver This driver supports high-resolution time measurement. An individual timer peripheral can behave as either a system clock or a timestamp, but not both. The HAL-speciic API unctions or accessing timer devices are deined in sys/ alt_alarm.h and sys/alt_timestamp.h. March 2009 Altera Corporation Nios II Sotware Developer s Handbook

6 16 Chapter 6: Developing Programs Using the Hardware Abstraction Layer Using Timer Devices System Clock Driver The HAL system clock driver provides a periodic heartbeat, causing the system clock to increment on each beat. Sotware can use the system clock acilities to execute unctions at speciied times, and to obtain timing inormation. You select a speciic hardware timer peripheral as the system clock device by manipulating BSP settings. For details about how to control BSP settings, reer to HAL BSP Settings on page 6 2. The HAL provides implementations o the ollowing standard UNIX unctions: gettimeoday(), settimeoday(), and times(). The times returned by these unctions are based on the HAL system clock. The system clock measures time in clock ticks. For embedded engineers who deal with both hardware and sotware, do not conuse the HAL system clock with the clock signal driving the Nios II processor hardware. The period o a HAL system clock tick is generally much longer than the hardware system clock. system.h deines the clock tick requency. At runtime, you can obtain the current value o the system clock by calling the alt_nticks() unction. This unction returns the elapsed time in system clock ticks since reset. You can get the system clock rate, in ticks per second, by calling the unction alt_ticks_per_second(). The HAL timer driver initializes the tick requency when it creates the instance o the system clock. The standard UNIX unction gettimeoday() is available to obtain the current time. You must irst calibrate the time o day by calling settimeoday(). In addition, you can use the times() unction to obtain inormation about the number o elapsed ticks. The prototypes or these unctions appear in times.h. For more inormation about the use o these unctions, reer to the HAL API Reerence chapter o the Nios II Sotware Developer s Handbook. Alarms You can register unctions to be executed at a speciied time using the HAL alarm acility. A sotware program registers an alarm by calling the unction alt_alarm_start(): int alt_alarm_start (alt_alarm* alarm, alt_u32 nticks, alt_u32 (*callback) (void* context), void* context); The unction callback() is called ater nticks have elapsed. The input argument context is passed as the input argument to callback() when the call occurs. The HAL does not use the context parameter. It is only used as a parameter to the callback() unction. Your code must allocate the alt_alarm structure, pointed to by the input argument alarm. This data structure must have a lietime that is at least as long as that o the alarm. The best way to allocate this structure is to declare it as a static or global. alt_alarm_start() initializes *alarm. Nios II Sotware Developer s Handbook March 2009 Altera Corporation

Chapter 6: Developing Programs Using the Hardware Abstraction Layer 6 17 Using Timer Devices The callback unction can reset the alarm. The return value o the registered callback unction is the number o ticks until the next call to callback. A return value o zero indicates that the alarm should be stopped. You can manually cancel an alarm by calling alt_alarm_stop(). One alarm is created or each call to alt_alarm_start(). Multiple alarms can run simultaneously. Alarm callback unctions execute in an interrupt context. This imposes unctional restrictions which you must observe when writing an alarm callback. For more inormation about the use o these unctions, reer to the Exception Handling chapter o the Nios II Sotware Developer s Handbook. The code ragment in Example 6 8 demonstrates registering an alarm or a periodic callback every second. Example 6 8. Using a Periodic Alarm Callback Function #include <stdde.h> #include <stdio.h> #include "sys/alt_alarm.h" #include "alt_types.h" /* * The callback unction. */ alt_u32 my_alarm_callback (void* context) { /* This unction is called once per second */ return alt_ticks_per_second(); }... /* The alt_alarm must persist or the duration o the alarm. */ static alt_alarm alarm;... i (alt_alarm_start (&alarm, alt_ticks_per_second(), my_alarm_callback, NULL) < 0) { print ("No system clock available\n"); } Timestamp Driver Sometimes you want to measure time intervals with a degree o accuracy greater than that provided by HAL system clock ticks. The HAL provides high resolution timing unctions using a timestamp driver. A timestamp driver provides a monotonically increasing counter that you can sample to obtain timing inormation. The HAL only supports one timestamp driver in the system. March 2009 Altera Corporation Nios II Sotware Developer s Handbook

6 18 Chapter 6: Developing Programs Using the Hardware Abstraction Layer Using Timer Devices You speciy a hardware timer peripheral as the timestamp device by manipulating BSP settings. The Altera-provided timestamp driver uses the timer that you speciy. I a timestamp driver is present, the ollowing unctions are available: alt_timestamp_start() alt_timestamp() Calling alt_timestamp_start() starts the counter running. Subsequent calls to alt_timestamp() return the current value o the timestamp counter. Calling alt_timestamp_start() again resets the counter to zero. The behavior o the timestamp driver is undeined when the counter reaches (2 32-1). You can obtain the rate at which the timestamp counter increments by calling the unction alt_timestamp_req(). This rate is typically the hardware requency o the Nios II processor system usually millions o cycles per second. The timestamp drivers are deined in the alt_timestamp.h header ile. For more inormation about the use o these unctions, reer to the HAL API Reerence chapter o the Nios II Sotware Developer s Handbook. The code ragment in Example 6 9 shows how you can use the timestamp acility to measure code execution time. Example 6 9. Using the Timestamp to Measure Code Execution Time #include <stdio.h> #include "sys/alt_timestamp.h" #include "alt_types.h" int main (void) { alt_u32 time1; alt_u32 time2; alt_u32 time3; i (alt_timestamp_start() < 0) { print ("No timestamp device available\n"); } else { time1 = alt_timestamp(); unc1(); /* irst unction to monitor */ time2 = alt_timestamp(); unc2(); /* second unction to monitor */ time3 = alt_timestamp(); print ("time in unc1 = %u ticks\n", (unsigned int) (time2 - time1)); print ("time in unc2 = %u ticks\n", (unsigned int) (time3 - time2)); print ("Number o ticks per second = %u\n", (unsigned int)alt_timestamp_req()); } return 0; } Nios II Sotware Developer s Handbook March 2009 Altera Corporation