diff --git a/BiDi/BiDi.ino b/BiDi/BiDi.ino new file mode 100644 index 0000000..3c80a6c --- /dev/null +++ b/BiDi/BiDi.ino @@ -0,0 +1,95 @@ +/* RS 485-Implementierung, die sowohl Schreiben als auch Lesen kann */ +/* Basis für andere Projekte */ + +#define BUTTON 2 +#define RECEIVE 3 +#define RECEIVE_ENABLE 4 +#define SEND 5 +#define SEND_ENABLE 6 + +#define MAX_LEN 128 + +void setup() { + // Buttons connected to analog input lines + pinMode(A0,INPUT_PULLUP); + pinMode(A1,INPUT_PULLUP); + pinMode(A2,INPUT_PULLUP); + pinMode(A3,INPUT_PULLUP); + pinMode(A4,INPUT_PULLUP); + pinMode(A5,INPUT_PULLUP); + pinMode(A6,INPUT_PULLUP); + pinMode(A7,INPUT_PULLUP); + // Currently, all buttons are also connected via a diode to an interruptable pin, to notify on input changes. + // This interruptable pin should be assgined to BUTTON + pinMode(BUTTON,INPUT_PULLUP); + attachInterrupt(digitalPinToInterrupt(BUTTON),button,FALLING); // interrupt for button change + + // Set up pins for RS485 connection + pinMode(RECEIVE, INPUT); + pinMode(RECEIVE_ENABLE, OUTPUT); + pinMode(SEND, OUTPUT); + pinMode(SEND_ENABLE, OUTPUT); + attachInterrupt(digitalPinToInterrupt(RECEIVE),receive,CHANGE); // interrupt for incoming RS485 traffic + + reset485(); + buttons = 0x0; +} + +void button() { + buttons = 0xFF ^ (digitalRead(A7)<<7 | digitalRead(A6)<<6 | digitalRead(A5)<<5 | digitalRead(A4)<<4 | digitalRead(A3)<<3 | (!digitalRead(A2))<<2 | digitalRead(A1)<<1 | digitalRead(A0)); +} + +void receive(){ + bool received_bit = digitalRead(RECEIVE); + curr = micros(); + duration = curr - last; + Serial.print("Input switched to "); + Serial.print(received_bit?"H":"L"); + Serial.print(" after "); + Serial.print(duration); + Serial.println(" ticks"); + last = curr; + if (duration > MAX_TICKS) reset485(); + received_bit = !received_bit; // received_bit is the current value, the duration of the previous value (=inverted) has been measured + duration /= BASE; + while (duration > 0){ + byte_idx--; + recv |= received_bit<0){ + for (int i=0; i<7; i++){ + if (buttons & (1<