## Project 1: Find the Wall

Documentation (description, images, video, code, etc) due to website by Wed (1/24) at 9pm.

Project Description: This project explores using an ultrasonic sensor to detect an object, and two simple types of control algorithms: a bang-bang controller and a simple proportional controller. You are to create a LEGO MINDSTORMS car robot that, using an ultrasonic sensor, approaches and detects a specific distance away from an object (e.g. 20cm).

## Project 1: Find the Wall

### Description:

Project 1 asks us to build up a car which can automatically stop when it reaches a certain distance to a front object. To achieve this functionality, I built a caterpillar using two motors, an ultrasonic sensor and other bricks to reinforce the structure. For the control part, I used Bang-Bang control and Proportional control.

### Bang-Bang Control

To avoid the car keep moving back and forth, I allowed 0.1 cm error to the car. The main part of the code is a cycle, which keep comparing the target value with the sensor value. when the car is too near to the wall, it will move backward, when it's too far, it will move forward, when the sensor value is between 19.9 cm and 20.1 cm, the program will jump out from the cycle, stop motors and output the sensor value.

Code:

```#!/usr/bin/python3 def main(): print('Bang Bang Control') ev3 = Device('this')
# define motors and the sensor motor1 = ev3.LargeMotor('outA') motor2 = ev3.LargeMotor('outD') sensor1 = ev3.UltrasonicSensor('in4')
# set initial speed speed = 200
# avoid the car moving back and forth Distance2 = 20.1 Distance3 = 19.9
# read sensor value S = sensor1.distance_centimeters%1
# control the car while 1: if S > Distance2 : motor1.run_forever(speed_sp=-speed) motor2.run_forever(speed_sp=-speed) elif S < Distance3: motor1.run_forever(speed_sp=speed) motor2.run_forever(speed_sp=speed) else : break S = sensor1.distance_centimeters
# stop motors when it reaches expected distance motor1.stop(stop_action='hold') motor2.stop(stop_action='hold') print(S)
if __name__ == '__main__': main()```

### Proportional Control:

The principle of my proportional control is, first,calculate the error between sensor value and target distance, then, set speed for motors as kp*error, after that, keep calculating the error and inputting it to motor. After the car reaches target distance, stop motors. The moving process of P control is quite different from Bang-Bang control, for the car moves in a decreasing speed and won't move backward.

Code:

```#!/usr/bin/python3 def main(): print('Proportional Control') ev3 = Device('this')
# define motors and the sensor motor1 = ev3.LargeMotor('outA') motor2 = ev3.LargeMotor('outD') sensor1 = ev3.UltrasonicSensor('in4')
# set expected distance Distance1 = 20 Distance2 = 20.1 Distance3 = 19.9
# read sensor value S = sensor1.distance_centimeters
# set proportional control parameters error = S - Distance1 kp=30 P=0.1*kp*error
# control the car while 1: if S > Distance2 : motor1.run_forever(speed_sp=-P) motor2.run_forever(speed_sp=-P) elif S < Distance3: motor1.run_forever(speed_sp=-P) motor2.run_forever(speed_sp=-P) else : break S = sensor1.distance_centimeters error = S - Distance1 P=kp*error
# stop the motor when it reaches expected distance motor1.stop(stop_action='hold') motor2.stop(stop_action='hold') print(S)
if __name__ == '__main__': main()```

## Imperial WalkerMax Luo and Aruni Kacker

Due to a variety of reasons, including switching partners and missed flights, we decided to repurpose our walker from Project 2 to fulfill the requirements to Project 1. The robot itself is modeled loosely after the heavy walker from Star Wars: the Last Jedi with the head and vaguely ape-shaped feet. It is a four-legged, two-actuator robot, where a gear train and careful joints convert rotational motion into linear motion.

The above image demonstrates the two-motor, four-legged configuration. It also shows an unpowered rear support wheel/leg; its sole purpose is to provide balance and does not contribute to the robot's forward motion.

The above image shows the position of the ultrasonic sensor. There were two different operating methods coded: a bang-bang, and a proportional control. The bang-bang program made the robot come to a complete stop from a given initial speed when it came within a defined distance of a wall, while the proportional control made the robot slow down upon entering a certain threshold until it came within a minimum distance. Furthermore, if the robot were to turn while within that threshold (i.e., the wall was removed), the robot would regain its initial speed until encountering another wall. Both code files are uploaded at the end of this post.

### Video:

Bang-bang control: the robot comes to a complete stop when it senses the wall at a fixed distance

Proportional control: The robot slows down proportional to its distance from the wall, until it comes to a complete stop at 5 cm away from the wall.

Proportional control: the robot slows as it approaches a wall, but returns to the original speed when it is moved away from the wall, and slows to a stop at a second wall.

The above screenshot is the Python code for the bang-bang operating method.

The above screenshot is the Python code for the proportional control operating method.

The goal of our project was to design a robot that would stop 20 cm from the wall using both a bang bang control and a proportional control. Our robot, the Batmobile consists of two motors to drive it forward and an ultrasonic sensor in the front to detect the distance from the wall.

For the bang bang controller, we programmed the robot to move forward until is reached 20 cm from the wall. Once it reaches this point, the robot is programmed to break and then automatically terminate the program.

Using a proportional control, we created a separate program that allowed the Batmobile to come to a more gradual stop. The Batmobile was designed to start slowing down proportional to its distance from the wall at 40 cm and come to a complete stop at 20 cm. The robot is also designed to work in the reverse. If it is placed too close to the wall (less than 20 cm), the robot will back away from the wall and come to a gradual stop 20 cm from the wall.

Above is the code for the bang bang control and below is the code for the proportional control.

## "Peggy" the Wallfinder

For our first project in ME84 we were tasked with designing a motorized robot that could sense when it was approaching a wall and stop at a predefined distance from that wall. Specifically, we were tasked with programming the robot to execute two solutions: the bang-bang control and a simple proportional control. The difference between the two solutions lied only in the code, and the robot remained the same from start to finish.

## The Design

Our robot is a rear wheel drive tricycle feature a front-facing ultrasonic sensor. The underbelly of the vehicle features a basic chassis which connects the two large motors in the rear to the EV3 computer on top. The front roller wheel is connect directly the front-bottom of the EV3 and the ultrasonic sensor is mounted on the side of the EV3.

The following images display how the motors and sensors, respectively,are connected to the EV3 brain.

As you can see, the rear left motor is connected to terminal A and the right side motor is connected to terminal B.

The ultrasonic sensor is connected to terminal 1.

## The Code

### Bang Bang Control

Bang Bang control uses sensor data to determine whether the car should be either moving at full speed or coming to a sudden stop and then backing up a bit.

The bang bang controller utilizes a while loop that continually updates the robot's location and then decides, based on the location, whether the motors should be on or not. Once the desired distance is reached, Peggy backs up to account for unwanted coasting.

Our code begins by printing "Test" and finishes by printing "Hello wall". This was included to ensure that the loop breaks and the code runs all the way through. Additionally, we added "print(distanceCM)" as a quality assurance measure. This line asks Peggy to report her final distance.

### Proportional Control

Proportional control uses sensor data to smoothly lower the speed of the car until it comes to a gentle stop 20 cm from the wall.

This code is similar to the bang bang controller but has different features in the while loop. Each time the loop runs, it calculates a new speed based on the current distance from the wall. A statement is included to ensure that the speed is set to 1000 if the calculation yields a speed beyond the max value. When the desired distance is reached, the motors should be at zero speed. Again, like in the bang bang code, Peggy greets her new friend and reports her relative location.

Look at her go.

## Overview:

The goal of this project was to design, build and code a robot that will detect an object in front of it and stop before it gets too close, either by stopping wholesale or by slowing down. To accomplish this project, a Lego Mindstorms EV3 kit was used to construct the design of a simple driving robot. Two programs, Bang-Bang and Proportional Control were used to control our robots motion. At the top of each coding file we made key parameters easily accessible to modify. An additional feature to these programs was added so that if the robot initially was too close to an object, it would back up until it had reached the desired distance.

This project was successful in creating a robot that could accomplish these goals: The robot was stable and built using only the EV3 kit, and the code for this robot successfully detects an object in front of it and stops according to the program running.

## Construction:

Our robot uses a two motor design with a caster wheel centered around the EV3 with an axis of symmetry through the ultrasonic sensor and caster wheel. The motors are secured and connected along the side, top and bottom of the EV3 unit, with the top support beam providing an easy handhold to move the robot during testing, while not blocking any buttons or the screen. This construction is sturdy under testing conditions.

## Bang-Bang:

The bang-bang program drives the robot (either forwards or backwards) at a fixed speed until it either detects that it is acceptably close to the target distance or has overshot. If it is at the target distance, the robot then stops. If it has overshot, then the robot drives the opposite direction at the same fixed speed. This process repeats until the robot reaches the target distance.

Since the bang-bang algorithm only has 2 speeds (full speed and stopped), this method results in the robot attempting to stop instantaneously, which is not possible. This results in the robot often over-shooting the target distance. The robot then attempts to correct for this and overshoots in the opposite direction. This repeats, resulting in the robot often oscillating repeatedly before finally stopping at the target distance.

## Proportional:

The proportional program drives the robot at a speed proportional to how far the robot is from the target distance. This causes the robot to gradually slow down until it reaches the target distance and stops. The only time motor speed is not proportional to distance is when the robot is so far away that the calculated speed is greater than the maximum speed of the motors used, in which case the robot drives at max speed. This control method results in a much smoother motion where the robot is much less likely to overshoot the target and oscillate around the target distance.

## Variance:

For both bang-bang and proportional control, we define the target distance as a range instead of an exact number. This is because it is unreasonable to expect a sensor reading to be an exact value. In addition, the precision of the sensor is greater than the expected precision of the robot. We added a variance parameter to account for this and settled on a value of 0.2 cm. This means that if the robot is within 0.2 cm of the target distance, the robot is considered at the target distance.

## Code:

### Proportional Control (proportional.py)

D'carula - by Alex Klein and Sahana Karthik

Description:

We present The D’carula - named after Dracula - with the c and the r switched so that the word car is in the name, because much like a vampire bat, the ultrasonic sensor uses waves to detect objects or obstacles in front of it. The D’carula was constructed with two motors, one attached to the left and one to the right side. Each motor controls one wheel and a roller was fixed to to the front at the bottom for more stability. Clip-like fixtures were added to the front of the car. These held the wires (connecting the motor to the brick) out of the ultrasonic sensor’s way, and the sensor was attached to the front of the car.

For the code that uses a bang-bang controller, the wheels moves at a constant power until it detects something that is 20 cm away from it. At this point it will stop. After stopping short, if the sensor still detects something within 20 cm, it will slowly start to back up until it is out of range (Top video). The code for the proportional controller (bottom video) uses an equation that multiplies some input value kp with the distance measured on the ultrasonic sensor. While the bang-bang controller simply makes the robot stop short, the proportional controller causes the car to slow down gradually from its top speed as it approaches an object, proportional to how far away the object is. This equation also ensures that the car stops before it is less than 20 cm away from the object. Further, we moved the box closer than 20 cm (also shown in video) and we can see that the car continued to move back and stop only when it was 20 cm away from the object.

Images:

Figure 1: View of the Overall design of The D'carula

Figure 2: Ultrasonic sensor attached to the back of the brick

Figure 3: Clip-like fixture that keeps the wire connecting the motor to the brick from obstructing the view of the sensor. The clip on the other side is used to hold up the ultrasonic sensor.

Figure 4: Side view of the supports that keep the motor stable and connected to the brick.

Figure 5: Front view of The D'Carula, showing the steel ball roller at the front to keep the entire robot level, and additional front supports for the motors (where the red connectors are).

Videos:

Bang-Bang Controller:

Proportional Controller:

Video

## Figure 1 - Plan view of car

Our car has a very simple design, using two motors (ports B and C) and wheels, along with a steel ball caster on the backside of the car to allow for movement. The ultrasonic sensor (input 1) is mounted on the front of the car pointing horizontally outward.

## Figures 2 and 3 - Rear view and Front view

The basic premise behind our car’s code is that when running, the ultrasonic sensor will continually take readings of the distance of the car to the nearest object in front of it. If this distance is greater than 20 cm, the car will move forward. After it detects that the distance is less than 20 cm, the car breaks and begins to back up. The backing up of the car is controlled by an i counter, starting at i = 0 and adding 1 after every reverse phase until i = 4. We chose a relatively small number as the car only needs to back up a few times to adjust and stop at approximately 20 cm from the wall.

When the car is placed near the wall (less than 20 cm away), the car automatically detects this and begins to back up and adjust to stay approximately 20 cm from the wall.

## Code Text

!/usr/bin/env python3

ev3 = Device("this")

from time import sleep

def main():

outC = ev3.LargeMotor('outC')

outB = ev3.LargeMotor('outB')

i = 0

while i < 4:

sensor = ev3.UltrasonicSensor('in1')

distanceCM = 0

distanceCM = sensor.distance_centimeters

if (distanceCM >= 20):

print("The distance in centimeters is:" + str(distanceCM))

outB = ev3.LargeMotor('outB')

outB.run_forever(speed_sp=90)

outC = ev3.LargeMotor('outC')

outC.run_forever(speed_sp=90)

sleep(0.1)

else:

print("The distance in centimeters is:" + str(distanceCM))

print("Reverse Thrusters")

outC = ev3.LargeMotor('outC')

outB = ev3.LargeMotor('outB')

outC.stop(stop_action='brake'); outB.stop(stop_action='brake')

sleep(0.5)

outC.run_forever(speed_sp=-90); outB.run_forever(speed_sp=-90)

sleep(1)

i = i+1

print (i)

outB.stop(stop_action='brake'), outC.stop(stop_action='brake')

if name == 'main':

main()

Intro:

For this assignment, we were told to build a robot that can sense an obstacle in front of it and stop to avoid collision. The robot should be able to do this through normal drive and through proportional control. Finally, bonus points would be awarded for a robot that could reverse away from the wall if it was too close.

The Robot:

To accomplish the  objectives above, we first constructed the physical robot. Using only the Lego kit provided, we built a semi-sturdy robot which moved on tank-treads driven by two motor modules. The distance from potential obstacles was sensed using an ultrasonic range finder, mounted on the forward face of the robot, approximately 2 inches above the ground.

We encountered some problems constructing a sturdy robot as the weight of the CPU tended to cause the middle of the robot to sag. This would not have been much of a problem if it had not caused the treads to become misaligned, driving the robot off course. We remedied the problem with a few extra linkages connecting the motors to the CPU in a second location. Our robot is now quite sturdy!

The Code:

The programming of the robot was quite simple, and came in two different flavors. The simpler version drives the motors forward at a constant speed, 75% of their full drive capability, until the robot comes within a certain distance of the wall. The more complex code incorporates a proportional controller, which slows the robot’s forward motion as it gets closer to the obstacle.

### Proportional Controller Drive Code:

Both versions begin by obtaining a distance reading from the ultrasonic range finder and storing this value in a variable called Distance. The values recorded to Distance did not appear to be of any known unit of length, rather some unscaled sensor output that ranged from 0 to 25.5. Through trial and error, we determined a good Distance value at which to stop the robot would be between 4 and 6, which corresponded to between 1 and 2 feet away from an obstacle.

Once a value was recorded to Distance, that value was passed to an if statement, which evaluated whether the robot was too close to continue. If Distance was less than 4, the Robot would not only stop moving forwards, but reverse direction to back away from the wall. An Else If ruled that if Distance was between 4 and 6, the robot would stop moving entirely. Finally, if Distance was greater than 6, the robot continued moving with a speed of MotorSpeed.

MotorSpeed is where the two flavors of robot code diverged. In the simpler code, MotorSpeed was always set to 75% of the highest possible speed, while in the proportional control code, it was a function of the distance from the object. This was accomplished by setting MotorSpeed equal to Distance times a constant. The constant (4) was a value that could scale the limited range of Distance to output all the way from 0 to 100 (or 0 to 1050) to drive the motors. Finally, in order to ensure no out of bounds values were passed to MotorSpeed, it was constrained to between 0-100 (later changed to 0-50 for testing in a small room).

All this code ran endlessly in a never-ending while loop.

Testing:

In testing, both versions of robot programming were able to stop the robot at the correct distance from the wall, and reverse accordingly if the robot was placed intentionally too close. The proportional controller steadily slows the robot to a crawl as it gets closer and closer to its stopping threshold. The robot does still tend to veer slightly off of a straight line when driving, though we feel this is likely due to shaking the robot experiences at what appears to be a resonant frequency at some low speeds. This could probably be corrected by building a robot with a lower center of mass and shorter linkages connecting all components. Overall, however, our project was a resounding success.

Video of Proportional Control Robot: https://drive.google.com/open?id=1KnJCxotErx5oTipOcEdLxKCzqd4XFGaL

### Proportional Control Code:

```#!/usr/bin/env python3 ev3 = Device("this")
def manageRange(n): return max(min(n,1050),-1050) def main(): distance = None error = None kp = None power = None user_prop_const = None text = None while True: distance = .1 * ev3.UltrasonicSensor('in2').distance_centimeters distance = distance * 10 print(distance) kp = 2 error = distance - 20 power = error * kp if error > 0.1: outA = ev3.LargeMotor('outA') outA.run_forever(speed_sp= manageRange(power* 10.50)) outB = ev3.LargeMotor('outB') outB.run_forever(speed_sp= manageRange(power* 10.50)) elif error < -0.1: outA = ev3.LargeMotor('outA') outA.run_forever(speed_sp= manageRange(power* 10.50)) outB = ev3.LargeMotor('outB') outB.run_forever(speed_sp= manageRange(power* 10.50)) elif error >= -0.1 or error <= 0.1: print('acceptable range has been reached') outA = ev3.LargeMotor('outA') outA.stop(stop_action="hold") outB = ev3.LargeMotor('outB') outB.stop(stop_action="hold") break else: break if __name__ == '__main__': main()```

### Simple Case Structure Code:

```#!/usr/bin/env python3 ev3 = Device("this")
def manageRange(n): return max(min(n,1050),-1050) def main(): distance = None while True: distance = .1 * ev3.UltrasonicSensor('in2').distance_centimeters distance = distance * 10 print(distance) if distance > 20.2: outA = ev3.LargeMotor('outA') outA.run_forever(speed_sp= manageRange(5* 10.50)) outB = ev3.LargeMotor('outB') outB.run_forever(speed_sp= manageRange(5* 10.50)) elif distance < 19.8: outA = ev3.LargeMotor('outA') outA.run_forever(speed_sp= manageRange((-5)* 10.50)) outB = ev3.LargeMotor('outB') outB.run_forever(speed_sp= manageRange((-5)* 10.50)) elif distance >= 19.8 or distance <= 20.2: print('acceptable range has been reached') outA = ev3.LargeMotor('outA') outA.stop(stop_action="hold") outB = ev3.LargeMotor('outB') outB.stop(stop_action="hold") break else: break if __name__ == '__main__': main()```

Professor Ethan Danahy

January 24th, 2018

## Finding the Wall Robot

For both tests, the car was assembled with the instruction manual. Ultrasonic sensor on the front will read the distance to the nearest object that the signal hits. Two motors control the right and left wheel respectively. We also made sure to plug in the motors and the sensor to appropriate port.

## CODE:

Bang-Bang Controller Code: This robot will stop when it reaches a wall

Bang bang control was implemented by setting the speed=0 when the car reaches within 10cm from the wall.

def main():

ev3 = Device('this')

Rmotor = ev3.LargeMotor('outC') #Large Motor Port C

Lmotor = ev3.LargeMotor('outB') #Large Motor Port B

UltraSonic = ev3.UltrasonicSensor('in4') #Ultrasonic Sensor Port 4

speed = 0 #initial speed

while True:

distance = UltraSonic.distance_centimeters #distance obtained from ultrasonic sensor

if (distance > 10): #travel as fast as possible if far away

speed = 1050

else:

speed = 0 # don't travel if slow

Rmotor.run_forever(speed_sp = speed) #executes speed

Lmotor.run_forever(speed_sp = speed)

if name == 'main':

main()

Proportional Controller Code: This robots will stop when it reaches a wall

Simple proportional control was implemented by making the speed proportional to the distance. The value of multiplier was determined by testing with few values.

def main():

ev3 = Device('this')

Rmotor = ev3.LargeMotor('outC') #Large Motor Port C

Lmotor = ev3.LargeMotor('outB') #Large Motor port B

UltraSonic = ev3.UltrasonicSensor('in4') #Ultrasonic Sensor Port 4

speed = 0

Kp = 10 #Proportional Control Value

while True:

distance = UltraSonic.distance_centimeters #Measured distance

if (distance < 5): #Car stops if within distance

speed = 0

else:

speed = distance *Kp #Speed value if further than 5 cm away

if (speed > 1050): #Constraints the motor speeeds to its max and min values

speed = 1050

if(speed < -1050):

speed = -1050

Rmotor.run_forever(speed_sp = speed)#Executes desired speed

Lmotor.run_forever(speed_sp = speed)

if name == 'main':

main()

## Video

Above: Bang Bang Control

As shown in the video, the car stops immediately after it reaches within the set distance from the wall since the bang bang control sets the speed to 0.

Below: Proportional Control

As shown in the video, the car begins to decelerate after it reaches within the set distance. The deceleration continues until it reaches the wall. With the proportional control, the car's speed is determined by the distance from the wall. In other words, the closer the distance between the car and the wall, slower the car will move.

### Martin and Omar's Wall Finding Robot

The goal of this project is to design and build a robot with the LEGO Mindstorms EV3 kit that will will detect when it is a certain distance away from an object / wall. The physical robot was designed to resembled a tank, hence the treads. A single motor was used to make coding slightly easier, and to because the robot does not need to turn. The ultrasonic sensor was placed as low as possible to the ground so that the robot would stop when it detects even the shortest object impeding its path.

Two algorithms were used to control when to stop the robot: bang-bang and proportional control. The bang-band algorithm simply stops the robot when it reaches the ideal distance. It will also reverse when the robot is too close to wall as well correct itself when it has driven too far. The proportional control algorithm slows down the robot as it approaches its ideal distance from the wall. The distance the robot starts to slow down is controlled in the code.