Program state echo to serial port

Hi All,

I have doing some basic testing with the below which works fine, i wanted to the status of the program to output on the serial port i.e. “starting to move” “at 45” etc i started by just putting simple Serial.print("") commands into points of the below code i.e. just after the “myservo” statements but what happend was for every set degree of movement the message repeated itself in a linear line, i guess this is because the print statements were inside the loop which goes round for each degree increment of movement. Is there a way of echoing to the serial port the stage the program is at. I thought about separate loops before the servo control loops with simple print statements but then these would not echo the specific servo rotation point i.e. 0,45,90,180

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600);
  
}

void loop() 
{
  for (pos = 0; pos <= 180; pos += 45) { 
    delay(500);
    myservo.write(pos);              
    delay(50);
        

  }
  
  for (pos = 180; pos >= 0; pos -= 45) {
    delay(500);
    myservo.write(pos); 
    delay(50);             
                          
  } }

I don't see any print statement and you don't move degree by degree but 45 degrees by 45 - If the delays are enough... can you clarify what you meant or want to ask?

If you were moving 1 degree at a time in a for loop and only want to print when post is a multiple of 45 then you could check that with modulo if ((pos % 45)== 0) Serial.println(pos);

I am not entirely clear what you want but try this

void loop()
{
  Serial.println("Moving to 180");
  for (pos = 0; pos <= 180; pos += 45)
  {
    delay(500);
    myservo.write(pos);
    delay(50);
  }
  Serial.println("Now at 180");
  Serial.println();
  Serial.println("Moving to 0");

  for (pos = 180; pos >= 0; pos -= 45)
  {
    delay(500);
    myservo.write(pos);
    delay(50);
  }
  Serial.println("Now at 180");
  Serial.println();
}

Thanks both,

UKHeliBob - i can see where i went wrong and will give it a try

J-M-L - would the command “Serial.println(pos);” work after the "for (pos = 0; pos <= 180; pos +=45)
to always report the position it is currently at i.e. if i change the degree increment to say 10degrees then would i get on the serial monitor 0 10 20 30---------upto 180 as an output from the arduino.

Thanks both, i incorporated both comments and now get on the serial monitor

Moving to 180 0 45 90 135 180 Now at 180

Moving to 0 180 135 90 45 0

Great - see just needed to try out :)