Untitled

mail@pastecode.io avatar
unknown
python
2 years ago
7.2 kB
2
Indexable
Never
import cv2
import pyzbar.pyzbar as pyzbar
import math
import RPi.GPIO as GPIO
import time, sys
import pandas as pd
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from time import sleep

misstime = 0                    ##global variable to check how many times of frame it misses
   


Item_name = ["Juice", "LaysChips", "Biscuit", "Cake", "Maggi", "Bananas", "NoteBook", "Shampoo"]
Price = [20, 20, 20, 15, 10, 30, 50, 170]
items = {Item_name[i]: Price[i] for i in range(len(Item_name))}


m11=16
m12=15
m21=18
m22=22

def stop()
    GPIO.output(m11, 0)
    GPIO.output(m12, 0)
    GPIO.output(m21, 0)
    GPIO.output(m22, 0)

def forward():

    GPIO.output(m11, 1)
    GPIO.output(m12, 0)
    GPIO.output(m21, 1)
    GPIO.output(m22, 0)
    print ("Forward")

def back():
    print ("back")
    GPIO.output(m11, 0)
    GPIO.output(m12, 1)
    GPIO.output(m21, 0)
    GPIO.output(m22, 1)

def stop(ina, inb)
    print("stop")
    GPIO.output(in1,GPIO.LOW)
    GPIO.output(in2,GPIO.LOW)

def forward(ina, inb)
    print("forward")
    GPIO.output(ina,GPIO.HIGH)
    GPIO.output(inb,GPIO.LOW)

def backward(ina, inb)
    print("backward")
    GPIO.output(ina,GPIO.HIGH)
    GPIO.output(inb,GPIO.LOW)

def left(ina, inb)
    print("left")
    GPIO.output(m11, 0)
    GPIO.output(m12, 0)
    GPIO.output(m21, 1)
    GPIO.output(m22, 0)

def right(ina, inb)
    print("right")
    GPIO.output(m11, 1)
    GPIO.output(m12, 0)
    GPIO.output(m21, 0)
    GPIO.output(m22, 0)

def obstacle(TRIG, ECHO):
    print("obstacle")
    i=0        
    avgDistance=0
    for i in range(5):
        GPIO.output(TRIG, False)                 #Set TRIG as LOW
        time.sleep(0.001)                        #Delay
        GPIO.output(TRIG, True)                  #Set TRIG as HIGH
        time.sleep(0.00001)                      #Delay of 0.00001 seconds
        GPIO.output(TRIG, False)                 #Set TRIG as LOW
        while GPIO.input(ECHO)==0:
            pass                                #Check whether the ECHO is LOW            
        pulse_start = time.time()
        while GPIO.input(ECHO)==1:              #Check whether the ECHO is HIGH
            pass
        pulse_end = time.time()
        pulse_duration = pulse_end - pulse_start #time to get back the pulse to sensor
        distance = pulse_duration * 17150        #Multiply pulse duration by 17150 (34300/2) to get distance
        distance = round(distance,2)             #Round to two decimal points
        avgDistance=avgDistance+distance
    avgDistance=avgDistance/5                    ##average the distance value and return the value
    return avgDistance
   

def decodeDisplay(image, orders):
    global misstime
    barcodes = pyzbar.decode(image)
    flag = 0
   
    for barcode in barcodes:                                 ##process every capture of frame of camera
        misstime = 0
        flag = 1
        barcodeData = barcode.data.decode("utf-8")
        print("barcodedata")
        barcodeType = barcode.type
        if barcodeData == 'avni.mittal2002@gmail.com':         ##check if the information of QRcode mathces
            # (p1,p2,p3,p4) = barcode.polygon                 ##get four points from image
            # (x, y, w, h) = barcode.rect
            print("Before obstacle")
            sensor_front_left = obstacle(31,29)                     ##get distance from two front ultrasonic sensors
            sensor_front_right = obstacle(40,37)
            print("sensorRight Distance: {}  sensorLeft Distance:{}".format(sensor_front_right, sensor_front_left))
            
            avgDistance = (sensor_left_front+sensor_right_front)/2

            flag=0
            if avgDistance < 15:      #Check whether the distance is within 15 cm range
                count=count+1
                stop()
                time.sleep(1)
                back()
                time.sleep(1.5)
                if (count%3 ==1) & (flag==0):
                    right()
                    flag=1
                else:
                    left()
                    flag=0
                time.sleep(1.5)
                stop()
                time.sleep(1)
            else:
                forward()
                flag=0
                    
        if barcodeData in Item_name:
            if barcodeData not in orders:
                orders.add(barcodeData)

                data=[]
                for i in orders:
                    data.append([i, items[i]])

                df = pd.DataFrame(data, columns=["ItemName", "Price"], index=None)
                df.to_csv("data.csv", index=None)
                scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets',
                        "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]

                credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
                client = gspread.authorize(credentials)

                spreadsheet = client.open('CSV-to-Google-Sheet')

                with open('data.csv', 'r') as file_obj:
                    content = file_obj.read()
                    client.import_csv(spreadsheet.id, data=content)

    if flag == 0:
        misstime +=  1

    if misstime > 10:    
        stop(m11, m12)
        stop(m21, m22)                            


def detect():

    camera = cv2.VideoCapture(-1)                ##initialize camera
    camera.set(cv2.CAP_PROP_FRAME_WIDTH,640)
    camera.set(cv2.CAP_PROP_FRAME_HEIGHT,400)
   
    # items that are bought by the user
    orders = set()
    print("working")
    while True:
        ret, frame = camera.read()              ##read from camera
        if ret == True:
            c = cv2.waitKey(5)
            cv2.imshow('video',frame)   ## commwnt out if don't want to see video
            if c == 27:                         ##press 'esc' to exit program
                break
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            decodeDisplay(gray,orders)                 ##image processing
           
        else:
            break

    camera.release()
    cv2.destroyAllWindows()                   ##finish program and close windows
    GPIO.cleanup()

GPIO.setmode(GPIO.BOARD)

GPIO.setup(40,GPIO.OUT)    ##right ultrasonic sensor
GPIO.setup(37,GPIO.IN)

GPIO.setup(31,GPIO.OUT)   ##left ultrasonic sensor
GPIO.setup(29,GPIO.IN)

GPIO.setup(35,GPIO.OUT)   ##lower left ultrasonic sensor
GPIO.setup(33,GPIO.IN)

GPIO.setup(36,GPIO.OUT)   ##lower right ultrasonic sensor
GPIO.setup(38,GPIO.IN)

# 12,13 --> speed control
# 16,15 -> motor left-> 12 en
# 18,22 -> motor left-> 32 en
GPIO.setup(12,GPIO.OUT)   ##12-16, motor on the left
GPIO.setup(32,GPIO.OUT)   ##13-18, motor on the right

GPIO.setup(16,GPIO.OUT) # in1
GPIO.setup(15,GPIO.OUT) # in2

GPIO.setup(18,GPIO.OUT) #in3
GPIO.setup(22,GPIO.OUT) #in4

# intializing parameters
GPIO.output(16, GPIO.LOW)  
GPIO.output(15, GPIO.LOW)  
GPIO.output(18, GPIO.LOW)  
GPIO.output(22, GPIO.LOW)  

motor1_speed = GPIO.PWM(12, 1000)   #en1
motor2_speed = GPIO.PWM(32, 1000)   #en2
motor1_speed.start(100)
motor2_speed.start(100)
print("Setup ok")
detect()