# The ROV Manatee - Part 3

## Build Your Own Remotely Operated Underwater Vehicle — Part 3: The Software and Final Observations

Last time, we covered the electronics package that reads the joystick and linear potentiometer, and then controls our motors. In this last part of the series, let’s finish with the software and some final thoughts.

## The Joystick Software

Here is the main loop that reads the joystick and the serial receive method. Several Serial.print statements used for debugging are removed, but they can be found in the complete program available at the article link:

void loop()<br /> {<br />     // Read joysticks - returns 0 to 1023<br />     xRight = analogRead(A3);<br />     yRight = analogRead(A2);<br />     xLeft = analogRead(A6);

// Normalize - returns a float -1 to +1 for<br />     //.x, + 1 to - 1 for y<br />     xNorm = normalizeX(float(xRight));<br />     yNorm = normalizeY(float(yRight));

// Now apply wheelchair algorithm<br />     if ((xNorm / 2.0) > 0.1) {nx = 0.1 + (xNorm<br />     /2.0 - 0.1) / 2.0;}<br />     else if ((xNorm / 2.0) < -0.1) {nx = -0.1 +<br />     (xNorm /2.0 + 0.1) / 2.0;}<br />     else {nx = xNorm/2.0;}

R = yNorm - nx;<br />     L = yNorm + nx;

// Clip as necessary<br />     if (R > 1.0) R = 1.0;<br />     if (R < -1.0) R = -1.0;<br />     if ((R <= 0.05) && (R >= -0.05)) R = 0.0;<br />     if (L > 1.0) L = 1.0;<br />     if (L < -1.0) L = -1.0;<br />     if ((L <= 0.05) && (L >= -0.05)) L = 0.0;

// Convert values to 0-255 for PWM<br />     iL = int(L * 255.0);<br />     iR = int(R * 255.0);

// Send new commands only if different<br />     if (iL != lastiL)<br />     {<br />         strTemp = formatString(abs(iL));<br />         if (iL > 0) {mySerial.println(“LMF” +<br />         strTemp);}<br />         else {mySerial.println(“LMR” + strTemp);}<br />         lastiL = iL;<br />     }<br />    <br />     if (iR != lastiR)<br />     {<br />         strTemp = formatString(abs(iR));<br />         if (iR > 0) {mySerial.println(“RMF” +<br />         strTemp);}<br />         else {mySerial.println(“RMR” + strTemp);}<br />         lastiR = iR;<br />     }

// Now look at Up/Down - strictly linear<br />     if (xLeft != lastxLeft)<br />     {<br />         // Up<br />         if (xLeft < 512)<br />         // Using X only for slider pot<br />         {<br />             yTemp = 255 - (xLeft / 2);<br />             if (yTemp < 15) yTemp = 0;<br />             strTemp = formatString(yTemp);<br />             mySerial.println(“UMU” + strTemp);<br />         }<br />         // Down<br />         else<br />         {<br />             yTemp = 255 - ((1023 - xLeft) / 2);<br />             if (yTemp < 15) yTemp = 0;<br />             strTemp = formatString(yTemp);<br />             mySerial.println(“UMD” + strTemp);<br />         }<br />         lastxLeft = xLeft;

}

// Now check for any messages received from<br />     // the ROV controller<br />     <br />     mySerialEvent();<br />     if (stringComplete)<br />     {<br />         String subStr = inputString.substring(0,<br />         3);<br />         if (subStr == “BAT”)<br />         {<br />             String temp = inputString.<br />             substring(3, inputString.length());<br />             float val = temp.toFloat();<br />             Serial.print(“ROV battery voltage<br />             = “);<br />             Serial.println(val);<br />         }<br />         stringComplete = false;<br />         inputString = “”;<br />     }

delay(200);<br /> }

void mySerialEvent()<br /> {<br />     while ((mySerial.available() > 0) &&<br />     (stringComplete == false))<br />     {<br />         // get the new byte:<br />         char inChar = (char)mySerial.read();<br />         // add it to the inputString:<br />         inputString += inChar;<br />         delay(2);<br />         // if the incoming character is a<br />         // newline, set a flag<br />         // so the main loop can do something<br />         // about it:<br />         if (inChar == ‘\n’)<br />         {<br />           stringComplete = true;<br />         }<br />     }<br /> }

## The ROV Controller Software

The main loop of the ROV controller is next, along with the battery read method. Again, Serial.print statements used for debugging have been removed but can be found in the complete download copy:

// These are for PWM

#define LMF   3<br /> #define LMR   5<br /> #define RMF   6<br /> #define RMR   9<br /> #define UMU   11<br /> #define UMD   10

const int bat = A0;

void loop()<br /> {<br />     mySerialEvent();<br />     if (stringComplete)<br />     {<br />         String subStr = inputString.substring<br />         (0, 3);<br />         String temp = inputString.substring<br />         (3, 6);<br />         byte val = (byte)temp.toInt();<br />         if ((val >= 0) && (val <= 255))<br />         {<br />             if (subStr == “LMF”)<br />             {<br />               // always turn off opposite<br />               // direction<br />               analogWrite(LMR, 0);<br />               analogWrite(LMF, val);<br />             }<br />             if (subStr == “LMR”)<br />             {<br />               analogWrite(LMF, 0);<br />               analogWrite(LMR, val);<br />             }<br />             if (subStr == “RMF”)<br />             {<br />               analogWrite(RMR, 0);<br />               analogWrite(RMF, val);<br />             }<br />             if (subStr == “RMR”)<br />             {<br />               analogWrite(RMF, 0);<br />               analogWrite(RMR, val);<br />             }<br />             if (subStr == “UMU”)<br />             {<br />               analogWrite(UMD, 0);<br />               analogWrite(UMU, val);<br />             }<br />             if (subStr == “UMD”)<br />             {<br />               analogWrite(UMU, 0);<br />               analogWrite(UMD, val);<br />             }<br />         }<br />         // Clear variables for next read<br />         stringComplete = false;<br />         inputString = “”;<br />     }

// Check 12 volt battery voltage and send topside<br /> battery();<br />  <br /> // Add a slight pause       <br /> delay(200);<br /> }

void battery()<br /> {<br />      // Check 12 volt battery voltage<br />     float fbat = float(analogRead(bat));<br />     // 2.734 factor adjusts from 5 volt analog<br />     // read to 12 volt scale<br />     //  adjusted to match voltmeter reading<br />     float voltage = ((fbat/1023.0)*5.0) * 2.734;<br />     mySerial.print(“BAT”);<br />     mySerial.println(voltage);<br /> }

## Optional Components

A two-resistor voltage divider brings the 12 volt battery voltage down to the five volt range that an Arduino needs to do an analogRead. Then, to compensate, the program simply multiplies the analog value by a constant to return it to the 12 volt range. A test read was done and compared to the actual voltage read by a digital voltmeter, then the multiplication factor was adjusted. The Arduino code for a simple battery read function is shown in the previous controller software example.

2. 9DOF
There are lots of options using Adafruit’s 9DOF (nine degrees of freedom). The outputs in the example here are in degrees, and from this you get a three-dimensional attitude in space. The sensor should be mounted so that the row of pins is oriented to the right and the board is level with the pitch-roll (x-y) plane; this way, the pitch, roll, and heading (yaw) come out correctly oriented. Here is some sample code that Adafruit provides:

/* Calculate pitch and roll from the raw accelerometer data */<br /> accel.getEvent(&accel_event);<br /> if (dof.accelGetOrientation(&accel_event, &orientation))<br /> {<br />         /* ‘orientation’ should have valid .roll<br />         /* and .pitch fields */<br />         Serial.print(F(“Roll: “));<br />         Serial.print(orientation.roll);<br />         Serial.print(F(“; “));  <br />         Serial.print(F(“Pitch: “));<br />         Serial.print(orientation.pitch);<br />         Serial.print(F(“; “));<br /> }<br />  <br /> /* Calculate the heading using the magnetometer */<br /> mag.getEvent(&mag_event);<br /> if (dof.magGetOrientation(SENSOR_AXIS_Z, &mag_event, &orientation))<br /> {<br />           /* ‘orientation’ should have valid<br />           /* .heading data now */<br />           Serial.print(F(“Heading: “));<br />           Serial.print(orientation.heading);<br />           Serial.print(F(“; “));<br /> }

3. Pressure
I have experimented with a 0-0.5 MPa (megaPascal) pressure sensor. This model and others with higher ranges are available on Amazon and eBay. These sensors have a simple three-wire interface: five volts, ground, and 0-5 volt analog out. I chose the smallest range to obtain the best accuracy. Testing this sensor by doing an analogRead showed that each additional value of one represented an additional 2.5 inches of fresh water pressure. For example, a reading going from 150 to 152 represents an additional 5.0 inches of fresh water depth. The Arduino analogRead returns values between 0 and 1023, but I found that my sensor read 113 with no water above it (probably to account for the drop across an output transistor).

The test code appears next. A function to smooth out the readings by taking an average of 10 readings is included. This function uses a circular buffer, avoiding the necessity of doing 10 reads from the sensor before averaging. After each read, the oldest value is discarded and the new value added to the sum. The last ten values are averaged:

int const BUFFER_SIZE = 10;<br />     // Number of samples you want to smooth out<br /> int press, indexBuffer = 0;<br /> int circularBuffer[BUFFER_SIZE];<br /> int sensorDataCircularSum;<br /> int filteredOutput;<br /> int average; //typically the value you read from<br />             //your sensor in your loop() function

void loop()<br /> {<br />   press = analogRead(A0);<br />   average = smoothSensorReadings(press);<br />   delay(100);<br /> }<br />  <br /> int smoothSensorReadings(int press){<br /> // We remove the oldest value from the buffer<br />   sensorDataCircularSum = sensorDataCircularSum -<br />   circularBuffer[indexBuffer];<br /> // The new input from the sensor is placed in the<br /> // buffer<br />   circularBuffer[indexBuffer] = press;<br /> // It is also added to the total sum of the<br /> // buffer<br /> // This method avoids needing sum all the<br /> // elements every time this function is called.<br />   sensorDataCircularSum += press;<br /> // We increment the pointer<br />   indexBuffer++;<br /> // We test if we arrived to the end of the buffer,<br /> // in which case we start again from index 0<br />   if (indexBuffer == BUFFER_SIZE) indexBuffer = 0;<br /> // The output is the mean value of the circular<br /> // buffer.<br />   filteredOutput =(sensorDataCircularSum/BUFFER_SIZE);<br />   return filteredOutput;<br /> }

4. Flood lamp
A flood lamp was added to the ROV. It’s a simple 12 volt lamp that is enclosed in a PVC coupling. A clear Plexiglas piece is cemented to the front and a PVC plug on the back. It is wired to the 12 volt battery so it is always on.

## Reflections

Here are some thoughts about what I might change or add. This ROV contains its battery power inside the watertight main tube. A second approach is to leave the main battery topside and run power down to the ROV in the tether. This means a larger, heavier tether that will probably need to have some floats added to make it approximately neutrally buoyant. As a trade-off, the main tube can be smaller.

The main tube should have been made a little longer, so the back of the tube extends out far enough for the black rubber cap to be removed without having to loosen the two large hose clamps that hold the main tube in place.

The uprights that mount the motors probably did not need to be extended outward. This will save a few elbows and simplify construction.

The motor mounting system was fairly simple. Quarter inch Plexiglas was glued with marine epoxy to the “ears” at the base of the motors, and then half-round plastic conduit clamps were used around the PVC uprights to attach the motors. The fit of the plastic conduit clamps was a bit loose, so a small square of 1/16 inch rubber was added inside the clamps to create a tighter fit. Additional instrumentation is certainly possible. The ROV controller board has connections for an Adafruit 9DOF board to add a compass, accelerometer, and gyroscope. There is also an additional place for a header to connect to a pressure gauge to measure the depth of water. A provision to remotely turn the flood lamp on and off would be useful.

A second vertical motor would allow the ROV to be tilted upward or downward for more natural movement. This would require a second joystick or linear potentiometer for control, and a fourth motor driver. A different microcontroller would also be necessary as additional PWM outputs would be needed. It is possible to connect the Arduino Nano controlling the joysticks via a USB cable to a laptop computer to read data (such as the battery’s voltage) using the Arduino’s GUI serial monitor. A useful additional feature would be a small LCD display mounted in the joystick box for reading returning data or status. The ROV Joystick board has pads for a header connected to the I2C bus (A4 and A5), as well as power connections that can be used to connect a serial type LCD display.

## Final Thoughts

I hope this homebrew project has served as an inspiration to go out and build stuff. Nothing is ever perfect the first time, but that’s part of the fun of the hobby: improvements.  SV