Grovepi and GPIO

Hello all,
I’m trying to access GPIO port to read HC-SR04 ultrasonic sensor values; when I try this code without the Grovepi plugged in the script works fine:


import time
import RPi.GPIO as GPIO

# Which GPIO's are used [0]=BCM Port Number [1]=BCM Name [2]=Use [3]=Pin
# ----------------------------------------------------------------------
arrgpio = [(23,"GPIO24","Echo",16),(24,"GPI23","Trig",18)]

# Set GPIO Channels
# -----------------
GPIO.setmode(GPIO.BCM)
GPIO.setup(arrgpio[0][0], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(arrgpio[1][0], GPIO.OUT)
GPIO.output(arrgpio[1][0], False)

# A couple of variables
# ---------------------
EXIT = 0                        # Infinite loop
decpulsetrigger = 0.0001        # Trigger duration
inttimeout = 2100               # Number of loop iterations before timeout called

# Wait for 2 seconds to allow the ultrasonics to settle (probably not needed)
# ---------------------------------------------------------------------------
print "Waiting for 2 seconds....."
time.sleep(2)

# Go
# --
print "Running...."

# Never ending loop
# -----------------
while EXIT == 0:
  try:
    # Trigger high for 0.0001s then low
        
  	GPIO.output(arrgpio[1][0], True)
  	time.sleep(decpulsetrigger)
  	GPIO.output(arrgpio[1][0], False)

  	# Wait for echo to go high (or timeout)

  	intcountdown = inttimeout

  	while (GPIO.input(arrgpio[0][0]) == 0 and intcountdown > 0):
  		intcountdown = intcountdown - 1

  	# If echo is high

  	if intcountdown > 0:

  		# Start timer and init timeout countdown

  		echostart = time.time()
  		intcountdown = inttimeout

  		# Wait for echo to go low (or timeout)

  		while (GPIO.input(arrgpio[0][0]) == 1 and intcountdown > 0):
  			intcountdown = intcountdown - 1

  		# Stop timer

  		echoend = time.time()

  		# Echo duration

  		echoduration = echoend - echostart

  	# Display distance

  	if intcountdown > 0:
  		intdistance = (echoduration*1000000)/58
  		print "Distance = " + str(intdistance) + "cm"
      time.sleep(100)
  	else:
  	  print "Distance - timeout"
          # Wait at least .01s before re trig (or in this case .1s)
          time.sleep(100)
  except KeyboardInterrupt:
        GPIO.cleanup()
<code></code>

When I try with the Grovepi plugged in I have this error:

RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(arrgpio[0][0], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

Are the GPIO’s port available when Grovepi is plugged in?
Thanks, bye bye

Hey,
We are not using the Pins 16 and 18 so you should be able to use them without any problem.

Can you try running this as root.

Thanks,
-Karan

Are all the other pins unusable when the GrovePi is connected?

Hi @liam37,

Almost all the 26 GPIO pins on the header of the GrovePi can be used, except the Pin 24 which is BCM 8 (Broadcom Pin Number). Using this pin resets the GrovePi and hence all the other Pins on the GPIO header of GrovePi can be used.

Only the Serial and I2C pins of the Raspberry Pi are exposed on the ports of the GrovePi (RPISER and I2C Ports), while all the other RaspberryPi GPIO pins have to be accessed through the 26 Pin GPIO header on the GrovePi.

-Shoban

1 Like

Hi @Shoban

I post this here as a reply because the problem i’m running in to also concerns GPIO with Grovepi.
I have a code in which I read out 3 light sensor data streams in threaded functions. This all works perfectly fine, untill I try to add GPIO functionaltiy to this code. Then I get errno 110:

Exception in thread Thread-8:
Traceback (most recent call last):
File “/usr/lib/python3.4/threading.py”, line 920, in _bootstrap_inner
self.run()
File “/usr/lib/python3.4/threading.py”, line 868, in run
self._target(*self._args, **self._kwargs)
File “/root/Desktop/LaserCodeThread.py”, line 58, in lightValue2
sensorReading2 = grovepi.analogRead(lightSensor2)
File “/root/Desktop/grovepi.py”, line 214, in analogRead
bus.write_i2c_block_data(address, 1, aRead_cmd + [pin, unused, unused])
TimeoutError: [Errno 110] Connection timed out

This is my code. If I don’t put in the #'d code it works. When I add these lines the [Errno 1110] starts and this doesn’t end untill I reboot my RPi. Any ideas?

    print("Initiating Laser Program Essentials")
from time import sleep
import grovepi
from pygame import mixer
from pythonosc import osc_message_builder
from pythonosc import udp_client
import argparse
from threading import Thread

import RPi.GPIO as GPIO
#GPIO.setmode(GPIO.BCM)
#GPIO.setwarnings(False)
#button1=2
#button2=3
#button3=4
#button4=17
#GPIO.setup(button1,GPIO.IN,pull_up_down=GPIO.PUD_UP)
#GPIO.setup(button2,GPIO.IN,pull_up_down=GPIO.PUD_UP)
#GPIO.setup(button3,GPIO.IN,pull_up_down=GPIO.PUD_UP)
#GPIO.setup(button4,GPIO.IN,pull_up_down=GPIO.PUD_UP)

#Connect the Grove Light Sensor to analag port A0
#Connect the Relay to digital port D4
#SIG, NC, VCC, GND
lightSensor1 = 0
lightSensor2 = 1
lightSensor3 = 2

#Set Channel Input/Output
grovepi.pinMode(lightSensor1,"INPUT")
grovepi.pinMode(lightSensor2,"INPUT")
grovepi.pinMode(lightSensor3,"INPUT")


#UDP Code ----------------------------------------------------
if __name__ == "__main__":
  parser = argparse.ArgumentParser()
  parser.add_argument("--ip", default="192.168.0.2",
      help="The ip of the OSC server")
  parser.add_argument("--port", type=int, default=5000,
      help="The port the OSC server is listening on")
  args = parser.parse_args()
  client = udp_client.UDPClient(args.ip, args.port)

def sendToMax(address,value): #inputs the address as string and value as whatever you want it
    msg = osc_message_builder.OscMessageBuilder(address = address)
    msg.add_arg(value)
    msg = msg.build()
    client.send(msg)

def lightValue1():
  sensorReading1 = grovepi.analogRead(lightSensor1)
  sendToMax("/lightSensor1", sensorReading1)
  #print ("Sensor 1 " + str(sensorReading1))
  (.1)

def lightValue2():
  sensorReading2 = grovepi.analogRead(lightSensor2)
  sendToMax("/lightSensor2", sensorReading2)
  #print ("Sensor 2 " + str(sensorReading2))
def lightValue3():
  sensorReading3 = grovepi.analogRead(lightSensor3)
  sendToMax("/lightSensor3", sensorReading3)
  #print ("Sensor 3 " + str(sensorReading3))
'''
def laserknoppen():
  if GPIO.input(button1)==0:
    print("Button 1 pressed")
  if GPIO.input(button2)==0:
    print("Button 2 pressed")
  if GPIO.input(button3)==0:
      print("Button 3 pressed")
  if GPIO.input(button4)==0:
      print("Button 4 pressed")
  if GPIO.input(button1)==0 or GPIO.input(button2)==0 or GPIO.input(button3)==0 or GPIO.input(button4)==0:
  #if GPIO.input(button1)==0 or GPIO.input(button2)==0 or GPIO.input(button3)==0 or GPIO.input(button4)==0:
      sendToMax("/laserknoppen",1)
      sleep(2)
      sendToMax("/laserknoppen",0)
print("Essentials Initiated")
#Laser Recognition Alarm System
GPIO.add_event_detect(button1,GPIO.FALLING, callback=laserknoppen, bouncetime=500)
GPIO.add_event_detect(button2,GPIO.FALLING, callback=laserknoppen, bouncetime=500)
GPIO.add_event_detect(button3,GPIO.FALLING, callback=laserknoppen, bouncetime=500)
GPIO.add_event_detect(button4,GPIO.FALLING, callback=laserknoppen, bouncetime=500)
'''
while True:
    try:
      Thread(target=lightValue1, args=()).start()
      sleep(.05)
      Thread(target=lightValue2, args=()).start()
      sleep(.05)
      Thread(target=lightValue3, args=()).start()
      sleep(.05)
        
    except IOError:
      print("Error")
      GPIO.cleanup()

    except KeyboardInterrupt:
      break
      GPIO.cleanup()
    finally:
      GPIO.cleanup()

Hey @liam37,
I had a look at the code and did look at the error too. The problem seems to coming from the socket connection and not from the GrovePi or the GPIO though some condition from how you are using them might be causing it. Here is a post that might help you: http://stackoverflow.com/questions/12145536/how-can-i-debug-what-is-causing-a-connection-refused-or-a-connection-time-out

Also, I saw that you were calling each analog reads from different threads. Any reason as to why you are doing this. We do not recommend using the GrovePi functions in parallel, because the Pi sends commands to the GrovePi and waits for a reply back. If you have parallel process sending and receiving data from the GrovePi, there is a chance that you can send another command to the GrovePi before receiving an reply back and this can cause problems with the program.