I am trying to trying to control the GPIOs on my RPi with Python but without one of those modules that require root permissions to be used. I found that trivial way of just "echoing" 1 or 0 to the value file of the GPIO through the console. I also wrote a Python script doing this automatically. So far so good. But this only works if the file (in this case: /sys/class/gpio/gpio17) already exists. I could easily create this folder everytime after booting the Pi, through the console like this:
pi@raspberrypi ~ $ cd /sys/class/gpio
pi@raspberrypi /sys/class/gpio $ echo "17" > export
After this I will have the folder /sys/class/gpio/gpio17 in which I find the information about the pin and can modify it.
So basically my question is: How would I incorporate this step into my Python script. Is there a way to move to the directory and export this folder using Python? I figured it out using a seperate Bash script whitch I then run inside my Python script, but I'd like to avoid using several languages and was wondering if there was an equivalent to the "echo" comand in Python. I searched for some days now but couldn't find anything. If there is, a link would be highly appreciated as well!
Thank You in advance,
a newbie
From your description you should simply need to write the required number to the file named /sys/class/gpio/export
.
GPIO_EXPORT = '/sys/class/gpio/export'
PIN = 17
with open(GPIO_EXPORT, 'w') as export:
export.write(str(PIN))
there a re a lot of options. you can directly use bash syntax in your python code with os
module (or more flexible - subprocess
module).
start python interpreter in your working directory and,
>>> import os
>>> os.system("echo 18>import")
0
>>> exit()
$ ls -a
. .. import
$ cat import
18
or write file.
>>> with open("newport", "w") as newport:
... newport.write("19")
...
>>> exit()
$ ls -a
. .. import newport
$ cat newport
19
and so on. have a look up to original documentation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.