The following document contains information on Cypress products. Colophon The products described in this document are designed, developed and manufactured as contemplated for general use, including without limitation, ordinary industrial use, general office use, personal use, and household use, but are not designed, developed and manufactured as contemplated (1) for any use that includes fatal risks or dangers that, unless extremely high safety is secured, could have a serious effect to the public, and could lead directly to death, personal injury, severe physical damage or other loss (i.e., nuclear reaction control in nuclear facility, aircraft flight control, air traffic control, mass transport control, medical life support system, missile launch control in weapon system), or (2) for any use where chance of failure is intolerable (i.e., submersible repeater and artificial satellite). Please note that Spansion will not be liable to you and/or any third party for any claims or damages arising in connection with above-mentioned uses of the products. Any semiconductor devices have an inherent chance of failure. You must protect against injury, damage or loss from such failures by incorporating safety design measures into your facility and equipment such as redundancy, fire protection, and prevention of over-current levels and other abnormal operating conditions. If any products described in this document represent goods or technologies subject to certain restrictions on export under the Foreign Exchange and Foreign Trade Law of Japan, the US Export Administration Regulations or the applicable laws of any other country, the prior authorization by the respective government entity will be required for export of those products. Trademarks and Notice The contents of this document are subject to change without notice. This document may contain information on a Spansion product under development by Spansion. Spansion reserves the right to change or discontinue work on any product without notice. The information in this document is provided as is without warranty or guarantee of any kind as to its accuracy, completeness, operability, fitness for particular purpose, merchantability, non-infringement of third-party rights, or any other warranty, express, implied, or statutory. Spansion assumes no liability for any damages of any kind arising out of the use of the information in this document. ® ® ® TM Copyright © 2013 Spansion Inc. All rights reserved. Spansion , the Spansion logo, MirrorBit , MirrorBit Eclipse , TM ORNAND and combinations thereof, are trademarks and registered trademarks of Spansion LLC in the United States and other countries. Other names used are for informational purposes only and may be trademarks of their respective owners. Fujitsu Microelectronics Europe Application Note MCU-AN-300119-E-V10 F²MC-8FX FAMILY 8-BIT MICROCONTROLLER MB95260 SERIES ULTRASONIC DISTANCE MEASUREMENT APPLICATION NOTE Ultrasonic distance measurement Revision History Revision History Date 2010-02-25 Issue V1.0, CIl, First Version This document contains 18 pages. MCU-AN-300119-E-V10 -2- © Fujitsu Microelectronics Europe GmbH Ultrasonic distance measurement Warranty and Disclaimer Warranty and Disclaimer The use of the deliverables (e.g. software, application examples, target boards, evaluation boards, starter kits, schematics, engineering samples of IC’s etc.) is subject to the conditions of Fujitsu Microelectronics Europe GmbH (“FME”) as set out in (i) the terms of the License Agreement and/or the Sale and Purchase Agreement under which agreements the Product has been delivered, (ii) the technical descriptions and (iii) all accompanying written materials. Please note that the deliverables are intended for and must only be used in an evaluation laboratory environment. The software deliverables are provided without charge and therefore provided on an as-is basis. The software deliverables are to be used exclusively in connection with FME products. Regarding hardware deliverables, FME warrants that they will be free from defects in material and workmanship under use and service as specified in the accompanying written materials for a duration of 1 year from the date of receipt by the customer. Should a hardware deliverable turn out to be defect, FME’s entire liability and the customer’s exclusive remedy shall be, at FME´s sole discretion, either return of the purchase price and the license fee, or replacement of the hardware deliverable or parts thereof, if the deliverable is returned to FME in original packing and without further defects resulting from the customer’s use or the transport. However, this warranty is excluded if the defect has resulted from an accident not attributable to FME, or abuse or misapplication attributable to the customer or any other third party not relating to FME or to unauthorised decompiling and/or reverse engineering and/or disassembling. FME does not warrant that the deliverables does not infringe any third party intellectual property right (IPR). In the event that the deliverables infringe a third party IPR it is the sole responsibility of the customer to obtain necessary licenses to continue the usage of the deliverable. In the event the software deliverables include the use of open source components, the provisions of the governing open source license agreement shall apply with respect to such software deliverables. To the maximum extent permitted by applicable law FME disclaims all other warranties, whether express or implied, in particular, but not limited to, warranties of merchantability and fitness for a particular purpose for which the deliverables are not designated. To the maximum extent permitted by applicable law, FME’s liability is restricted to intention and gross negligence. FME is not liable for consequential damages. Should one of the above stipulations be or become invalid and/or unenforceable, the remaining stipulations shall stay in full effect. The contents of this document are subject to change without a prior notice, thus contact FME about the latest one. © Fujitsu Microelectronics Europe GmbH -3- MCU-AN-300119-E-V10 Ultrasonic distance measurement Contents Contents REVISION HISTORY ............................................................................................................ 2 WARRANTY AND DISCLAIMER ......................................................................................... 3 CONTENTS .......................................................................................................................... 4 1 INTRODUCTION .............................................................................................................. 5 1.1 Features .................................................................................................................. 5 1.2 Functional principle ................................................................................................. 5 2 HARDWARE .................................................................................................................... 6 2.1 2.2 Ultrasonic and analog circuit.................................................................................... 7 2.1.1 Coupling capacitor ..................................................................................... 7 2.1.2 Non-inverting amplifiers ............................................................................. 7 2.1.3 Active low-pass filter .................................................................................. 7 2.1.4 Total gain ................................................................................................... 7 Microcontroller ......................................................................................................... 8 3 SOFTWARE ..................................................................................................................... 9 3.1 3.2 Main code.............................................................................................................. 10 USART interface ................................................................................................... 11 3.3 Flash writing .......................................................................................................... 12 3.4 Timing routines ...................................................................................................... 12 4 INTERFACE PROTOCOL .............................................................................................. 13 4.1 4.2 Packages sent by the ultrasonic module ............................................................... 13 4.1.1 Raw sample data ..................................................................................... 13 4.1.2 Evaluated measurement values ............................................................... 13 4.1.3 Reply to command ................................................................................... 13 4.1.4 Calibration saved or unknown command ................................................. 14 Commands ............................................................................................................ 14 4.2.1 Raw data mode ....................................................................................... 14 4.2.2 Pause ...................................................................................................... 14 4.2.3 Calibrate .................................................................................................. 15 4.2.4 Clear calibration ....................................................................................... 15 4.2.5 Pin data ................................................................................................... 15 4.2.6 4.2.7 Pin configuration ...................................................................................... 15 Reserved IDs ........................................................................................... 16 5 CONCLUSION ............................................................................................................... 17 6 ADDITIONAL INFORMATION ....................................................................................... 18 MCU-AN-300119-E-V10 -4- © Fujitsu Microelectronics Europe GmbH Ultrasonic distance measurement Chapter 1 Introduction 1 Introduction This application note will show how to implement distance measurement based on ultrasonic sensors. It will give both an example hardware and software implementation with a Fujitsu 8 bit microcontroller. 1.1 1.2 Features • Measure distances from about 20 to 400 cm • Storage of calibration data in internal Flash • USART as communication interface • Standalone operation possible • Single 5 V power supply Functional principle The distance measurement with ultrasonic modules is based on the reflection of sound waves. An ultrasonic wave, i.e. a sound with a high frequency of normally about 40 kHz, is generated in a speaker which is also called ultrasonic transducer. This wave is reflected by objects. When the reflected wave reaches the ultrasonic transducer it converts the energy back into electrical voltage which can be measured. The time between sending the signal and receiving the reflected signal can then be used to calculate the distance of the reflecting object based on the velocity of sound. ~2.9 ms Total signal propagation time (t): ~5.8 ms Object Signal propagation time one way: ~2.9 ms Velocity of sound (v): ~340 m/s ~2.9 ms d=1m © Fujitsu Microelectronics Europe GmbH Distance d: d = v * t = 340 m/s * 2.9 ms = 0.99 m -5- MCU-AN-300119-E-V10 MCU-AN-300119-E-V10 1 2 3 4 5 6 7 8 9 10 -6- GND Pin14 P06 2 GND Pin1 X1 GND VCC Pin2 Q1 16 MHz X0 GND 1 2 3 4 5 6 7 8 OUT 7 GND C9 680pF/25V R7 4.7k R6 100k 2 3 GND R15 1k Pin5 PG1 MB95F284KPF LD2 LGT679 (green) GND R16 1k Pin4 PG2 16 15 14 13 12 11 10 9 OUT Pin16 Pin15 Pin14 Pin13 Pin12 Pin11 Pin10 Pin9 R1 4.7k VCC LM324 IN- IN+ U2A LD3 LGT679 (green) X0/PF0 P12/EC0/DBG X1/PF1 P07/INT07 Vss P06/INT06/TO01 X1A/PG2 P05/INT05/AN05/TO00/HCLK2 X0A/PG1 P04/INT04/AN04/SIN/HCLK1/EC0 Vcc P03/INT03/AN03/SOT RST/PF2 P01/AN01 C P02/INT02/AN02/SCK U1 LM324 IN- IN+ C1 22nF/25V Pin8 C Pin1 Pin2 GND Pin4 Pin5 VCC Pin7 Pin8 6 5 100k R5 U2B 10k C8 10nF/25V R4 Pin14 P06 C2 100nF/25V DBG Pin16 GND C3 100nF/25V xRST Pin7 R2 10k C6 22uF/16V GND VCC VCC Pin15 P07 1 VCC 15pF/25V C5 15pF/25V C4 BGMA IF X1 2 1 UltrasonicTransducer US1 GND Pin11 Pin12 Pin9 Pin10 Pin4 Pin5 1N4148 D3 SOT SIN P02 P01 PG2 PG1 C10 680pF/25V R9 2.7k R8 100k Pin13 AN05 1 GND 100k R13 R12 68k GND 100nF/25V C12 R11 100k VCC GND 10nF/25V C11 R10 100k VCC 9 10 OUT 680pF/25V C13 100k R14 LM324 IN- IN+ U2C 8 Ultrasonic distance measurement Chapter 2 Hardware 2 Hardware © Fujitsu Microelectronics Europe GmbH Ultrasonic distance measurement Chapter 2 Hardware The schematic consists of two functional blocks: • Ultrasonic and analog circuit • Microcontroller circuit 2.1 Ultrasonic and analog circuit The pins of the ultrasonic transducer US1 are attached to two IO pins of the microcontroller. Sending the ultrasonic bursts is done by setting one pin to high while the other is low and vice versa. This way a +/- 5 V square wave signal is generated. When sending is done one pin of the ultrasonic transducer, connected to P07 (pin 15) of the microcontroller, is set to ground so the received power from the ultrasonic signal can be measured as a voltage on the second pin. The connected microcontroller IO P06 (pin 14) is set to high impedance so the signal can be amplified through the operational amplifier circuit. It consists of four blocks: • Coupling capacitor • Non-inverting amplifier 1 • Non-inverting amplifier 2 • Active low-pass filter The amplified signal is measured by the analog input AN05 (pin 13) of the microcontroller. 2.1.1 Coupling capacitor The coupling capacitor (C8) is used to couple the AC signal from the ultrasonic transducer on a 2 V DC voltage generated by the voltage divider R11/R12. This is needed to be able to use the single-supply operational amplifiers. 2.1.2 Non-inverting amplifiers The first amplifier stage consists of U2B, R6, R7 and C9, the second one of U2A, R8, R9 and C10. Their amplification can be calculated as: v1 = 1 + R6 / R7 = 1 + (100 kJ) / (4.7 kJ) K 22.3 v2 = 1 + R8 / R9 = 1 + (100 kJ) / (2.7 kJ) K 38.0 C9 and C10 are required to reduce DC amplification of the operational amplifiers. 2.1.3 Active low-pass filter The low-pass filter is used to smooth the half-wave signal coming from D3 after being amplified by U2A. Its amplification is: v3 = - (R14 / R13) * 1 / (1 + j * L * C13 * R14) = - (R14 / R13) * 1 / (1 + j * 2 * M * f * C13 * R14) = - (100 kJ / 100 kJ) * 1 / (1 + j * 2 M * 40 kHz * 680 pF * 100 kJ) K 0.06 The cutoff frequency of the filter is: fc = 1 / (2 * M * R14 * C13) = 1 / (2 * M * 100 kJ * 680 pF) K 2341 Hz 2.1.4 Total gain Total gain of the amplification circuit is calculated by: vt = v1 * v2 * v3 = 22.3 * 38.0 * 0.06 = 49.6 © Fujitsu Microelectronics Europe GmbH -7- MCU-AN-300119-E-V10 Ultrasonic distance measurement Chapter 2 Hardware 2.2 Microcontroller The microcontroller (U1) is a Fujitsu MB95F284K 8 bit microcontroller. It is used to generate the 40 kHz ultrasonic bursts and to measure the time until the echo is received. The clock is provided by a 16 MHz crystal oscillator resulting in 8 MHz CPU clock which allows a measurement resolution of 128 Os or about 2 cm. LEDs are attached to pins PG1 and PG2 which can be either controlled through the USART interface or for standalone operation by enhancing the software. Pins P01, P02, PG1 and PG2 can be used as GPIOs, SIN and SOT provide the control interface. Connector X1 provides the debug interface for the BGM-Adapter MB2146-08-E. MCU-AN-300119-E-V10 -8- © Fujitsu Microelectronics Europe GmbH Ultrasonic distance measurement Chapter 3 Software 3 Software The firmware on the ultrasonic module (95280_adc_ultrasonic) samples the echo of the ultrasonic transmission and provides an evaluated output of that data which gives the distance to a detected object. Reset Initialization (MCU_Initialization) Load calibration (loadCalibration) Command received? (usart_getChar) Yes Handle command (handle_rx) Yes Save calibration (saveCalibration) No Ultrasonic measure (ultrasonic_measure) Transmit data Calibration done? No Wait (waitTimer) Figure 1: Flowchart of ultrasonic module firmware The measurement routine first sends 13 ultrasonic bursts. Then it converts 8 samples of the returned signal which are averaged in each of 250 timeslots. From the averaged value the stored calibration value is subtracted. The timeslots are 128 Os each which results in about 2 cm of additional distance per timeslot until a peak is detected. © Fujitsu Microelectronics Europe GmbH -9- MCU-AN-300119-E-V10 Ultrasonic distance measurement Chapter 3 Software The code is split into four modules: • Main code including protocol handler and ultrasonic measurement (main.c) • USART interface (usart.c) • Flash writing (flash.c) • Timing routine (util.c) 3.1 Main code Main code first initializes the used hardware macros (routine MCU_Initialization): • Selecting the external crystal as main clock source • Set Timebase Timer to 128 Os interval • Analog/digital converter (AN05) • USART interface • Pins for the ultrasonic transducer output (P06, P07) • User I/O pins (P01, P02, PG1, PG2) Next step is to load the calibration data from the lower Flash bank (loadCalibration). At this point the CPU enters the infinite loop which does the following: • Check whether a command was received via USART (usart_getChar) o • If so try to handle the received byte (handle_rx) Do one measurement run (ultrasonic_measure) o Send the ultrasonic burst (sendUSburst) o Get 250 samples from the analog converter in 128 Os interval o Return the index of the first detected peak • Save calibration data if a calibration was just finished (saveCalibration) • Wait for a configurable multiple of 50 ms (see 4.2.2 - Pause) MCU-AN-300119-E-V10 - 10 - © Fujitsu Microelectronics Europe GmbH Ultrasonic distance measurement Chapter 3 Software Signal output to US transducer Stored calibration data (no object) Signal received by US transducer (with object) Evaluated signal Detected peak Figure 2: Ultrasonic measurement process 3.2 USART interface This module (usart.c) provides methods to initialize the USART, send bytes, decimal values and strings and receive bytes. • usart_init initializes the USART to asynchronous 8N1 with 1 MBaud • usart_putChar sends a single byte • usart_putString sends a null-terminated string • usart_putDec sends a decimal value between 000 and 999 • usart_putDecInt sends a decimal value between 00000 and 65535 • usart_getChar gets a single byte if USART receive register is not empty Since the interface is running at 1 MBaud it is not usable with a normal RS232 interface of a PC. It can be used through USB to serial adapters though. The baudrate is set to 1 MBaud in order to reduce the time needed to transfer the data while measuring. © Fujitsu Microelectronics Europe GmbH - 11 - MCU-AN-300119-E-V10 Ultrasonic distance measurement Chapter 3 Software 3.3 Flash writing This module (flash.c) is used to erase the first sector of lower flash bank (SA0, starting at B000H) and write bytes to it. • flash_erase erases the sector containing the specified address. Used to remove stored calibration data in clearCalibration. • flash_write writes a single byte to a Flash address. Writing to flash is used by saveCalibration to permanently store calibration data. Flash bank Sector name SA0 Lower flash bank SA1 Upper flash bank 3.4 SA2 Start/end address B000H B7FFH B800H BFFFH C000H FFFFH Timing routines This module (util.c) provides timing routines to precisely control execution of measurement operations. • timer_init initializes the Timebase Timer for 128 Os ticks • waitTimer waits the specified amount of ticks • wait10times inserts 10 NOP instructions • timer_delay waits the specified times multiplied by 50 ms The sourcecode of the methods waitTimer and wait10times are not included in util.c but in main.c because they are inlined in other methods to remove function call overhead. MCU-AN-300119-E-V10 - 12 - © Fujitsu Microelectronics Europe GmbH Ultrasonic distance measurement Chapter 4 Interface protocol 4 Interface protocol The firmware features a small command protocol to control the behavior of the ultrasonic module. This protocol will be explained in this chapter. 4.1 Packages sent by the ultrasonic module Data sent from the module is fit into packages. Each package is prefixed with a 0 value byte whereas no other 0 value will be in the data bytes of the package. The second byte in a package determines the type of the package. Byte 0 0x00 Byte 1 Type of package Byte 2..n Data; length depending on type of package Table 1: Ultrasonic module package structure The following types of packages are defined and will be described in the following chapters: Type value 0x01 0x02 0x03 0x04 Data length n 250 3 1 1 Description Raw sample data Evaluated measurement values Reply to command Calibration saved or unknown command Table 2: Ultrasonic module package types 4.1.1 Raw sample data This package is sent during each measurement run if the raw data mode is enabled (see 4.2.1 - Raw data mode). It represents the averaged sample values of the analog to digital converter per timeslot. Each of the bytes is one average value. Byte 0 Byte 1 Byte 2..251 0x00 0x01 Averaged AD sample values The first value is for timeslot 0 which starts at about 581 us. The value for timeslot 0 is always 1. 4.1.2 Evaluated measurement values This package is sent after each measurement run if raw mode is disabled. It contains the timeslot index and the distance in cm where an object was detected. Byte 0 Byte 1 Byte 2 Byte 3 Byte 4 0x00 0x02 Index of timeslot Upper 7 bits of distance Lower 7 bits of distance The bytes for the distance in cm are OR’ed with 0x80 and the lower 7 bits of each byte contain the actual value. Thus the distance in cm can be taken from bytes 3 and 4 by: Distance [cm] = ((Byte3 and 0x7f) << 7) or (Byte4 and 0x7f) 4.1.3 Reply to command If a command was received and could be handled correctly a reply will be generated. This reply contains the original command. If the command was a read command the value fields will be filled by the current internal values of the running software. Byte 0 0x00 Byte 1 0x03 Byte 2 Handled command © Fujitsu Microelectronics Europe GmbH - 13 - MCU-AN-300119-E-V10 Ultrasonic distance measurement Chapter 4 Interface protocol 4.1.4 Calibration saved or unknown command When a calibrate command was received and calibration is done or when an unknown command was received this package will be sent. Byte 0 0x00 4.2 Byte 1 0x04 Byte 2 0x10 – Calibration done 0x11 – Unknown command Commands Commands are single bytes sent to the ultrasonic module. Since only one command is handled after each measurement run only one command may be sent until the reply is received. Alternatively a wait time may be used to make sure that the command has been processed. Commands have the following format: Bit 7..4 Parameter data Bit 3 Bit 2..0 Read (0) / Write (1) Command id Table 3: Structure of ultrasonic commands The commands defined are as following: Command id 0 1 2 3 4 5 6 7 Description Raw data mode Pause between measurement runs in units of 50 ms Calibrate to current measurement values Clear calibration Pin data (PDR register) Pin configuration (DDR and PUL registers) Reserved Reserved Remarks Write only Write only Table 4: Ultrasonic commands 4.2.1 Raw data mode This command allows selection of raw data mode or evaluated data mode. Bit 7 1 6 - 5 - 4 Mode 3 R/W 2 0 1 0 0 0 1 0 0 1 Mode bit Mode description 0 Evaluated data mode 1 Raw data mode 4.2.2 Pause A pause between each measurement run can be set from 0 to 750 ms. Bit 7 6 5 Number of 50 ms pause states Default value is 0 ms delay. MCU-AN-300119-E-V10 4 3 R/W - 14 - 2 0 © Fujitsu Microelectronics Europe GmbH Ultrasonic distance measurement Chapter 4 Interface protocol 4.2.3 Calibrate Stores the current measurement values as calibration data in the Flash of the 8 bit controller. These values are subtracted from the measured values in measurements after this command has finished. Bit 7 6 5 4 3 2 1 0 1 0 1 0 1 0 1 0 When calibration has finished a “calibration saved” package (see 4.1.4) is sent by the ultrasonic module. Note: Calibration should be issued while the ultrasonic transducers are directed at an empty room so a good null measurement value can be taken. 4.2.4 Clear calibration This command clears stored calibration data setting every value to 0. This way the sampled data can be received in an unaltered way in raw data mode. Bit 7 6 5 4 3 2 1 0 0 1 1 0 1 0 1 1 Note: After this command was issued evaluated data mode will not return useful data. 4.2.5 Pin data This command is used to write to or read from the PDR registers of the unused IO pins of the microcontroller. Bit 7 - 6 Value Pin1..0 bits 00 01 10 11 5 Pin1 4 Pin0 3 R/W 2 1 1 0 0 0 Pin PG1 PG2 P01 P02 4.2.6 Pin configuration With this command the DDR (data direction) and PUL (pull-up enable) registers can be accessed. Bit 7 6 5 4 3 2 Register Value Pin1 Pin0 R/W 1 Pin1..0 are the same values as for the pin data command. 1 0 0 1 Register bit Register 0 DDR 1 PUL Value bit DDR register meaning 0 Input pin 1 Output pin © Fujitsu Microelectronics Europe GmbH - 15 - PUL register meaning Pull-up disabled Pull-up enabled MCU-AN-300119-E-V10 Ultrasonic distance measurement Chapter 4 Interface protocol 4.2.7 Reserved IDs These two command ids are reserved for future extensions. Bit 7 - 6 - MCU-AN-300119-E-V10 5 - 4 - 3 - - 16 - 2 1 1 1 1 1 0 0 1 © Fujitsu Microelectronics Europe GmbH Ultrasonic distance measurement Chapter 5 Conclusion 5 Conclusion This application note describes a functional but basic implementation for distance measurement based on ultrasonic modules. Improvements could be: • Completely standalone operation without the need of another controller reading out distance values • Increased resolution of measurement • Increased maximum measurable distance • Improved echo peak detection algorithm © Fujitsu Microelectronics Europe GmbH - 17 - MCU-AN-300119-E-V10 Ultrasonic distance measurement Chapter 6 Additional information 6 Additional information Information about Fujitsu microcontrollers can be found on the following internet page: http://mcu.emea.fujitsu.com/ This application note and its accompanying software examples can be found on: http://mcu.emea.fujitsu.com/mcu_product/mcu_all_appnotes.htm The software example of this application note is: • 95280_adc_ultrasonic It can be found on the following internet page: http://mcu.emea.fujitsu.com/mcu_product/mcu_all_software.htm MCU-AN-300119-E-V10 - 18 - © Fujitsu Microelectronics Europe GmbH