For the past few weeks, I have been trying to figure out how to make my encoder work but i can't seem to find a solution to the problem. The problem is that the encoder won't count or counts but doesn't send it back to the computer. Can you guys suggest what is wrong or even give me a new code.
Here is my code
int rawsensorValue = 0; // variable to store the value coming from the sensor
int sensorcount0 = 0;
int sensorcount1 = 0;
long count = 0;
int RightMotorSpeedPin = 5; //M1 Speed Control
int LeftMotorSpeedPin = 6; //M2 Speed Control
int RightMotorDirectionPin = 7; //M1 Direction Control
int LeftMotorDirectionPin = 8; //M2 Direction Control
void setup() {
int i;
for(i=5;i<=8;i++)
pinMode(i, OUTPUT);
Serial.begin(9600);
int leftspeed = 255; //255 is maximum speed
int rightspeed = 255;
}
void loop() {
analogWrite (10,255);
digitalWrite(12,LOW);
analogWrite (11,255);
digitalWrite(13,LOW);
delay(20);
rawsensorValue = analogRead(0);
if (rawsensorValue < 600){ //Min value is 400 and max value is 800, so state chance can be done at 600.
sensorcount1 = 1;
}
else {
sensorcount1 = 0;
}
if (sensorcount1 != sensorcount0){
count ++;
}
sensorcount0 = sensorcount1;
Serial.println(count);
int leftspeed = 255; //255 is maximum speed
int rightspeed = 255;
int wait_period = 15000;
forward(rightspeed,leftspeed);
delay(wait_period);
stop();
delay(500);
stop();
while(1) {};
}
void stop(void) //Stop
{
digitalWrite(RightMotorSpeedPin,LOW);
digitalWrite(LeftMotorSpeedPin,LOW);
}
void forward(char right_speed, char left_speed)
{
analogWrite (RightMotorSpeedPin,right_speed);
digitalWrite(RightMotorDirectionPin,LOW);
analogWrite (LeftMotorSpeedPin,left_speed);
digitalWrite(LeftMotorDirectionPin,LOW);
}
void reverse (char right_speed,char left_speed)
{
analogWrite (RightMotorSpeedPin,right_speed);
digitalWrite(RightMotorDirectionPin,HIGH);
analogWrite (LeftMotorSpeedPin,left_speed);
digitalWrite(LeftMotorDirectionPin,HIGH);
}
void left (char right_speed,char left_speed)
{
analogWrite (RightMotorSpeedPin,right_speed);
digitalWrite(RightMotorDirectionPin,HIGH);
analogWrite (LeftMotorSpeedPin,left_speed);
digitalWrite(LeftMotorDirectionPin,LOW);
}
void right (char right_speed,char left_speed)
{
analogWrite (RightMotorSpeedPin,right_speed);
digitalWrite(RightMotorDirectionPin,LOW);
analogWrite (LeftMotorSpeedPin,left_speed);
digitalWrite(LeftMotorDirectionPin,HIGH);
}