GRBL with Rotary Encoders

Hey Guys!

For my homemade CNC mill I'd like to add some rotary encoders to get the exact positions. For this project I connected 2 Arduinos one is programmed with the GRBL firmware the other is only for the encoder the problem I have now is how to make them to communicate.

I tried to connect the Rotary Arduino to the PC and read the value of the encoder over Serial Port and send Data over the Serial Port to the GRBL Arduino.

The Arduinos are connected over the RX and TX line. I think there are several better ways to do that but I dont know how to program the Arduino firmware correctly.

So I'm asking you guys, does anybody got an idea for that?

Hope you can help.

Send the data from one Arduino to the other over Serial. No need to involve the PC in the data transfer.

The PC is not involved in Data Transfer it looks like this:

**PC ** --G-Code--> ARotary --RX/tX--> AGRBL

This way is working but I the Datatransfer is really slow sure it's because I use the readString Method, is there a better way? Here's my code

const int pin_A = 10;
const int pin_B = 9;
unsigned char encoder_A;
unsigned char encoder_B;
unsigned char encoder_A_prev=0;
int i = 0;

void setup()  {
  Serial.begin(115200);
  pinMode(pin_A, INPUT_PULLUP);
  pinMode(pin_B, INPUT_PULLUP);
} 

void loop()  {
  while (Serial.available() > 0) {
    String code = Serial.readString();
    Serial.println(code);
  }

  
    encoder_A = digitalRead(pin_A);
    encoder_B = digitalRead(pin_B);   
    if((!encoder_A) && (encoder_A_prev)){
      if(encoder_B) {
        i++;              
      }else {
        i--;           
      } 
     Serial.println(i);
    }   
    encoder_A_prev = encoder_A;
}

Here’s my code

Why do you read in a String and then do nothing with it ?

Serial.readString() reads characters from the serial buffer into a string. The function terminates when it times out. Consider using C style strings (zero terminated arrays of chars) instead and write your own input routine

See Serial input basics - updated

Thanks a lot this works great! But I got one last question: Is a Rotary Encoder Speed limited or am i doing something wrong?

Now I send my G-Code and receive the Position from the encoder.

My Rotary encoder is direct connected to the NEMA17 Stepper motor with double shaft.

Max Feed Rate: 3000 mm/min

If I try to send G1 X100 F300 the value of the encoder is always right but if I send G0 X100 the value only counts til ~40 mm but the Stepper ran 100 mm so the problem might be the encoder or the rpm of the encoder.

This is the encoder: Wisamic 600p/r Incremental Rotary Encoder Dc5-24v

Hope you can help once more