Skip to content

Instantly share code, notes, and snippets.

@ryuichiueda
Last active November 6, 2015 15:41
Show Gist options
  • Save ryuichiueda/b5f1b5705f0d6bfff425 to your computer and use it in GitHub Desktop.
Save ryuichiueda/b5f1b5705f0d6bfff425 to your computer and use it in GitHub Desktop.
blink LED without WiringPi
#include <iostream>
#include <stdint-gcc.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
using namespace std;
/* GPIOで一つだけLEDを点滅させるC++のコード
* written by Ryuichi Ueda
参考文献
米田聡: Raspberry Piで学ぶARMデバイスドライバープログラミング, ソシム, 2014
*/
/* このコードは上記参考文献のコードの必要な部分を
* 目で追い、C++化、RaspberryPi2対応、ミニマム化
* を行ったものです。*/
static volatile uint32_t *gpio_base = NULL;
int main(int argc, char const* argv[])
{
/* step1: 仮想メモリとレジスタのマッピング */
int fd = open("/dev/mem", O_RDWR | O_SYNC);
if(fd < 0){
cerr << "/dev/memが開けません。" << endl;
exit(1);
}
const uint32_t rpi_gpio_base = 0x3f000000 + 0x200000;//レジスタのベース+ GPIOのオフセット
const uint32_t rpi_block_size = 4096;
void *gpio_mmap = mmap(NULL,rpi_block_size,
PROT_READ | PROT_WRITE, MAP_SHARED,fd,rpi_gpio_base);
if(gpio_mmap == MAP_FAILED){
cerr << "GPIOのmmapに失敗しました。" << endl;
exit(1);
}
close(fd);
gpio_base = (volatile uint32_t *)gpio_mmap;
/* step2: GPIOの初期化 */
const int led = 21;
//GPIO Function Setレジスタに機能を設定
const uint32_t index = 0 + led/10;// 0: index of GPFSEL0
const unsigned char shift = (led%10)*3;
const uint32_t mask = ~(0x7 << shift);
gpio_base[index] = (gpio_base[index] & mask) | (1 << shift);//1: OUTPUTのフラグ
/* step3: GPIOに値を送る */
for(int i=0;i<2;i++){
gpio_base[7] = 1<<led;//7: index of GPSET0
sleep(1);
gpio_base[10] = 1<<led;//10: index of GPCLR0
sleep(1);
}
/* step4: 後始末(無限ループならシグナルで)*/
munmap((void *)gpio_base,rpi_block_size);
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment