// Transmitter code (Arduino UNO to Arduino UNO communication)
// this version includes the use of potentiometer to set the transmission bitrate (bps) in the setup funtion (to change the bitrate, reset the MCU )
// The bitrate is selected by adjusting the potentiometer and pressing the pushbutton to exit WHILE loop
// In the LOOP function the pushbutton is used to restart transmission (resend message)
// The receiver part can be updated with pushbutton, that resets receiver (ground the reset pin) to wait for new incoming message
#include <LiquidCrystal.h>
// Pin assignments
#define buttonPin 2
#define LCD_D4 4
#define LCD_D5 5
#define LCD_D6 6
#define LCD_D7 7
#define LCD_RS 8
#define LCD_EN 9
const int ledPin = 11;
const unsigned long bitDuration = 1000000;
unsigned long lastSendTime = 0;
const unsigned long sendInterval = 1000; // Interval between full messages
const byte preamble = 0xAA; // Preamble to signal start of new message
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
unsigned long currentTime = millis();
if (currentTime - lastSendTime >= sendInterval) {
sendPreamble();
String message = "Hello, World!";
Serial.println("\nSending message:");
for (int i = 0; i < message.length(); i++) {
byte data = message[i];
uint16_t encoded = hammingEncode(data);
Serial.print((char)data);
sendHamming(encoded, true);
delay(100); // Short delay between characters for clarity
}
Serial.println("\nMessage sent.");
lastSendTime = currentTime; // Update last send time
}
}
void sendPreamble() {
for (int i = 0; i < 8; i++) {
sendBit((preamble >> i) & 1);
}
Serial.println("\nPreamble sent.");
}
uint16_t hammingEncode(byte data) {
uint16_t encoded = 0;
// Insert data bits into their positions (positions 3, 5, 6, 7, 9, 10, 11, 12)
encoded |= (data & 0x01) << 2;
encoded |= (data & 0x02) << 3;
encoded |= (data & 0x04) << 3;
encoded |= (data & 0x08) << 4;
encoded |= (data & 0x10) << 4;
encoded |= (data & 0x20) << 4;
encoded |= (data & 0x40) << 4;
encoded |= (data & 0x80) << 5;
// Calculate parity bits and place them at positions 1, 2, 4, 8
for (int i = 1; i <= 12; i *= 2) {
int parity = 0;
// Check all bits where the ith bit of the index is 1
for (int j = 1; j <= 12; j++) {
if ((j & i) && (encoded & (1 << j))) parity ^= 1;
}
encoded |= parity << i;
}
return encoded;
}
void sendHamming(uint16_t encoded, bool logBits) {
Serial.print("\nBits: ");
for (int i = 0; i < 12; i++) {
bool bit = (encoded >> i) & 1;
sendBit(bit);
if (logBits) {
Serial.print(bit ? "10" : "01");
}
}
Serial.print("\n"); // Move to the next line after bits are displayed
}
void sendBit(bool bit) {
unsigned long startTime = micros();
if (bit) {
digitalWrite(ledPin, LOW);
while (micros() - startTime < bitDuration / 2);
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, HIGH);
while (micros() - startTime < bitDuration / 2);
digitalWrite(ledPin, LOW);
}
while (micros() - startTime < bitDuration);
}