Page 10 of 21
Chapter 13
Page 223
#include <bcm2835.h>
#include <stdio.h>
#include <sched.h>
#include <sys/mman.h>
int presence(uint8_t pin);
void writeByte(uint8_t pin, int byte);
uint8_t crc8(uint8_t *data, uint8_t len);
int readByte(uint8_t pin);
int readiButton(uint8_t pin, uint8_t *data);
int main(int argc, char **argv)
{
const struct sched_param priority = {1};
sched_setscheduler(0, SCHED_FIFO, &priority);
mlockall(MCL_CURRENT | MCL_FUTURE);
if (!bcm2835_init())
return 1;
bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
int i;
uint8_t code[8];
for (;;)
{
int p = readiButton(RPI_BPLUS_GPIO_J8_07, code);
if (p == 1)
{
for (i = 0; i < 8; i++)
{
printf("%hhX ", code[i]);
}
printf("\n\r");
fflush(stdout);
}
bcm2835_delayMicroseconds(100000);
};
bcm2835_close();
return 0;
}
int presence(uint8_t pin)
{
bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_write(pin, LOW);
bcm2835_delayMicroseconds(480);
bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
bcm2835_delayMicroseconds(70);
uint8_t b = bcm2835_gpio_lev(pin);
bcm2835_delayMicroseconds(410);
return b;
}
void writeBit(uint8_t pin, int b)
{
int delay1, delay2;
if (b == 1)
{
delay1 = 6;
delay2 = 64;
}
else
{
delay1 = 80;
delay2 = 10;
}
bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_write(pin, LOW);
bcm2835_delayMicroseconds(delay1);
bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
bcm2835_delayMicroseconds(delay2);
}
uint8_t readBit(uint8_t pin)
{
bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_write(pin, LOW);
bcm2835_delayMicroseconds(6);
bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
bcm2835_delayMicroseconds(9);
uint8_t b = bcm2835_gpio_lev(pin);
bcm2835_delayMicroseconds(55);
return b;
}
void writeByte(uint8_t pin, int byte)
{
int i;
for (i = 0; i < 8; i++)
{
if (byte & 1)
{
writeBit(pin, 1);
}
else
{
writeBit(pin, 0);
}
byte = byte >> 1;
}
}
int readByte(uint8_t pin)
{
int byte = 0;
int i;
for (i = 0; i < 8; i++)
{
byte = byte | readBit(pin) << i;
};
return byte;
}
uint8_t crc8(uint8_t *data, uint8_t len)
{
uint8_t i;
uint8_t j;
uint8_t temp;
uint8_t databyte;
uint8_t crc = 0;
for (i = 0; i < len; i++)
{
databyte = data[i];
for (j = 0; j < 8; j++)
{
temp = (crc ^ databyte) & 0x01;
crc >>= 1;
if (temp)
crc ^= 0x8C;
databyte >>= 1;
}
}
return crc;
}
int readiButton(uint8_t pin, uint8_t *data)
{
int b = presence(pin);
if (b != 0)
return 0;
writeByte(pin, 0x33);
int i;
for (i = 0; i < 8; i++)
{
data[i] = readByte(pin);
}
uint8_t crc = crc8(data, 8);
if (crc == 0)
return 1;
return 0;
}