Okay, so basically, I’m trying to have my robot go forwards, until it detects a wall, then reverse, and then turn into a random direction. Problem is, it’s only turning right. If anyone can help with this, I will be VERY appreciative, because I’ve spent about two days on it, and not even my teacher can figure out what’s wrong with it. It is more of a robotics thing rather than just a code thing, but you can probably just ignore the motor/servo jargon. Thanks!
#include <PRIZM.h> // include PRIZM library
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define RAND_MAX 1
PRIZM prizm; // instantiate a PRIZM object “prizm” so we can use its functions
void setup() {
prizm.PrizmBegin(); //initialize PRIZM
prizm.setServoSpeed(1,50);
prizm.setMotorInvert(1,1); // invert the direction of DC Motor 1
// to harmonize the direction of
// opposite facing drive motors
}
void loop() {
int x;
x = 1;
int r;
while((prizm.readSonicSensorCM(3) > 50)&&(x == 1))
{
prizm.setMotorPowers(40,40); // if distance greater than 25cm, do this
prizm.setServoPosition(1,146.75);
prizm.setServoPosition(2,55.5);
r = rand();
}
if((prizm.readSonicSensorCM(3) <= 50)||(x == 0))
{
x--;
prizm.setServoPosition(1, 54.5);
prizm.setServoPosition(2,145.25);
prizm.setMotorPowers(0,0);
delay(250);
prizm.setMotorPowers(-30,-30);
delay(750);
prizm.setMotorPowers(0,0);
delay(300);
if (r == 0) {
prizm.setMotorPowers(-50,50);
delay(1100);
}
else {
prizm.setMotorPowers(50,-50);
delay(1100);
}
prizm.setMotorPowers(0,0);
delay(200);
x++;
}
}
>Solution :
Note that your redefinition of RAND_MAX has no effect on the output of the rand() function. This is not a parameter for the function, but a constant telling you what the maximum value of the output is.
The best way to get a 50% of probability in your if (r == 0), is to go one side if r is even, the other if it is odd:
if ((r % 2) == 0) {
prizm.setMotorPowers(-50,50);
delay(1100);
}
else {
prizm.setMotorPowers(50,-50);
delay(1100);
}