Пример #1
0
class Main:
    def __init__(self):
        print ("start main")
        self.green_led = Led(GREEN)
        self.yellow_led = Led(YELLOW)
        self.red_led = Led(RED)

    def run(self):
        if 1 < 2:
            self.red_led.blink()

    def blink(self, led):
        led.blink()
Пример #2
0
 def __init__(self):
     self.PWM = Motor()
     self.servo = Servo()
     self.led = Led()
     self.ultrasonic = Ultrasonic()
     self.buzzer = Buzzer()
     self.adc = Adc()
     self.light = Light()
     self.infrared = Line_Tracking()
     self.tcp_Flag = True
     self.sonic = False
     self.Light = False
     self.Mode = 'one'
     self.endChar = '\n'
     self.intervalChar = '#'
Пример #3
0
    def __init__(self, gpio, pin, ledPin):

        # initialize class variables
        self.gpio = gpio
        self.pir = pin

        self.led = Led.Led(gpio, ledPin)
        self.led.setup()
 def __init__(self):
     self.tcp_flag = False
     self.led = Led()
     self.adc = ADS7830()
     self.servo = Servo()
     self.buzzer = Buzzer()
     self.control = Control()
     self.sonic = Ultrasonic()
     self.control.Thread_conditiona.start()
Пример #5
0
 def __init__(self):
     self.headUpDownAngle = 90
     self.headLeftRightAngle = 90
     self.PWM = Motor()
     self.servo = Servo()
     self.horn = Buzzer()
     self.speed = 1000
     # corrected servo positions
     # adjust these to suit your car
     # so head is front and centre at start
     self.headLRcorrect = -3
     self.headUDcorrect = 4
     self.reset_head()
     self.selector = DefaultSelector()
     # set true for mecanum wheels
     self.mecanum = False
     self.useLights = True
     self.led = Led()
     self.mouse = evdev.InputDevice('/dev/input/event1')
     self.keybd = evdev.InputDevice('/dev/input/event0')
     self.readingKeys = False
     self.led.colorWipe(self.led.strip, Color(0,0,0),0)
     self.brake = False
     self.reverse = False
     self.indicating = False
     self.leftTurn = False
     self.rightTurn = False
     self.moving = False
     self.indi_time = datetime.now()
     self.indi_off = True
     self.brake_time = datetime.now()
     self.brake_off = True
     atexit.register(self.keybd.ungrab)  # Don't forget to ungrab the keyboard on exit!
     atexit.register(self.mouse.ungrab)
     self.keybd.grab()  # Grab, i.e. prevent the keyboard from emitting original events.#
     self.mouse.grab()
     # This works because InputDevice has a `fileno()` method.
     self.selector.register(self.mouse, EVENT_READ)
     self.selector.register(self.keybd, EVENT_READ)
Пример #6
0
    def __init__(self):
        rospy.init_node('IO_Interface', anonymous=False)
        # pub = rospy.Publisher('IO_Interface/', String, queue_size=10)

        #create motors
        self.motor_1 = Motors.Motor(motorID='t1', pin = 1, pwm_output = 0)
        self.motor_2 = Motors.Motor(motorID='t2', pin = 2, pwm_output = 0)
        self.motor_3 = Motors.Motor(motorID='t3', pin = 3, pwm_output = 0)
        self.motor_4 = Motors.Motor(motorID='t4', pin = 4, pwm_output = 0)

        #create inu sensors
        self.mpu = IMU.Inertia_Measurement_Unit('mpu')
        self.lsm = IMU.Inertia_Measurement_Unit('lsm')
        
        #create led output
        self.led = Led.Navio2_LED()
Пример #7
0
class Server:
    def __init__(self):
        self.PWM = Motor()
        self.servo = Servo()
        self.led = Led()
        self.ultrasonic = Ultrasonic()
        self.buzzer = Buzzer()
        self.adc = Adc()
        self.light = Light()
        self.infrared = Line_Tracking()
        self.tcp_Flag = True
        self.sonic = False
        self.Light = False
        self.Mode = 'one'
        self.endChar = '\n'
        self.intervalChar = '#'

    def get_interface_ip(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(
            fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
                                                        b'wlan0'[:15]))[20:24])

    def StartTcpServer(self):
        HOST = str(self.get_interface_ip())
        self.server_socket1 = socket.socket()
        self.server_socket1.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT,
                                       1)
        self.server_socket1.bind((HOST, 5000))
        self.server_socket1.listen(1)
        self.server_socket = socket.socket()
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT,
                                      1)
        self.server_socket.bind((HOST, 8000))
        self.server_socket.listen(1)
        print('Server address: ' + HOST)

    def StopTcpServer(self):
        try:
            self.connection.close()
            self.connection1.close()
        except Exception as e:
            print('\n' + "No client connection")

    def Reset(self):
        self.StopTcpServer()
        self.StartTcpServer()
        self.SendVideo = Thread(target=self.sendvideo)
        self.ReadData = Thread(target=self.readdata)
        self.SendVideo.start()
        self.ReadData.start()

    def send(self, data):
        self.connection1.send(data.encode('utf-8'))

    def sendvideo(self):
        try:
            self.connection, self.client_address = self.server_socket.accept()
            self.connection = self.connection.makefile('wb')
        except:
            pass
        self.server_socket.close()
        try:
            with picamera.PiCamera() as camera:
                camera.resolution = (400, 300)  # pi camera resolution
                camera.framerate = 15  # 15 frames/sec
                time.sleep(2)  # give 2 secs for camera to initilize
                start = time.time()
                stream = io.BytesIO()
                # send jpeg format video stream
                print("Start transmit ... ")
                for foo in camera.capture_continuous(stream,
                                                     'jpeg',
                                                     use_video_port=True):
                    try:
                        self.connection.flush()
                        stream.seek(0)
                        b = stream.read()
                        length = len(b)
                        if length > 5120000:
                            continue
                        lengthBin = struct.pack('L', length)
                        self.connection.write(lengthBin)
                        self.connection.write(b)
                        stream.seek(0)
                        stream.truncate()
                    except Exception as e:
                        print(e)
                        print("End transmit ... ")
                        break
        except:
            #print "Camera unintall"
            pass

    def stopMode(self):
        try:
            stop_thread(self.infraredRun)
            self.PWM.setMotorModel(0, 0, 0, 0)
        except:
            pass
        try:
            stop_thread(self.lightRun)
            self.PWM.setMotorModel(0, 0, 0, 0)
        except:
            pass
        try:
            stop_thread(self.ultrasonicRun)
            self.PWM.setMotorModel(0, 0, 0, 0)
            self.servo.setServoPwm('0', 90)
            self.servo.setServoPwm('1', 90)
        except:
            pass

    def readdata(self):
        try:
            try:
                self.connection1, self.client_address1 = self.server_socket1.accept(
                )
                print("Client connection successful ! ---- SURE?")
            except:
                print("Client connect failed")
            restCmd = ""
            self.server_socket1.close()
            while True:
                try:
                    AllData = restCmd + self.connection1.recv(1024).decode(
                        'utf-8')
                except:
                    if self.tcp_Flag:
                        self.Reset()
                    break
                print('AllData is', AllData)
                if len(AllData) < 5:
                    restCmd = AllData
                    if restCmd == '' and self.tcp_Flag:
                        self.Reset()
                        break
                restCmd = ""
                if AllData == '':
                    break
                else:
                    cmdArray = AllData.split("\n")
                    if (cmdArray[-1] != ""):
                        restCmd = cmdArray[-1]
                        cmdArray = cmdArray[:-1]

                for oneCmd in cmdArray:
                    data = oneCmd.split("#")
                    if data == None:
                        continue
                    elif cmd.CMD_MODE in data:
                        if data[1] == 'one':
                            self.stopMode()
                            self.Mode = 'one'
                        elif data[1] == 'two':
                            self.stopMode()
                            self.Mode = 'two'
                            self.lightRun = Thread(target=self.light.run)
                            self.lightRun.start()
                        elif data[1] == 'three':
                            self.stopMode()
                            self.Mode = 'three'
                            self.ultrasonicRun = threading.Thread(
                                target=self.ultrasonic.run)
                            self.ultrasonicRun.start()
                        elif data[1] == 'four':
                            self.stopMode()
                            self.Mode = 'four'
                            self.infraredRun = threading.Thread(
                                target=self.infrared.run)
                            self.infraredRun.start()

                    elif (cmd.CMD_MOTOR in data) and self.Mode == 'one':
                        print('Data is', data)
                        try:
                            data1 = int(data[1])
                            data2 = int(data[2])
                            data3 = int(data[3])
                            data4 = int(data[4])
                            if data1 == None or data2 == None or data2 == None or data3 == None:
                                continue
                            self.PWM.setMotorModel(data1, data2, data3, data4)
                        except:
                            pass
                    elif cmd.CMD_SERVO in data:
                        try:
                            data1 = data[1]
                            data2 = int(data[2])
                            if data1 == None or data2 == None:
                                continue
                            self.servo.setServoPwm(data1, data2)
                        except:
                            pass

                    elif cmd.CMD_LED in data:
                        try:
                            data1 = int(data[1])
                            data2 = int(data[2])
                            data3 = int(data[3])
                            data4 = int(data[4])
                            if data1 == None or data2 == None or data2 == None or data3 == None:
                                continue
                            self.led.ledIndex(data1, data2, data3, data4)
                        except:
                            pass
                    elif cmd.CMD_LED_MOD in data:
                        self.LedMoD = data[1]
                        if self.LedMoD == '0':
                            try:
                                stop_thread(Led_Mode)
                            except:
                                pass
                            self.led.ledMode(self.LedMoD)
                            time.sleep(0.1)
                            self.led.ledMode(self.LedMoD)
                        else:
                            try:
                                stop_thread(Led_Mode)
                            except:
                                pass
                            time.sleep(0.1)
                            Led_Mode = Thread(target=self.led.ledMode,
                                              args=(data[1], ))
                            Led_Mode.start()
                    elif cmd.CMD_SONIC in data:
                        if data[1] == '1':
                            self.sonic = True
                            self.ultrasonicTimer = threading.Timer(
                                0.5, self.sendUltrasonic)
                            self.ultrasonicTimer.start()
                        else:
                            self.sonic = False
                    elif cmd.CMD_BUZZER in data:
                        try:
                            self.buzzer.run(data[1])
                        except:
                            pass
                    elif cmd.CMD_LIGHT in data:
                        if data[1] == '1':
                            self.Light = True
                            self.lightTimer = threading.Timer(
                                0.3, self.sendLight)
                            self.lightTimer.start()
                        else:
                            self.Light = False
                    elif cmd.CMD_POWER in data:
                        ADC_Power = self.adc.recvADC(2) * 3
                        try:
                            self.send(cmd.CMD_POWER + '#' + str(ADC_Power) +
                                      '\n')
                        except:
                            pass
        except Exception as e:
            print(e)
        self.StopTcpServer()

    def sendUltrasonic(self):
        if self.sonic == True:
            ADC_Ultrasonic = self.ultrasonic.get_distance()
            if ADC_Ultrasonic == self.ultrasonic.get_distance():
                try:
                    self.send(cmd.CMD_SONIC + "#" + str(ADC_Ultrasonic) + '\n')
                except:
                    self.sonic = False
            self.ultrasonicTimer = threading.Timer(0.13, self.sendUltrasonic)
            self.ultrasonicTimer.start()

    def sendLight(self):
        if self.Light == True:
            ADC_Light1 = self.adc.recvADC(0)
            ADC_Light2 = self.adc.recvADC(1)
            try:
                self.send(cmd.CMD_LIGHT + '#' + str(ADC_Light1) + '#' +
                          str(ADC_Light2) + '\n')
            except:
                self.Light = False
            self.lightTimer = threading.Timer(0.17, self.sendLight)
            self.lightTimer.start()

    def Power(self):
        while True:
            ADC_Power = self.adc.recvADC(2) * 3
            time.sleep(3)
            if ADC_Power < 6.8:
                for i in range(4):
                    self.buzzer.run('1')
                    time.sleep(0.1)
                    self.buzzer.run('0')
                    time.sleep(0.1)
            elif ADC_Power < 7:
                for i in range(2):
                    self.buzzer.run('1')
                    time.sleep(0.1)
                    self.buzzer.run('0')
                    time.sleep(0.1)
            else:
                self.buzzer.run('0')
Пример #8
0
import time
from Led import *
led=Led()

try:
    led.ledIndex(0x01,255,0,0)      #Red
    led.ledIndex(0x02,255,125,0)    #orange
    led.ledIndex(0x04,255,255,0)    #yellow
    led.ledIndex(0x08,0,255,0)      #green
    led.ledIndex(0x10,0,255,255)    #cyan-blue
    led.ledIndex(0x20,0,0,255)      #blue
    led.ledIndex(0x40,128,0,128)    #purple
    led.ledIndex(0x80,255,255,255)  #white'''
    print ("The LED has been lit, the color is red orange yellow green cyan-blue blue white")
    time.sleep(10)               #wait 3s
    led.colorWipe(led.strip, Color(0,0,0))  #turn off the light
    print ("\nEnd of program")
except KeyboardInterrupt:
    led.colorWipe(led.strip, Color(0,0,0))  #turn off the light
    print ("\nEnd of program")
Пример #9
0
from datetime import datetime
import pytz
import time #For time.sleep()

#Log Data
from logData import logData

 #24Hours Format
flag =1
while True: 
	location_india=pytz.timezone('Asia/Kolkata')
	time_india=datetime.now(location_india)
	timestamp='{:%H:%M}'.format(time_india)
	
	if timestamp>=("6:00") && flag=0:
		led_on=Led.LedOn()
		air_on=AirPump.AirPumpOn()
		flag=1 #LED ON
		#logData()
	if timestamp==("22:00"):
		led_off=Led.LedOff()
		air_off=AirPumpOff()
		flag=0
		
	#Put if(s) and check time for LED and AirPump
	#Add a while loop to hit the sensors and get value
	#Call the Display function from Display_oled with time, to display this data. 5 sec each. 20 Seconds gap between every data update
	#1
	co2ppm=mh_z14.co2()
	display("CO2 ppm is",co2ppm,5)
	print("CO2 ppm is",co2ppm)
Пример #10
0
import CmdMessenger
import CmdManager
import Motors
import Gripper
import Led

import SpeedControl

if __name__ == '__main__':

    cMes = CmdMessenger.CmdMessenger()
    cMes.start()

    cMan = CmdManager.CmdManager(cMes)

    cMotor = Motors.Motors(cMes, 5)
    cMotor.start()

    cSpeed = SpeedControl.SpeedControl(cMotor)

    gripper = Gripper.Gripper(cMes)
    led = Led.Led(cMes)
Пример #11
0
    def Run_Cart4(self):

        #------------------------------------------Ultrasonic sensor and Servo Motor Class
        self.Ultrasonic = Ultrasonic()

        self.LED = Led()

        self.Buzzer = Buzzer()

        self.Junction = 0

        #--------------------------------------------------------------------------------------
        while True:

            self.Movement_Type = 0

            Distance = self.Ultrasonic.get_distance()

            IR_Left = GPIO.input(IR01)

            IR_Mid = GPIO.input(IR02)

            IR_Right = GPIO.input(IR03)

            if (Distance > 15.0):

                if ((IR_Left == 0) and (IR_Mid == 1) and (IR_Right == 0)):
                    if (self.Moved_Reverse_New != self.Moved_Reverse_Old):
                        self.Movement_Type = 11  #Move Reverse
                    else:
                        self.Movement_Type = 5  #Move Forward
                    self.Junction = 0  #Clear the Junction Variable

                elif ((IR_Left == 1) and (IR_Mid == 0) and (IR_Right == 0)):
                    self.Movement_Type = 3  #Take Slight Left

                elif ((IR_Left == 1) and (IR_Mid == 1) and (IR_Right == 0)):
                    self.Movement_Type = 3  #Take Slight Left

                elif ((IR_Left == 0) and (IR_Mid == 0) and (IR_Right == 1)):
                    self.Movement_Type = 7  #Take Slight Right

                elif ((IR_Left == 0) and (IR_Mid == 1) and (IR_Right == 1)):
                    self.Movement_Type = 7  #Take Slight Right

                elif ((IR_Mid == 1) and (IR_Left == 1) and (IR_Right == 1)):
                    if (self.Junction == 0):
                        self.Movement_Type = self.Mov_According_To_Specified_position(
                        )
                    self.Junction = 1

                else:
                    pass

            else:
                self.Movement_Type = 0  #Stop Movement
                self.LED.ledIndex(0x20, 255, 125, 0)  #Orange
                self.LED.ledIndex(0x40, 255, 125, 0)  #Orange
                time.sleep(1)
                self.LED.ledIndex(0x60, 0, 0, 0)

            #Actuate the motors to move cart to the specific Coordinate
            self.Move_Cart(self.Movement_Type)

            if (self.Is_Intermediate_DestinTion_Reached()):
                break
#Number of readings to take. If set to 0 then an infinite number of reeds will be taken
readsToTake = 0
#Delay between reads (seconds)
delay = 60

#get time spamp
timeStamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y%m%d%H%M%S')

#open log file for writing
#logFile = open("templog-"+timeStamp, "w")
logFileName = "templog-continuous"
#Live Log Path is the ip address and port where the temp_WebServer.py is running.
#Live Log Path is in the format http://127.0.0.1:8000/tempMonitor?"
liveLogPath = "http://server.host.com:8080/tempMonitor?"

redLed = Led(23)
redLed.ledOff()
#####***END CONSTANTS SECTION***#####

"""
Function used to load webpage that records data.
Uses liveLogPath and appends data read in from the sensors.
"""
def writeLiveData(liveLogPath, sensor1, sensor2):
    data = "sensor1=" + sensor1 + "&sensor2=" + sensor2
    try:
        urllib2.urlopen(liveLogPath + data)
    except Exception:
        return

#####***BEGIN PROGRAM***#####
Пример #13
0
 def __init__(self):
     self.led = Led.Led()
     self.player = Player2.Player()
     self.btManager = BluetoothManager.BluetoothManager(
         self.onConnect, self.onDisconnect, self.player.on_property_changed)
     self.apds = Apds.Apds()
Пример #14
0
def test_Led():
    led = Led()
    try:
        #Red wipe
        print("\nRed wipe")
        led.colorWipe(led.strip, Color(255, 0, 0))
        time.sleep(1)

        #Green wipe
        print("\nGreen wipe")
        led.colorWipe(led.strip, Color(0, 255, 0))
        time.sleep(1)

        #Blue wipe
        print("\nBlue wipe")
        led.colorWipe(led.strip, Color(0, 0, 255))
        time.sleep(1)

        #White wipe
        print("\nWhite wipe")
        led.colorWipe(led.strip, Color(255, 255, 255))
        time.sleep(1)

        led.colorWipe(led.strip, Color(0, 0, 0))  #turn off the light
        print("\nEnd of program")
    except KeyboardInterrupt:
        led.colorWipe(led.strip, Color(0, 0, 0))  #turn off the light
        print("\nEnd of program")
Пример #15
0
 def __init__(self):
     self.led = Led()
Пример #16
0
def led():
    Led.LedLamp(26).flikker_bg(5)
    return redirect('/')
Пример #17
0
#Una vez se haya colocado el objeto en el centro, se pulsara el boton para iniciar el escaneo.

def makeScan(code):
#Aqui ira la logica del movimiento del motor 1/8 de la vuelta y tomara una foto.
    
    ThunderBorg_moveStepper.MoveStep(SPR / config.numSteps)  #Llama a la libreria de la shield con el controlador de motor y le pasa el parametro de cuanto se tiene que mover.
    global actualStep                                       #Declara una variable global que es el paso actual en el que va.
    actualStep += 1                                         #Suma uno a la variable del paso acutal en el que va.
    print(actualStep)                                       #Imprime por terminal el paso actual en el que va.
    takePicture.takePicture(code,config.loc,actualStep)     #Toma una foto con la PiCamera, pasandole el codigo para poner nombre a la imagen, la localizacion de guardado y el paso actual.

print("Starting...")    #Al inicio de todo imprime por terminal que la maquina se esta inicializando...

#Aqui inicia el proceso del scanner para detectar el codigo QR
Led.setup()
while True:
    if state == 'QR':
        
        #Una vez se detecte el QR se encendera una luz para avisar que fue registrado el QR
        # led 1 on, led 2 off
        Led.ledOn(1)
        Led.ledOff(2)
        Led.ledOff(3)
        
        print("Waiting for QR code")

        # limpia el buffer de input
        tcflush(sys.stdin, TCIFLUSH)

        #ESTO HAY QUE CAMBIARLO PARA QUE NO SEA UN NUMERO, SEA UNA URL.
Пример #18
0
 def __init__(self):
     print("start main")
     self.green_led = Led(GREEN)
     self.yellow_led = Led(YELLOW)
     self.red_led = Led(RED)
     self.detected = False
Пример #19
0
class FaceLock:
    def __init__(self):
        print("start main")
        self.green_led = Led(GREEN)
        self.yellow_led = Led(YELLOW)
        self.red_led = Led(RED)
        self.detected = False

    def run(self):
        if self.detect() == True:
            self.unlock()
            self.green_led.on()
        else:
            self.lock()
            self.red_led.on()

    def detect(self):
        return False

    def failure(self):
        self.red_led.blink()

    def pending(self):
        self.yellow_led.on()

    def complete(self):
        self.yellow_led.off()

    def access(self):
        self.green_led.on()

    def lock(self):
        print("Locked")

    def unlock(self):
        print("Unlocked")
Пример #20
0
 def __init__(self):
     print ("start main")
     self.green_led = Led(GREEN)
     self.yellow_led = Led(YELLOW)
     self.red_led = Led(RED)
     self.detected = False
Пример #21
0
class FaceLock:
    def __init__(self):
        print ("start main")
        self.green_led = Led(GREEN)
        self.yellow_led = Led(YELLOW)
        self.red_led = Led(RED)
        self.detected = False

    def run(self):
        if self.detect() == True:
            self.unlock()
            self.green_led.on()
        else:
            self.lock()
            self.red_led.on()

    def detect(self):
        return False

    def failure(self):
        self.red_led.blink()

    def pending(self):
        self.yellow_led.on()

    def complete(self):
        self.yellow_led.off()

    def access(self):
        self.green_led.on()

    def lock(self):
        print("Locked")

    def unlock(self):
        print("Unlocked")
Пример #22
0
class LED:
    def __init__(self):
        self.led = Led()

    def LED_on(self, led_ID, Red_Intensity, Blue_Intensity, Green_intensity):
        """
        Parameters
        ----------
        led_ID: This is the ID of leds. It can be from 1 to 8
        Red_Intensity: 1 to 255, from dimmest to brightest
        Blue_Intensity: 1 to 255, from dimmest to brightest
        Green_intensity: 1 to 255, from dimmest to brightest
        -------
        """
        try:
            self.led.ledIndex(led_ID, Red_Intensity, Blue_Intensity, Green_intensity)
        except KeyboardInterrupt:
            self.led.colorWipe(led.strip, Color(0, 0, 0))  ##This is to turn all leds off/

    def test_Led(self):
        """
        This is to test all leds and do several different leds.
        """
        try:
            self.led.ledIndex(0x01, 255, 0, 0)  # Red
            self.led.ledIndex(0x02, 255, 125, 0)  # orange
            self.led.ledIndex(0x04, 255, 255, 0)  # yellow
            self.led.ledIndex(0x08, 0, 255, 0)  # green
            self.led.ledIndex(0x10, 0, 255, 255)  # cyan-blue
            self.led.ledIndex(0x20, 0, 0, 255)  # blue
            self.led.ledIndex(0x40, 128, 0, 128)  # purple
            self.led.ledIndex(0x80, 255, 255, 255)  # white'''
            print("The LED has been lit, the color is red orange yellow green cyan-blue blue white")
            time.sleep(3)  # wait 3s
            self.led.colorWipe("", Color(0, 0, 0))  # turn off the light
            print("\nEnd of program")
        except KeyboardInterrupt:
            self.led.colorWipe("", Color(0, 0, 0))  # turn off the light
            print("\nEnd of program")

    def leds_off(self):
        self.led.colorWipe("", Color(0, 0, 0))  ##This is to turn all leds off/
Пример #23
0
	def __init__(self):
		self.lcd = Lcd.__init__()
		self.green = Led.__init__()
		self.red = Led.__init__()
Пример #24
0
class localKeyboard:
    def __init__(self):
        self.headUpDownAngle = 90
        self.headLeftRightAngle = 90
        self.PWM = Motor()
        self.servo = Servo()
        self.horn = Buzzer()
        self.speed = 1000
        # corrected servo positions
        # adjust these to suit your car
        # so head is front and centre at start
        self.headLRcorrect = -3
        self.headUDcorrect = 4
        self.reset_head()
        self.selector = DefaultSelector()
        # set true for mecanum wheels
        self.mecanum = False
        self.useLights = True
        self.led = Led()
        self.mouse = evdev.InputDevice('/dev/input/event1')
        self.keybd = evdev.InputDevice('/dev/input/event0')
        self.readingKeys = False
        self.led.colorWipe(self.led.strip, Color(0,0,0),0)
        self.brake = False
        self.reverse = False
        self.indicating = False
        self.leftTurn = False
        self.rightTurn = False
        self.moving = False
        self.indi_time = datetime.now()
        self.indi_off = True
        self.brake_time = datetime.now()
        self.brake_off = True
        atexit.register(self.keybd.ungrab)  # Don't forget to ungrab the keyboard on exit!
        atexit.register(self.mouse.ungrab)
        self.keybd.grab()  # Grab, i.e. prevent the keyboard from emitting original events.#
        self.mouse.grab()
        # This works because InputDevice has a `fileno()` method.
        self.selector.register(self.mouse, EVENT_READ)
        self.selector.register(self.keybd, EVENT_READ)

    def read_keys_loop(self):
        self.readingKeys = True
        while self.readingKeys:
            self.read_keys()
            # only manage lights after a key press so brake lights, if on,
            # will stay on until next key event
            if self.useLights: self.manage_lights()

    def manage_lights(self):
        # indicators
        if not self.indicating and not self.reverse:
            self.led.colorWipe(self.led.strip, Color(0,0,0),0)
        else:
            if self.indicating:
                if (datetime.now() - self.indi_time).microseconds > 250000:
                    self.indi_off = not self.indi_off
                    self.indi_time = datetime.now()
                if self.indi_off:
                    if self.leftTurn:
                        self.led.strip.setPixelColor(2, Color(125,85,0) )
                        self.led.strip.setPixelColor(5, Color(125,85,0) )
                    if self.rightTurn:
                        self.led.strip.setPixelColor(1, Color(125,85,0) )
                        self.led.strip.setPixelColor(6, Color(125,85,0) )
                    self.led.strip.show()
                else:
                    self.led.colorWipe(self.led.strip, Color(0,0,0),0)
            if self.reverse:
                self.led.strip.setPixelColor(1, Color(255,255,255) )
                self.led.strip.setPixelColor(2, Color(255,255,255) )
                self.led.strip.show()

        if self.brake:
            self.brake = False
            if self.brake_off:
                self.brake_off = False
                self.brake_time = datetime.now()
                self.led.strip.setPixelColor(1, Color(255,0,0) )
                self.led.strip.setPixelColor(2, Color(255,0,0) )
                self.led.strip.show()
                
        if not self.brake_off:
            #this is a minimum time on, they stay on until next key press
            if (datetime.now() - self.brake_time).microseconds > 250000:
                self.led.colorWipe(self.led.strip, Color(0,0,0),0)
                self.brake = False
                self.brake_off = True

    def read_keys(self):
        for key, mask in self.selector.select():
            device =key.fileobj
            for event in device.read():
                if event.type == evdev.ecodes.EV_KEY:
                    # print("key press")
                    # print(evdev.ecodes.bytype[evdev.ecodes.EV_KEY][event.code])
                    if event.value == 1 or event.value == 2: 
                        self.key_press(event, self.keybd)
                    elif event.value == 0:
                        self.drive_stop()
                elif event.type == evdev.ecodes.EV_REL:
                    if event.code == evdev.ecodes.REL_X:
                        if event.value < 0:
                            self.head_left()
                        else:
                            self.head_right()
                    if event.code == evdev.ecodes.REL_Y:
                        if event.value < 0:
                            self.head_down()
                        else:
                            self.head_up()
                else:
                    pass
                    #print(event)

    def key_press(self, ev, kbd):
            if (ev.value == 1 or ev.value == 2): # 1 PRESS or 2 HOLD
                # EVENTS CALLED ON PRESS AND ON HOLD
                # HEAD POSITION
                if ev.code == evdev.ecodes.KEY_Z: self.head_down()
                elif ev.code == evdev.ecodes.KEY_A: self.head_left()
                elif ev.code == evdev.ecodes.KEY_S: self.head_right()
                elif ev.code == evdev.ecodes.KEY_W: self.head_up()
                # HORN
                elif ev.code == evdev.ecodes.KEY_T: self.toot()
                # not interested in any other held keys
                elif ev.value == 2: pass

                #EVENTS THAT SHOULD ONLY BE CALLED ON PRESS AND NOT HOLD
                # SPEED SETTING
                elif ev.code == evdev.ecodes.KEY_1: self.speed = 1000
                elif ev.code == evdev.ecodes.KEY_2: self.speed = 1200
                elif ev.code == evdev.ecodes.KEY_3: self.speed = 1400
                elif ev.code == evdev.ecodes.KEY_4: self.speed = 1700
                elif ev.code == evdev.ecodes.KEY_5: self.speed = 2000
                elif ev.code == evdev.ecodes.KEY_6: self.speed = 2400
                elif ev.code == evdev.ecodes.KEY_7: self.speed = 2800
                elif ev.code == evdev.ecodes.KEY_8: self.speed = 3200
                elif ev.code == evdev.ecodes.KEY_9: self.speed = 3600
                elif ev.code == evdev.ecodes.KEY_0: self.speed = 4000

                # DRIVE FUNCTIONS
                elif ev.code == evdev.ecodes.KEY_UP: self.drive_forward()
                elif ev.code == evdev.ecodes.KEY_DOWN: self.drive_backward()
                elif ev.code == evdev.ecodes.KEY_LEFT: self.turn_left()
                elif ev.code == evdev.ecodes.KEY_RIGHT: self.turn_right()
                elif ev.code == evdev.ecodes.KEY_COMMA: self.crab_left()
                elif ev.code == evdev.ecodes.KEY_DOT: self.crab_right()
                elif ev.code == evdev.ecodes.KEY_SEMICOLON: self.diag_right()
                elif ev.code == evdev.ecodes.KEY_K: self.diag_left()
                elif ev.code == evdev.ecodes.KEY_SLASH: self.diag_rev_right()
                elif ev.code == evdev.ecodes.KEY_M: self.diag_rev_left()
                elif ev.code == evdev.ecodes.KEY_U: self.curve_right()
                elif ev.code == evdev.ecodes.KEY_Y: self.curve_left()
                elif ev.code == evdev.ecodes.KEY_J: self.curve_rev_right()
                elif ev.code == evdev.ecodes.KEY_H: self.curve_rev_left()

                # USE OR DONT USE LIGHTS
                elif ev.code == evdev.ecodes.KEY_L:
                    self.useLights = not self.useLights
                    if not self.useLights: self.led.colorWipe(self.led.strip, Color(0,0,0),0)

                # RESET TO START STATE
                elif ev.code == evdev.ecodes.KEY_HOME: #RESET TO START STATE
                    self.drive_stop()
                    self.servo.setServoPwm('0', int(self.headLeftRightAngle))
                    self.servo.setServoPwm('1', int(self.headUpDownAngle))
                    self.speed = 1000
                    self.led.colorWipe(self.led.strip, Color(0,0,0),0)

                # PROG FUNCTIONS
                elif ev.code == evdev.ecodes.KEY_LEFTMETA: self.close()
                elif ev.code == evdev.ecodes.KEY_END: self.shutdown_pi()
                elif ev.code == evdev.ecodes.KEY_SYSRQ: self.reboot_pi()

                else:
                    print("UNUSED KEY CODE")
                    print(evdev.ecodes.bytype[evdev.ecodes.EV_KEY][ev.code])        
            if ev.value == 0:
                self.drive_stop()
            # flush backed up key presses
            while kbd.read_one() is not None:
                if ev.value == 0 :
                    self.drive_stop()


    def close(self):
        self.readingKeys = False
        self.selector.unregister(self.mouse)
        self.selector.unregister(self.keybd)
        self.led.colorWipe(self.led.strip, Color(0,0,0),0)
        # kbd should be ungrabbed by atexit
        # but belt and braces
        try:
            self.keybd.ungrab
            self.mouse.ungrab
        except:
            pass
        sys.exit()

    def shutdown_pi(self):
        self.readingKeys = False
        self.toot()
        time.sleep(0.2)
        self.toot()
        call("sudo nohup shutdown -h now", shell=True)

    def reboot_pi(self):
        self.readingKeys = False
        self.toot()
        call("sudo nohup reboot", shell=True)

    def toot(self):
        self.horn.run('1')
        time.sleep(0.2)
        self.horn.run('0')

    def drive_forward(self):
        self.moving = True
        PWM.setMotorModel(self.speed, self.speed, self.speed, self.speed)

    def turn_left(self):
        self.moving = True
        self.indicating = True
        self.leftTurn = True
        self.rightTurn = False
        PWM.setMotorModel(-self.speed, -self.speed, self.speed, self.speed)

    def drive_backward(self):
        self.moving = True
        self.reverse = True
        PWM.setMotorModel(-self.speed, -self.speed, -self.speed, -self.speed)

    def turn_right(self):
        self.moving = True
        self.indicating = True
        self.leftTurn = False
        self.rightTurn = True
        PWM.setMotorModel(self.speed, self.speed, -self.speed, -self.speed)

    def curve_left(self, biasPcent=20):
        self.moving = True
        PWM.setMotorModel(int(self.speed * (100 - biasPcent) / 100), int(self.speed * (100 - biasPcent) / 100),
                          int(self.speed * (100 + biasPcent) / 100), int(self.speed * (100 + biasPcent) / 100))

    def curve_right(self, biasPcent=20):
        self.moving = True
        PWM.setMotorModel(int(self.speed * (100 + biasPcent) / 100), int(self.speed * (100 + biasPcent) / 100),
                          int(self.speed * (100 - biasPcent) / 100), int(self.speed * (100 - biasPcent) / 100))

    def curve_rev_left(self, biasPcent=20):
        self.moving = True
        self.reverse = True
        PWM.setMotorModel(-int(self.speed * (100 - biasPcent) / 100), -int(self.speed * (100 - biasPcent) / 100),
                          -int(self.speed * (100 + biasPcent) / 100), -int(self.speed * (100 + biasPcent) / 100))

    def curve_rev_right(self, biasPcent=20):
        self.moving = True
        self.reverse = True
        PWM.setMotorModel(-int(self.speed * (100 + biasPcent) / 100), -int(self.speed * (100 + biasPcent) / 100),
                          -int(self.speed * (100 - biasPcent) / 100), -int(self.speed * (100 - biasPcent) / 100))

    def crab_left(self): #REQUIRES MECANUM WHEELS
        if self.mecanum:
            self.moving = True
            self.indicating = True
            self.leftTurn = True
            self.rightTurn = False
            PWM.setMotorModel(-self.speed, self.speed, self.speed, -self.speed)

    def crab_right(self): #REQUIRES MECANUM WHEELS
        if self.mecanum:
            self.moving = True
            self.indicating = True
            self.leftTurn = False
            self.rightTurn = True
            PWM.setMotorModel(self.speed, -self.speed, -self.speed, self.speed)

    def diag_right(self): #REQUIRES MECANUM WHEELS
        if self.mecanum: 
            self.moving = True
            PWM.setMotorModel(self.speed, 0, 0, self.speed)

    def diag_left(self): #REQUIRES MECANUM WHEELS
        if self.mecanum: 
            self.moving = True
            PWM.setMotorModel(0, self.speed, self.speed, 0)

    def diag_rev_left(self): #REQUIRES MECANUM WHEELS
        if self.mecanum: 
            self.moving = True
            self.reverse = True
            PWM.setMotorModel(-self.speed, 0, 0, -self.speed)

    def diag_rev_right(self): #REQUIRES MECANUM WHEELS
        if self.mecanum: 
            self.moving = True
            self.reverse = True
            PWM.setMotorModel(0, -self.speed, -self.speed, 0)

    def drive_stop(self):
        if self.moving:
            self.brake = True
            self.moving = False
            PWM.setMotorModel(0, 0, 0, 0)
            self.reverse = False
            self.indicating = False
            self.leftTurn = False
            self.rightTurn = False

    def head_up(self):
        self.headUpDownAngle += 1
        if self.headUpDownAngle > 180 + self.headUDcorrect:
            self.headUpDownAngle = 180 + self.headUDcorrect
        self.servo.setServoPwm('1', self.headUpDownAngle)
        # print("Up/down " + str(self.headUpDownAngle))

    def head_down(self):
        self.headUpDownAngle -= 1
        if self.headUpDownAngle < 80 + self.headUDcorrect:
            self.headUpDownAngle = 80 + self.headUDcorrect
        self.servo.setServoPwm('1', self.headUpDownAngle)
        # print("Up/down " + str(self.headUpDownAngle))

    def head_left(self):
        self.headLeftRightAngle -= 1
        if self.headLeftRightAngle < 10 + self.headLRcorrect:
            self.headLeftRightAngle = 10 + self.headLRcorrect
        self.servo.setServoPwm('0', self.headLeftRightAngle)
        # print("Left/Right " + str(self.headLeftRightAngle))

    def head_LRpos(self, angle):
        # print("Move head to " + str(self.headLeftRightAngle))
        self.headLeftRightAngle = angle + self.headLRcorrect
        self.servo.setServoPwm('0', self.headLeftRightAngle)

    def head_right(self):
        self.headLeftRightAngle += 1
        if self.headLeftRightAngle > 170 + self.headLRcorrect:
            self.headLeftRightAngle = 170 + self.headLRcorrect
        self.servo.setServoPwm('0', self.headLeftRightAngle)
        # print("Left/Right " + str(self.headLeftRightAngle))

    def reset_head(self):
        self.headLeftRightAngle = 90 + self.headLRcorrect
        self.headUpDownAngle = 90 + self.headUDcorrect
        self.servo.setServoPwm('0', int(self.headLeftRightAngle))
        self.servo.setServoPwm('1', int(self.headUpDownAngle))
Пример #25
0
test_images = [
    ('01.jpg', [
        1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0,
        1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0
    ]),
    ('02.jpg', [1, 1, 1, 0, 1, 1, 0, 0]),  # is tail 0,0 or 0,0,1?
    ('03.jpg', [0, 1, 1, 1, 0, 1, 1]),
    ('04.jpg', [1, 1, 0, 1, 1, 0, 0, 1])
]

start_time = time.time()
print 'Slow algorithm'
for test_image in test_images:
    image_original = cv2.imread('img_in' + os.sep + test_image[0])
    led = ll.Led(image_original)
    counted_array = led.getCode()
    if cmp(counted_array, test_image[1]) != 0:
        print 'Error in decoding {}:'.format(test_image[0])
        print 'correct:', test_image[1]
        print 'counted:', counted_array
    else:
        print test_image[0] + ' is correct!'
print("--- %s seconds ---" % (time.time() - start_time))

# test fast method
start_time = time.time()
print '\nFast algorithm'
for test_image in test_images:
    img_gray = cv2.imread('img_in' + os.sep + test_image[0], 0)
    counted_array = ll.Led.getCodeFast(img_gray)
Пример #26
0
 def TurnOn(self,color):
     L.send(self.findledVal(),color)
Пример #27
0
class SPUG:
    def Initialize_Values(self):

        #Itial position
        self.x_init = 0
        self.y_init = 0

        #Product Location Positions
        self.x_pro_des = 3  #Test Initialization
        self.y_pro_des = 3  #Test Initialization

        #Intermediate Destination Positions
        self.x_inter_des = 3  #Test Initialization
        self.y_inter_des = 3  #Test Initialization

        #Local Position of the SPUG
        self.l_x = 0
        self.l_y = 0

        #SPUG Starts at Coordinate [0 ,0] facing North
        self.Orientation = "North"

        #SPUG Number
        self.Cart_Number = 4

        #Variable to calculate the Position of SPUG after movement
        self.Moved_Straight_New = 0
        self.Moved_Straight_Old = 0

        self.Moved_Reverse_New = 0
        self.Moved_Reverse_Old = 0

        self.Moved_Left_New = 0
        self.Moved_Left_Old = 0

        self.Moved_Right_New = 0
        self.Moved_Right_Old = 0

        #Total moves made by SPUG
        self.Total_Moves = 0

        #Intermediate Position Reached by SPUG
        self.Inter_Target_Reached = 0

        #Product Location Reached by SPUG
        self.Product_Des_Reached = 0

        #SPUG presesnt at junction
        self.Junction = 0

        #SPUG at [0 ,0] coordinate:
        # 0 - Present at [0,0] coordinate
        # 1 - Not pressent at [0,0] coordinate
        self.IntialJunction = 0

    #Function to set the intermediate coordinates to navigate SPUG
    def Set_intermediate_destnation_position(self, x_destination,
                                             y_destnation):
        self.x_inter_des = x_destination
        self.y_inter_des = y_destnation

        self.Inter_Target_Reached = 0

    #Function to set the Product locations to message the server if the product location is reached
    def Set_product_destnation_position(self, x_destination, y_destnation):
        self.x_pro_des = x_destination
        self.y_pro_des = y_destnation

        self.Product_Des_Reached = 0

    #Function to get the current coordinates of SPUG
    def Get_curent_position(self):
        return self.l_x, self.l_y

    #Function to get if Intermediate position is reached
    def Is_Intermediate_DestinTion_Reached(self):
        return self.Inter_Target_Reached

    #Function to get if Product location is reached
    def Is_Product_DestinTion_Reached(self):
        return self.Product_Des_Reached

    #Function to update the coordinates and get the direction to move
    def Mov_According_To_Specified_position(self):

        #Intial Position Before Movement
        self.x_init = self.l_x
        self.y_init = self.l_y

        #Do not update the coordinates for the first junction
        if (self.IntialJunction != 0):

            Coordinates_Updated = 0

            #Code for updating the co-ordinates
            if (self.Moved_Straight_New != self.Moved_Straight_Old):
                if (self.Orientation == "North"):
                    self.l_x = self.l_x
                    self.l_y = self.l_y + 1

                elif (self.Orientation == "South"):
                    self.l_x = self.l_x
                    self.l_y = self.l_y - 1

                elif (self.Orientation == "East"):
                    self.l_x = self.l_x + 1
                    self.l_y = self.l_y

                elif (self.Orientation == "West"):
                    self.l_x = self.l_x - 1
                    self.l_y = self.l_y

                Coordinates_Updated = 1

            elif (self.Moved_Reverse_New != self.Moved_Reverse_Old):
                if (self.Orientation == "North"):
                    self.l_x = self.l_x
                    self.l_y = self.l_y - 1

                elif (self.Orientation == "South"):
                    self.l_x = self.l_x
                    self.l_y = self.l_y + 1

                elif (self.Orientation == "East"):
                    self.l_x = self.l_x - 1
                    self.l_y = self.l_y

                elif (self.Orientation == "West"):
                    self.l_x = self.l_x + 1
                    self.l_y = self.l_y

                Coordinates_Updated = 1

            elif (self.Moved_Left_New != self.Moved_Left_Old):
                if (self.Orientation == "North"):
                    self.l_x = self.l_x - 1
                    self.l_y = self.l_y
                    self.Orientation = 'West'

                elif (self.Orientation == "South"):
                    self.l_x = self.l_x + 1
                    self.l_y = self.l_y
                    self.Orientation = 'East'

                elif (self.Orientation == "East"):
                    self.l_x = self.l_x
                    self.l_y = self.l_y + 1
                    self.Orientation = 'North'

                elif (self.Orientation == "West"):
                    self.l_x = self.l_x
                    self.l_y = self.l_y - 1
                    self.Orientation = 'South'

                Coordinates_Updated = 1

            elif (self.Moved_Right_New != self.Moved_Right_Old):
                if (self.Orientation == "North"):
                    self.l_x = self.l_x + 1
                    self.l_y = self.l_y
                    self.Orientation = 'East'

                elif (self.Orientation == "South"):
                    self.l_x = self.l_x - 1
                    self.l_y = self.l_y
                    self.Orientation = 'West'

                elif (self.Orientation == "East"):
                    self.l_x = self.l_x
                    self.l_y = self.l_y - 1
                    self.Orientation = 'South'

                elif (self.Orientation == "West"):
                    self.l_x = self.l_x
                    self.l_y = self.l_y + 1
                    self.Orientation = 'North'

                Coordinates_Updated = 1

            if (Coordinates_Updated != 0):
                self.Total_Moves = self.Total_Moves + 1

            self.Moved_Straight_New = self.Moved_Straight_Old
            self.Moved_Reverse_New = self.Moved_Reverse_Old
            self.Moved_Left_New = self.Moved_Left_Old
            self.Moved_Right_New = self.Moved_Right_Old

        #Calculate the next move
        if (self.Orientation == "North"):
            if ((self.y_inter_des - self.l_y) > 0):
                self.Moved_Straight_New = self.Moved_Straight_Old + 1
                ret = 5  #Straight

            elif ((self.x_inter_des - self.l_x) > 0):
                self.Moved_Right_New = self.Moved_Right_Old + 1
                ret = 9  #Right

            elif ((self.x_inter_des - self.l_x) < 0):
                self.Moved_Left_New = self.Moved_Left_Old + 1
                ret = 1  #Left

            elif ((self.y_inter_des - self.l_y) < 0):
                self.Moved_Reverse_New = self.Moved_Reverse_Old + 1
                ret = 11  #Reverse

            elif ((self.y_inter_des == self.l_y)
                  and (self.x_inter_des == self.l_x)):
                ret = 0  #Stop

        elif (self.Orientation == "South"):
            if ((self.y_inter_des - self.l_y) < 0):
                self.Moved_Straight_New = self.Moved_Straight_Old + 1
                ret = 5  #Straight

            elif ((self.x_inter_des - self.l_x) < 0):
                self.Moved_Right_New = self.Moved_Right_Old + 1
                ret = 9  #Right

            elif ((self.x_inter_des - self.l_x) > 0):
                self.Moved_Left_New = self.Moved_Left_Old + 1
                ret = 1  #Left

            elif ((self.y_inter_des - self.l_y) > 0):
                self.Moved_Reverse_New = self.Moved_Reverse_Old + 1
                ret = 11  #Reverse

            elif ((self.y_inter_des == self.l_y)
                  and (self.x_inter_des == self.l_x)):
                ret = 0  #Stop

        elif (self.Orientation == "East"):
            if ((self.x_inter_des - self.l_x) > 0):
                self.Moved_Straight_New = self.Moved_Straight_Old + 1
                ret = 5  #Straight

            elif ((self.y_inter_des - self.l_y) < 0):
                self.Moved_Right_New = self.Moved_Right_Old + 1
                ret = 9  #Right

            elif ((self.y_inter_des - self.l_y) > 0):
                self.Moved_Left_New = self.Moved_Left_Old + 1
                ret = 1  #Left

            elif ((self.x_inter_des - self.l_x) < 0):
                self.Moved_Reverse_New = self.Moved_Reverse_Old + 1
                ret = 11  #Reverse

            elif ((self.y_inter_des == self.l_y)
                  and (self.x_inter_des == self.l_x)):
                ret = 0  #Stop

        elif (self.Orientation == "West"):
            if ((self.x_inter_des - self.l_x) < 0):
                self.Moved_Straight_New = self.Moved_Straight_Old + 1
                ret = 5  #Straight

            elif ((self.y_inter_des - self.l_y) > 0):
                self.Moved_Right_New = self.Moved_Right_Old + 1
                ret = 9  #Right

            elif ((self.y_inter_des - self.l_y) < 0):
                self.Moved_Left_New = self.Moved_Left_Old + 1
                ret = 1  #Left

            elif ((self.x_inter_des - self.l_x) > 0):
                self.Moved_Reverse_New = self.Moved_Reverse_Old + 1
                ret = 11  #Reverse

            elif ((self.y_inter_des == self.l_y)
                  and (self.x_inter_des == self.l_x)):
                ret = 0  #Stop

        #Set the inital junction value to 1
        self.IntialJunction = 1

        #Update if the intermediate position is reached
        if ((self.y_inter_des == self.l_y) and (self.x_inter_des == self.l_x)):
            self.Inter_Target_Reached = 1
        else:
            self.Inter_Target_Reached = 0

        #Update if the product location coordinate is reached
        if ((self.y_pro_des == self.l_y) and (self.x_pro_des == self.l_x)):
            self.Product_Des_Reached = 1
        else:
            self.Product_Des_Reached = 0
        #------------------------------------------------------------------------------------------------------------------------

        #--------------------Print data for debugging-------------------------------------------------------------------------
        print("Orientation - %s" % self.Orientation)
        print("X Coordinate - %d " % self.l_x)
        print("Y Coordinate - %d " % self.l_y)
        print("Intermediate Destination Reached - %d " %
              self.Inter_Target_Reached)
        print("Product Destination Reached - %d " % self.Product_Des_Reached)
        print("Total Moves - %d " % self.Total_Moves)
        #------------------------------------------------------------------------------------------------------------------------

        #----------------------Write data into Google Firebase Cloud Database-------------------------------------------------
        # Create a dictionary to store the data before sending to the database
        data_to_upload = {
            'Time': time.ctime(),
            'Current X Coordinate': self.l_x,
            'Current Y Coordinate': self.l_y,
            'Intermed Destination X': self.x_inter_des,
            'Intermed Destination Y': self.y_inter_des,
            'Product Destination X': self.x_pro_des,
            'Product Destination Y': self.y_pro_des,
            'Movement': ret,
            'Orientation': self.Orientation,
            'Intermed Destination Reached': self.Inter_Target_Reached,
            'Product Destination Reached': self.Product_Des_Reached,
            'Total Moves': self.Total_Moves
        }
        #Post the data to the appropriate folder/branch within your database
        result = FBConn.post('/Cart4/SPUG_PI2PC_Coordinates_Data/',
                             data_to_upload)
        #------------------------------------------------------------------------------------------------------------------------

        #----------------------------------------Send MQTT Path Occupy Message-------------------------------------------------
        client = mqtt.Client("RaspBerry_PI_1")  #create new instance

        client.connect('192.168.1.9', 1883, 70)  #connect to broker

        client.loop_start()

        message1 = {
            "X": str(self.x_inter_des),
            "Y": str(str(self.y_inter_des))
        }

        msg1 = json.dumps(message1)

        client.publish("pointOccupy/", msg1, 2)

        time.sleep(0.1)

        print("Point Occupy message Sent from Pi :" + time.ctime() + " " +
              msg1)
        #------------------------------------------------------------------------------------------------------------------------

        #----------------------------------------Send MQTT Path Un-Occupy Message-------------------------------------------------
        if (self.Is_Intermediate_DestinTion_Reached()):
            client = mqtt.Client("RaspBerry_PI_2")  #create new instance

            client.connect('192.168.1.9', 1883, 70)  #connect to broker

            client.loop_start()

            message2 = {
                "X": str(self.x_inter_des),
                "Y": str(str(self.y_inter_des))
            }

            msg2 = json.dumps(message2)

            client.publish("pointUnoccupy/", msg2, 2)

            time.sleep(0.1)

            print("Point Un-Occupy message Sent from Pi :" + time.ctime() +
                  " " + msg2)
        #-------------------------------------------------------------------------------------------------------------------------

        #----------------------------------------Send MQTT Item Purchased Message-------------------------------------------------
        if (self.Is_Product_DestinTion_Reached()):
            client = mqtt.Client("RaspBerry_PI_3")  #create new instance

            client.connect('192.168.1.9', 1883, 70)  #connect to broker

            client.loop_start()

            message3 = { "itemPurchasedX" : str(self.l_x), "itemPurchasedY" : str(self.l_y), \
                         "cartName" : "cart"+str(self.Cart_Number)}

            msg3 = json.dumps(message3)

            client.publish("item/", msg3, 2)

            time.sleep(0.1)

            print("Item Purchased message Sent from Pi :" + time.ctime() +
                  " " + msg3)

            self.LED.ledIndex(0xFF, 0, 0, 0)  # Switch off all LED's
            self.Buzzer.run('1')
            time.sleep(0.5)
            self.Buzzer.run('0')
        #---------------------------------------------------------------------------------------------------------------------

        #Return Value from the Calculations
        return int(ret)

    def Move_Cart(self, l_Movement_Type):

        if (l_Movement_Type == 5):
            self.LED.ledIndex(0xFF, 0, 0, 0)  #Turn Off
            self.LED.ledIndex(0xF0, 0, 255, 0)  #Green
            #PWM.setMotorModel(800,800,800,800)
            #time.sleep(0.1)
            #PWM.setMotorModel(0,0,0,0)

        elif (l_Movement_Type == 1):
            self.LED.ledIndex(0xFF, 0, 0, 0)  #Turn Off
            self.LED.ledIndex(0x3C, 0, 255, 0)  #Green
            #PWM.setMotorModel(-2000,-2000,4000,4000)
            #time.sleep(0.2)

        elif (l_Movement_Type == 3):
            self.LED.ledIndex(0xFF, 0, 0, 0)  #Turn Off
            self.LED.ledIndex(0x3C, 0, 0, 0)  #Green
            #PWM.setMotorModel(-1200,-1200,2000,2000)
            #time.sleep(0.2)

        elif (l_Movement_Type == 7):
            self.LED.ledIndex(0xFF, 0, 0, 0)  #Turn Off
            self.LED.ledIndex(0xC3, 0, 0, 0)  #Green
            #PWM.setMotorModel(2000,2000,-1200,-1200)
            #time.sleep(0.2)

        elif (l_Movement_Type == 9):
            self.LED.ledIndex(0xFF, 0, 0, 0)  #Turn Off
            self.LED.ledIndex(0xC3, 0, 255, 0)  #Green
            #PWM.setMotorModel(4000,4000,-2000,-2000)
            #time.sleep(0.5)

        elif (l_Movement_Type == 11):
            self.LED.ledIndex(0xFF, 0, 0, 0)  #Turn Off
            self.LED.ledIndex(0x0F, 0, 255, 0)  #Green
            #PWM.setMotorModel(-600,-600,-600,-600)

        elif (l_Movement_Type == 0):
            time.sleep(0.001)
            #PWM.setMotorModel(0,0,0,0)

    def Run_Cart4(self):

        #------------------------------------------Ultrasonic sensor and Servo Motor Class
        self.Ultrasonic = Ultrasonic()

        self.LED = Led()

        self.Buzzer = Buzzer()

        self.Junction = 0

        #--------------------------------------------------------------------------------------
        while True:

            self.Movement_Type = 0

            Distance = self.Ultrasonic.get_distance()

            IR_Left = GPIO.input(IR01)

            IR_Mid = GPIO.input(IR02)

            IR_Right = GPIO.input(IR03)

            if (Distance > 15.0):

                if ((IR_Left == 0) and (IR_Mid == 1) and (IR_Right == 0)):
                    if (self.Moved_Reverse_New != self.Moved_Reverse_Old):
                        self.Movement_Type = 11  #Move Reverse
                    else:
                        self.Movement_Type = 5  #Move Forward
                    self.Junction = 0  #Clear the Junction Variable

                elif ((IR_Left == 1) and (IR_Mid == 0) and (IR_Right == 0)):
                    self.Movement_Type = 3  #Take Slight Left

                elif ((IR_Left == 1) and (IR_Mid == 1) and (IR_Right == 0)):
                    self.Movement_Type = 3  #Take Slight Left

                elif ((IR_Left == 0) and (IR_Mid == 0) and (IR_Right == 1)):
                    self.Movement_Type = 7  #Take Slight Right

                elif ((IR_Left == 0) and (IR_Mid == 1) and (IR_Right == 1)):
                    self.Movement_Type = 7  #Take Slight Right

                elif ((IR_Mid == 1) and (IR_Left == 1) and (IR_Right == 1)):
                    if (self.Junction == 0):
                        self.Movement_Type = self.Mov_According_To_Specified_position(
                        )
                    self.Junction = 1

                else:
                    pass

            else:
                self.Movement_Type = 0  #Stop Movement
                self.LED.ledIndex(0x20, 255, 125, 0)  #Orange
                self.LED.ledIndex(0x40, 255, 125, 0)  #Orange
                time.sleep(1)
                self.LED.ledIndex(0x60, 0, 0, 0)

            #Actuate the motors to move cart to the specific Coordinate
            self.Move_Cart(self.Movement_Type)

            if (self.Is_Intermediate_DestinTion_Reached()):
                break
Пример #28
0
import time
from Led import *
from servo import *
from Motor import *

led = Led()


def test_Led():
    try:
        led.ledIndex(0x01, 255, 0, 0)  #Red
        led.ledIndex(0x02, 255, 125, 0)  #orange
        led.ledIndex(0x04, 255, 255, 0)  #yellow
        led.ledIndex(0x08, 0, 255, 0)  #green
        led.ledIndex(0x10, 0, 255, 255)  #cyan-blue
        led.ledIndex(0x20, 0, 0, 255)  #blue
        led.ledIndex(0x40, 128, 0, 128)  #purple
        led.ledIndex(0x80, 255, 255, 255)  #white'''
        print "The LED has been lit, the color is red orange yellow green cyan-blue blue white"
        time.sleep(3)  #wait 3s
        led.colorWipe(led.strip, Color(0, 0, 0))  #turn off the light
        print "\nEnd of program"
    except KeyboardInterrupt:
        led.colorWipe(led.strip, Color(0, 0, 0))  #turn off the light
        print "\nEnd of program"


PWM = Motor()


def test_Motor():
Пример #29
0
    print('Initialize motor control...')
    myEngine = Motor.Motor()
    
    print('Initialize servo control ... ')
    myServo = ServoControl(debug = True)

    print('Initialize Buzzer Driver...')
    myBuzzer = Buzzer.Buzzer()

    print('Initialize ADC Driver...')
    myAdc = ADC.Adc()
    Thread_Monitor = threading.Thread(target = monitorBattery, args=[myAdc, myBuzzer])
    Thread_Monitor.start()

    print('Initialize LED Driver...')
    myLed = Led.Led()

    try:
        print('Center camera head...')
        myServo.center()
        time.sleep(2)

        print('Enter 50ms control loop...')
        disableMotor = False
        while True:
            # 1st stick controls the wheel motors
            stick1_hor = myPad.get_axis_scaled(0)
            stick1_ver = myPad.get_axis_scaled(1)
            if not disableMotor:
                process_stick1(stick1_hor, stick1_ver, myEngine)
            else: