Arduino Code Refactoring

The code we ended with in the previous chapter is functional, but it is not the easiest to read or maintain. In this chapter, we will refactor the code to make it more readable and maintainable.

What you will learn

  • How to refactor code to make it more readable and maintainable
  • How to write code in C++

Terminology

member initializer list
A list of initializations for member variables in a C++ class

Lecture

The main goal of this chapter is to show a better version of the code we wrote in the previous chapter. We will refactor the code to make it more readable and maintainable.

Refactoring our WebSocket Arduino code

In this video, you will see steps to refactor our led blinking code from the previous chapter. Specifically, we will:

  1. Create a new file for our main program
  2. Create a new class to encapsulate our WebSocket code
  3. Implement a constructor, setup, and loopStep functions
  4. Create an instance of our new WebSocket class in the global scope
  5. Call the setup method inside the Arduino setup function
  6. Call the loopStep method inside the Arduino loop function

Refactoring our LED blinking code

Testing our refactored code

After-video cleanup

After recording the videos above, I spent some timing cleaning up the code. Here is a listing of the changes from the video.

Exercise

The goal of this exercise is to pull changes to the MobileRoboticsCode repository and make sure that you can get it to compile and run on your Arduino.

You will submit your responses on gradescope. Only one partner should submit. The submitter will add the other partner through the gradescope interface.

Additional details for using gradescope can be found here:

You should open the gradescope assignment now so that you know what to work complete.

Grading

I will grade all exercises using a scale of “Nailed It” / “Not Yet”. See the course grading policy for more information, and check gradescope for deadlines.

Overview

You will do the following:

  1. Pull changes from (or clone) the MobileRoboticsCode repository.
  2. Open the WSHeartbeatRefactored.ino file in the Arduino IDE.
  3. Upload the code to your Arduino.

Wrap-Up

In the next chapter, we will take what we’ve learned and add motor control to our robot.

Resources