2D Mapping With Arduino and ThingSpeak 

 August 14, 2020

By  Abhishek Agrawal

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:

  1. Installing the required Arduino Hardware Support Packages for MATLAB.
  2. Installing the required support Hardware package for ultrasonic sensor HC-SR04
  3. About Ultrasonic sensor HC-SR04 and Servo motor
  4. About ThingSpeak
  5. Creating channels and fields in ThingSpeak
  6. Circuit Connection
  7. Programming the Arduino for Ultrasonic Mapmaker
  8. 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

Install the required HC-SR04 ultrasonic Sensor Add-on Library for Arduino

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.

Ultrasonic Sensor

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.

Ultrasonic Sensor

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

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.

What is IoT?

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:

Getting Started with ThingSpeak

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:

Circuit connectiom

MATLAB Code for Arduino {Use with R2016 to R2018 version}


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.

2D map of environment

Data Visualization over ThingSpeak

MATLAB Code for Visualization in ThingSpeak 


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.

Thank you.

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!

About the author 

Abhishek Agrawal

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’.

    Give the Solution For this

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

    MATLAB Helper ®

    Follow: YouTube Channel, LinkedIn Company, Facebook Page, Instagram Page

    Join Community of MATLAB Enthusiasts: Facebook Group, Telegram, LinkedIn Group

    Use Website Chat or WhatsApp at +91-8104622179