Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem with Random Integer in C Robotics

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading