1

i have a python code which is running and has no errors, it is connected with arduino uno using nanpy firmware and lcd which has the library of adafruit/Adafruit_Python_CharLCD and it uses gpio BCM, i also using pi camera, but when i run the code the pi shuts down here is the code:

server.py

import apptopi
from socket import *
from time import ctime
from nanpy import (ArduinoApi, SerialManager)
import thread
from time import sleep



ledpin = 13
buttonpin = 2
buttonstate = 1
add = 0

apptopi.setup()

connection = SerialManager()
a = ArduinoApi(connection = connection)

a.pinMode(ledpin, a.OUTPUT)
a.pinMode(buttonpin, a.INPUT)

ctrCmd = ['Up','Down','Left','Right','Stop','Connect','Balls']

HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

def con():
        while True:
                print 'Waiting for connection'
                tcpCliSock,addr = tcpSerSock.accept()
                print '...connected from :', addr
                try:
                        while True:
                                data = ''
                                data = tcpCliSock.recv(BUFSIZE)

                                if not data:
                                        break
                                if data == ctrCmd[0]:
                                        apptopi.home()
                                        print 'forward'
                                if data == ctrCmd[1]:
                                        apptopi.back()
                                        print 'backward'
                                if data == ctrCmd[2]:
                                        apptopi.left()
                                        print 'leftturn'
                                if data == ctrCmd[3]:
                                        apptopi.right()
                                        print 'rightturn'
                                if data == ctrCmd[4]:
                                        apptopi.stp()
                                        print 'stop'




                except KeyboardInterrupt:
                        apptopi.close()
                        GPIO.cleanup()
                else:
                        print 'reply'
                        tcpCliSock.send('1')
        tcpSerSock.close();


def but():
        while True:
                add += 1
                s = str(add)
                lcd.message ('Balls collected\n'+s)
                sleep(3.0)
                lcd.clear()               



thread.start_new_thread(con, ())
thread.start_new_thread(but, ())

apptopi.py

from nanpy import (ArduinoApi, SerialManager)
from picamera.array import PiRGBArray     
from picamera import PiCamera
import RPi.GPIO as GPIO
import time
import cv2
import cv2.cv as cv
import numpy as np
import Adafruit_CharLCD as LCD
import math

def setup():
        lcd_rs        = 26  
        lcd_en        = 19
        lcd_d4        = 13
        lcd_d5        = 6
        lcd_d6        = 5
        lcd_d7        = 11
        lcd_backlight = 4

        lcd_columns = 16
        lcd_rows    = 2
        lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, 

                  lcd_d7,lcd_columns,lcd_rows,lcd_backlight)


         GPIO.setmode(GPIO.BCM)

        global GPIO_TRIGGER1            #Left ultrasonic sensor
        GPIO_TRIGGER1 = 29
        global GPIO_ECHO1
        GPIO_ECHO1 = 31

        global GPIO_TRIGGER2
        GPIO_TRIGGER2 = 36      #Front ultrasonic sensor
        global GPIO_ECHO2
        GPIO_ECHO2 = 37

        global GPIO_TRIGGER3
        GPIO_TRIGGER3 = 33      #Right ultrasonic sensor
        global GPIO_ECHO3
        GPIO_ECHO3 = 35

        global LED_PIN
        LED_PIN=13 

        global motor1a
        motor1a = 5
        global motor1b
        motor1b = 4
        global motor1c
        motor1c = 6

        global motor2a 
        motor2a = 8
        global motor2b
        motor2b = 7
        global motor2c
        motor2c = 9

        connection = SerialManager()
        global a
        a = ArduinoApi(connection = connection)

GPIO.setup(GPIO_TRIGGER1,GPIO.OUT)  # Trigger
        GPIO.setup(GPIO_ECHO1,GPIO.IN)      # Echo
        GPIO.setup(GPIO_TRIGGER2,GPIO.OUT)  # Trigger
        GPIO.setup(GPIO_ECHO2,GPIO.IN)
        GPIO.setup(GPIO_TRIGGER3,GPIO.OUT)  # Trigger
        GPIO.setup(GPIO_ECHO3,GPIO.IN)
        GPIO.setup(LED_PIN,GPIO.OUT)

        GPIO.output(GPIO_TRIGGER1, False)
        GPIO.output(GPIO_TRIGGER2, False)
        GPIO.output(GPIO_TRIGGER3, False)

        a.pinMode(motor1a, a.OUTPUT)
        a.pinMode(motor1b, a.OUTPUT)
        a.pinMode(motor1c, a.OUTPUT)

        a.pinMode(motor2a, a.OUTPUT)
        a.pinMode(motor2b, a.OUTPUT)
        a.pinMode(motor2c, a.OUTPUT)


def froward():
        a.digitalWrite(motor1a, a.HIGH)
        a.digitalWrite(motor1b, a.LOW)
        a.analogWrite(motor1c, 200)
        a.digitalWrite(motor2a, a.HIGH)
        a.digitalWrite(motor2b, a.LOW)
        a.analogWrite(motor2c, 200)


def reverse():

        a.digitalWrite(motor1a, a.LOW)
        a.digitalWrite(motor1b, a.HIGH)
        a.analogWrite(motor1c, 255)

        a.digitalWrite(motor2a, a.LOW)
        a.digitalWrite(motor2b, a.HIGH)
        a.analogWrite(motor2c, 255)

def leftturn():

        a.digitalWrite(motor1a, a.LOW)
        a.digitalWrite(motor1b, a.HIGH)
        a.analogWrite(motor1c, 255)
        a.digitalWrite(motor2a, a.HIGH)
        a.digitalWrite(motor2b, a.LOW)
        a.analogWrite(motor2c, 255)

def rightturn():
        a.digitalWrite(motor1a, a.HIGH)
        a.digitalWrite(motor1b, a.LOW)
        a.analogWrite(motor1c, 255)
        a.digitalWrite(motor2a, a.LOW)
        a.digitalWrite(motor2b, a.HIGH)
        a.analogWrite(motor2c, 255)

def stop():
        a.digitalWrite(motor1a, a.LOW)
        a.digitalWrite(motor1a, a.LOW)
        a.analogWrite(motor1c, 0)

        a.digitalWrite(motor2a, a.LOW)
        a.digitalWrite(motor2a, a.LOW)
        a.analogWrite(motor2c, 0)


def forw():
        froward()
        time.sleep(1)

        stop()
        time.sleep(1)

def back():
        reverse()
        time.sleep(1)

        stop()
        time.sleep(1)

def left():
        leftturn()
        time.sleep(1)

        stop()
        time.sleep(1)

def right():
        rightturn()
        time.sleep(1)

        stop()
        time.sleep(1)

def stp():
        stop()
        time.sleep(1)

def sonar(GPIO_TRIGGER,GPIO_ECHO):
      start=0
      stop=0
      # Set pins as output and input
      GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  # Trigger
      GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo

      # Set trigger to False (Low)
      GPIO.output(GPIO_TRIGGER, False)

      # Allow module to settle
      time.sleep(0.01)

      #while distance > 5:
      #Send 10us pulse to trigger
      GPIO.output(GPIO_TRIGGER, True)
      time.sleep(0.00001)
      GPIO.output(GPIO_TRIGGER, False)
      begin = time.time()
      while GPIO.input(GPIO_ECHO)==0 and time.time()<begin+0.05:
            start = time.time()

      while GPIO.input(GPIO_ECHO)==1 and time.time()<begin+0.1:
            stop = time.time()

      # Calculate pulse length
      elapsed = stop-start
      # Distance pulse travelled in that time is time
      # multiplied by the speed of sound (cm/s)
      distance = elapsed * 34000

      # That was the distance there and back so halve the value
      distance = distance / 2

      print "Distance : %.1f" % distance
      # Reset GPIO settings
      return distance

def segment_colour(frame):    #returns only the red colors in the frame
    hsv_roi =  cv2.cvtColor(frame, cv2.cv.CV_BGR2HSV)
    mask_1 = cv2.inRange(hsv_roi, np.array([160, 160,10]), np.array([190,255,255]))
    ycr_roi=cv2.cvtColor(frame,cv2.cv.CV_BGR2YCrCb)
    mask_2=cv2.inRange(ycr_roi, np.array((0.,165.,0.)), np.array((255.,255.,255.)))

    mask = mask_1 | mask_2
    kern_dilate = np.ones((8,8),np.uint8)
    kern_erode  = np.ones((3,3),np.uint8)
    mask= cv2.erode(mask,kern_erode)      #Eroding
    mask=cv2.dilate(mask,kern_dilate)     #Dilating
    cv2.imshow('mask',mask)
    return mask

def find_blob(blob): #returns the red colored circle
    largest_contour=0
    cont_index=0
    contours, hierarchy = cv2.findContours(blob, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
    for idx, contour in enumerate(contours):
        area=cv2.contourArea(contour)
        if (area >largest_contour) :
            largest_contour=area

            cont_index=idx
            #if res>15 and res<18:
            #    cont_index=idx

    r=(0,0,2,2)
    if len(contours) > 0:
        r = cv2.boundingRect(contours[cont_index])

    return r,largest_contour

def target_hist(frame):
    hsv_img=cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    hist=cv2.calcHist([hsv_img],[0],None,[50],[0,255])
    return hist

camera = PiCamera()
camera.resolution = (160, 120)
camera.framerate = 16
rawCapture = PiRGBArray(camera, size=(160, 120))

# allow the camera to warmup
time.sleep(0.001)

def home():
        for image in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
              #grab the raw NumPy array representing the image, then initialize the timestamp and occupied/unoccupied text
              frame = image.array
              frame=cv2.flip(frame,1)
              global centre_x
              global centre_y
              centre_x=0.
              centre_y=0.
              hsv1 = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
              mask_red=segment_colour(frame)      #masking red the frame
              loct,area=find_blob(mask_red)
              x,y,w,h=loct

              #distance coming from front ultrasonic sensor
              distanceC = sonar(GPIO_TRIGGER2,GPIO_ECHO2)
              #distance coming from right ultrasonic sensor
              distanceR = sonar(GPIO_TRIGGER3,GPIO_ECHO3)
              #distance coming from left ultrasonic sensor
              distanceL = sonar(GPIO_TRIGGER1,GPIO_ECHO1)

              if (w*h) < 10:
                    found=0
              else:
                    found=1
                    simg2 = cv2.rectangle(frame, (x,y), (x+w,y+h), 255,2)
                    centre_x=x+((w)/2)
                    centre_y=y+((h)/2)
                    cv2.circle(frame,(int(centre_x),int(centre_y)),3,(0,110,255),-1)
                    centre_x-=80
                    centre_y=6--centre_y
                    print centre_x,centre_y
              initial=400
              flag=0
              GPIO.output(LED_PIN,GPIO.LOW)          
              if(found==0):
                    #if the ball is not found and the last time it sees ball in which direction, it will start to rotate in that direction
                    if flag==0:
                          rightturn()
                          time.sleep(0.05)
                    else:
                          leftturn()
                          time.sleep(0.05)
                    stop()
                    time.sleep(0.0125)

              elif(found==1):
                    if(area<initial):
                           if(distanceC<10):
                                #if ball is too far but it detects something in front of it,then it avoid it and reaches the ball.
                                if distanceR>=8:
                                      rightturn()
                                      time.sleep(0.00625)
                                      stop()
                                      time.sleep(0.0125)
                                      forward()
                                      time.sleep(0.00625)
                                      stop()
                                      time.sleep(0.0125)
                                      #while found==0:
                                      leftturn()
                                      time.sleep(0.00625)
                                elif distanceL>=8:
                                      leftturn()
                                      time.sleep(0.00625)
                                      stop()
                                      time.sleep(0.0125)
                                      forward()
                                      time.sleep(0.00625)
                                      stop()
                                      time.sleep(0.0125)
                                      rightturn()
                                      time.sleep(0.00625)
                                      stop()
                                      time.sleep(0.0125)
                                else:
                                      stop()
                                      time.sleep(0.01)
                          else:
                                #otherwise it move forward
                                forward()
                                time.sleep(0.00625)
                    elif(area>=initial):
                          initial2=6700
                          if(area<initial2):
                                if(distanceC>10):
                                      #it brings coordinates of ball to center of camera's imaginary axis.
                                      if(centre_x<=-20 or centre_x>=20):
                                            if(centre_x<0):
                                                  flag=0
                                                  rightturn()
                                                  time.sleep(0.025)
                                            elif(centre_x>0):
                                                  flag=1
                                                  leftturn()
                                                  time.sleep(0.025)
                                      forward()
                                      time.sleep(0.00003125)
                                      stop()
                                      time.sleep(0.00625)
                                else:
                                  stop()
                                  time.sleep(0.01)

                          else:
                                #if it founds the ball and it is too close it lights up the led.
                                GPIO.output(LED_PIN,GPIO.HIGH)
                                time.sleep(0.1)
                                stop()
                                time.sleep(0.1)

              cv2.imshow("draw",frame)    
              rawCapture.truncate(0)  # clear the stream in preparation for the next frame                
              if(cv2.waitKey(1) & 0xff == ord('q')):
                    break

        GPIO.cleanup() #free all the GPIO pins
  • Does it shut down or reboot? In either case it suggests an inadequate power supply. – joan Jan 24 '18 at 4:15
  • it shut down and does not reboot i have a power supply of 5v and 2.5a is it not enough ? – Mahilum Jm Jan 24 '18 at 4:17
  • As Joan said, sounds like it might be power. Find the specs on all the items you are running off the power supply and add up the current draw. – Chef Flambe Jan 24 '18 at 9:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.