I had a idea to simulate PLC in a very simple way in Arduino IDE. 😉
- I need 2 array there I configure the input and output pins.
- I need functions to do the logic with pin number as argument
- The task function executed in the run loop.
This example show 3 function, input, output and blink. Every function take int pin number as argument.
Any idea are welcome, it was fun to do it 😉
int input_pins[] = {2, 3, 4, 5, 6, 7};
int output_pins[] = {9, 10, 11, 12, 13};
const int size1 = sizeof(input_pins) / sizeof(input_pins[0]);
const int size2 = sizeof(output_pins) / sizeof(output_pins[0]);
const int pins_size = size1 + size2;
int pins[pins_size];
void setup() {
Serial.begin(115200);
delay(2000);
// Copy elements of arr1 to pins
for (int i = 0; i < size1; i++) {
pins[i] = input_pins[i];
}
// Copy elements of arr2 to pins
for (int i = 0; i < size2; i++) {
pins[size1 + i] = output_pins[i];
}
int pinModes[pins_size];
for (int i = 0; i < pins_size; i++) {
if (i < size1) {
pinMode(pins[i], INPUT);
pinModes[i] = INPUT;
} else {
pinMode(pins[i], OUTPUT);
pinModes[i] = OUTPUT;
}
}
for (int i = 0; i < pins_size; i++) {
Serial.print("Pin ");
Serial.print(pins[i]);
Serial.print(" is set to ");
if (pinModes[i] == INPUT) {
Serial.println("INPUT");
} else if (pinModes[i] == OUTPUT) {
Serial.println("OUTPUT");
}
}
}
int task_input(int pin) {
int input_state = 0;
for (int i = 0; i < pins_size; i++) {
if (pins[i] == pin) {
//pinMode(pin, INPUT_PULLUP); // used for simulation
input_state = digitalRead(pins[i]);
}
}
return input_state;
}
void task_output(int pin) {
for (int i = 0; i < pins_size; i++) {
if (pins[i] == pin) {
digitalWrite(pins[i], HIGH);
}
}
}
void task_blink(int pin) {
for (int i = 0; i < pins_size; i++) {
if (pins[i] == pin) {
digitalWrite(pins[i], HIGH);
delay(1000);
digitalWrite(pins[i], LOW);
delay(1000);
}
}
}
void loop() {
task_output(13);
//task_blink(13);
// To simulate a input use INPUT_PULLUP
//if (task_input(2) == HIGH) {
// task_blink(13);
//}
}