I tried calling functions without Serial input and it worked just fine , but with this piece of code it just doesnt work, not quite sure why is this happening.
Your code doesn't compile, so I don't know how you can say whether it "works" or not.
I added this accidentally when posting a code here
MarkT:
Your code as posted has syntax errors and undeclared variables.
Please post the actual code that is failing together with a careful explanation of what
it should do and in what way it isn't working.
Those variables that are not declared were part of HC - SR04 detecting if a car is going to some object and making car to stop so it doesnt hit any object, forgot to delete it.
const int in1Pin = 5;
const int in2Pin = 4;
const int in3Pin = 3;
const int in4Pin = 2;
void stopMotors(void);
void rearWheelsForwards(void);
void rearWheelsBackswards(void);
void frontWheelsRight(void);
void frontWheelsLeft(void);
void setup()
{
Serial.begin(9600);
pinMode(in1Pin, OUTPUT); // first motor pin
pinMode(in2Pin, OUTPUT); // first motor pin
pinMode(in3Pin, OUTPUT); // second motor pin
pinMode(in4Pin, OUTPUT); // second motor pin
Serial.println("1 - forwards , 2 - backwards, 3 - left , 4 - right");
}
void loop()
{
if ( Serial.available()) {
char ch = Serial.read();
if (ch == '1')
{
Serial.println("CW");
rearWheelsForwards(); // makes rear DC motor go CW ,so car moves forward
}
else if (ch == '2' )
{
Serial.println("CCW");
rearWheelsBackwards(); // makes rear DC motor go CCW ,so car moves backwards
}
else if( ch == '3')
{
Serial.println("Left");
frontWheelsLeft(); // makes front DC motor go left, so car turns left side
}
else if( ch == '4'){
Serial.println("Right");
frontWheelsRight(); // makes front DC motor go right, so car turns left side
}
else if( ch == '0'){
stopMotors(); // if '0' is pressed car just shuts down all the motors
}
}
}
void stopMotors(void){
digitalWrite(in1Pin,LOW);
digitalWrite(in2Pin,LOW);
digitalWrite(in3Pin,LOW);
digitalWrite(in4Pin,LOW);
Serial.println("Motors stopped!");
}
void rearWheelsForwards(void){
digitalWrite(in1Pin,LOW);
digitalWrite(in2Pin,HIGH);
}
void rearWheelsBackwards(void){
digitalWrite(in1Pin,HIGH);
digitalWrite(in2Pin,LOW);
}
void frontWheelsRight(void){
digitalWrite(in3Pin,LOW);
digitalWrite(in4Pin,HIGH);
}
void frontWheelsLeft(void){
digitalWrite(in3Pin,HIGH);
digitalWrite(in4Pin,LOW);
}