cm3588-gpio-led-blink.ino

Module SOM FriendlyElec CM3588 (Rockchip RK3588) · Fichier : cm3588-gpio-led-blink.ino · Langage : C · Usage : Allumer et éteindre une LED connectée à un GPIO via sysfs.

Exemple C utilisant l'interface sysfs pour contrôler un GPIO sur le CM3588.

Matériel : LED avec résistance connectée à un GPIO exposé via les connecteurs 100 broches. Le noyau Linux doit avoir le support GPIO sysfs activé. Compilez avec gcc blink.c -o blink. Exécutez en root : sudo ./blink.

cm3588-gpio-led-blink.ino

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

#define GPIO_PIN "gpio100"
#define DIRECTION_PATH "/sys/class/gpio/%s/direction"
#define VALUE_PATH "/sys/class/gpio/%s/value"
#define EXPORT_PATH "/sys/class/gpio/export"
#define UNEXPORT_PATH "/sys/class/gpio/unexport"

void write_to_file(const char *path, const char *value) {
    int fd = open(path, O_WRONLY);
    if (fd < 0) {
        perror("Failed to open file");
        exit(EXIT_FAILURE);
    }
    if (write(fd, value, strlen(value)) < 0) {
        perror("Failed to write");
        close(fd);
        exit(EXIT_FAILURE);
    }
    close(fd);
}

int main() {
    // Export GPIO
    write_to_file(EXPORT_PATH, GPIO_PIN);
    sleep(1);

    // Set direction to output
    char dir_path[256], val_path[256];
    snprintf(dir_path, sizeof(dir_path), DIRECTION_PATH, GPIO_PIN);
    snprintf(val_path, sizeof(val_path), VALUE_PATH, GPIO_PIN);
    write_to_file(dir_path, "out");

    // Blink loop
    for (int i = 0; i < 10; i++) {
        write_to_file(val_path, "1");
        usleep(500000);
        write_to_file(val_path, "0");
        usleep(500000);
    }

    // Unexport GPIO
    write_to_file(UNEXPORT_PATH, GPIO_PIN);
    return 0;
}

← Retour à la fiche