Encoder Test program help!

Hi!

So I'm trying to test my encoders to see what the returned values are for different speeds. So I have produced this program to receive a serial integer value and set the motor speed to that value. Then i want to continuously output the PPS (pulses per second) of the encoder. However at the moment the program is only sending a PPS value after a serial command has been sent. Any suggestions or help would be very kindly appreciated!

Thanks :smiley:

unsigned long count = 0;        //Encoder pulse count
unsigned long timep, time, etime;    //Time tracking
int E1 = 5;    //motor speed and direction pins (i have two motors on the robot)
int E2 = 6;
int M1 = 4;
int M2 = 7;

long SPD = 0;                             //Set speed from serial

void setup() {
  Serial.begin(9600);
  pinMode(3,INPUT);
attachInterrupt(0,transition, CHANGE);
timep = micros();

  int i;
  for(i=4;i<=7;i++){
    pinMode(i, OUTPUT);  
  }
  
}
void loop() {
if(Serial.available()){
  
  SPD = Serial.parseInt();
  Serial.println(SPD);
  if (SPD >= 0){
  analogWrite (E1,SPD);                
  digitalWrite(M1,LOW);    
  analogWrite (E2,SPD);    
  digitalWrite(M2,LOW);
  }else if (SPD < 0){
  SPD = (SPD*-1);
  analogWrite (E1,SPD);                
  digitalWrite(M1,HIGH);    
  analogWrite (E2,SPD);    
  digitalWrite(M2,HIGH);  
  }
  
  time = micros();
  etime = time - timep;
  if (etime > 1000000)
  {
  Serial.println(count);
  count = 0;
  timep = time;
  }

}
}
void transition()
{
  count ++;
}

The variable "count" must be declared as volatile. For starters. You also need to disable interrupts in the main program while you access it.

Why is ALL of the code in loop() inside the if(Serial.available()) block?

If you put evry { on a new line, and used Tools + Auto Format, you'd see that, and it would be obvious what you need to do.

Ahhh yes, I'm sorry for my obvious inexperience in regards's to programming. However the above suggestions have been very useful to me and have fixed the problems i was experiencing. Furthermore PaulS, your suggestion with the auto format has pretty much slapped me in the face and said "your an idiot why didn't you do this before" kind of thing. Thank you so much!