I encountered problems trying to get readouts from the ultrasonic sensor in the mBot. After much tinkering and forum reading (with help from a post by @benjamin.m,) I was able to come up with this code that allows you to get sensor readouts using the COM window while connected via USB cable.
NOTE: Original code from @benjamin.m is in this link.
Modified code, below:
#include <Arduino.h>
#include <Wire.h>
#include <SoftwareSerial.h>
#include "MeMCore.h" // note the change in header for mBot
// Please read the comments. They include info to help customize the code for your particular set up.
// This code was borrowed and then revised from this one by @benjamin.m
// You can paste this directly to Arduino. Make sure your mBot is linked to the Arduino IDE using Tools > Port
// To see the ultrasonic readings, open Arduino IDE: Tools > Serial Monitor
MeBuzzer buzzer; // Initialize buzzer
MeUltrasonicSensor ultrasonic(3); // Initialize ultrasonic sensor. Change the number inside the parentheses to the port where you plugged your sensor
void setup()
{
Serial.begin(9600); //Begins communication with the computer at a baud rate of 9600
}
void loop()
{
Serial.print("Distance : "); //Prints the string "Distance : " over the serial most likely the usb. Can be seen using serial monitor in arduino tools setting
Serial.print(ultrasonic.distanceCm()); //Prints the value received from the Ultrasonic Sensor in Centimeters. Can be changed to inches with .distanceIn()
// mBot note: .distanceIn() does not seem to work on my mBot.
Serial.println(" cm");//Prints the string "cm" followed by a new line
if(ultrasonic.distanceCm()<20) { //if statement to check if data received is less than the value 20, in this case 20 centimeters
//If value is true the following code executes if false, code will skip this section
buzzer.tone(262,500); //turns buzzer on
delay(500); //waits 500 milliseconds or half a second with a minimum value of 100 or 1/10 of a second
buzzer.tone(0); //turns buzzer off
}
delay(100); //wait 100 milliseconds - Increase this for less frequent readings.
}