I have been working on writing a code to control the iRobot Create movements (forward, backward, right, left and stop) from serial monitor and finally I got the correct code. I was trying to understand how to make stop moving when it face an obstacle but I couldn't get it. Also, I didn't know how to make move for a specific distance. Could anyone help me with this?
Here is my code:
#include "Arduino.h"
#include "Morse.h"
#include <SoftwareSerial.h>
#define rxPin 10
#define txPin 11
SoftwareSerial softSerial = SoftwareSerial(rxPin, txPin);
char inByte = 0; // incoming serial byte
irobot::irobot(int pin)
{
pinMode(pin, OUTPUT);
_pin = pin;
}
void irobot::Begin()
{
delay(2000); // Needed to let the robot initialize
// define pin modes for software tx, rx pins:
pinMode(rxPin, INPUT);
pinMode(txPin, OUTPUT);
// start the the SoftwareSerial port 19200 bps (robotís default)
softSerial.begin(19200);
// start hardware serial port
Serial.begin(19200);
softSerial.write(128); // This command starts the OI.
softSerial.write(131); // set mode to safe (see p.7 of OI manual)
delay(2000);
}
void irobot::runIt()
{
softSerial.write(142); // requests the OI to send a packet of
// sensor data bytes
softSerial.write(9); // request cliff sensor value specifically
delay(250); // poll sensor 4 times a second
if (Serial.available() > 0) {
inByte = Serial.read();
if(inByte == '8')
{
goForward();
}
if(inByte == '2'){
goBackward();
}
if(inByte == '4')
goLeft();
if(inByte == '6')
goRight();
if(inByte == '5')
stop();
}
Serial.println(inByte);
}
void irobot::goForward()
{
// Drive op code
softSerial.write(137);
// Velocity (-500 ñ 500 mm/s)
softSerial.write((byte)0);
softSerial.write((byte)200);
//Radius (-2000 - 2000 mm)
softSerial.write((byte)128);
softSerial.write((byte)0);
}
void irobot::goBackward()
{
// Drive op code
softSerial.write(137);
// Velocity (-500 ñ 500 mm/s)
softSerial.write(255);
softSerial.write(56);
//Radius (-2000 - 2000 mm)
softSerial.write((byte)128);
softSerial.write((byte)0);
}
void irobot::goLeft()
{
// Drive op code
softSerial.write(137);
// Velocity (-500 ñ 500 mm/s)
softSerial.write((byte)0);
softSerial.write((byte)200);
//Radius (-2000 - 2000 mm)
softSerial.write((byte)0);
softSerial.write((byte)1);
}
void irobot::goRight()
{
// Drive op code
softSerial.write(137);
// Velocity (-500 ñ 500 mm/s)
softSerial.write((byte)0);
softSerial.write((byte)200);
//Radius (-2000 - 2000 mm)
softSerial.write((byte)255);
softSerial.write((byte)255);
}
void irobot::stop()
{
softSerial.write(137);
softSerial.write((byte)0);
softSerial.write((byte)0);
//Radius (-2000 - 2000 mm)
softSerial.write((byte)0);
softSerial.write((byte)0);
}