jwilleke / ArduinoHA-examples

Various attempts to Connect to home assistant using MQTT
0 stars 0 forks source link

Call Back function needs an Interval added #2

Closed jwilleke closed 5 months ago

jwilleke commented 6 months ago

Currently in the call back function for switches where have a delay which stops all operations for the MCU.

Bard's advice

jwilleke commented 6 months ago

Correct pin Mapping for UNO R4 WiFi (ABX00087)

Define the callback function:

void activatePins(uint8_t pinStates) {
  // Update pin states based on the provided byte (pinStates)
  // Use bit manipulation if pins are on the same port:
  PORTC = (PORTC & 0b11001111) | (pinStates & 0b00110000); // Update pins 2-5 on Port C
  PORTE = (PORTE & 0b00111100) | ((pinStates << 3) & 0b11000000); // Update pins 6-9 on Port E

  // Alternatively, write to individual pins if not contiguous:
  // digitalWrite(2, pinStates & 0b00000001); // Example for pin 2
  // ... similar for other pins

  // Start a timer or flag to indicate activation
  lastPinChangeTime = millis();
  active = true;
}

This function takes a single byte (pinStates) as input, where each bit represents the desired state (HIGH or LOW) for the corresponding pin (bit 0 for pin 2, bit 1 for pin 3, and so on). It then updates the pin states using bit manipulation for efficiency if they are on the same port or through individual digitalWrite calls otherwise. Additionally, it sets a flag (active) and stores the current time (lastPinChangeTime) to track the activation period.

Trigger the callback function:

You can trigger this callback function from an external event (e.g., button press) or within your loop() function at a desired interval. Here are two approaches:

External event:

void buttonInterrupt() {
  activatePins(0b11111111); // Set all pins HIGH (example)
}

void setup() {
  // Set pin modes for pins 2, 3, 4, 5, 6, 7, 8, and 9
  // ... also attach interrupt for button

}

void loop() {
  // ... your other code
}

## Deactivate pins in the main loop:
```c++
bool active = false;
unsigned long lastPinChangeTime = 0;

void loop() {
  // ... other code

  if (active && millis() - lastPinChangeTime >= 15000) {
    // Reset pin states (e.g., all LOW)
    PORTC &= 0b11001111;
    PORTE &= 0b00111100;
    // ... or set individual pins LOW
    active = false;
  }
}

This code checks the active flag and time elapsed since the last activation to manage deactivation after the 15-second period.

jwilleke commented 5 months ago

Will not pursue this at present time. Moving to MQTT made this easier.