ive got the coordinate reading on point, but the frequency number doesnt wanna be read out
const int inputPin = 8;
const int bitRate = 100;
const int bitDuration = 1000 / bitRate;
unsigned long lastSampleTime = 0;
const String startHeader = "1111111001";
const String endHeader = "1111111011";
String bitBuffer = "";
bool inSync = false;
int numCoordinates = 0;
void setup() {
Serial.begin(9600);
pinMode(inputPin, INPUT);
lastSampleTime = millis();
}
void loop() {
unsigned long currentTime = millis();
if (currentTime - lastSampleTime >= bitDuration) {
int bitVal = digitalRead(inputPin);
char bitChar = (bitVal == HIGH) ? '0' : '1'; // Based on your encoding
bitBuffer += bitChar;
if (!inSync) {
// Look for start header
int idx = bitBuffer.indexOf(startHeader);
if (idx != -1) {
inSync = true;
bitBuffer = bitBuffer.substring(idx + startHeader.length());
} else if (bitBuffer.length() > 20) {
// Trim buffer to avoid unbounded growth
bitBuffer = bitBuffer.substring(bitBuffer.length() - 10);
}
} else if (numCoordinates == 0) {
// After start header, read message count (6 bits)
if (bitBuffer.length() >= 6) {
String countBits = bitBuffer.substring(0, 6);
numCoordinates = strtol(countBits.c_str(), NULL, 2); // Convert binary to decimal
bitBuffer = bitBuffer.substring(6); // Remove message count from buffer
Serial.print("Number of Coordinates: ");
Serial.println(numCoordinates);
}
} else {
// After message count, extract X and Y coordinates
if (bitBuffer.length() >= 5 * numCoordinates * 2) { // 5 bits for X and 5 bits for Y per coordinate
int xCoordinates[numCoordinates];
int yCoordinates[numCoordinates];
// Extract X coordinates
for (int i = 0; i < numCoordinates; i++) {
String xBits = bitBuffer.substring(0, 5); // First 5 bits for X
xCoordinates[i] = strtol(xBits.c_str(), NULL, 2); // Convert binary to decimal
bitBuffer = bitBuffer.substring(5); // Remove the X coordinate from the buffer
}
// Extract Y coordinates
for (int i = 0; i < numCoordinates; i++) {
String yBits = bitBuffer.substring(0, 5); // Next 5 bits for Y
yCoordinates[i] = strtol(yBits.c_str(), NULL, 2); // Convert binary to decimal
bitBuffer = bitBuffer.substring(5); // Remove the Y coordinate from the buffer
}
// Print all coordinates in the format (X1,Y1) (X2,Y2) ...
Serial.print("Coordinates: ");
for (int i = 0; i < numCoordinates; i++) {
Serial.print("(");
Serial.print(xCoordinates[i]);
Serial.print(",");
Serial.print(yCoordinates[i]);
Serial.print(") ");
}
Serial.println();
// Extract and print the last 7 bits from the bitBuffer
if (bitBuffer.length() >= 7) {
String last7Bits = bitBuffer.substring(0, 7); // Get the last 7 bits
Serial.print("Last 7 Bits: ");
Serial.println(last7Bits);
bitBuffer = bitBuffer.substring(7); // Remove the last 7 bits from the buffer
}
// Reset for next message
numCoordinates = 0;
inSync = false;
bitBuffer = "";
delay(1000); // optional pause before next message
}
}
lastSampleTime = currentTime;
}
}