Week 04 Example Code


// Program week4Example.c
// Author Andy Hatfield
// Alleluia Community School
// Date Oct 24 2018
// Desc This program is used as a training/example program for ACS Afterschool Robotics Club.
// It has functions that move the robot forward, backward, turnLeft and turnRight

void moveDcm(float d, int pwr) {
//d is distance in cm based on the diameter
//pwr is the power in %
float dia = 5.6; //Standard EV3 wheel diameter in cm
float pi = 3.14; //PI approximation
float circ = pi * dia; //calculate the circumference
float deg = (360 / circ) * d; //calculate the circumference
eraseDisplay();
displayTextLine(2, "Move Forward");
displayTextLine(4, "Power=%d, dist=%d cm", pwr, d);
//Resets the motor encoder using the resetMotorEncoder command
resetMotorEncoder(motorC);
//While the encoder for the motorC is less than deg
while(getMotorEncoder(motorC) < deg) {//move until requested deg motor[motorC] = pwr; motor[motorB] = pwr; } motor[motorC] = 0; motor[motorB] = 0; } //Ends the function void backDcm(float d, int pwr) { //d is distance in cm based on the diameter //pwr is the power in % float dia = 5.6; float pi = 3.14; float circ = pi * dia; float deg = (360 / circ) * d; eraseDisplay(); displayTextLine(2, "Move backwards"); displayTextLine(4, "Power=%d, dist=%d cm", pwr, d); resetMotorEncoder(motorC); while(getMotorEncoder(motorC) > -deg) {//notice the negative sign
motor[motorC] = -pwr; //notice the negative sign
motor[motorB] = -pwr; //notice the negative sign
}
motor[motorC] = 0;
motor[motorB] = 0;
}

void turnLeft(int deg, int pwr) {
//deg is encoder degrees of the wheel
//pwr is the power in %
eraseDisplay();
displayTextLine(2, "Turn Left");
displayTextLine(4, "Power=%d, Degrees=%d", pwr, deg);
resetMotorEncoder(motorC); //only motorC is turning
//While the encoder for the motorC is less than deg
while(getMotorEncoder(motorC) < deg) {//move until requested deg motor[motorC] = pwr; //Wheel turns at power pwr motor[motorB] = 0; //Wheel does not turn } motor[motorC] = 0; motor[motorB] = 0; } void turnRight(int deg, int pwr) { //deg is encoder degrees of the wheel //pwr is the power in % eraseDisplay(); displayTextLine(2, "Turn Right"); resetMotorEncoder(motorB); //only motorB is turning displayTextLine(4, "Power=%d, Degrees=%d", pwr, deg); //While the encoder for the motorB is less than deg while(getMotorEncoder(motorB) < deg) {//move until requested deg motor[motorC] = 0; //Wheel does not turn motor[motorB] = pwr; //Wheel turns at power pwr } motor[motorC] = 0; motor[motorB] = 0; } task main() { moveDcm(10, 50); //Moves the robot forward sleep(1000); turnLeft(180, 50); //a small left turn sleep(1000); turnRight(720, 50); //a big right turn sleep(1000); backDcm(12.5, 25); //Moves the robot backwards sleep(1000); }

Leave a Reply

Your email address will not be published. Required fields are marked *

*