0

I have a setup like below:

enter image description here

The script is supposed to turn the led on, sleep and turn it off again. And the script does work.

import RPi.GPIO as GPIO
import time

# This script will turn on the LED for 1 second and turn it off again

# setup GPIO
GPIO.setmode(GPIO.BCM)
# disable warnings
GPIO.setwarnings(False)
# set GPIO.OUT to pin 18
GPIO.setup(18,GPIO.OUT)

# turn on LED
print "LED on"
GPIO.output(18,GPIO.HIGH)
# wait for 1 second
time.sleep(1)
# turn off led
print "LED off"
GPIO.output(18,GPIO.LOW)

If I reboot the pi the led suddenly is on again and I wonder why. Is it because I am missing something important about the pi's functionality or am I making mistakes here? By the way the same behavior occurs with rgb leds too.

I also read up on GPIO.setmode(GPIO.BCM) and it seems that the only difference between the modes BCM and BOARD are the number one uses when referring to pins, or might the mode be the issue?

チーズパン
  • 167
  • 1
  • 8
  • I am a complete noob with the RPi hardware, but it just so happens that I might have read up on this very issue last night. As I understand it, the initial state of the GPIO pins on boot can fluctuate. A lot of people dealing with motor controls were particularly concerned about this. There is discussion about this on the [RPi forums](https://www.raspberrypi.org/forums/viewtopic.php?f=44&t=35321) and jojopi's 12/31/16 reply might be helpful. I researched it far enough to discover [device tree overlays](http://int03.co.uk/blog/2015/01/11/raspberry-pi-gpio-states-at-boot-time/) but no further. – bobstro Mar 21 '17 at 20:34
  • What happens if you set the pin back to INPUT at the very end of the script? Does that fix the issue? – stevieb Mar 22 '17 at 13:52

2 Answers2

1

You can't guarantee the state of the GPIO pins during the boot process; all sorts of things from the kernel configuration, device tree, modules etc can mess with this.

See Why are some GPIO pins HIGH when the Raspberry Pi boots up?

You could run a script from /etc/rc.local to reset this pin on boot, as described here.

nickcrabtree
  • 438
  • 4
  • 13
1

Try to cleanup the GPIO pins to restore them to low state. Try the following code for example:

import RPi.GPIO as GPIO  
import time

PIN = 12

GPIO.setwarnings(False)

# blinking function  
def blink(pin):
        GPIO.output(pin,GPIO.HIGH)  
        time.sleep(1)  
        GPIO.output(pin,GPIO.LOW)  
        time.sleep(1)  
        return

# to use Raspberry Pi board GPIO Board Numbering
GPIO.setmode(GPIO.BOARD)

# set up GPIO output channel  
GPIO.setup(PIN, GPIO.OUT)  

# blink GPIO18 10 times  
for i in range(0, 10):  
        blink(PIN)  
GPIO.cleanup()   

I have modified the code from the site a bit to match your code's pin numbers.

Tes3awy
  • 318
  • 1
  • 2
  • 14