Vision is one of the most overwhelming senses you can endow on your robot. The ability to perceive obstacles allows a robot to make an educated decision regarding further movements.
In this Blog Post, we will explore the following topics and code the Arduino:
Installing the required Arduino Hardware Support Packages for MATLAB.
Installing the required support Hardware package for ultrasonic sensor HC-SR04
About Ultrasonic sensor HC-SR04 and Servo motor
About ThingSpeak
Creating channels and fields in ThingSpeak
Circuit Connection
Programming the Arduino for Ultrasonic Mapmaker
Data Visualization Over ThingSpeak
This blog deals specifically with autonomous robots that use sensors (in this case, ultrasonic sensors) to create a 2D map of their surroundings. Autonomous robot systems depend highly on their ability to recover a durable spatial model of their surroundings from sensory information and use it in robot planning and control. All these abilities enable the robot to make its own temporary decisions based on the data collected by the sensor.
The data received from the sensors can be used to create a 2D/3D model for later use in different research programs and studies. Initially, the sensors will be used for gathering data that will produce a 2D image of its surroundings. The robot can be used for mapping known as well as unknown indoor or outdoor locations based on its need.
Install the required Arduino Hardware Support Packages for MATLAB
A support package is an addon that enables you to use a MathWorks® product with specific third-party hardware and software.
For installing Hardware Packages for MATLAB
One can easily install the Arduino Support packages for MATLAB by Navigating to the Home >>Add ons>> Get Hardware Support Packages >> MATLAB Support Package for Arduino Hardware >> Install >> Install / Download only.'
Now, let's move on to the home screen, where we get the option for AddOns which can be understood from the figure below:
After clicking on Add Ons, a drop-down menu will appear from where we can get the Get Hardware Support Package option, which is depicted in the following figure.
After clicking on Get Hardware Support Package option, we will be getting different Hardware Support Packages from where we will get our MATLAB Support Package for Arduino Hardware which is depicted in the following figure:
For more details, you can read our blog on the Installation of Hardware Support Packages below.
Unpackage the zip into the local directory and rename the folder to 'Ultrasonic'
Move the 'Ultrasonic' folder into the "libraries" folder inside your Arduino sketchbook folder: On Windows, the default path is "My Documents\Arduino\libraries\"
After Searching for Legacy HC-SR04 Add on Library for Arduino in the search bar, we will be getting the library as shown in the figure below. Then we need to install it as mentioned before.
About Ultrasonic sensor HC-SR04 and Servo motor:
In this project, we are using an ultrasonic distance sensor. It generates sound waves beyond the scope of human hearing and measures distance by calculating the time required by these waves to hit an obstacle and travel back. This is similar to the principle used by bats.
The sensor HC-SR04 is basically what guides the bot and takes all the readings. It emits ultrasonic waves, which hits an obstacle and reflects back to the sensor, after which it calculates the distance between the bot and the obstacle. There are four pins on the sensor as visible in Figure, VCC, TRIG, ECHO, and GND.
Each of these pins is connected to the Arduino board via jumper wires. The VCC pin is connected to the 5V volt power supply, the TRIG and ECHO pins are connected to output and input pins respectively on the Arduino board and the GND to one of the three ground connection pins on the board.
The two circular structures placed on the sensor's circuit board are the main parts of the module. These are the parts, which deal with sending out and receiving ultrasounds.
Now let's see how the ultrasonic sensor works!!
A short 10uS pulse is needed to the trigger input for the sensor to start the ranging; the module will start by sending out a burst of ultrasound waves at 40KHz and raise its echo. The range/distance of the sensor is calculated by the time taken of the reflection of the ultrasound to reach the sensor. In simpler words, it is the time interval between the initial signal sent and the echo signal received by the sensor.
The formula for this calculation is D = ½ T x C (where D is the distance, T is the time, and C is the speed of sound ~ 340 meters/second).
Eager to know the Advantages of Using the HC-SR04 ultrasonic sensor? Let's see the advantages:
Low cost.
It can effectively provide distance to objects.
Produces tractable amount of data for interpretation.
Another component that we are going to use is a servo motor. Now let's explore the servo motor.
Servo motor differs from the usual DC motor in that it can turn very precisely to a given angular position and hold its state there. When a servo motor is given pulses of a specific duration, it moves to the corresponding angular position.
Servo Motor
The Ultrasonic Sensor is placed on the servo so that it can take a 180-degree reading of its surroundings. The servo has three wires coming out of it, of the three one is for power, one for grounding and another for input that will be connected to the microcontroller, i.e., Arduino.
However, there are a couple of downsides of using the SG90 tower pro servo motor they are:
The motor cannot take readings of the surroundings of more than 180 degrees.
The motor only moves horizontally and not vertically
We will be using both these components to get a 180-degree field of view for our robot.
About ThingSpeak :
ThingSpeak™ is an IoT analytics platform service that allows you to aggregate, visualize, and analyze live data streams in the cloud. ThingSpeak provides instant visualizations of data posted by your devices to ThingSpeak. With the ability to execute MATLAB® code in ThingSpeak, you can perform online analysis and processing of the data as it comes in. ThingSpeak is often used for prototyping and proof of concept IoT systems that require analytics.
Now, let's explore the term IoT which is a very commonly used word these days.
Internet of Things (IoT) describes an emerging trend where a large number of embedded devices (things) are connected to the internet. These connected devices communicate with people and other things. They often provide sensor data to cloud storage and cloud computing resources, where the data is processed and analyzed to gain valuable insights. Cheap cloud computing power and increased device connectivity are enabling this trend.
IoT solutions are built for many vertical applications such as environmental monitoring and control, health monitoring, vehicle fleet monitoring, industrial monitoring and control, and home automation.
At a high level, many IoT systems can be described using the diagram below:
On the left, we have the smart devices (the "things" in IoT) that live at the edge of the network. These devices collect data and include things like wearable devices, wireless temperatures sensors, heart rate monitors, hydraulic pressure sensors, machines on the factory floor, etc.
In the middle, we have the cloud where data from many sources is aggregated and analyzed in real-time, often by an IoT analytics platform designed for this purpose.
The right side of the diagram depicts the algorithm development associated with the IoT application. Here an engineer or data scientist tries to gain insight into the collected data by performing historical analysis on the data. In this case, the data is pulled from the IoT platform into a desktop software environment to enable the engineer or scientist to prototype algorithms that may eventually execute in the cloud or on the smart device itself.
An IoT system includes all these elements. ThingSpeak fits in the cloud part of the diagram and provides a platform to quickly collect and analyze data from internet-connected sensors.
ThingSpeak Key Features:
ThingSpeak allows you to aggregate, visualize, and analyze live data streams in the cloud. Some of the critical capabilities of ThingSpeak include the ability to:
Easily configure devices to send data to ThingSpeak using popular IoT protocols.
Visualize your sensor data in real-time.
Aggregate data on-demand from third-party sources.
Use the power of MATLAB to make sense of your IoT data.
Run your IoT analytics automatically based on schedules or events.
Prototype and build IoT systems without setting up servers or developing web software.
Automatically act on your data and communicate using third-party services like Twilio® or Twitter®.
ThingSpeak is a platform providing various services exclusively targeted for building IoT applications. It offers the capabilities of real-time data collection, visualizing the collected data in the form of charts, the ability to create plugins and apps for collaborating with web services, social networks, and other APIs. We will consider each of these features in detail below.
The core element of ThingSpeak is a 'ThingSpeak Channel.' A channel stores the data that we send to ThingSpeak and comprises of the below elements:
8 fields for storing data of any type - These can be used to store the data from a sensor or an embedded device.
3 location fields - Can be used to store the latitude, longitude, and elevation. These are very useful for tracking a moving device.
1 status field - A short message to describe the data stored in the channel.
To use ThingSpeak, we need to sign up and create a channel. Once we have a channel, we can send the data, allow ThingSpeak to process it, and also retrieve the same. Let us start exploring ThingSpeak by signing up and setting up a channel.
Getting Started with ThingSpeak
Open https://thingspeak.com/ and click on the 'Get Started for Free' button on the center of the page, and you will be redirected to the Login page Click on create a new account at the bottom. Fill out the required details and click on the 'Create Account' button.
Create a new MathWorks account if you don't have one if filling the form, as shown in the image below.
Now you should see a page with a confirmation that the account was successfully created. The confirmation message disappears after a few seconds, and the final page should look as in the below screen:
Go ahead and click on 'New Channel'. You should see a page like the below:
You can change the name to fit your need, and you can add a description corresponding to the channel. You can add any other useful description to the metadata field. On the same page, you should see the fields for Latitude, Longitude, and Elevation. Also, when you scroll down, you should see a checkbox that says 'Make Public?'. Let us consider the significance of the various fields and the tabs:
Latitude, longitude, and elevation - These fields correspond to the location of a 'thing' and are especially significant for moving things.
Make Public? - If the channel is made public, anyone can view the channel's data feed and the corresponding charts. If this checkbox is not checked, the channel is private, which means for every read or write operation, the user has to pass a corresponding API key.
URL - This can be the URL of your blog or website and, if specified, will appear on the public view of the channel.
Video ID - This is the ID corresponding to your YouTube or Vimeo ID. If specified, the video appears on the public view of the channel.
Fields 1 to 8 - These are the fields that correspond to the data sent by a sensor or a 'thing'. A field has to be added before it can be used to store data. By default, Field 1 is added. In case you try posting to fields that you have not added, your request will still be successful, but you will not be able to see the field in the charts and the corresponding data. You can click on the small box after the 'field' text box corresponding to each field to add it. Once you click the checkbox, a default label name appears in the text box corresponding to each field, and to remove the field, just uncheck the checkbox. You can edit the field text that appears by default when a field is added to make more sense.
Once you have edited the fields, click on the 'Save Channel' button. You should now see a page like the below in which the 'Private View' tab is shown by default:
Now click on the 'API Keys' tab. You should see a screen similar to the below. The write API key is used for sending data to the channel, and the read API key(s) is used to read the channel data. When we create a channel, by default, a write API key is generated. We generate read API keys by clicking the 'Generate New Read API Key' button under this tab. You can also add a note corresponding to each of the read API keys.
Note: Please note that clicking on the 'Generate New Write API Key' will overwrite the previous key. You will only have one Write API key at any point in time. Also, in case your channel is private, others can only view the channel's feed and charts by using a Read API key. Please share the Read API keys with people who are approved and authorized to view your channel.
Now click on the 'Data Import/Export' tab, and you should see a screen similar to the below. This tab is used to import the 'Comma Separated Values (CSV)' data from a file into the channel. You can also download the channel's feed from here in CSV format. This tab also outlines how to send and view data by providing the URLs to the send and view APIs.
We can also combinedly visualize the data from different fields in a single plot using MATLAB by creating our custom code or by using different templates such as 2D area plot, line plot, etc. present in the ThingSpeakwebsite. To visualize the data, click on MATLAB Visualization in the Private View tab.
Then select any of the options as per the need. Either we can write our own customize code, or we can use any of the inbuilt templates by ThingSpeak, and after selecting, we just need to click on create.
Circuit Connection of different Components:
The hardware components, i.e., the Arduino Uno, Ultrasonic sensor HC- SR04 and the servo motor, are connected as described by the circuit diagram in the figure below:
MATLAB Code for Arduino {Use with R2016 to R2018 version}
We are using MATLAB R2018a for this project, and the code has been implemented on that version. Since MATLAB Support Package for Arduino includes Ultrasonic Library from MATLAB R2019, your initial code might be different. Put a comment if you are not able to make the connection working.
We will be using some of the inbuilt functions in MATLAB for the coding. In the first section, We will be creating an Arduino object by using the inbuilt function in MATLAB 'Arduino() ', and the arguments this function takes are the port in which the Arduino is connected. In my case,Arduino is connected to 'COM3'. The Arduino board that I am using is 'Uno.' Also, I have to mention the libraries that I am using, i.e. 'JRodrigoTech/HCSR04' library and 'Servo' library.
%% Create an Arduino object with the necessary addons.
a = arduino('COM3','Uno','Libraries',{'JRodrigoTech/HCSR04','Servo'});
In the next section, we will be creating an object both for the ultrasonic sensor as well as the servo motor. As the ultrasonic sensor library is an add on, we will be using the 'addon ()' function and the arguments this function takes are the Arduino object to which the sensor is interfaced, the library name, and the pins of Arduino to which sensor is connected, i.e., D12 and D13. Similarly, we will create an object for the servo motor by using the 'servo()' function.
%% Create an ultrasonic sensor object with trigger pin D12 and echo pin D13. % Create a servo object for the servo connected to pin D3. Ultrasonic_sensor = addon(a, 'JRodrigoTech/HCSR04', 'D12', 'D13'); servo_motor = servo(a, 'D3');
Then we will rotate the servo motor from 0 to 180 degrees and will get two readings from the ultrasonic sensor for each degree of position. Then we will average the two readings for better accuracy. For rotating the servo motor, we will be using 'writePosition()' function, and the angle to which the servo needs to be rotated will be mentioned as an argument to the function. To get the time for the echo to reach the ultrasonic sensor will be determined by the function'readTravelTime()' and then we will be calculating the distance by the formula mentioned before.
%% Rotate the servo motor from 0 to 180 degrees. % Every time the motor rotates by one degree, determine the distance of any obstacles % via the bounceback time of the ultrasonic ping. Take two measurements % and average them for accuracy. Record the angle and the distance (in cm)
i = 1;
% Creating a matrix having 2 coloums for angle and distance
table = zeros(180,2); for theta = 0 : 1/180 : 1 writePosition(servo_motor, theta); dist1 = readTravelTime(Ultrasonic_sensor)*340/2; pause(.1); dist2 = readTravelTime(Ultrasonic_sensor)*340/2; dist = (dist1+dist2)/2; table(i,1) = (i-1); table(i,2) = round(dist * 100,2); i = i + 1; end
% Rotate the servo motor from 180 to 0 degrees. Replace the values in the % table with the average of the clockwise and counterclockwise scans to % improve the accuracy of the map.
To send data over ThingSpeak channel we will need a timestamp for every row of data, so will create a vector of timestamps for 181 rows, i.e., 0 to 180 degrees and will merge with the data table by using the 'timetable()' function and by using the ThingSpeakWrite function we will be writing the data to the ThingSpeak server.
%% Sending data over Thingspeak % Mentioning channel ID and Write API key
%% Make a polar plot of the distance data to display the map. % Limit the theta values to be between 0 and 180 because the map is only % for obstacles in front of the servo.
polarplot (table(:,1)*pi/180, table (:,2)); title('Map of the Environment'); thetalim([0 180]); grid on;
OUTPUT:
The output is a polar plot that shows the distance of the obstacles from the sensor in 0 to 180 degrees field of view.The output shows the 2D map of the surroundings, and this mapping of the environment can be used for path planning and control for the robots.
Data Visualization over ThingSpeak
The above output that we got from the Arduino and MATLAB can also be visualized over the cloud in a distant location by sending the data over the internet. We will be using ThingSpeak to visualize the data and get the above plot over ThingSpeak.
To visualize the data over ThingSpeak, create a channel with two fields, one for the angle of rotation of the servo motor and another for the distance of obstacle in centimeter.
After creating the channel, replace the channel ID and API keys in the above MATLAB Code with the one from your channel and run the above MATLAB Code on your PC.
After running the above code, you will see these two plots, as shown below in the Private View tab of your channel. These two plots are for data of individual fields, i.e., angle of rotation of servo and the distance of obstacles.
Now, to combine the data of both the fields and get a single polar plot of the angle of rotation of servomotor and distance, click on MATLAB Visualization in the private View tab as shown in the below figure
Then click on Custom (no starter code) and then click on Create to write the code for getting the polar plot.
Write the MATLAB code for plotting the polar plot in the MATLAB code section and then click on Save, to view the data.
After writing the MATLAB code, click on Save and Run in-order to visualize the data. Now we can see three plots in the Private View Tab, i.e., Field-1 data, Field-2 data, and the Polar plot that we created. We can also visualize the polar plot in a public URL by clicking on the checkbox as shown in the below figure.
MATLAB Code for Visualization in ThingSpeak
% MATLAB code for visualizing correlated data using the polarplot function. % Prior to running this MATLAB code template, assign the channel variables. % Set 'readChannelID' to the channel ID of the channel to read from. % Also, assign the read field IDs to the variables 'fieldID1', and 'fieldID2'.
readChannelID =1096480;
fieldID1 =1; fieldID2 =2;
% Channel Read API Key % If your channel is private, then enter the read API
readAPIKey = 'PP14SWQ37PPLR22Z';
%% Read Data %% % Read first data variable data2 = thingSpeakRead(readChannelID, 'Field', fieldID1, 'NumPoints', 181, 'ReadKey', readAPIKey);
% Read second data variable data1 = thingSpeakRead(readChannelID, 'Field', fieldID2, 'NumPoints', 181, 'ReadKey', readAPIKey);
%% Visualize Data %% polarplot (data1*pi/180, data2); title('Map of the Environment'); thetalim([0 180]); grid on;
Conclusion
This is how we can use the MATLAB support package for Arduino and an ultrasonic sensor to create an ultrasonic map of the environment. Also, the blog explains about sending the data over the internet to the cloud platform ThingSpeak and visualization of the data over ThingSpeak.
The MATLAB code deals more with data than the actual control of the board, so all the sensor data is pushed over serial communication to the PC, where it is read by MATLAB.
Now, the data that we receive from the Arduino tells us two things, the degree of rotation of the servo and the distance of an obstacle in that direction. Hence, the data that we have at this point is in the Polar coordinate system.
And with that, I'm sure you must have got an insight into how to 2D map an environment using Arduino and MATLAB.
Get instant access to the code, model, or application of the video or article you found helpful! Simply purchase the specific title, if available, and receive the download link right away!#MATLABHelper #CodeMadeEasy
Ready to take your MATLAB skills to the next level? Look no further! At MATLAB Helper, we've got you covered. From free community support to expert help and training, we've got all the resources you need to become a pro in no time. If you have any questions or queries, don't hesitate to reach out to us. Simply post a comment below or send us an email at [email protected].
And don't forget to connect with us on LinkedIn, Facebook, and Subscribe to our YouTube Channel! We're always sharing helpful tips and updates, so you can stay up-to-date on everything related to MATLAB. Plus, if you spot any bugs or errors on our website, just let us know and we'll make sure to fix it ASAP.
Ready to get started? Book your expert help with Research Assistance plan today and get personalized assistance tailored to your needs. Or, if you're looking for more comprehensive training, join one of our training modules and get hands-on experience with the latest techniques and technologies. The choice is yours – start learning and growing with MATLAB Helper today!
Education is our future. MATLAB is our feature. Happy MATLABing!
I am a tech enthusiast, currently pursuing my Bachelor's under Electronics and Telecommunications Engineering. I have a keen interest in the field of MATLAB, Robotics, IoT, and Embedded systems. Currently working as a MATLAB Developer with MATLAB Helper.
i using the MATLAB R2020b , there is an error Message No add-on library uploaded to the board. Clear and recreate the current arduino object to include the appropriate library. For a list of available libraries, type ‘listArduinoLibraries’.
i using the MATLAB R2020b , there is an error Message No add-on library uploaded to the board. Clear and recreate the current arduino object to include the
appropriate library. For a list of available libraries, type ‘listArduinoLibraries’.
Give the Solution For this