Subversion Repositories Projects

Compare Revisions

Ignore whitespace Rev 2104 → Rev 2105

/RaspberryPi/ExPlat/gpio.c
0,0 → 1,98
#include "main.h"
#include "gpio.h"
 
 
struct timeval startTime; //Times needed for calculating Distance
struct timeval travelTime;
 
// IO Acces
struct bcm2835_peripheral {
unsigned long addr_p;
int mem_fd;
void *map;
volatile unsigned int *addr;
};
struct bcm2835_peripheral gpio = {GPIO_BASE};
 
 
//>> Create MMAP for GPIO
//------------------------------------------------------------------------------------------------------
int map_peripheral(struct bcm2835_peripheral *p)
{
// Open /dev/mem
if ((p->mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) {
printf("Failed to open /dev/mem, try checking permissions.\n");
return -1;
}
p->map = mmap(
NULL,
BLOCK_SIZE,
PROT_READ|PROT_WRITE,
MAP_SHARED,
p->mem_fd,
p->addr_p
);
if (p->map == MAP_FAILED) {
perror("mmap");
return -1;
}
p->addr = (volatile unsigned int *)p->map;
return 0;
}
void unmap_peripheral(struct bcm2835_peripheral *p) {
munmap(p->map, BLOCK_SIZE);
close(p->mem_fd);
}
 
//>> Funktion for short buzzing Sound
//------------------------------------------------------------------------------------------------------
void buzzer_short(int seq){
INP_GPIO(4);
OUT_GPIO(4);
for (int i = 0; i < seq; ++i)
{
if(seq > 1){usleep(50000);}
GPIO_SET = 1 << 4;
usleep(50000);
GPIO_CLR = 1 << 4;
}
}
 
//>> Calculate Distance with external sonar
//------------------------------------------------------------------------------------------------------
int calculate_distance(){
int distanceTemp;
int loopbreaker = 10000; //Breaks the first loop in case it gets stuck (which happens from time to time if the Objekt facing the sensor is too close)
GPIO_SET = 1 << ULTRA_TRIGGER;
usleep(10);
GPIO_CLR = 1 << ULTRA_TRIGGER;
 
while(!(GPIO_READ(ULTRA_ECHO)))
{
loopbreaker--;
if(!loopbreaker){break;}
}
gettimeofday(&startTime, NULL);
 
while((GPIO_READ(ULTRA_ECHO)))
gettimeofday(&travelTime, NULL);
 
loopbreaker = 0;
distanceTemp = (travelTime.tv_usec - startTime.tv_usec) / 58;
return distanceTemp;
}
 
//>> Initialize GPIO
//------------------------------------------------------------------------------------------------------
void gpio_init(){
if(map_peripheral(&gpio) == -1)
{
printf("Failed to map the physical GPIO registers into the virtual memory space.\n");
}
 
INP_GPIO(ULTRA_ECHO);
OUT_GPIO(ULTRA_TRIGGER);
GPIO_CLR = 1 << ULTRA_TRIGGER;
sleep(1);
}