// Function to encode the RPM value for transmission to the ESP32 (Little Endian)
uint16_t encode_rpm(uint16_t actual_rpm) {
// Multiply the RPM by 50 and then by 4
//actual_rpm *= 50; // commented for Simulation
actual_rpm *= 4;
// Calculate A and B for the encoded value
uint8_t A = highByte(actual_rpm); // Extract the most significant byte (A)
uint8_t B = lowByte(actual_rpm); // Extract the least significant byte (B)
// Combine A and B into the encoded value
uint16_t encoded_value = (A * 256) + B; // Combine A and B into a 16-bit value in little-endian order
return encoded_value; // Return the encoded RPM value
}
// Function to decode the RPM from an encoded value ODB app (Little Endian)
uint16_t decode_rpm(uint16_t encoded_value) {
// Extract A and B from the encoded value
uint8_t A = highByte(encoded_value); // Shift right by 8 bits to get the most significant byte (A)
uint8_t B = lowByte(encoded_value); // Mask to get the least significant byte (B)
// Calculate the actual RPM using the formula: (256 * A) + B, then divide by 4
uint16_t actual_rpm = ((256 * A) + B) / 4; // Perform integer division
return actual_rpm; // Return the decoded RPM
}
void setup() {
Serial.begin(115200);
}
void loop() {
static bool input_received = false;
// Ask for input RPM if input is not received yet
if (!input_received) {
Serial.println("Enter the RPM value (Max RPM: 16383) and press Enter:");
input_received = true; // Set input_received to true to indicate that input has been asked for
}
// Check if input RPM is available
if (Serial.available() > 0) {
// Read input RPM from Serial
uint16_t input_rpm = Serial.parseInt();
// Check if a valid integer has been parsed
if (input_rpm != 0) {
// Reset input_received to allow asking for input again
input_received = false;
// Encode the RPM value
uint16_t encoded_rpm = encode_rpm(input_rpm);
// Decode the encoded RPM value
uint16_t decoded_rpm = decode_rpm(encoded_rpm);
// Print input RPM, encoded RPM, and decoded RPM
Serial.print("Input RPM: ");
Serial.println(input_rpm);
Serial.print("Encoded RPM: ");
Serial.println(encoded_rpm);
Serial.print("Decoded RPM: ");
Serial.println(decoded_rpm);
}
}
}