Hello there!
I am relatively new to programming and i have a small project for my school that is very simple but i have a little bug or code error but not quite sure what i am doing wrong.
Its a small robot that i control with wii joysticks via wireless serial communication.
I tried adding obstacle avoidance but after i added the code it seems if the serial communication is not working anymore.
So if someone could point out what im doing wrong it would be much appreciated!
Code with obstacle avoidance:
#include <Servo.h>
#define trigPin 12
#define echoPin 13
#define led 10
Servo myServo, motor;
String pos;
String sped;
String readString;
void setup(){
Serial.begin(19200);
myServo.attach(8);
motor.attach(9);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
}
void loop(){
int duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration/58.2;
if(distance < 7 && distance > 0 ){
digitalWrite(led, HIGH);
}else{
digitalWrite(led, LOW);
}
if (Serial.available()) {
char c = Serial.read(); //gets one byte from serial buffer
if (c == '*') {
//do stuff
int ind1 = readString.indexOf(','); //finds location of first ,
pos = readString.substring(0, ind1);
int ind2 = readString.indexOf(',', ind1+1);
sped = readString.substring(ind1+1, ind2);
int Pos = pos.toInt();
int Sped = sped.toInt();
if (Pos == 125){
Pos = 90;
}else if( Pos > 125){
Pos = map(Pos, 126, 225, 90, 160);
}else if ( Pos < 125){
Pos = map(Pos, 124, 30, 90, 20);
}else;
Pos = Pos;
myServo.write(Pos);
if(distance < 7 && distance > 0 ){
digitalWrite(led, HIGH);
}else{
digitalWrite(led, LOW);
if (Sped == 100){
motor.write(30);
}else{
motor.write(90);
}
}
readString = "";
pos = "";
sped = "";
}else{
readString += c;
}
}
}
Original code (Communication works fine):
#include <Servo.h>
Servo myServo, motor;
String pos;
String sped;
String readString;
void setup(){
Serial.begin(19200);
myServo.attach(8);
motor.attach(9);
pinMode(led, OUTPUT);
}
void loop(){
if (Serial.available()) {
char c = Serial.read(); //gets one byte from serial buffer
if (c == '*') {
//do stuff
int ind1 = readString.indexOf(','); //finds location of first ,
pos = readString.substring(0, ind1);
int ind2 = readString.indexOf(',', ind1+1);
sped = readString.substring(ind1+1, ind2);
int Pos = pos.toInt();
int Sped = sped.toInt();
if (Pos == 125){
Pos = 90;
}else if( Pos > 125){
Pos = map(Pos, 126, 225, 90, 160);
}else if ( Pos < 125){
Pos = map(Pos, 124, 30, 90, 20);
}else;
Pos = Pos;
myServo.write(Pos);
digitalWrite(led, LOW);
if (Sped == 100){
motor.write(30);
}else{
motor.write(90);
}
readString = "";
pos = "";
sped = "";
}else{
readString += c;
}
}
}
Thank you!