GPIO control example

I include this as I wanted to test out GPIO and could not find a simple code example. The information given at GPIO Access Usage | Khadas Documentation needs a little unpacking.

For my application I need to drive 6 GPIO pins as outputs - and am testing them using LEDs (+680R bias resistor for each).

On the schematic (https://dl.khadas.com/Hardware/VIM3/Schematic/VIM3_V12_Sch.pdf) page 4 you find the GPIO connector pin-out. Ground is on Pin40. Most other pins are dual-function direct from the A311D SoC. For each pin I want to use as a GPIO I need to ensure that its peripheral function is disabled. The pins on the connector I selected in this case were GPIOH_4 (pin 37), GPIOH_5 (pin35 - marked as PWM_F on the connector - matches with pin W38 on U11D, schematic p.10). Similarly you can trace the outputs corresponding to GPIO_H6 (pin 15), GPIO_H7 (pin16), GPIOA_14 (pin23), GPIOA_15 (pin22).

The corresponding peripherals (PWM_F, UART3, I2C3) need disabling, which is done by editing /boot/env.txt and removing pwm_f, i2c3 and uart3 from the definition of ‘overlays’. Then restart.

The GPIO documentation gives the basic information for identifying gpio numbers for peripherals. This short C++ program will go through the 6 outputs switching each on and off in turn, having first enabled them all as outputs.

#include <stdio.h>
#include
#include <unistd.h>

int main(int argc, char *argv[]) {
const int pPin[] = {474, 475, 431, 432, 433, 434};
char pBuffer[128];

    // Enable pins and set up as outputs
    for(int i=0; i<6; i++) {
            sprintf(pBuffer, "%d", pPin[i]);
            FILE *pEnable(fopen("/sys/class/gpio/export", "wb"));
            fwrite(pBuffer, strlen(pBuffer), 1, pEnable);
            fclose(pEnable);

            sprintf(pBuffer, "/sys/class/gpio/gpio%d/direction", pPin[i]);
            FILE *pDir(fopen(pBuffer, "wb"));
            fwrite("out", 3, 1, pDir);
            fclose(pDir);
    }

    // Loop over pins - switching on, pause, off
    while(true) {
            for(int i=0; i<6; i++) {
                    sprintf(pBuffer, "/sys/class/gpio/gpio%d/value", pPin[i]);
                    printf("GPIO %d\n", pPin[i]);
                    FILE *pPin(fopen(pBuffer, "wb"));
                    fwrite("1", 1, 1, pPin);
                    fclose(pPin);

                    usleep(200000);
                    pPin = fopen(pBuffer, "wb");
                    fwrite("0", 1, 1, pPin);
                    fclose(pPin);
            }
    }

    return 0;       // Never hit

}

I hope this helps.

Cheers
Don