Hello everyone.
I have a two wheel robot "Alphabot2" that works on Arduino Uno,
I want the robot to stop when detecting an obstacle and turn 90 degrees.
I managed so far to let the robot stop when detecting an obstacle, but I couldn't let it
turn. Please help.
this is the code:
#include <Wire.h>
#define PWMA 6 //Left Motor Speed pin (ENA)
#define AIN2 A0 //Motor-L forward (IN2).
#define AIN1 A1 //Motor-L backward (IN1)
#define PWMB 5 //Right Motor Speed pin (ENB)
#define BIN1 A2 //Motor-R forward (IN3)
#define BIN2 A3 //Motor-R backward (IN4)
#define Addr 0x20
int Speed = 120;
byte value;
void PCF8574Write(byte data);
byte PCF8574Read();
void forward();
void backward();
void right();
void left();
void stop();
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Wire.begin();
pinMode(PWMA,OUTPUT);
pinMode(AIN2,OUTPUT);
pinMode(AIN1,OUTPUT);
pinMode(PWMB,OUTPUT);
pinMode(AIN1,OUTPUT);
pinMode(AIN2,OUTPUT);
Serial.println("infrared Obstacle Avoidance example");
analogWrite(PWMA,Speed);
analogWrite(PWMB,Speed);
stop();
}
void loop() {
// put your main code here, to run repeatedly:
PCF8574Write(0xC0 | PCF8574Read()); //set Pin High
value = PCF8574Read() | 0x3F; //read Pin
if(value != 0xFF)
{
delay(50);
stop();
}
else
{
forward();
}
}
void PCF8574Write(byte data)
{
Wire.beginTransmission(Addr);
Wire.write(data);
Wire.endTransmission();
}
byte PCF8574Read()
{
int data = -1;
Wire.requestFrom(Addr, 1);
if(Wire.available()) {
data = Wire.read();
}
return data;
}
void forward()
{
analogWrite(PWMA,Speed);
analogWrite(PWMB,Speed);
digitalWrite(AIN1,LOW);
digitalWrite(AIN2,HIGH);
digitalWrite(BIN1,LOW);
digitalWrite(BIN2,HIGH);
}
void backward()
{
analogWrite(PWMA,Speed);
analogWrite(PWMB,Speed);
digitalWrite(AIN1,HIGH);
digitalWrite(AIN2,LOW);
digitalWrite(BIN1,HIGH);
digitalWrite(BIN2,LOW);
}
void right()
{
analogWrite(PWMA,50);
analogWrite(PWMB,50);
digitalWrite(AIN1,LOW);
digitalWrite(AIN2,HIGH);
digitalWrite(BIN1,HIGH);
digitalWrite(BIN2,LOW);
}
void left()
{
analogWrite(PWMA,50);
analogWrite(PWMB,50);
digitalWrite(AIN1,HIGH);
digitalWrite(AIN2,LOW);
digitalWrite(BIN1,LOW);
digitalWrite(BIN2,HIGH);
}
void stop()
{
analogWrite(PWMA,0);
analogWrite(PWMB,0);
digitalWrite(AIN1,LOW);
digitalWrite(AIN2,LOW);
digitalWrite(BIN1,LOW);
digitalWrite(BIN2,LOW);
}