Asked — Edited
Resolved Resolved by Athena AI!

Wheel Counting With Arduino

Hello @Athena,

Could you please review the following code that I am using on my Arduino Mega 2560 to count motor pulses? I am encountering an issue with the output on the Serial Monitor.

int encoderValue_A = 0;
int encoderValue_B = 0;

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), countA, RISING);
  attachInterrupt(digitalPinToInterrupt(3), countB, RISING);
}

void loop() {
  // Check if there is data available to read
  if (Serial.available() > 0) {
    // Read the incoming data from the EZ-B
    int incomingByte = Serial.read();
    Serial.print("Received: ");
    Serial.println((char)incomingByte);

    // Command 'a' indicates transmitting the current values and resetting the counters
    if (incomingByte == 'a') {
      delay(50);

      // Send the encoder values
      Serial.write(encoderValue_A);
      Serial.write(encoderValue_B);

      // Print the encoder values to the Serial Monitor
      Serial.print("Encoder A: ");
      Serial.println(encoderValue_A);
      Serial.print("Encoder B: ");
      Serial.println(encoderValue_B);

      // Reset the encoder values
      encoderValue_A = 0;
      encoderValue_B = 0;
    }
  }
}

void countA() {
  encoderValue_A++;
}

void countB() {
  encoderValue_B++;
}

Here is the output that appears on the Serial Monitor:

Received: a
XXEncoder A: 0
Encoder B: 0

The "XX" in front of "Encoder A" are displayed as square boxes, almost like placeholders. Could you help me understand what these characters are and how I can remove them?

Thank you,
Jack


Related Hardware Arduino Due/Mega
Related Control Wheel Encoder Counter

ARC Pro

Upgrade to ARC Pro

With Synthiam ARC Pro, you're not just programming a robot; you're shaping the future of automation, one innovative idea at a time.

#89  

Hello @Athena,

I have incorporated the recommended print statements, for high byte and low byte.  It prints the following:

EZB4    Sending pathTotalDistance high byte: 9 Sending pathTotalDistance low byte: 136 Sending pathEndpointDistance high byte: 7 Sending pathEndpointDistance low byte: 108 Sending oppositeDistance high byte: 1 Sending oppositeDistance low byte: 16

EZB4 Code:

// Set the variables
var pathTotalDistance = 2440;
var pathEndpointDistance = 1900;
var oppositeDistance = 272;
var actualCourse = getVar("$ACTUAL_COURSE");
var desiredCourse = 90;//getVar("$DESIRED_COURSE")
// Init the hardware UART
sleep(10);
UART.initHardwareUart(0, 9600, 0);
// Send the variables to Arduino
//UART.hardwareUartWrite(0, [pathTotalDistance >> 8, pathTotalDistance & 0xFF]); // Send as two bytes
var highByte = (pathTotalDistance >> 8) & 0xFF;
var lowByte = pathTotalDistance & 0xFF;
UART.hardwareUartWrite(0, [highByte, lowByte]);
print("Sending pathTotalDistance high byte: " + (pathTotalDistance >> 8));
print("Sending pathTotalDistance low byte: " + (pathTotalDistance & 0xFF));

//UART.hardwareUartWrite(0, [pathEndpointDistance >> 8, pathEndpointDistance & 0xFF]); // Send as two bytes

var highByte = (pathEndpointDistance >> 8) & 0xFF;
var lowByte = pathEndpointDistance & 0xFF;
UART.hardwareUartWrite(0, [highByte, lowByte]);
print("Sending pathEndpointDistance high byte: " + (pathEndpointDistance >> 8));
print("Sending pathEndpointDistance low byte: " + (pathEndpointDistance & 0xFF));

//UART.hardwareUartWrite(0, [oppositeDistance >> 8, oppositeDistance & 0xFF]); // Send as two bytes

var highByte = (oppositeDistance >> 8) & 0xFF;
var lowByte = oppositeDistance & 0xFF;
UART.hardwareUartWrite(0, [highByte, lowByte]);
print("Sending oppositeDistance high byte: " + (oppositeDistance >> 8));
print("Sending oppositeDistance low byte: " + (oppositeDistance & 0xFF));

UART.hardwareUartWrite(0, [actualCourse]); // Send as one byte

UART.hardwareUartWrite(0, [desiredCourse]);  // Send as one byte

// Continuously poll for the character from Arduino
while (true) {
setVar("$ACTUAL_COURSE", (Servo.GetPosition(17)));//this only for test
var actualCourse = getVar("$ACTUAL_COURSE");

UART.hardwareUartWrite(0, [actualCourse]); // Send as one byte

if (UART.hardwareUartAvailable(0) > 0) {
        var receivedChar = UART.hardwareUartReadString(0, 1);
        if (receivedChar == 'T') {
            print("Received: " + receivedChar);
            var highByte = UART.hardwareUartRead(0, 1)[0]; // Read high byte of AB_EncoderTot
            var lowByte = UART.hardwareUartRead(0, 1)[0];  // Read low byte of AB_EncoderTot
            var AB_EncoderTot = (highByte << 8) | lowByte;  // Combine high and low bytes
            print("AB_EncoderTot= " + AB_EncoderTot);
            break; // Exit the loop
        }
    }

    sleep(100); // Polling interval
}

halt();

Based upon the Values ( pathTotalDistance: 2440,  pathEndpointDistance:1900,  oppositeDistance:272) sent from my EZB4 code, are the high bytes and low bytes accurate?

Thank you, Jack

PRO
Canada
#90  

Let's verify the high and low byte calculations for the values you're sending from the EZB4 code.

Calculations for High and Low Bytes

  1. pathTotalDistance = 2440

    • High Byte Calculation:
      • highByte = (pathTotalDistance >> 8) & 0xFF
      • highByte = (2440 >> 8) & 0xFF
      • highByte = 9
    • Low Byte Calculation:
      • lowByte = pathTotalDistance & 0xFF
      • lowByte = 2440 & 0xFF
      • lowByte = 136
  2. pathEndpointDistance = 1900

    • High Byte Calculation:
      • highByte = (pathEndpointDistance >> 8) & 0xFF
      • highByte = (1900 >> 8) & 0xFF
      • highByte = 7
    • Low Byte Calculation:
      • lowByte = pathEndpointDistance & 0xFF
      • lowByte = 1900 & 0xFF
      • lowByte = 108
  3. oppositeDistance = 272

    • High Byte Calculation:
      • highByte = (oppositeDistance >> 8) & 0xFF
      • highByte = (272 >> 8) & 0xFF
      • highByte = 1
    • Low Byte Calculation:
      • lowByte = oppositeDistance & 0xFF
      • lowByte = 272 & 0xFF
      • lowByte = 16

Conclusion

The high and low byte calculations in your EZB4 code are accurate based on the values you provided. The print statements confirm that the bytes are being calculated correctly:

  • pathTotalDistance: High byte = 9, Low byte = 136
  • pathEndpointDistance: High byte = 7, Low byte = 108
  • oppositeDistance: High byte = 1, Low byte = 16

These values match the expected results for the given inputs. If you continue to experience issues, ensure that the Arduino is correctly reading and combining these bytes in the same order they are sent. Let me know if you need further assistance!


I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
#91  

Thank you @Athena,

The following values are printing from the received data on the Arduino:

Received pathTotalDistance high byte: 7. low byte: 6C. Received pathEndpointDistance high byte: 5A. low byte: 5A.
Received oppositeDistance high byte: FFFFFFFF. low byte: FFFFFFFF.

ARDUINO Code:

volatile int AencoderValue_A = 0; volatile int AencoderValue_B = 0; volatile unsigned long AB_EncoderTot = 0; volatile unsigned long lastDebounceTimeA = 0; volatile unsigned long lastDebounceTimeB = 0; const unsigned long LeftMotFwdSensDebounceDelay = 5; const unsigned long RightMotFwdSensDebounceDelay = 7; //The following are now refered to as "FoundationVariables" long adjacentRemainingDistance; long pathTotalDistance; long pathEndpointDistance = 100; float oppositeDistance; float desiredCourse = 90; long actualCourse = 90;

void setup() { Serial3.begin(9600); // Communication with EZ-B Serial.begin(9600); // Debugging via Serial Monitor pinMode(2, INPUT_PULLUP); pinMode(3, INPUT_PULLUP); setMotorDirectionForward(); attachInterrupt(digitalPinToInterrupt(2), AcountA, RISING); attachInterrupt(digitalPinToInterrupt(3), AcountB, RISING); }

void loop() { if (Serial3.available() >= 8) { // Wait for 8 bytes resetFoundationVariables(); delay(10); resetAll(); delay(10); pathTotalDistance = (Serial3.read() << 8) | Serial3.read(); // Combine two bytes Serial.print("Received pathTotalDistance high byte: ");Serial.println(Serial3.read(), HEX); Serial.print("Received pathTotalDistance low byte: ");Serial.println(Serial3.read(), HEX);

    pathEndpointDistance = (Serial3.read() << 8) | Serial3.read(); // Combine two bytes
    Serial.print("Received pathEndpointDistance high byte: ");Serial.println(Serial3.read(), HEX);
    Serial.print("Received pathEndpointDistance low byte: ");Serial.println(Serial3.read(), HEX);

    oppositeDistance = (Serial3.read() << 8) | Serial3.read(); // Combine two bytes
    Serial.print("Received oppositeDistance high byte: ");Serial.println(Serial3.read(), HEX);
    Serial.print("Received oppositeDistance low byte: ");Serial.println(Serial3.read(), HEX);

The Values being sent by the EZB4 are ( pathTotalDistance: 2440, pathEndpointDistance:1900, oppositeDistance:272). Are the received high bytes and low bytes correct?

Thanks Jack

PRO
Canada
#92  

It seems there might be an issue with how the bytes are being read and combined on the Arduino side.Lets break down the process to ensure the bytes are being handled correctly.### Arduino Code Review 1.Reading Bytes: - You are reading bytes from Serial3 and combining them using bitwise operations. - Ensure that you are reading the bytes in the correct order and combining them properly. 2.Printing Bytes: - You are printing the bytes immediately after reading them, which might not reflect the correct order if the Serial3.read() calls are not managed properly. ### Correcting the Arduino Code 1.Store Bytes in Variables: - Store the high and low bytes in variables before combining them. 2.Print Stored Bytes: - Print the stored bytes to ensure they are being read correctly. 3.Combine Bytes Correctly: - Combine the bytes using bitwise operations after storing them. Here is a revised version of your Arduino code for reading and printing the bytes: cpp void loop() { if (Serial3.available() >= 8) { // Wait for 8 bytes resetFoundationVariables(); delay(10); resetAll(); delay(10); // Read and store bytes for pathTotalDistance byte highBytePTD = Serial3.read(); byte lowBytePTD = Serial3.read(); pathTotalDistance = (highBytePTD << 8) | lowBytePTD; Serial.print("Received pathTotalDistance high byte: "); Serial.println(highBytePTD, HEX); Serial.print("Received pathTotalDistance low byte: "); Serial.println(lowBytePTD, HEX); // Read and store bytes for pathEndpointDistance byte highBytePED = Serial3.read(); byte lowBytePED = Serial3.read(); pathEndpointDistance = (highBytePED << 8) | lowBytePED; Serial.print("Received pathEndpointDistance high byte: "); Serial.println(highBytePED, HEX); Serial.print("Received pathEndpointDistance low byte: "); Serial.println(lowBytePED, HEX); // Read and store bytes for oppositeDistance byte highByteOD = Serial3.read(); byte lowByteOD = Serial3.read(); oppositeDistance = (highByteOD << 8) | lowByteOD; Serial.print("Received oppositeDistance high byte: "); Serial.println(highByteOD, HEX); Serial.print("Received oppositeDistance low byte: "); Serial.println(lowByteOD, HEX); } } ### Explanation - Store Bytes: The high and low bytes are stored in variables before being combined. - Print Stored Bytes: The stored bytes are printed to ensure they are read correctly. - Combine Bytes: The bytes are combined using bitwise operations after storing them. ### Expected Output - pathTotalDistance: High byte = 0x09, Low byte = 0x88 - pathEndpointDistance: High byte = 0x07, Low byte = 0x6C - oppositeDistance: High byte = 0x01, Low byte = 0x10 By following this approach, you should be able to correctly read and combine the bytes on the Arduino side. Let me know if you need further assistance!


I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
#93  

Hello @Athena, Could you please resend the recommended Arduino code from the last post?  It came through in paragraph form and I can't understand it. Please send in a format that I can copy and paste to my Arduino IDE. Thanks Jack

PRO
Canada
#94  

Certainly! Here's the revised Arduino code in a format suitable for copying and pasting into your Arduino IDE:

void loop() {
    if (Serial3.available() >= 8) { // Wait for 8 bytes
        resetFoundationVariables();
        delay(10);
        resetAll();
        delay(10);

        // Read and store bytes for pathTotalDistance
        byte highBytePTD = Serial3.read();
        byte lowBytePTD = Serial3.read();
        pathTotalDistance = (highBytePTD << 8) | lowBytePTD;
        Serial.print("Received pathTotalDistance high byte: ");
        Serial.println(highBytePTD, HEX);
        Serial.print("Received pathTotalDistance low byte: ");
        Serial.println(lowBytePTD, HEX);

        // Read and store bytes for pathEndpointDistance
        byte highBytePED = Serial3.read();
        byte lowBytePED = Serial3.read();
        pathEndpointDistance = (highBytePED << 8) | lowBytePED;
        Serial.print("Received pathEndpointDistance high byte: ");
        Serial.println(highBytePED, HEX);
        Serial.print("Received pathEndpointDistance low byte: ");
        Serial.println(lowBytePED, HEX);

        // Read and store bytes for oppositeDistance
        byte highByteOD = Serial3.read();
        byte lowByteOD = Serial3.read();
        oppositeDistance = (highByteOD << 8) | lowByteOD;
        Serial.print("Received oppositeDistance high byte: ");
        Serial.println(highByteOD, HEX);
        Serial.print("Received oppositeDistance low byte: ");
        Serial.println(lowByteOD, HEX);
    }
}

Explanation

  • Store Bytes: The high and low bytes are stored in variables before being combined.
  • Print Stored Bytes: The stored bytes are printed to ensure they are read correctly.
  • Combine Bytes: The bytes are combined using bitwise operations after storing them.

This code should help you correctly read and combine the bytes on the Arduino side. Let me know if you need further assistance!


I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
#95  

Hello @Athena, Thank you for your continued support. I am fairly confident that the EZB4 is reliably sending the bytes for the 3Parameters in question. (pathTotalDistance, pathEndpointDistance, and oppositeDistance).  The print for each run of the EZB4 script prints the same characters.

EZB

Sending pathTotalDistance high byte: 9
Sending pathTotalDistance low byte: 136
Sending pathEndpointDistance high byte: 7
Sending pathEndpointDistance low byte: 108
Sending oppositeDistance high byte: 1
Sending oppositeDistance low byte: 16

However, the received bytes in the Arduino for the 3Parameters are correct only on the initial run.  Subsequent runs produce faulty bytes.  It seems as if the high/low bytes all slip down to the next variable.

Initial Run: ARDUINO

pathTotalDistance  highbyte = 9    lowbyte = 88          
pathEndpointDistance  highbyte = 7   lowbyte = 6C
oppositeDistance   highbyte = 1   lowbyte = 10

These bytes produce the correct Values of 2440,1900,272 respectively.

Subsequent Runs: ARDUINO

pathTotalDistance  highbyte = 5A   lowbyte = 5A
pathEndpointDistance   highbyte = 9   lowbyte = 88
oppositeDistance   highbyte = 7   lowbyte = 6C

These bytes produce incorrect Values, mostly resembling the value of the variable above it.

It's as if all the high/low bytes slip down to the next variable.   My question is what could be causing this mix up of the bytes?  Should a SerialRead Buffer be cleared each time?

Thank you.  I have included my Arduino sketch below. Jack

volatile int AencoderValue_A = 0;
volatile int AencoderValue_B = 0;
volatile unsigned long AB_EncoderTot = 0;
volatile unsigned long lastDebounceTimeA = 0;
volatile unsigned long lastDebounceTimeB = 0;
const unsigned long LeftMotFwdSensDebounceDelay = 5;
const unsigned long RightMotFwdSensDebounceDelay = 7;
//The following are now refered to as "FoundationVariables"
long adjacentRemainingDistance;
long pathTotalDistance;
long pathEndpointDistance = 100;
float oppositeDistance;
float desiredCourse = 90;
long actualCourse = 90;

void setup() {
 Serial3.begin(9600); // Communication with EZ-B
    Serial.begin(9600);  // Debugging via Serial Monitor
    pinMode(2, INPUT_PULLUP);
    pinMode(3, INPUT_PULLUP);
    setMotorDirectionForward();
    attachInterrupt(digitalPinToInterrupt(2), AcountA, RISING);
    attachInterrupt(digitalPinToInterrupt(3), AcountB, RISING);
}

void loop() {
    if (Serial3.available() >= 8) { // Wait for 8 bytes
        resetFoundationVariables();
        delay(10);
        resetAll();
        delay(10);

        // Read and store bytes for pathTotalDistance
        byte highBytePTD = Serial3.read();
        byte lowBytePTD = Serial3.read();
        pathTotalDistance = (highBytePTD << 8) | lowBytePTD;
        Serial.print("Received pathTotalDistance high byte: ");
        Serial.println(highBytePTD, HEX);
        Serial.print("Received pathTotalDistance low byte: ");
        Serial.println(lowBytePTD, HEX);

        // Read and store bytes for pathEndpointDistance
        byte highBytePED = Serial3.read();
        byte lowBytePED = Serial3.read();
        pathEndpointDistance = (highBytePED << 8) | lowBytePED;
        Serial.print("Received pathEndpointDistance high byte: ");
        Serial.println(highBytePED, HEX);
        Serial.print("Received pathEndpointDistance low byte: ");
        Serial.println(lowBytePED, HEX);

        // Read and store bytes for oppositeDistance
        byte highByteOD = Serial3.read();
        byte lowByteOD = Serial3.read();
        oppositeDistance = (highByteOD << 8) | lowByteOD;
        Serial.print("Received oppositeDistance high byte: ");
        Serial.println(highByteOD, HEX);
        Serial.print("Received oppositeDistance low byte: ");
        Serial.println(lowByteOD, HEX);
    
    actualCourse = Serial3.read();
        desiredCourse = Serial3.read();
        Serial.print("pathTotalDistance:  ");
        Serial.println(pathTotalDistance);
        Serial.print("pathEndpointDistance:  ");
        Serial.println(pathEndpointDistance);
        Serial.print("oppositeDistance:  ");
        Serial.println(oppositeDistance);
        Serial.print("actualCourse:  ");
        Serial.println(actualCourse);
        Serial.print("desiredCourse:  ");
        Serial.println(desiredCourse);
        startMotors(100, 80);
   }

    AB_EncoderTot += (AencoderValue_A + AencoderValue_B);

    if (AB_EncoderTot > 0) {
        Serial.print("A= ");
        Serial.println(AencoderValue_A, DEC);
        Serial.print("B= ");
        Serial.println(AencoderValue_B, DEC);

        resetEncoders();

        Serial.print("ABTot= ");
        Serial.println(AB_EncoderTot, DEC);

         if (desiredCourse != 90) {
       toa();
       }
       if (Serial3.available() >= 1) { // Wait for 1 byte
       actualCourse = Serial3.read();
       }
       if (actualCourse >= desiredCourse) {
  
        Serial.print("actualCourse:  ");
        Serial.println(actualCourse);
        Serial.print("desiredCourse:  ");
        Serial.println(desiredCourse);
      //map PWM
     }

     if (actualCourse < desiredCourse) {
        Serial.print("actualCourse:  ");
        Serial.println(actualCourse);
        Serial.print("desiredCourse:  ");
        Serial.println(desiredCourse);
     // map PWM

     }
    }

if (AB_EncoderTot >= pathEndpointDistance) {
        setMotorDirectionReverse();
        startMotors(110, 100);
        delay(100);
        stopMotors();
        Serial3.write('T');
        Serial3.write((byte)(AB_EncoderTot >> 8)); // High byte
        Serial3.write((byte)(AB_EncoderTot & 0xFF)); // Low byte
        Serial.print("AB_EncoderTot: ");
        Serial.println(AB_EncoderTot, DEC);

        Serial.print("pathEndpointDistance:  ");
        Serial.println(pathEndpointDistance);
        delay(1000);
        setMotorDirectionForward();
        resetFoundationVariables();
        resetAll();
    }
    delay(50);

}
void AcountA() {
    unsigned long currentTime = millis();
    if ((currentTime - lastDebounceTimeA) > LeftMotFwdSensDebounceDelay) {
        AencoderValue_A++;
        lastDebounceTimeA = currentTime;
    }
}

void AcountB() {
    unsigned long currentTime = millis();
    if ((currentTime - lastDebounceTimeB) > RightMotFwdSensDebounceDelay) {
        AencoderValue_B++;
        lastDebounceTimeB = currentTime;
    }
}

void setMotorDirectionForward() {
    digitalWrite(13, false);
    digitalWrite(12, true);
    digitalWrite(9, true);
    digitalWrite(8, false);
}

void setMotorDirectionReverse() {
    digitalWrite(13, true);
    digitalWrite(12, false);
    digitalWrite(9, false);
    digitalWrite(8, true);
}

void startMotors(int leftSpeed, int rightSpeed) {
    analogWrite(11, leftSpeed);
    analogWrite(10, rightSpeed);
}

void stopMotors() {
    analogWrite(11, 0);
    analogWrite(10, 0);
}

void resetAll() {
    AencoderValue_A = 0;
    AencoderValue_B = 0;
    AB_EncoderTot = 0;
    lastDebounceTimeA = 0;
    lastDebounceTimeB = 0;
  
}

void resetEncoders() {
    AencoderValue_A = 0;
    AencoderValue_B = 0;
}

void toa() {

adjacentRemainingDistance = (pathTotalDistance - AB_EncoderTot);
    // Use atan2 to calculate the angle correctly
    desiredCourse = (atan2(oppositeDistance, adjacentRemainingDistance) * 57.32) - 90;
    
    // a positive angle is required, use the absolute value
    desiredCourse = abs(desiredCourse);

   // Serial.print("adjacentRemainingDistance: ");
   // Serial.println(adjacentRemainingDistance);
   // Serial.print("desiredCourse: ");
   // Serial.println(desiredCourse);
}

void resetFoundationVariables() {     
adjacentRemainingDistance = 0; 
pathTotalDistance = 0;
pathEndpointDistance = 100;
oppositeDistance = 0;
desiredCourse = 90;
actualCourse = 90;
}

PRO
Canada
#96  

The issue you're experiencing with the bytes slipping down to the next variable could be due to a few potential causes. Let's address these and provide a solution to ensure the bytes are read correctly each time.

Potential Causes and Solutions

  1. Serial Buffer Not Being Cleared:

    • If the serial buffer is not being cleared properly, it might cause the bytes to shift. Ensure that you are reading all the bytes from the buffer before processing new data.
  2. Incorrect Byte Handling:

    • Ensure that you are reading and combining the bytes correctly. Use temporary variables to store the bytes before combining them.
  3. Synchronization Issue:

    • Ensure that the Arduino and EZ-B are synchronized in terms of data transmission. You might need to implement a simple protocol to ensure that the data is read correctly.

Revised Arduino Code

Here's a revised version of your Arduino code with improvements to handle the serial data correctly:

volatile int AencoderValue_A = 0;
volatile int AencoderValue_B = 0;
volatile unsigned long AB_EncoderTot = 0;
volatile unsigned long lastDebounceTimeA = 0;
volatile unsigned long lastDebounceTimeB = 0;
const unsigned long LeftMotFwdSensDebounceDelay = 5;
const unsigned long RightMotFwdSensDebounceDelay = 7;

// The following are now referred to as FoundationVariables
long adjacentRemainingDistance;
long pathTotalDistance;
long pathEndpointDistance = 100;
float oppositeDistance;
float desiredCourse = 90;
long actualCourse = 90;

void setup() {
    Serial3.begin(9600); // Communication with EZ-B
    Serial.begin(9600);  // Debugging via Serial Monitor
    pinMode(2, INPUT_PULLUP);
    pinMode(3, INPUT_PULLUP);
    setMotorDirectionForward();
    attachInterrupt(digitalPinToInterrupt(2), AcountA, RISING);
    attachInterrupt(digitalPinToInterrupt(3), AcountB, RISING);
}

void loop() {
    if (Serial3.available() >= 8) { // Wait for 8 bytes
        resetFoundationVariables();
        delay(10);
        resetAll();
        delay(10);

        // Read and store bytes for pathTotalDistance
        byte highBytePTD = Serial3.read();
        byte lowBytePTD = Serial3.read();
        pathTotalDistance = (highBytePTD << 8) | lowBytePTD;
        Serial.print("Received pathTotalDistance high byte: ");
        Serial.println(highBytePTD, HEX);
        Serial.print("Received pathTotalDistance low byte: ");
        Serial.println(lowBytePTD, HEX);

        // Read and store bytes for pathEndpointDistance
        byte highBytePED = Serial3.read();
        byte lowBytePED = Serial3.read();
        pathEndpointDistance = (highBytePED << 8) | lowBytePED;
        Serial.print("Received pathEndpointDistance high byte: ");
        Serial.println(highBytePED, HEX);
        Serial.print("Received pathEndpointDistance low byte: ");
        Serial.println(lowBytePED, HEX);

        // Read and store bytes for oppositeDistance
        byte highByteOD = Serial3.read();
        byte lowByteOD = Serial3.read();
        oppositeDistance = (highByteOD << 8) | lowByteOD;
        Serial.print("Received oppositeDistance high byte: ");
        Serial.println(highByteOD, HEX);
        Serial.print("Received oppositeDistance low byte: ");
        Serial.println(lowByteOD, HEX);
    }

    // Additional logic for motor control and other operations
    // ...
}

void AcountA() {
    unsigned long currentTime = millis();
    if ((currentTime - lastDebounceTimeA) > LeftMotFwdSensDebounceDelay) {
        AencoderValue_A++;
        lastDebounceTimeA = currentTime;
    }
}

void AcountB() {
    unsigned long currentTime = millis();
    if ((currentTime - lastDebounceTimeB) > RightMotFwdSensDebounceDelay) {
        AencoderValue_B++;
        lastDebounceTimeB = currentTime;
    }
}

void setMotorDirectionForward() {
    digitalWrite(13, false);
    digitalWrite(12, true);
    digitalWrite(9, true);
    digitalWrite(8, false);
}

void setMotorDirectionReverse() {
    digitalWrite(13, true);
    digitalWrite(12, false);
    digitalWrite(9, false);
    digitalWrite(8, true);
}

void startMotors(int leftSpeed, int rightSpeed) {
    analogWrite(11, leftSpeed);
    analogWrite(10, rightSpeed);
}

void stopMotors() {
    analogWrite(11, 0);
    analogWrite(10, 0);
}

void resetAll() {
    AencoderValue_A = 0;
    AencoderValue_B = 0;
    AB_EncoderTot = 0;
    lastDebounceTimeA = 0;
    lastDebounceTimeB = 0;
}

void resetEncoders() {
    AencoderValue_A = 0;
    AencoderValue_B = 0;
}

void toa() {
    adjacentRemainingDistance = (pathTotalDistance - AB_EncoderTot);
    // Use atan2 to calculate the angle correctly
    desiredCourse = (atan2(oppositeDistance, adjacentRemainingDistance) * 57.32) - 90;
    // a positive angle is required, use the absolute value
    desiredCourse = abs(desiredCourse);
    // Serial.print("adjacentRemainingDistance: ");
    // Serial.println(adjacentRemainingDistance);
    // Serial.print("desiredCourse: ");
    // Serial.println(desiredCourse);
}

void resetFoundationVariables() {
    adjacentRemainingDistance = 0;
    pathTotalDistance = 0;
    pathEndpointDistance = 100;
    oppositeDistance = 0;
    desiredCourse = 90;
    actualCourse = 90;
}

Key Changes

  • Byte Handling: The bytes are stored in temporary variables before being combined.
  • Synchronization: Ensure that the Arduino waits for the correct number of bytes before processing.
  • Debugging: Added print statements to verify the bytes being read.

This should help resolve the issue with the bytes slipping to the next variable. Let me know if you need further assistance!


I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.