STM32 – Biliothekensammlung

pca9545 .c/.h (MUX)

------------------------------------------------------------------
pca9545.h:
------------------------------------------------------------------
#ifndef PCA9545_H
#define PCA9545_H

#include "stm32h7xx_hal.h"

typedef struct {
    I2C_HandleTypeDef *hi2c;
    uint8_t address; // 7-bit Adresse, z. B. 0x70 (ohne R/W-Bit)
} PCA9545_HandleTypeDef;

/**
 * Aktiviert nur den angegebenen Kanal (0–3).
 * Deaktiviert alle anderen.
 */
HAL_StatusTypeDef PCA9545_SelectChannel(PCA9545_HandleTypeDef *hpca, uint8_t channel);

/**
 * Liest das aktuelle Steuerregister (aktive Kanäle + Interruptstatus)
 */
HAL_StatusTypeDef PCA9545_ReadControl(PCA9545_HandleTypeDef *hpca, uint8_t *control);

#endif // PCA9545_H

------------------------------------------------------------------
pca9545.c:
------------------------------------------------------------------
#include "pca9545.h"

HAL_StatusTypeDef PCA9545_SelectChannel(PCA9545_HandleTypeDef *hpca, uint8_t channel) {
    if (channel > 3) return HAL_ERROR;

    uint8_t config = 1 << channel; // Nur einen Kanal aktivieren
    return HAL_I2C_Master_Transmit(hpca->hi2c, hpca->address << 1, &config, 1, HAL_MAX_DELAY);
}

HAL_StatusTypeDef PCA9545_ReadControl(PCA9545_HandleTypeDef *hpca, uint8_t *control) {
    if (control == NULL) return HAL_ERROR;

    return HAL_I2C_Master_Receive(hpca->hi2c, hpca->address << 1, control, 1, HAL_MAX_DELAY);
}

------------------------------------------------------------------
Anwendungsbeispiel:
------------------------------------------------------------------
#include "pca9545.h"
#include "mcp3424.h" // z. B. falls an Multiplexer hängt

extern I2C_HandleTypeDef hi2c1;

void Test_PCA9545_Multiplexer(void) {
    PCA9545_HandleTypeDef mux = {
        .hi2c = &hi2c1,
        .address = 0x70 // Standardadresse des PCA9545
    };

    // ADC an Kanal 0 (z. B. MCP3424)
    MCP3424_HandleTypeDef adc = {
        .hi2c = &hi2c1,
        .address = 0x68
    };

    // Wähle Kanal 0
    PCA9545_SelectChannel(&mux, 0);
    HAL_Delay(1); // kleine Pause nach Umschaltung

    int32_t value;
    if (MCP3424_ReadChannel(&adc, MCP3424_CHANNEL_1, MCP342X_16BIT, MCP342X_GAIN_1, &value) == HAL_OK) {
        float voltage = ((float)value) * 2.048f / 32768.0f;
        // Debug: printf("CH0 ADC = %.3f V\n", voltage);
    }

    // Wähle Kanal 1
    PCA9545_SelectChannel(&mux, 1);
    HAL_Delay(1);
    // → Jetzt mit einem anderen Gerät auf Kanal 1 kommunizieren
}

void StartDefaultTask(void *argument) {
    for (;;) {
        Test_PCA9545_Multiplexer();
        osDelay(1000);
    }
}

Tags:

Comments

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Search


Categories


Recent Posts


Tags