This repository has been archived on 2023-12-22. You can view files and clone it, but cannot push or open issues or pull requests.
old-monorepo/Arduino/Control/src/main.cpp

113 lines
2 KiB
C++
Raw Normal View History

2020-12-27 16:54:53 +01:00
#include <Arduino.h>
#include <EEPROM.h>
2020-12-27 19:19:16 +01:00
#include <Wire.h>
2020-12-27 16:54:53 +01:00
2020-12-27 19:19:16 +01:00
#define SLAVE_ADDR 9
2020-12-27 16:54:53 +01:00
const int bjtCount = 4;
const int bjtPin[bjtCount] = {6, 5, 3, 10};
int bjtState[bjtCount] = {255, 255, 255, 255}; //255 -> bjt max "open"
2020-12-27 19:19:16 +01:00
String receivedSerialData;
String pendingSerialData;
String receivedI2cData;
void receiveEvent(int howMany)
{
char buff[howMany];
for (int i = 0; i < howMany; i++)
{
buff[i] = Wire.read();
}
receivedI2cData = String(buff);
}
2020-12-27 16:54:53 +01:00
void setup()
{
Serial.begin(9600);
Serial.setTimeout(5);
2020-12-27 19:19:16 +01:00
Wire.begin(SLAVE_ADDR);
Wire.onReceive(receiveEvent);
2020-12-27 16:54:53 +01:00
for (int i = 0; i < bjtCount; i++)
{
pinMode(bjtPin[i], OUTPUT);
bjtState[i] = EEPROM.read(i);
digitalWrite(bjtPin[i], bjtState[i]);
}
}
void toggleLED(int i)
{
if (bjtState[i] != 0)
{
bjtState[i] = 0;
}
else
{
bjtState[i] = 255;
}
}
void absoluteLED(String data, int i)
{
if (data == "off")
{
bjtState[i] = 0;
}
if (data == "on")
{
bjtState[i] = 255;
}
}
void loop()
{
while (Serial.available())
{
2020-12-27 19:19:16 +01:00
receivedSerialData = Serial.readString(); //FORMAT: index of light + t oggle, i ncrease, d ecrease -> eg. 0t
2020-12-27 16:54:53 +01:00
Serial.flush();
2020-12-27 19:19:16 +01:00
Serial.println("cum");
2020-12-27 16:54:53 +01:00
}
for (int i = 0; i < bjtCount; i++)
{
2020-12-27 19:19:16 +01:00
if ((receivedI2cData.indexOf(String(i)) == 0)) //changed to i2c for testing
2020-12-27 16:54:53 +01:00
{
2020-12-27 19:19:16 +01:00
if (receivedI2cData.indexOf("t") >= 0) //changed to i2c for testing
2020-12-27 16:54:53 +01:00
{
toggleLED(i);
}
2020-12-27 19:19:16 +01:00
else if (receivedSerialData.indexOf("i") >= 0)
2020-12-27 16:54:53 +01:00
{
bjtState[i] += 5;
}
2020-12-27 19:19:16 +01:00
else if (receivedSerialData.indexOf("d") >= 0)
2020-12-27 16:54:53 +01:00
{
bjtState[i] -= 5;
}
}
2020-12-27 19:19:16 +01:00
absoluteLED(receivedSerialData, i);
2020-12-27 16:54:53 +01:00
2020-12-27 19:19:16 +01:00
//clamp state between 0 and 255 if (bjtState[i] > 255)
2020-12-27 16:54:53 +01:00
{
bjtState[i] = 255;
}
if (bjtState[i] < 0)
{
bjtState[i] = 0;
}
analogWrite(bjtPin[i], bjtState[i]);
EEPROM.update(i, bjtState[i]);
2020-12-27 19:19:16 +01:00
pendingSerialData += String(bjtState[i]) + ",";
2020-12-27 16:54:53 +01:00
}
2020-12-27 19:19:16 +01:00
Serial.println(pendingSerialData);
pendingSerialData = "";
receivedSerialData = "";
receivedI2cData = "";
2020-12-27 16:54:53 +01:00
}