Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 1225

Python • need to run as sudo

$
0
0
When I run my code I get the following error message and have to run my code as sudo python.
which I always forget to do.


File "/home/pi/watering/wateronce.py", line 21, in <module>
GPIO.setup(pinPump, GPIO.OUT) # Pi can send voltage to pump
RuntimeError: No access to /dev/mem. Try running as root!

What causes this?
The code does run when I type sudo python code.py

Code:

# revised 1st march 2025import RPi.GPIO as GPIO  # interact with Pis pinsimport datetime          # to log the current timeimport spidev            # to interact with the MCP3008 via SPIimport time              # to run our pump for 5 sec# create SPI connectionspi = spidev.SpiDev()spi.open(0,0)spi.max_speed_hz = 1000000 # 1 MHz# function to read out data from MCP3008def readData(channel):      adc = spi.xfer2([1,(8+channel)<<4,0])      data = ((adc[1]&3) << 8) + adc[2]      return datapinPump = 22                      # GPIO pin of pump pin 40needsWater = 630                 # sensor value for dry air# general GPIO settingsGPIO.setwarnings(False)          # ignore warnings (unrelevant here)GPIO.setmode(GPIO.BCM)           # refer to GPIO pin numbersGPIO.setup(pinPump, GPIO.OUT)    # Pi can send voltage to pumpGPIO.output(pinPump, GPIO.LOW)   # turn pump off# read moisture data from channel 0moisture = readData(0)# write time and current moisture in statistic filef = open("/home/pi/WateringStats.txt", "a")currentTime = datetime.datetime.now()f.write(str(currentTime) + ":\n")print(str(currentTime) + ":\n")# 450 = 780 - 330f.write("Current moisture: " + str(round((moisture-430) / 450 * 100, 2)) +"% (" + str(moisture) + ")\n")# if plants are too dry, start pumping and record the moisture in fileif moisture > needsWater:    t_end = time.time() + 4               # pump runs 4 seconds    print(moisture)    # actual pumping    while (time.time() < t_end):        GPIO.output(pinPump, GPIO.HIGH)    GPIO.output(pinPump, GPIO.LOW)        # turn pump off    f.write("Plants got watered!\n")f.write("\n")    # line break for next log entryf.write("\n")    # line break for next log entryf.close()        # close fileprint(moisture)GPIO.cleanup()   # proper clean up of used pins

Statistics: Posted by sandy70 — Tue Mar 04, 2025 5:12 pm



Viewing all articles
Browse latest Browse all 1225

Trending Articles