Created
March 13, 2017 16:34
-
-
Save mvduin/8f7ff56e60109e3d9dcaa04bc915daf0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include "die.h" | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <fcntl.h> | |
class Gpio { | |
int fd = -1; | |
char *path = NULL; | |
Gpio() = delete; | |
Gpio( Gpio const & ) = delete; | |
protected: | |
Gpio( const char *name, int mode ) | |
{ | |
if( asprintf( &path, "/dev/gpio/%s/value", name ) < 0 ) { | |
path = NULL; | |
sysdie( "asprintf" ); | |
} | |
fd = open( path, mode | O_CLOEXEC ); | |
if( fd < 0 ) | |
sysdie( "open %s", path ); | |
} | |
public: | |
~Gpio() | |
{ | |
if( fd >= 0 ) | |
close( fd ); | |
free( path ); | |
} | |
operator bool () const | |
{ | |
char c; | |
auto res = pread( fd, &c, 1, 0 ); | |
if( res < 0 ) | |
sysdie( "pread %s", path ); | |
if( res == 0 ) | |
die( "pread %s: no data", path ); | |
return c & 1; | |
} | |
}; | |
class GpIn : public Gpio { | |
GpIn( const char *name ) : Gpio( name, O_RDONLY ) {} | |
}; | |
class GpOut : public Gpio { | |
GpOut( const char *name ) : Gpio( name, O_RDWR ) {} | |
bool operator = ( bool value ) & | |
{ | |
char c = '0' + value; | |
auto res = pwrite( fd, &c, 1, 0 ); | |
if( res < 0 ) | |
sysdie( "pwrite %s", path ); | |
return value; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment