/* GPIO.c */ /* This file is the abstraction layer for the BROADCOM BCM2835, (raspberry pi 4b) if you need to update the GPIO for a later raspberry pi revision, this should be the only file you need to touch. */ /* Links used: https://www.man7.org/linux/man-pages/man2/mmap.2.html */ /* History: 07/08/2022, Julian Zelazny; added the extra code to set the pins to output by default in init. 06/20/2022, Julian Zelazny: made a basic suite of routines that can set the pins to hight or low. need to test reading input from the GPIO pins. 06/20/2022, Julian Zelazny: file created, just getting to know the hardware and its registers. Its a good thing that we can access the pins without needing to be root to do so. */ /*============================================================================*/ #include "GPIO.h" static volatile uint32_t *gpioReg; /*============================================================================*/ void gpio_setPinType(gpioPin_t pinNumber, gpioPinFunction_t mode){ uint8_t regNumber,numShifts; regNumber = pinNumber/10; // 10 pins per register numShifts = pinNumber%10 * 3; // 3 bits per pin gpioReg[regNumber] = (gpioReg[regNumber] & ~(7<>= pinNumber; if(input % 2) result = true; else result = false; return result; } /*============================================================================*/ void gpio_SetPin(gpioPin_t pinNumber){ uint32_t pinSelect; pinSelect = 1; pinSelect <<= pinNumber; gpioReg[GPSET0] |= (pinSelect); } /*============================================================================*/ void gpio_ClearPin(gpioPin_t pinNumber){ uint32_t pinSelect; pinSelect = 1; pinSelect <<= pinNumber; gpioReg[GPCLR0] |= (pinSelect); } /*============================================================================*/ bool gpio_init(void){ int fileDescriptor; bool result; gpioReg = MAP_FAILED; result = false; //get this resource with read/write access with sync fileDescriptor = open("/dev/gpiomem", O_RDWR | O_SYNC) ; if(fileDescriptor){ gpioReg = (uint32_t *)mmap(NULL, 0xB4, PROT_READ|PROT_WRITE, MAP_SHARED, fileDescriptor, 0); close(fileDescriptor); //this will not invalidate the mmap //if that mmap does not fail, set all 26 pins to output and set them logic high if(gpioReg != MAP_FAILED){ gpioReg[GPFSEL0] = 0x09249249; gpioReg[GPFSEL1] = 0x09249249; gpioReg[GPFSEL2] &= 0xff000000; gpioReg[GPFSEL2] |= 0x00249249; gpioReg[GPSET0] = 0x0FFFFFFF; result = true; }else fprintf(stderr, "failed to mmap /dev/gpiomem\n"); } else fprintf(stderr, "failed to open /dev/gpiomem\n"); return result; } /*============================================================================*/