Question

In: Computer Science

How do I change my if statements into while and for loops, so that I can...

How do I change my if statements into while and for loops, so that I can make my bot go straight and turn exactly 12 times.

/***********************************************************************
* Exp7_1_RotaryEncoder -- RedBot Experiment 7_1
*
* Knowing where your robot is can be very important. The RedBot supports
* the use of an encoder to track the number of revolutions each wheels has
* made, so you can tell not only how far each wheel has traveled but how
* fast the wheels are turning.
*
* This sketch was written by SparkFun Electronics, with lots of help from
* the Arduino community. This code is completely free for any use.
*
* 8 Oct 2013 M. Hord
* Revised, 31 Oct 2014 B. Huang
***********************************************************************/

#include <RedBot.h>
RedBotMotors motors;

RedBotEncoder encoder = RedBotEncoder(3,9); // initializes encoder on pins A2 and 10
int buttonPin = 12;
int countsPerRev = 192; // 4 pairs of N-S x 48:1 gearbox = 192 ticks per wheel rev

// variables used to store the left and right encoder counts.
int lCount;
int rCount;

void setup()
{
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
Serial.println("left right");
Serial.println("================");
}

void turn()

{

long lCount = 0;

long rCount = 0;

long targetCount;

float numRev;

motors.leftMotor(-80);

motors.rightMotor(0);
// variables for tracking the left and right encoder counts

long prevlCount, prevrCount;

long lDiff, rDiff; // diff between current encoder count and previous count

encoder.clearEnc(BOTH); // clear the encoder count

delay(100); // short delay before starting the motors.

while (lCount < 0)

{

// while the right encoder is less than the target count – debug print

// the encoder values and wait – this is a holding loop.

lCount = encoder.getTicks(LEFT);

rCount = encoder.getTicks(RIGHT);

Serial.print(lCount);

Serial.print("\t");

Serial.print(rCount);

Serial.print("\t");

Serial.println(targetCount);

// calculate the rotation “speed” as a difference in the count from previous cycle.

lDiff = (lCount - prevlCount);

rDiff = (rCount - prevrCount);

// store the current count as the “previous” count for the next cycle.

prevlCount = lCount;

prevrCount = rCount;

}

delay(500); // short delay to give motors a chance to respond.
motors.brake();

}


void loop(void)
{
  
// wait for a button press to start driving.

  
if(digitalRead(buttonPin) == LOW)
{
encoder.clearEnc(BOTH); // Reset the counters.
delay(500);
motors.drive(180); // Start driving forward.
}
  

// store the encoder counts to a variable.
lCount = encoder.getTicks(LEFT); // read the left motor encoder
rCount = encoder.getTicks(RIGHT); // read the right motor encoder

// print out to Serial Monitor the left and right encoder counts.
Serial.print(lCount);
Serial.print("\t");
Serial.println(rCount);

// if either left or right motor are more than 5 revolutions, stop
  
if ((lCount >= 5*countsPerRev) || (rCount >= 5*countsPerRev ))
{
  
turn();
encoder.clearEnc(BOTH);
//motors.brake();
delay(500);
motors.drive(180); // Start driving forward.
  
  
}
  
}

Solutions

Expert Solution

Below is a sample code doing the same:

CODE

#include <RedBot.h>
RedBotMotors motors;

RedBotEncoder encoder = RedBotEncoder(3,9); // initializes encoder on pins A2 and 10
int buttonPin = 12;
int countsPerRev = 192; // 4 pairs of N-S x 48:1 gearbox = 192 ticks per wheel rev

// variables used to store the left and right encoder counts.
int lCount;
int rCount;

void setup()
{
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
Serial.println("left right");
Serial.println("================");
}

void turn()

{

long lCount = 0;

long rCount = 0;

long targetCount;

float numRev;

motors.leftMotor(-80);

motors.rightMotor(0);
// variables for tracking the left and right encoder counts

long prevlCount, prevrCount;

long lDiff, rDiff; // diff between current encoder count and previous count

encoder.clearEnc(BOTH); // clear the encoder count

delay(100); // short delay before starting the motors.

while (lCount < 0)

{

// while the right encoder is less than the target count – debug print

// the encoder values and wait – this is a holding loop.

lCount = encoder.getTicks(LEFT);

rCount = encoder.getTicks(RIGHT);

Serial.print(lCount);

Serial.print("\t");

Serial.print(rCount);

Serial.print("\t");

Serial.println(targetCount);

// calculate the rotation “speed” as a difference in the count from previous cycle.

lDiff = (lCount - prevlCount);

rDiff = (rCount - prevrCount);

// store the current count as the “previous” count for the next cycle.

prevlCount = lCount;

prevrCount = rCount;

}

delay(500); // short delay to give motors a chance to respond.
motors.brake();

}


void loop(void)
{
  
// wait for a button press to start driving.

  
if(digitalRead(buttonPin) == LOW)
{
encoder.clearEnc(BOTH); // Reset the counters.
delay(500);
motors.drive(180); // Start driving forward.
}
  

// store the encoder counts to a variable.
lCount = encoder.getTicks(LEFT); // read the left motor encoder
rCount = encoder.getTicks(RIGHT); // read the right motor encoder

// print out to Serial Monitor the left and right encoder counts.
Serial.print(lCount);
Serial.print("\t");
Serial.println(rCount);

// if either left or right motor are more than 5 revolutions, stop

int count = 0;
  
while (count < 12)
{

if (lCount >= 5*countsPerRev) || (rCount >= 5*countsPerRev )
{
turn();
encoder.clearEnc(BOTH);
//motors.brake();
delay(500);
motors.drive(180); // Start driving forward.

count ++;
}
  
}
  
}


Related Solutions

how would i change the for loops to while loops in the code below #include<stdio.h> #include<stdlib.h>...
how would i change the for loops to while loops in the code below #include<stdio.h> #include<stdlib.h> int main() { int seed; // Taking seed value as input from the user printf("Enter a seed value (0 to quit): \n"); scanf("%d", &seed); // Running the loop until user enters 0 to quit // count array will count frequency of 0 , 1 , 2 ,3 int count[4]; for (int i = 0; i < 4; i++) count[i] = 0; while (seed !=...
while doing FPLC my dye(MHI-148) got stuck in column? . so how can i clean the...
while doing FPLC my dye(MHI-148) got stuck in column? . so how can i clean the column efficient? and why some particle stuck in column?
Objectives To reinforce the use of If-Else statements To learn how to use while loops Introduction:...
Objectives To reinforce the use of If-Else statements To learn how to use while loops Introduction: Mission to Mars Your friend has been playing a new Mars Colony simulator nonstop! They are always talking about how cool it would be if they could be a on the first real-life mission to Mars! To amuse your friend, you have decided to create a series of programs about the possible first colony on Mars. Problem: Where Can We Get the Best Deal?...
JAVA: How do I fix the last "if" statement in my code so that outputs the...
JAVA: How do I fix the last "if" statement in my code so that outputs the SECOND HIGHEST/MAXIMUM GPA out of the given classes? public class app { private static Object minStudent; private static Object maxStudent; public static void main(String args[ ]) { student st1 = new student("Rebecca", "Collins", 22, 3.3); student st2 = new student("Alex", "White", 19, 2.8); student st3 = new student("Jordan", "Anderson", 22, 3.1); student[] studentArray; studentArray = new student[3]; studentArray[0] = st1; studentArray[1] = st2; studentArray[2]...
How can i modify my c code so that each number stored in the array is...
How can i modify my c code so that each number stored in the array is not the array index but the value of the array index converted to radians. I have already made a function for this converion above main(). Below is the code: #include <stdio.h> #include <stdlib.h> #include <math.h> float Deg2Rad (float degrees) { // Calculate & return value float Result; Result = ((M_PI*degrees)/180.0); return (Result); } int main(void) { // Declare variables int Array[90]; int i; //...
THE NOT REPLACE PROBLEM Must use loops. Please do not use sequence of if statements. I...
THE NOT REPLACE PROBLEM Must use loops. Please do not use sequence of if statements. I need it in C++. Given an input string, set result to a string where every appearance of the lowercase word "is" has been replaced with "is not". The word "is" should not be immediately preceded or followed by a letter -- so for example the "is" in "this" does not count.   • for input of "is test" → "is not test" • for input...
Code in Python. You can only use while loops NOT for loops. Program 1: cost_living In...
Code in Python. You can only use while loops NOT for loops. Program 1: cost_living In 2020 the average cost of living/month (excluding housing) for a family of 4 in Pittsburgh was $3850 per month. Write a program to print the first year in which the cost of living/month is over $4450 given that it will rise at a rate of 2.1% per year. (Note:  this program requires no input). Program 2: discount A discount store is having a sale where...
How can I make my own function for rbinom(n, size, prob) in R. So, basically I...
How can I make my own function for rbinom(n, size, prob) in R. So, basically I want to build my own rbinom function that gives me the same result as rbinom that's built in R software.
Python I want to name my hero and my alien in my code how do I...
Python I want to name my hero and my alien in my code how do I do that: Keep in mind I don't want to change my code except to give the hero and alien a name import random class Hero:     def __init__(self,ammo,health):         self.ammo=ammo         self.health=health     def blast(self):         print("The Hero blasts an Alien!")         if self.ammo>0:             self.ammo-=1             return True         else:             print("Oh no! Hero is out of ammo.")             return False     def...
A father wants to know "How do I invest $73041 now so that my daughter gets...
A father wants to know "How do I invest $73041 now so that my daughter gets $900 per month of income for the next 15 years? Calculate the answer for this dad The interest rate of this investment should be ... % per month?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT