Raspberry pi 3 : sample python snap to read data gpio pins

Hi Team,

Am very new to the snap world . Could some one suggest if you have any sample python snap to read data gpio pins.

Much appreciated.

Naresh.

EDIT

See RPi3 GPIO confinement from a SNAP called from another SNAP

This won’t work until snapd 2.31, and exposes the “gpio-memory-control” slot

Also your program will have to run as a daemon (which should not be a problem)

I’ve edited my OP to reflect these changes, minding any errors as this is untested.

I will also make a full example and edit this post again.

OP

Hello

The easiest way (imo) is to use the RPI.GPIO python package;

In your snapcraft.yaml, define a part such as:

parts:
  setup:
    plugin: python
    python-version: python3
    python-packages: [RPi.GPIO]

Now you can have an app which has the gpio gpio-memory-control plug:

apps:
  myprogram:
    command: bin/myprogram
    daemon: simple
    plugs: [gpio-memory-control] 

Your “myprogram” script daemon could look like this:

#!/usr/bin/env python3

import RPi.GPIO as GPIO
import time

# Set up PIN 0 as output
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(0, GPIO.OUT)	

on = True

# Every second toggle output
while True:
    GPIO.output(0, on)
    on = not on
    time.sleep(1)

Do not forget to connect the slot/plug!

RPi.GPIO is an excellent option, although it uses memory mapping with /dev/gpiomem or even /dev/mem. Are you wanting something different, e.g. sysfs?

Thanks for the inputs @pvanloo and @kyrofa.

I have the below code snippet in myprogram. Where it should read the temperature Sensor data which is connected to the GPIO Pins.

Appreciate if you you have inputs for this.

import os
import glob
import time
os.system(‘modprobe w1-gpio’)
os.system(‘modprobe w1-therm’)
base_dir = ‘/sys/bus/w1/devices/’
device_folder = glob.glob(base_dir + ‘28*’)[0]
device_file = device_folder + ‘/w1_slave’
serialNO = device_folder.split(’-’)[1]
def read_temp_raw():
f = open(device_file, ‘r’)
lines = f.readlines()
f.close()
return lines

def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != ‘YES’:
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find(‘t=’)
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return round(temp_c,1)
while True:
print “Temp in C: {}, Temp in F: {}”.format(round(read_temp()[0],1),round(read_temp()[1],1))
time.sleep(1)

Not sure where your error might be from the sample you gave, possibly the “/sys/bus/w1/devices” is not accessible from within your snap, try running your snap with

snap run --shell snapname.appname

and check if that it is accessible.

Also take note my OP to reflect some changes.

Note that RPi.GPIO attempts to use /dev/gpiomem (which is covered by the gpio-memory-control interface), but falls back to /dev/mem (which is covered by the phyiscal-memory-control interface). You can use the latter while waiting for the former.

Please format your code, it’s very difficult to read (you can surround your code with three backticks, ```).

However, it looks like you’re wanting to use sysfs, in which case you should read this post. tl;dr: Individual interfaces for GPIO pins don’t exist on the stable rpi images, you need to use the edge image instead.

If you just want to read and write the RPi3 gpio from the command line, you could install the pi3gpio snap (sudo snap install pi3gpio). There are a lot of other ways to get the gpio’s working. If you are totally new to snaps, I heavily suggest:


This will teach you about classic mode. The tutorial doesn’t really say what instructions to do in classic mode and which ones to do in normal mode. If you have trouble with it, like I did the first time through, ping me.

for different ways to control the RPi gpio (in classic mode) look at this:

https://elinux.org/RPi_GPIO_Code_Samples
Really cool stuff here. I eventually decided to take the first one, c program, and modify it for my needs.

But the short answer is “sudo snap install pi3gpio”. And don’t forget to connect the plugs…

Is this python program snapped? Have you been able to get “myprogram” to run in classic mode?

If you feel this tutorial could be improved, please feel free to take a crack at it. All tutorials are hosted here.

@kyrofa

It does spell it out clearly in the beginning of the first tutorial here:

We can now run the commands and build a snap as if we were on a classic system (we won’t remind you about that in the following and others tutorial. Just remember that when you run the “snap” (and not snapcraft) command to interact or install a snap, you need to be outside of this classic snap (you can open a second ssh connection for instance).

But i missed it…which led to confusion.

Thanks for the link. I will take a look.

Thanks for the reply’s

Am having issue with the sensor detected by the pi. Am trying to fix this with some other sensor . Will update.

Have filed the issue of Sensor detection. Am able to compile the code normally.

But getting error while building the snap. Below is my code snippet.

name: temphumid
version: ‘0.1’
summary: Read Temperature and Humidity from DHT11 using RPi3
description: Read Temperature and Humidity from DHT11 using RPi3
grade: devel
confinement: devmode

grade: devel
confinement: devmode
parts:
temphumid:
source: .
plugin: make

apps:
temphumid:
command: bin/temphumid

Contents of make file:
temphumid: temp_humidity.c
gcc -o bin/temphumid temp_humidity.c -lwiringPi -lcrypt -lrt -lpthread -lm -I.

Error:
(classic)naresh@localhost:~/temphumid$ snapcraft
Preparing to pull temphumid
Pulling temphumid
Preparing to build temphumid
Building temphumid
make -j4
gcc -o bin/temphumid temp_humidity.c -lwiringPi -lcrypt -lrt -lpthread -lm -I.
make install DESTDIR=/home/nareshbvemula/temphumid/parts/temphumid/install
make: *** No rule to make target ‘install’. Stop.
Traceback (most recent call last):
File “/usr/bin/snapcraft”, line 9, in
load_entry_point(‘snapcraft==2.35’, ‘console_scripts’, ‘snapcraft’)()
File “/usr/lib/python3/dist-packages/pkg_resources/init.py”, line 542, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File “/usr/lib/python3/dist-packages/pkg_resources/init.py”, line 2569, in load_entry_point
return ep.load()
File “/usr/lib/python3/dist-packages/pkg_resources/init.py”, line 2229, in load
return self.resolve()
File “/usr/lib/python3/dist-packages/pkg_resources/init.py”, line 2235, in resolve
module = import(self.module_name, fromlist=[‘name’], level=0)
File “/usr/lib/python3/dist-packages/snapcraft/cli/main.py”, line 19, in
run(prog_name=‘snapcraft’)
File “/usr/lib/python3/dist-packages/click/core.py”, line 716, in call
return self.main(*args, **kwargs)
File “/usr/lib/python3/dist-packages/click/core.py”, line 696, in main
rv = self.invoke(ctx)
File “/usr/lib/python3/dist-packages/click/core.py”, line 1037, in invoke
return Command.invoke(self, ctx)
File “/usr/lib/python3/dist-packages/click/core.py”, line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File “/usr/lib/python3/dist-packages/click/core.py”, line 534, in invoke
return callback(*args, **kwargs)
File “/usr/lib/python3/dist-packages/click/decorators.py”, line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File “/usr/lib/python3/dist-packages/snapcraft/cli/init.py”, line 124, in run
ctx.forward(lifecyclecli.commands[‘snap’])
File “/usr/lib/python3/dist-packages/click/core.py”, line 552, in forward
return self.invoke(cmd, **kwargs)
File “/usr/lib/python3/dist-packages/click/core.py”, line 534, in invoke
return callback(*args, **kwargs)
File “/usr/lib/python3/dist-packages/snapcraft/cli/lifecycle.py”, line 140, in snap
project_options, directory=directory, output=output)
File “/usr/lib/python3/dist-packages/snapcraft/internal/lifecycle/_packer.py”, line 45, in snap
execute(‘prime’, project_options)
File “/usr/lib/python3/dist-packages/snapcraft/internal/lifecycle/_runner.py”, line 80, in execute
_Executor(config, project_options).run(step, part_names)
File “/usr/lib/python3/dist-packages/snapcraft/internal/lifecycle/_runner.py”, line 175, in run
self._run_step(step, part, part_names)
File “/usr/lib/python3/dist-packages/snapcraft/internal/lifecycle/_runner.py”, line 212, in _run_step
getattr(part, step)()
File “/usr/lib/python3/dist-packages/snapcraft/internal/pluginhandler/init.py”, line 330, in build
self.plugin.build()
File “/usr/lib/python3/dist-packages/snapcraft/plugins/make.py”, line 128, in build
self.make()
File “/usr/lib/python3/dist-packages/snapcraft/plugins/make.py”, line 124, in make
self.run(command, env=env)
File “/usr/lib/python3/dist-packages/snapcraft/_baseplugin.py”, line 202, in run
return common.run(cmd, cwd=cwd, **kwargs)
File “/usr/lib/python3/dist-packages/snapcraft/internal/common.py”, line 63, in run
subprocess.check_call([’/bin/sh’, f.name] + cmd, **kwargs)
File “/usr/lib/python3.5/subprocess.py”, line 581, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command ‘[’/bin/sh’, ‘/tmp/tmp9d2g9nm9’, ‘make’, ‘install’, ‘DESTDIR=/home/nareshbvemula/temphumid/parts/temphumid/install’]’ returned non-zero exit status 2
(classic)naresh@localhost:~/temphumid$

Could you try to format your pasted code and snapcraft.yaml snippets ? it is really easy to do, just mark the code part and click on the </> icon in the editor … (or use three backticks ``` around the code snippet) … your current form of pasting makes it very hard to read the code pieces you include.

Sorry My Bad, below are the details.

</ name: temphumid version: ‘0.1’ summary: Read Temperature and Humidity from DHT11 using RPi3 description: Read Temperature and Humidity from DHT11 using RPi3 grade: devel confinement: devmode

grade: devel confinement: devmode parts: temphumid: source: . plugin: make

apps: temphumid: command: bin/temphumid

could some one please suggest on this.

If you answer my original questions, I may be able to help.

@ogra meant for you to use the button in the editor which looks like </>, not to type </ and > around your code. If you’re used to markdown you can use the triple backtick (```) both before and after your code (each triple backtick group on a line by themselves:

```
code here
```