Skip to content

Instantly share code, notes, and snippets.

@mvduin
Created March 13, 2017 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvduin/8f7ff56e60109e3d9dcaa04bc915daf0 to your computer and use it in GitHub Desktop.
Save mvduin/8f7ff56e60109e3d9dcaa04bc915daf0 to your computer and use it in GitHub Desktop.
#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