SlideShare a Scribd company logo
(218) 454-0766   
MAXBOTIX
BX24
‘MaxSonar®-EZ1™ Code Example
‘By Chris Harriman
’01/09/2006
‘The program below continues to read the MaxSonar®-EZ1™
‘It uses the AD to read, and debug to output the data.Const RX As Byte = 10
Const AN As Byte = 13
Dim AnalogOutPut As Byte
Dim SerialOutPut As Byte
Dim PWOutPut As Byte ”********************************************
Sub Main()
Do
AnalogOutPut = RangeA       ‘ Get the Range
Debug.Print “Analog ” & CStr(AnalogOutPut)  ‘ Print the Range
Call SLeep(512)
Loop
End Sub”********************************************
Function RangeA() As Byte
‘ Reads the Analog output of the MAXSonar® EZ1™ (AN Pin) and returns the target
range as a Byte
Dim AValue As Integer
Call PutPin (RX, 0)     ‘ Turn off the EZ1™ just in case we started with it on
Call PutPin (RX, 1)  ‘ Turn on the EZ1™
Call Sleep(40)   ‘ Wait about 50 ms
AValue = GetADC(AN)  ‘ Read the ADC
RangeA = Cbyte(AValue  2)  ‘ Convert value to Byte and return
End Function
Code Example for BasicX, BX24p
Code Examples
info@maxbotix.com  (1)
High Performance Ultrasonic Range Finders
(218) 454-0766   
MAXBOTIX
‘BasicAtom Code
‘Reads MaxSonar®-EZ1™
‘Bob Gross
’01/14/2005
‘5V connect to +5V
‘GND connect to common
‘TX, connect to Atom P7
‘RX, connect to Atom P5
‘The serial data will be sent when the reading is complete,
‘This is very fast when an object is close.
‘Only four lines of code required
RS232Data var byte                                              ‘Set up variable to hold the data
High P5                                                             ‘Hold high to start the reading
SerIn P7, n9600, [WAIT(“R”), dec RS232Range ]   ‘wait for “R” and get the data
Low P5                                                              ‘Set low when complete
info@maxbotix.com  (2)
Code example for the Basic Micro, Atom
(218) 454-0766   
MAXBOTIXinfo@maxbotix.com  (3)
Code example using DevBoard-M32 (AVR using Bascom)
‘Using the MaxSonar®-EZ1™ with the DevBoard-M32
‘By Eddy Wright, Wright Hobbies Robotics, 2006
‘http://www.wrighthobbies.net
‘We will read both the analog and serial outputs of the MaxSonar®
‘The M32 A/D converter has an internal voltage
‘Reference of 2.56v which is perfect for output
‘of the MaxSonar® – 2.55v
‘The analog output (AN)of the MaxSonar® is connected to
‘Port A.0, the ADC Channel 0
‘The serial output (TX) is connected to to Port D.7
‘Each loop, we read the analog and serial values
‘This code can be used with any AVR with ADC that is supported by Bascom
Dim Dist As Word , Strdist As String * 8 , Serdist As Byte
‘Config the softare UART, we need to use the INVERTED option with the MaxSonar®
Open “comd.7:9600,8,n,1,INVERTED” For Input As #1
‘Configure ADC
Config Adc = Single , Prescaler = Auto , Reference = Internal
Start Adc
Do
Dist = Getadc(0)
Shift Dist , Right , 2        ‘The M32 has 10bit ADC, shifting it twice makes it 8bit
Input #1 , Strdist Strdist = Right(strdist , 3)     ‘Strip off the letter R
Serdist = Val(strdist)      ‘Convert to a number
Print “Analog Distance = ” ; Dist ; ” Inches”
Print “Serial Distance = ” ; Serdist ; ” Inches”
Loop 
(218) 454-0766   
MAXBOTIXinfo@maxbotix.com  (4)
Code Example using Parallax Basic Stamp BS2, BasicStamp
‘Reads both the PW and serial outputs
‘ {$STAMP BS2}
‘ {$PBASIC 2.5}
‘ www.danderrick.com/
‘ permission for unlimited use granted to all
‘ First test of the MaxSonar®-EZ1™
‘ micro µ
‘ ——- P PINs —————————–
pMaxRecv PIN 15
pMaxClock PIN 14
pMaxPWM PIN 0
‘ ————— X Variables —————–
xDist VAR Word
xPulse VAR Word
xX VAR Byte
‘ ============ Main loop ================
DO GOSUB sPWM
GOSUB sSerial
DEBUG CR, CR
PAUSE 50
LOOP
END  ‘ never reached
‘ 
————- Subs ————————
sPWM: ‘Max sends 147 µs per inch
‘BS2 reads for 2 µs
FOR xX = 1 TO 5
HIGH pMaxClock
PULSIN pMaxPWM, 1, xPulse
LOW pMaxClock
DEBUG DEC5 xPulse, ” “
PAUSE 50
NEXT
DEBUG CR
RETURN
sSerial:
FOR xX = 1 TO 5
SERIN pMaxRecvpMaxClock, 16468, [WAIT (“R”), DEC xDist] DEBUG DEC5 xDist, ” “
PAUSE 50
NEXT
DEBUG CR
RETURN
‘ ——– Physical end of file ————
(218) 454-0766   
MAXBOTIXinfo@maxbotix.com  (5)
C Program Driver for MaxBotix MB7066 PW Ultrasonic Sensor
By Paul Sfetku, July 2011
Development System – Mikroelektronika
http://www.mikroe.com/
Develop. Board:     BigPic6 with GLCD (128×64)
Microcontroller:      PIC18F8520/8722 family
Compiler:              mikroC PRO for PIC
Interface:              BigPic6 SW7 RG0:  PORTG.B0 (output) → MB7066<4>  start/stop ranging
BigPic6 SW7 RG1:  PORTG.B1 (input)  → MB7066<2>  PW – pulse width
NOTE: BigPic6 SW7 is set for pull-up on PORTG pins RG0/B0 & RG1/B1.
MB7066 Pin Out
Pin 2 – PW: This pin outputs a pulse width representation of range. To calculate distance, you can a scale factor of
58us/cm.
Pin 4 – RX: This pin is internally pulled high. The MB7066 will continually measure range and output if the pin is left
unconnected or held high. If held low the MB7066 will stop ranging. Bring pin high for >= 20uS for range reading.
Pin 6 – Vcc (3V – 5.5V): Average and peak current draw for 3.3V operation is 2.1mA (50mA peak). 5V operation is 3.4mA
(100mA peak) respectively. Peak current is used during sonar pulse transmit.
Pin 7 – GND: Return for the DC power supply. GND (& V+) must be ripple and noise free for best operation.
NOTE: Refer to the MB7066 PW documentation for an explanation of MB7066 Real-time Operation & Timing
Program Code Explanation
The C code listed below was generated using the mikroC Pro PIC compiler. The code will drive the MaxBotix MB7066
pulse width (PW) sensor, and any MaxBotix pulse width sensor.
The MB7066 is operated in free running mode with MB7066<4> pulled High. To operate the MB7066 in start/stop
mode, you can uncomment code statements 8,9,10 and code statements 17,18,19.
Statements 15-20 can be used to determine when and if the MB7066 fails to detect a return pulse from the given
target. A value for maxvalue in statement 15 is needed to calibrate the sensor for a maximum time or maximum
distance value.
The code to drive the MB7066 is contained within an infinite loop declared in statement 11. The MB7066 operates on
a 100ms PW cycle. MB7066 pin-2 PW sets high to start a ranging cycle, and sets Low if and when a target object is
detected. If no target is detected, pin-2 PW will be held high for up to 62ms or 1068cm, the maximum range value.
Code statements 12-25 are designed detect and measure the period of each PW begin/end cycle. Statement 12
detects when the PW goes High. The delay in statement 13 is used to calibrate the sensor’s ranging resolution to
detect changes at one inch increments. The variable in statement 14 counts the number of delays until the PW signal
does low.
Statements 21-24 calculate the range and detect the beginning of the next 100ms PW cycle. Statement 22 calculates
the range based on the time counted in statement 14, and based on a constant factor (.5) that can be adjusted to
provide an accurate range measurement.
(218) 454-0766   
MAXBOTIXinfo@maxbotix.com  (6)
C Program Driver for MaxBotix MB7066 PW Ultrasonic Sensor Cont.
The loop in statement 24 is used to wait for the PW to set High, indicating the beginning of the next 100ms PW
ranging cycle.
// Declarations ——————————————————-
TRISG = 0x02;                  // PORTG DDR: RG0 (output), RG1 (input)
unsigned int msec    = 0;    // time counter – microseconds
unsigned int inches   = 0;   // calculated distance
unsigned maxvalue   = 0;   // sensor maximum – echo not detected
void main() {
//PORTG.B0 = 0;             // MB7066<4>: stop ranging – set Low
//PORTG.B0 = 1;             // MB7066<4>: start ranging – set High
//Delay_us(20);               // 20us delay for start of ranging
while (1) {                      // infinite loop
if (PORTG.B1) {                  // MB7066<2>: PW – check if High
Delay_us(30);                  // delay factor 30us – gives 1 inch resolution
msec++;                         // count time PW is High each microseconds
//if (msec > maxvalue) {   // PW max time 62ms -> echo not detected
// msec = 0;                    // clear counter
// PORTG.B0 = 0;             // MB7066<4>: stop ranging – set Low
// PORTG.B0 = 1;             // MB7066<4>: start ranging – set High
// Delay_us(20);               // 20us delay for start of ranging
//}
} else {                             // MB7066<2>: PW -> Low
inches = .5*msec;            // range (inches): target correction factor = .5
msec = 0;                        // clear counter
while (!PORTG.B1);            // wait for MB7066<2> PW to go High -> start 100ms range cycle
}
}
}
(218) 454-0766   
MAXBOTIXinfo@maxbotix.com  (7)
Arduino I2C Code Example for I2CXL-MaxSonar Products
Development System – Arduino Uno (as of Arduino 1.0.1)
Develop. Board:     Arduino Uno R3
/* Code for Arduino Uno R3
Assumes the sensor is using the default address
Sensor Connections:
Pin 7 to GND
Pin 6 to 5V
Pin 5 to SCL
Pin 4 to SDA
Requires pull‑ups for SCL and SDA connected to 5V to work reliably
*/
#include “Wire.h”
//The Arduino Wire library uses the 7-bit version of the address, so the code example uses 0x70 instead of the 8‑bit
0xE0
#define SensorAddress byte(0x70)
//The Sensor ranging command has a value of 0x51
#define RangeCommand byte(0x51)
//These are the two commands that need to be sent in sequence to change the sensor address
#define ChangeAddressCommand1 byte(0xAA)
#define ChangeAddressCommand2 byte(0xA5)
void setup() {
Serial.begin(9600);//Open serial connection at 9600 baud
Wire.begin();//Initiate Wire library for I2C communications with I2CXL‑MaxSonar‑EZ
}
void loop() {
takeRangeReading();                                       //Tell the sensor to perform a ranging cycle
delay(100);                                                    //Wait for the sensor to finish
word range = requestRange();                           //Get the range from the sensor
Serial.print(“Range:”);Serial.println(range);          //Print to the user
}
//Commands the sensor to take a range reading
void takeRangeReading(){
Wire.beginTransmission(SensorAddress);             //Start addressing
Wire.write(RangeCommand);                             //send range command
Wire.endTransmission();                                  //Stop and do something else now
}
(218) 454-0766   
MAXBOTIXinfo@maxbotix.com  (8)
Arduino I2C Code Example for I2CXL-MaxSonar Products Cont. 
//Returns the last range that the sensor determined in its last ranging cycle in centimeters. Returns 0 if there is no
communication.
word requestRange(){
Wire.requestFrom(SensorAddress, byte(2));
if(Wire.available() >= 2){                            //Sensor responded with the two bytes
byte HighByte = Wire.read();                        //Read the high byte back
byte LowByte = Wire.read();                        //Read the low byte back
word range = word(HighByte, LowByte);         //Make a 16-bit word out of the two bytes for the range
return range;
}
else {
return word(0);                                             //Else nothing was received, return 0
}
}
/* Commands a sensor at oldAddress to change its address to newAddress
oldAddress must be the 7-bit form of the address that is used by Wire
7BitHuh determines whether newAddress is given as the new 7 bit version or the 8 bit version of the address
 If true, if is the 7 bit version, if false, it is the 8 bit version
*/
void changeAddress(byte oldAddress, byte newAddress, boolean SevenBitHuh){
Wire.beginTransmission(oldAddress);                 //Begin addressing
Wire.write(ChangeAddressCommand1);              //Send first change address command
Wire.write(ChangeAddressCommand2);              //Send second change address command
byte temp;
if(SevenBitHuh){ temp = newAddress << 1; }     //The new address must be written to the sensor
else     { temp = newAddress;         }               //in the 8bit form, so this handles automatic shifting
Wire.write(temp);                                          //Send the new address to change to
Wire.endTransmission();
}
As a minor note, in old Arduino IDE’s
Wire.read() should be substituted by Wire.receive()
and
Wire.write() should be substituted by Wire.send()

More Related Content

DOCX
How to configure interior gateway routing protocol (igrp)
PPT
In depth understanding network security
PPTX
Cisco CCNA Port Security
PPT
Ospf Cisco
PDF
Multicast IP addresses Part 1
PPT
1 egp
PPTX
DMVPN configuration - Configuring Cisco dynamic Multipoint VPN - HUB, SPOKES,...
PDF
Gre tunnel pdf
How to configure interior gateway routing protocol (igrp)
In depth understanding network security
Cisco CCNA Port Security
Ospf Cisco
Multicast IP addresses Part 1
1 egp
DMVPN configuration - Configuring Cisco dynamic Multipoint VPN - HUB, SPOKES,...
Gre tunnel pdf

What's hot (13)

PDF
CCIE R&S Real Lab Workbbok 2018 updated
PDF
CCNP Lab Guide CCIE University
PDF
PPTX
Cisco CCNA GRE Tunnel Configuration
DOCX
Lab 9 instructions
PDF
Securing Switch Access
PDF
Tutorial 8 frequency counter
PPTX
GRE Tunnel Configuration
PDF
PDF
1-300-206 (SENSS)=Firewall (642-618)
PDF
selected input/output - sensors and actuators
PDF
Connectivity for Local Sensors and Actuators Using nRF24L01+
PPT
SAS (Secure Active Switch)
CCIE R&S Real Lab Workbbok 2018 updated
CCNP Lab Guide CCIE University
Cisco CCNA GRE Tunnel Configuration
Lab 9 instructions
Securing Switch Access
Tutorial 8 frequency counter
GRE Tunnel Configuration
1-300-206 (SENSS)=Firewall (642-618)
selected input/output - sensors and actuators
Connectivity for Local Sensors and Actuators Using nRF24L01+
SAS (Secure Active Switch)
Ad

Similar to MaxBotix Code Examples (20)

PDF
Mb1003 hrlv max sonar-ez0 ultrasonic rangefinder
PPTX
Topic 7 - Servo_US_Temp_IRrrrrrrrrrrrrrrrrrrrrrrrrr.pptx
PDF
Multipilot pres-ufficiale def
PPTX
Alcohol detection & driver safety
PDF
Advanced motion controls azxbe6c20
PDF
Advanced motion controls dzsantu 040b080
PDF
Advanced motion controls dzcantu 040b080
PDF
G320 x rev 10 manual formatted
PPTX
PARAMETER SENSING REMOTE OPERATED VIDEO ENHANCED RECEIVER
PDF
Galil dmc18x2 catalog
PDF
Galil dmc18x6 catalog
PDF
Folheto nova LSIS 220
PDF
ADS1256 library documentation
PPTX
Obstacle avoiding Robot
PPTX
PDF
Low cost data acquisition from digital caliper to pc
ODP
Multipilot pres-ufficiale alpago 2011
PDF
Advanced motion controls dzsantu 020b080
PDF
ICplus902_Manual_EN.pdf iskkksmmsmmmskakjdskla
PDF
Advanced motion controls dzcantu 020b200
Mb1003 hrlv max sonar-ez0 ultrasonic rangefinder
Topic 7 - Servo_US_Temp_IRrrrrrrrrrrrrrrrrrrrrrrrrr.pptx
Multipilot pres-ufficiale def
Alcohol detection & driver safety
Advanced motion controls azxbe6c20
Advanced motion controls dzsantu 040b080
Advanced motion controls dzcantu 040b080
G320 x rev 10 manual formatted
PARAMETER SENSING REMOTE OPERATED VIDEO ENHANCED RECEIVER
Galil dmc18x2 catalog
Galil dmc18x6 catalog
Folheto nova LSIS 220
ADS1256 library documentation
Obstacle avoiding Robot
Low cost data acquisition from digital caliper to pc
Multipilot pres-ufficiale alpago 2011
Advanced motion controls dzsantu 020b080
ICplus902_Manual_EN.pdf iskkksmmsmmmskakjdskla
Advanced motion controls dzcantu 020b200
Ad

Recently uploaded (20)

PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Spectroscopy.pptx food analysis technology
PPTX
Machine Learning_overview_presentation.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Electronic commerce courselecture one. Pdf
PDF
Encapsulation theory and applications.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
cuic standard and advanced reporting.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
Building Integrated photovoltaic BIPV_UPV.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Spectroscopy.pptx food analysis technology
Machine Learning_overview_presentation.pptx
Chapter 3 Spatial Domain Image Processing.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Electronic commerce courselecture one. Pdf
Encapsulation theory and applications.pdf
Empathic Computing: Creating Shared Understanding
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
The Rise and Fall of 3GPP – Time for a Sabbatical?
20250228 LYD VKU AI Blended-Learning.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
MIND Revenue Release Quarter 2 2025 Press Release
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Per capita expenditure prediction using model stacking based on satellite ima...
cuic standard and advanced reporting.pdf
The AUB Centre for AI in Media Proposal.docx

MaxBotix Code Examples

  • 1. (218) 454-0766    MAXBOTIX BX24 ‘MaxSonar®-EZ1™ Code Example ‘By Chris Harriman ’01/09/2006 ‘The program below continues to read the MaxSonar®-EZ1™ ‘It uses the AD to read, and debug to output the data.Const RX As Byte = 10 Const AN As Byte = 13 Dim AnalogOutPut As Byte Dim SerialOutPut As Byte Dim PWOutPut As Byte ”******************************************** Sub Main() Do AnalogOutPut = RangeA       ‘ Get the Range Debug.Print “Analog ” & CStr(AnalogOutPut)  ‘ Print the Range Call SLeep(512) Loop End Sub”******************************************** Function RangeA() As Byte ‘ Reads the Analog output of the MAXSonar® EZ1™ (AN Pin) and returns the target range as a Byte Dim AValue As Integer Call PutPin (RX, 0)     ‘ Turn off the EZ1™ just in case we started with it on Call PutPin (RX, 1)  ‘ Turn on the EZ1™ Call Sleep(40)   ‘ Wait about 50 ms AValue = GetADC(AN)  ‘ Read the ADC RangeA = Cbyte(AValue 2)  ‘ Convert value to Byte and return End Function Code Example for BasicX, BX24p Code Examples info@maxbotix.com  (1) High Performance Ultrasonic Range Finders
  • 2. (218) 454-0766    MAXBOTIX ‘BasicAtom Code ‘Reads MaxSonar®-EZ1™ ‘Bob Gross ’01/14/2005 ‘5V connect to +5V ‘GND connect to common ‘TX, connect to Atom P7 ‘RX, connect to Atom P5 ‘The serial data will be sent when the reading is complete, ‘This is very fast when an object is close. ‘Only four lines of code required RS232Data var byte                                              ‘Set up variable to hold the data High P5                                                             ‘Hold high to start the reading SerIn P7, n9600, [WAIT(“R”), dec RS232Range ]   ‘wait for “R” and get the data Low P5                                                              ‘Set low when complete info@maxbotix.com  (2) Code example for the Basic Micro, Atom
  • 3. (218) 454-0766    MAXBOTIXinfo@maxbotix.com  (3) Code example using DevBoard-M32 (AVR using Bascom) ‘Using the MaxSonar®-EZ1™ with the DevBoard-M32 ‘By Eddy Wright, Wright Hobbies Robotics, 2006 ‘http://www.wrighthobbies.net ‘We will read both the analog and serial outputs of the MaxSonar® ‘The M32 A/D converter has an internal voltage ‘Reference of 2.56v which is perfect for output ‘of the MaxSonar® – 2.55v ‘The analog output (AN)of the MaxSonar® is connected to ‘Port A.0, the ADC Channel 0 ‘The serial output (TX) is connected to to Port D.7 ‘Each loop, we read the analog and serial values ‘This code can be used with any AVR with ADC that is supported by Bascom Dim Dist As Word , Strdist As String * 8 , Serdist As Byte ‘Config the softare UART, we need to use the INVERTED option with the MaxSonar® Open “comd.7:9600,8,n,1,INVERTED” For Input As #1 ‘Configure ADC Config Adc = Single , Prescaler = Auto , Reference = Internal Start Adc Do Dist = Getadc(0) Shift Dist , Right , 2        ‘The M32 has 10bit ADC, shifting it twice makes it 8bit Input #1 , Strdist Strdist = Right(strdist , 3)     ‘Strip off the letter R Serdist = Val(strdist)      ‘Convert to a number Print “Analog Distance = ” ; Dist ; ” Inches” Print “Serial Distance = ” ; Serdist ; ” Inches” Loop 
  • 4. (218) 454-0766    MAXBOTIXinfo@maxbotix.com  (4) Code Example using Parallax Basic Stamp BS2, BasicStamp ‘Reads both the PW and serial outputs ‘ {$STAMP BS2} ‘ {$PBASIC 2.5} ‘ www.danderrick.com/ ‘ permission for unlimited use granted to all ‘ First test of the MaxSonar®-EZ1™ ‘ micro µ ‘ ——- P PINs —————————– pMaxRecv PIN 15 pMaxClock PIN 14 pMaxPWM PIN 0 ‘ ————— X Variables —————– xDist VAR Word xPulse VAR Word xX VAR Byte ‘ ============ Main loop ================ DO GOSUB sPWM GOSUB sSerial DEBUG CR, CR PAUSE 50 LOOP END  ‘ never reached ‘  ————- Subs ———————— sPWM: ‘Max sends 147 µs per inch ‘BS2 reads for 2 µs FOR xX = 1 TO 5 HIGH pMaxClock PULSIN pMaxPWM, 1, xPulse LOW pMaxClock DEBUG DEC5 xPulse, ” “ PAUSE 50 NEXT DEBUG CR RETURN sSerial: FOR xX = 1 TO 5 SERIN pMaxRecvpMaxClock, 16468, [WAIT (“R”), DEC xDist] DEBUG DEC5 xDist, ” “ PAUSE 50 NEXT DEBUG CR RETURN ‘ ——– Physical end of file ————
  • 5. (218) 454-0766    MAXBOTIXinfo@maxbotix.com  (5) C Program Driver for MaxBotix MB7066 PW Ultrasonic Sensor By Paul Sfetku, July 2011 Development System – Mikroelektronika http://www.mikroe.com/ Develop. Board:     BigPic6 with GLCD (128×64) Microcontroller:      PIC18F8520/8722 family Compiler:              mikroC PRO for PIC Interface:              BigPic6 SW7 RG0:  PORTG.B0 (output) → MB7066<4>  start/stop ranging BigPic6 SW7 RG1:  PORTG.B1 (input)  → MB7066<2>  PW – pulse width NOTE: BigPic6 SW7 is set for pull-up on PORTG pins RG0/B0 & RG1/B1. MB7066 Pin Out Pin 2 – PW: This pin outputs a pulse width representation of range. To calculate distance, you can a scale factor of 58us/cm. Pin 4 – RX: This pin is internally pulled high. The MB7066 will continually measure range and output if the pin is left unconnected or held high. If held low the MB7066 will stop ranging. Bring pin high for >= 20uS for range reading. Pin 6 – Vcc (3V – 5.5V): Average and peak current draw for 3.3V operation is 2.1mA (50mA peak). 5V operation is 3.4mA (100mA peak) respectively. Peak current is used during sonar pulse transmit. Pin 7 – GND: Return for the DC power supply. GND (& V+) must be ripple and noise free for best operation. NOTE: Refer to the MB7066 PW documentation for an explanation of MB7066 Real-time Operation & Timing Program Code Explanation The C code listed below was generated using the mikroC Pro PIC compiler. The code will drive the MaxBotix MB7066 pulse width (PW) sensor, and any MaxBotix pulse width sensor. The MB7066 is operated in free running mode with MB7066<4> pulled High. To operate the MB7066 in start/stop mode, you can uncomment code statements 8,9,10 and code statements 17,18,19. Statements 15-20 can be used to determine when and if the MB7066 fails to detect a return pulse from the given target. A value for maxvalue in statement 15 is needed to calibrate the sensor for a maximum time or maximum distance value. The code to drive the MB7066 is contained within an infinite loop declared in statement 11. The MB7066 operates on a 100ms PW cycle. MB7066 pin-2 PW sets high to start a ranging cycle, and sets Low if and when a target object is detected. If no target is detected, pin-2 PW will be held high for up to 62ms or 1068cm, the maximum range value. Code statements 12-25 are designed detect and measure the period of each PW begin/end cycle. Statement 12 detects when the PW goes High. The delay in statement 13 is used to calibrate the sensor’s ranging resolution to detect changes at one inch increments. The variable in statement 14 counts the number of delays until the PW signal does low. Statements 21-24 calculate the range and detect the beginning of the next 100ms PW cycle. Statement 22 calculates the range based on the time counted in statement 14, and based on a constant factor (.5) that can be adjusted to provide an accurate range measurement.
  • 6. (218) 454-0766    MAXBOTIXinfo@maxbotix.com  (6) C Program Driver for MaxBotix MB7066 PW Ultrasonic Sensor Cont. The loop in statement 24 is used to wait for the PW to set High, indicating the beginning of the next 100ms PW ranging cycle. // Declarations ——————————————————- TRISG = 0x02;                  // PORTG DDR: RG0 (output), RG1 (input) unsigned int msec    = 0;    // time counter – microseconds unsigned int inches   = 0;   // calculated distance unsigned maxvalue   = 0;   // sensor maximum – echo not detected void main() { //PORTG.B0 = 0;             // MB7066<4>: stop ranging – set Low //PORTG.B0 = 1;             // MB7066<4>: start ranging – set High //Delay_us(20);               // 20us delay for start of ranging while (1) {                      // infinite loop if (PORTG.B1) {                  // MB7066<2>: PW – check if High Delay_us(30);                  // delay factor 30us – gives 1 inch resolution msec++;                         // count time PW is High each microseconds //if (msec > maxvalue) {   // PW max time 62ms -> echo not detected // msec = 0;                    // clear counter // PORTG.B0 = 0;             // MB7066<4>: stop ranging – set Low // PORTG.B0 = 1;             // MB7066<4>: start ranging – set High // Delay_us(20);               // 20us delay for start of ranging //} } else {                             // MB7066<2>: PW -> Low inches = .5*msec;            // range (inches): target correction factor = .5 msec = 0;                        // clear counter while (!PORTG.B1);            // wait for MB7066<2> PW to go High -> start 100ms range cycle } } }
  • 7. (218) 454-0766    MAXBOTIXinfo@maxbotix.com  (7) Arduino I2C Code Example for I2CXL-MaxSonar Products Development System – Arduino Uno (as of Arduino 1.0.1) Develop. Board:     Arduino Uno R3 /* Code for Arduino Uno R3 Assumes the sensor is using the default address Sensor Connections: Pin 7 to GND Pin 6 to 5V Pin 5 to SCL Pin 4 to SDA Requires pull‑ups for SCL and SDA connected to 5V to work reliably */ #include “Wire.h” //The Arduino Wire library uses the 7-bit version of the address, so the code example uses 0x70 instead of the 8‑bit 0xE0 #define SensorAddress byte(0x70) //The Sensor ranging command has a value of 0x51 #define RangeCommand byte(0x51) //These are the two commands that need to be sent in sequence to change the sensor address #define ChangeAddressCommand1 byte(0xAA) #define ChangeAddressCommand2 byte(0xA5) void setup() { Serial.begin(9600);//Open serial connection at 9600 baud Wire.begin();//Initiate Wire library for I2C communications with I2CXL‑MaxSonar‑EZ } void loop() { takeRangeReading();                                       //Tell the sensor to perform a ranging cycle delay(100);                                                    //Wait for the sensor to finish word range = requestRange();                           //Get the range from the sensor Serial.print(“Range:”);Serial.println(range);          //Print to the user } //Commands the sensor to take a range reading void takeRangeReading(){ Wire.beginTransmission(SensorAddress);             //Start addressing Wire.write(RangeCommand);                             //send range command Wire.endTransmission();                                  //Stop and do something else now }
  • 8. (218) 454-0766    MAXBOTIXinfo@maxbotix.com  (8) Arduino I2C Code Example for I2CXL-MaxSonar Products Cont.  //Returns the last range that the sensor determined in its last ranging cycle in centimeters. Returns 0 if there is no communication. word requestRange(){ Wire.requestFrom(SensorAddress, byte(2)); if(Wire.available() >= 2){                            //Sensor responded with the two bytes byte HighByte = Wire.read();                        //Read the high byte back byte LowByte = Wire.read();                        //Read the low byte back word range = word(HighByte, LowByte);         //Make a 16-bit word out of the two bytes for the range return range; } else { return word(0);                                             //Else nothing was received, return 0 } } /* Commands a sensor at oldAddress to change its address to newAddress oldAddress must be the 7-bit form of the address that is used by Wire 7BitHuh determines whether newAddress is given as the new 7 bit version or the 8 bit version of the address If true, if is the 7 bit version, if false, it is the 8 bit version */ void changeAddress(byte oldAddress, byte newAddress, boolean SevenBitHuh){ Wire.beginTransmission(oldAddress);                 //Begin addressing Wire.write(ChangeAddressCommand1);              //Send first change address command Wire.write(ChangeAddressCommand2);              //Send second change address command byte temp; if(SevenBitHuh){ temp = newAddress << 1; }     //The new address must be written to the sensor else     { temp = newAddress;         }               //in the 8bit form, so this handles automatic shifting Wire.write(temp);                                          //Send the new address to change to Wire.endTransmission(); } As a minor note, in old Arduino IDE’s Wire.read() should be substituted by Wire.receive() and Wire.write() should be substituted by Wire.send()