Introduction: How to Build an Arduino With an Ultrasonic Sensor

Ever wondered how you could move your body from our atmosphere to the one of Mars? No? Well, we didn't either until we came across the magic and excitement of a Cubesat and Arduino that would give us the experience of a real journey (with the limited cost;)).

Welcome to our very first Instructable regarding how to build an Arduino and Cubesat to use an Ultrasonic Sensor to map out the geography of Mars. Our goals are to obtain quality data that would showcase accurate depths and distances from our orbiting Cubesat to our SD card/computer that will analyze and give us a better idea of what Mars would look like based on our experiment. Overall, there are several steps to building this project and this tutorial will take you through with a variety of pictures and images to get you to create our final product for yourself! The process will be fairly simple and uses materials that should be accessible to most everyone such as: Legos, a basic Arduino Uno model, and some wires among a single sensor. This project is the second to last step for us to complete our journey to Mars from Earth, all hypothetically of course. Some constraints of this project for our team were time, materials, schedule (how much in class work time we have available), and scope (which we couldn't exceed). Several times, we experienced scope creep (where we had ideas that would go beyond our designated boundaries) and we had to scale back the project to fit our constraints. As you will see as our assignment progressed, we shifted our ideas only slightly such as our designs or where we had to fit in a certain parts; overall, we stayed primarily on task and stuck to our original plan. The criteria for success for our group was a solid design and strong building structure, and also communication and teamwork among all members to pull their own weight. Each member is in charge of a piece and works on all others as well in collaboration to finish the final product. Luckily, each of us had a strong suit such as Jacob with coding, Marco with constructing/building the Lego Cubesat, and Riley with designing and planning, as well as writing to describe our objectives. In our high school physics classroom, we first completed the initial leg of the journey by creating airplane gliders, then moved to a bottle rocket to break free of Earth's atmosphere, and finally we have transitioned to this Cubesat project to test Mar's conditions and environment from our circular orbits above. Along the way, we have learned about circular motion, Newton's Laws of Motion, Arduino programming and a variety of other concepts that have led us up to this more intense project. We hope you can complete this project very easily through our extended explanations and pictures, as well as have a fun time in doing so! Keep reading for our full tutorial and an overall video of our final design and project.


Step 1: Material List- Riley

For the Arduino (electronics, etc.):

1) 1 Ultrasonic Sensor

2) Several Wires

3) 1 9V Battery

4) 1 Battery Connector Cable

5) Arduino itself (a necessity)

6) 2-3 Resistors

7) SD Card Reader (read with a laptop using the SD Card from Arduino)

8) LCD Screen (optional: to read data)

For Cubesat:

1) Legos (a variety of sizes- small and large pieces)

Very simple materials for the Cubesat, NO GLUE NEEDED!!

But, what is a Cubesat?

Simply put by NASA's Cubesat Organization, a Cubesat is a "class of research spacecraft called nanosatellites... built to standard dimensions (Units or “U”) of 10 cm x 10 cm x 10 cm... and typically weigh less than 1.33 kg (3 lbs) per U. NASA's CubeSats are deployed from a Poly-Picosatellite Orbital Deployer [on missions in real space}."

Basically, Cubesats are tiny cubes that are much cheaper to launch into space and don't leave as much space debris after they die. They last a decently long time in orbit, but the piloting of them is basically non-existent as they have to be directed in the accurate direction of motion as they are first deployed. These Cubesats are a revolutionary satellite that allow NASA to dive deeper into space in an easier, more accessible, cost-friendly way.

Step 2: Begin the Process of Designing the Cubesat and Beginning to Construct- Riley

Starting from the beginning of our journey to create our Cubesat, we had to first create a design using standard Cubesat dimensions. We learned that 1U is the correct dimensions for the small box which is also known as 10cm by 10cm by 10cm. Our mass restriction was 1.33 kg as well, so our model does fit within those parameters with a 10% error allowance (as permitted by our teacher). This knowledge allowed us to ensure that our designs and sketches were as accurate as possible, and could be easily mapped out.


The layout our group decided would be best to house all our Arduino equipment, breadboard, etc., as well as a battery, was to create a shelf in the middle of the Cubesat with a window poking out to allow the sensor a direct exit out of the Cubesat, so no distances between the sensor and wall would be recorded. See pictures above for our first initial sketches! Each individual created their own design, but we ended up with the same consensus: a Cubesat with a window, 4 walls and a middle shelf. The next picture will show our final model complete with a full-scale depiction including all sizes and the potential issues we may encounter.

From this point on, we started building using a wide variety of Legos (see our picture for a full example of the range we had). The Lego sizes we used most often to build our Cubesat were 4x4s, 4x1s, 2x1s, 4x6s and 2x2s! These gave us the right amount of sizes to build our standard 1U design Cubesat. Next, we will move on to the actual construction of our Cubesat.

Step 3: The Actual Building of Our 1U Lego Cubesat -Riley

The next major step after designing is experimenting with the sizes and ideas of our final design to start the constructing process. As mentioned above, we used a variety of sizes mostly ones with 4" or 2" lengths to complete the build. The pictures featured show some of the process and the specific Lego pieces we used like hinges and other smaller pieces to truly get this Cubesat to survive our multiple tests it will undergo before its final round. Using Legos does require some testing and moving around pieces to fit your size dimensions and you will most likely need multiple tests and switching of pieces to complete your build. The key to creating a solid base is having a 14 by 11 panel as your bottom piece (counted using the Lego pegs for reference), and then making each of those 4 panels for your sides the same dimensions. Then, your top part can easily be made using simple Lego hinges or just a on and off top (regular Lego base). Experimentation will allow you to create your perfect 1U Cubesat, and hopefully our pictures will serve as quality references.

Step 4: Finding Code and Wiring- Prepping the Arduino/ FINAL MEASUREMENTS (PHYSICS CONCEPTS)-Riley

Once your Cubesat is solid and performs well under self- multiple stress/ shake tests, it is then time to program the Arduino using your chosen sensor. We used an Ultrasonic Sensor for our project, which would allow us to use its echolocation abilities to map out distances from our Cubesat to "Mars" (our simulated project, more details below) and then we could see the varying depths and size of "Mar's" surface. Firstly, we had to find suitable code online to make our Ultrasonic perform as needed (please see code above). Some of the best resources for code that we found was and which both provided easily accessible programming manuals and fritzing diagrams (also see above). Another reference for step by step instructions is shown in the video below from How To Mechatronics who explains in-depth the magic behind the SR04 Ultrasonic Sensor and the wiring as well.

Using our fritzing diagram developed by Arduino, we began the process of testing and wiring of our Arduino including our SR04 Ultrasonic Sensor.

Ultrasonic Sensor Data Sheet (all the information you would EVER need on the tiny data-processor):

NOTE: the last two fritzing diagrams are our exact designs, but the first was our inspiration:)


#include #include File dataLog; #define trigPin 8 #define echoPin 9 const int chipSelect = 4; void setup() { // put your setup code here, to run once: Serial.begin(9600); SD.begin(4); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(10, OUTPUT); pinMode(chipSelect, OUTPUT); if (!SD.begin(4)) { Serial.println("Dumb Error"); } dataLog ="log.txt", FILE_WRITE); dataLog.close(); if (SD.exists("log.txt")) { Serial.println("Awright we got em boys"); if (SD.remove("dataLog.txt") == true) { Serial.println("SD has been removed"); } else { Serial.println("Couldn't do it bro... the file remains."); }

} }

void loop() { // put your main code here, to run repeatedly: Serial.println("Go"); dataLog ="log.txt", FILE_WRITE); long duration, distance; if (dataLog) { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration / 2) / 29.1; if (distance >= 200 || distance <= 0) { dataLog.println("Out of range"); } else { dataLog.print(distance); dataLog.println(" cm"); } } delay(500); }

LINK FOR MORE SPECIFIED (for other purposes) CODE:


*The variables we solved for were the period, frequency, velocity, centripetal acceleration and centripetal force in our final tests. We also used our knowledge of Newton's Laws of Motion and the concept of gravity to complete our project. First, we started with learning the definitions of each of these variables, as listed below:

Period "T"- Time it takes to complete one full cycle around

Frequency "f"- Number of cycles in one full second

Velocity "distance/time"- Velocity is a measure of how fast something moves in a particular direction

Centripetal Force (Fc) "mv^2/r"- a force that acts on a body moving in a circular path and is directed toward the center around which the body is moving

Centripetal Acceleration (Ac) "v^2/r"- motion inwards towards the center of a circle

As we learned these concepts, we found that the period and frequency are based on seconds divided by cycles and vice versus as they are inverses of each other. The velocity is tangent to the circle and both centripetal acceleration and force are inward to the circle's center. We also must know that there is a tension force of the string that allows for the rotation of the Cubesat around our Mars model. This is shown up above in the diagram, as the tension force is a crucial component of our satellite in orbit process! All of this information helped us fully understand our experiment and understand how we would have to acquire our data. See our calculations below & pictures above:

Period "T": 0.395 seconds per cycle (shake test)/ 1.75 seconds per cycle

Frequency "f": 2.53 Hertz (shake test)/ 0.80 cycle per 1.5 seconds

Velocity: 2.2 m/s

Centripetal Acceleration: 9.1 m/s^2

Centripetal Force: 3.05 N (newtons)


In the last section, we discussed the wiring of the Arduino and how the sensor must be attached to the breadboard. But now, we must talk about safety practices we have used throughout the project! Be sure to first read any manuals and know the basic components of the Arduino before attempting any daring feats.

1) Start by experimenting with the Arduino and its technology. The main goal is to not accidentally short something on your circuit.

2) As with most electronic pieces, keep away from water and protect it from accidents and collisions.

3) THE MOST IMPORTANT: Make sure you are always grounded before touching any wires or electronic parts.

4) Keep the Arduino away from metal surfaces and ALWAYS leave the back on the breadboard so it doesn't short out as well.

5) Take proper static precautions & test one thing at a time (you never want a BIG BANG)

6) Use the right voltage amount always & don't use more than you need (for example, we are using a 9V battery as that is all we really need to work with)

7) DO NOT LET ANYTHING OVERHEAT: This has been a major issue with Arduino's in our physics classroom as LEDs have glitched and died, and batteries have gotten overheated. To prevent this, keep careful watch over your electrical materials and batteries always.

Basic Safety Practices:

-Always wear protective eyewear if cutting pieces (no matter what)

-Never leave cords or other small pieces exposed or for others to trip on

-Always unplug all electrical devices, when not in use

-If sawing or drilling, always have the item safely secured before proceeding with the initial action

-Check the conditions of all pieces you are working with: no broken wires, etc.


The process of wiring as described in the next section caused many issues that needed to be troubleshooted with the help of our teachers and some Reddit users as well. If you simply follow the final diagram as created by our team, not the inspired professional model, and use the code mentioned before, your Arduino should be set up with the Ultrasonic sensor to use echolocation for whatever experiment or test you completed. The full model we completed is accurate exactly down to the color of the wires we used on our own. Even though you will see that our test didn't go as planned, our Arduino and Cubesat was wired and even gathered some data that we will share in the final piece of this Instructable.

A few reminders:

1) We used a 9V battery for our system, but the voltage may vary depending on your experiment's needs.

2) When implementing the code, be sure to click verify and test as well, in order for the code to be correct and work with your Arduino/wiring.

3) We used a small/mini sized breadboard to fit within our Cubesat's necessary size requirements.

4) Plug the battery in last when wiring; this should be one of your final steps.

5) It is very important to double check which wires you put in which pins: say you need to wire it into an analog pin, but instead you use a digital pin, this will have an effect on the correct wiring of your Arduino with the code.

6) Resistors and LEDs can be common in many Arduino projects, but our team didn't use either. We also read our data from the SD card & adapter in the computer after our tests, but could use a digital reader display or bluetooth as well!

Step 6: Troubleshooting With the Arduino and Sensor -Riley/Jacob

While attempting our designs for the wiring and iteration of the Arduino with the Ultrasonic Sensor, we encountered numerous small challenges we had to overcome in a variety of ways. Jacob, our wiring expert, first had a difficult time finding code for the Sensor to the Micro SD Card Adapter and he used his knowledge from previous projects to ask questions on the help forum of Reddit. There, numerous experts reached out from his question with helpful advice that ultimately allowed him to find the code mentioned before to connect the two processors.

The codes for the original sensor and the adapter were different when it came to troubleshooting for them. The Ultrasonic sensor was coded relatively easily and the code was used as reference for the rest of the project. The code for the microSD was a struggle however, requiring multiple different trials using various tutorials as examples. The final product is an adaption of a code made by one of the Physics teachers in our school, Mr. Kuhlman, who managed to figure out how to transfer the data successfully.

Step 7: Sending Data to a MicroSD Card Adapter -Jacob

Mr. Kuhlman's code was used as an example to properly write a new code. Mr. Kuhlman discovered that the process involved managing files within the SD card using the built-in SD library within Aduino IDE, the coding program we used. The code created a new text file within SD card that the data would be written to. The Data that was gathered by the sensor was a distance in centimeters, within 0 to 200 cm. If the range was out of these bounds, the code would write "Out of Bounds". The data test worked swimmingly, gathering a bit of data that transferred over to the microSD card which could be read.

Step 8: Testing the Cubesat for Strength, Durability and Safety!- Marco

Testing the Cubesat for durability was the scariest part for our group to experience. Every time, we thought we were done building it a piece would fall off or the whole thing would fall apart; taking us back to square one. We would take time to analyze what the Cubesat needed, making sure that the testing wouldn't destroy the model. After multiple HAND shake test we secured the Cubesat, fixed any pieces that were out of place and ensured that the whole thing would maintain its shape. After all the time that we spent building the Cubesat we made sure to test it as soon as possible in order to see if all our hard work and efforts had paid off. Once we were on the testing lab we felt really nervous, only feeling the anxiety of what if this doesn't work, what if this piece falls off and the rest breaks. It was all building up to a climax when we finally turned on the shake table; we started slowly at first and then increased as time went by, we had to reach 25 volts for 30 seconds, to our surprise the Cubesat kept shaking and holding its structure. The reason we think the Cubesat lasted was because it was wedged into place tightly, interfering with the vibrations affecting the Cubesat's shape and strength. As time passed, we saw that our Cubesat had finally made it through the "earth's atmosphere", and we then tested the endurance of the Cubesat which withstood everything that we sent its way. Our Cubesat was finally done and ready for our final flight test with data.

Step 9: Final Adjustments and Securing the Arduino in the Cubesat- Marco/Riley

One of the issues we encountered was getting our Cubesat to face our Mars model and while we attempted with a Popsicle stick contraption, as seen above, a major issue we still faced was getting the Cubesat revolving around the model by the fan model (that propelled the experiment) at the correct speed, not too fast or slow. This forced 2 of our group members to stand near the Cubesat slightly pushing it as it went around, to allow the sensor to face the right way. As we began testing we had another member increase the speed of the fan in order to have the Cubesat face the right direction; once it started going it was hard to maintain the way in which it needed to face. With the speed increase, we needed to work together and make sure that the direction would remain constant with the speed. We finally reached our point of constant speed and direction after several minutes. Sadly, the CubeSat was notwithstanding the force of the tangent and met the fate of the floor as it came crashing down to the ground splitting into each individual Lego piece. The only thing left intact were the two levels holding the Arduino and breadboard in place, with both pieces safe and sound. After facing our demise we collected our piece and found that what had led to our CubeSats crash was a zip tie that had not been placed properly, and since in previous test and tries we had not used a zip tie; it was the variable that led to our massive crash. Finally, we checked if our data was recorded and luckily it seemed to gain enough data for us to present what we needed to show. Even though our Cubesat did not survive it did what it was meant to initially do, protecting our data, Arduino, and sensor from harm; our Cubesat had done its’ job.

Step 10: The FINAL PROJECT/ TEST (What Happened??)/ OUR DATA-Riley

Now came test day, where we would finally would see if our goal of finding the echolocation of Mars would be found using our data and tests. As we began our final test, we used a new method of securing the Cubesat to the ceiling fan type flight module we used to fly our Cubesat around the Mars model- a zip tie. Unfortunately, this small change had a very large consequence which can be seen in the pictures up above. Once at maximum speed (which we had already tested on), the stick contraption we used to face the Cubesat towards "Mars" stayed up while the Cubesat fell and smashed to the ground. Since our wiring was extremely secure and accurate, the limited data that had been recorded was still received and could be analyzed to a small extent, which can be seen ABOVE. The flat line of data is considered out of bounds and irrelevant when analyzing specific points, while luckily we do still have a maximum and minimum point. Still the out of bounds, shows our struggle and the path of our Cubesat to "Mars" as we tried to position the sensor to face the right way towards the model. The maximum shows a farther point that we can't necessarily trust as our model wasn't always in the correct path of motion, but it states that it was right under 200 cm at around 90 1/2 secs of our final flight. It shows our attempt at finding the echolocation, that would have been successful and more even data, if we would have had a consistent final flight with no issues/upsets. The minimum actually did not show up on the graph, as it would have gone beyond the out of bounds data, as decided by our wiring/data interpreter-expert, Jacob. While the scatter data and plots may not seem like much coherent knowledge, it does show that the Arduino and our wiring was accurate and connected well despite our issues previously mentioned with the SD Card reader/adapter. Overall, even though our project can be classified as a fail, had we not made one final change with the zip-tie, we would have had a successful project and recording Cubesat, that you can follow and make one of your own! Had we been able to continue our test, our data would have looked much different and we quite possibly could have found the geography of "Mars" using our Ultrasonic Sensor and echolocation.