I2CRelay/src/I2CRelay.cpp

103 lines
3.1 KiB
C++

#include "I2CRelay.h"
I2CRelay::I2CRelay(uint8_t address, uint8_t sda, uint8_t scl)
: _address(address), _sda(sda), _scl(scl) {}
void I2CRelay::begin() {
Wire.begin(_sda, _scl);
}
void I2CRelay::setRelay(uint8_t relayNum, uint8_t state) {
if (relayNum < 1 || relayNum > 8) return;
Wire.beginTransmission(_address);
Wire.write(0xA0);
Wire.write(relayNum - 1); // Map 1-8 to 0-7
Wire.write(state);
Wire.endTransmission();
}
void I2CRelay::setAllRelays(uint8_t state) {
for (uint8_t i = 1; i <= 8; i++) {
setRelay(i, state);
delay(10);
}
}
void I2CRelay::setDeviceName(const String &name) {
Wire.beginTransmission(_address);
Wire.write(0xD0);
for (uint8_t i = 0; i < name.length() && i < 24; i++) {
Wire.write(name[i]);
}
Wire.endTransmission();
}
void I2CRelay::setI2CAddress(uint8_t newAddr) {
if (newAddr < 8 || newAddr > 119) return;
Wire.beginTransmission(_address);
Wire.write(0xC0);
Wire.write(newAddr);
Wire.endTransmission();
}
String I2CRelay::getIdentification() {
Wire.requestFrom(_address, (uint8_t)40);
String id = "";
while (Wire.available()) {
char c = Wire.read();
id += c;
}
return id;
}
void I2CRelay::handleSerialCommand(const String &cmd) {
if (cmd.startsWith("r ")) {
int space1 = cmd.indexOf(' ');
int space2 = cmd.indexOf(' ', space1 + 1);
if (space1 > 0 && space2 > space1) {
int relay = cmd.substring(space1 + 1, space2).toInt();
int state = cmd.substring(space2 + 1).toInt();
if (relay >= 1 && relay <= 8 && (state == 0 || state == 1)) {
setRelay(relay, state);
Serial.print("Relay ");
Serial.print(relay);
Serial.print(" set to ");
Serial.println(state ? "ON" : "OFF");
} else {
Serial.println("Invalid relay number or state. Use 1-8 and 0/1.");
}
} else {
Serial.println("Usage: r <relayNum 1-8> <0|1>");
}
} else if (cmd.startsWith("all ")) {
int state = cmd.substring(4).toInt();
if (state == 0 || state == 1) {
setAllRelays(state);
Serial.print("All relays set to ");
Serial.println(state ? "ON" : "OFF");
} else {
Serial.println("Invalid state for all.");
}
} else if (cmd.startsWith("name ")) {
String name = cmd.substring(5);
setDeviceName(name);
Serial.print("Device name set to: ");
Serial.println(name);
} else if (cmd.startsWith("addr ")) {
int newAddr = cmd.substring(5).toInt();
if (newAddr >= 8 && newAddr <= 119) {
setI2CAddress(newAddr);
Serial.print("I2C address set to: ");
Serial.println(newAddr, HEX);
} else {
Serial.println("Invalid address.");
}
} else if (cmd == "id") {
String id = getIdentification();
Serial.print("ID: ");
Serial.println(id);
} else {
Serial.println("Unknown command.");
}
}