 ## 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
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
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()```