Arduino Mega 2560 Ultrasonic Control Code

Ultrasonic sensors measure distance with ultrasonic waves. It measures timeframe from emitting sound until receiving the rebounced soundwaves. By knowing the soundspeed (340.29m/s), the ultrasonic controller can calculate the distance in 0.01cm accuracy. You can always ask the current distance between any object and the sensor. This a perfect tool for building small robots.

ultrasonic control arduino

Required hardware

  • Arduino Mega 2560
  • Ultrasonic sensor(s)

Source code to install on controller


Before you upload this code to your Arduino, please format the EEPROM...
#include <OzIDManager.h>
#include <OzUltraSonicSensor.h>

OzIDManager* manager;
OzUltraSonicSensor* ultraSonicSensor;

const int triggerPin = 2;
const int echoPin = 4;

void setup()
{
  Serial.begin(115200);

  manager = new OzIDManager;
  manager->_sendACK = true;
  manager->_checksum = true;

  OzCommunication::setIDManager(manager);

  ultraSonicSensor = new OzUltraSonicSensor(triggerPin, echoPin);

  int x=1;
  manager->sendLinkSetup();
  manager->PrintWelcomeLine(ultraSonicSensor, x++, "Ultra_1");
}

void loop()
{
  ultraSonicSensor->ownLoop();
  OzCommunication::communicate();
}

More information