Beispiel #1
0
def misc_init():
    print("misc_init()\n")
    wp.wiringPiSetup()
    for i in range(len(misc_dev_status)):
        pin = misc_dev_status[i][0]
        wp.pinMode(pin, wp.OUTPUT)
        wp.digitalWrite(pin, wp.LOW)
Beispiel #2
0
def init(mission):
    global state, setpoint, run, pose, home, init
    global arming_client, set_mode_client
    #Global variable initialisation
    state, pose, setpoint, home = State(), PoseStamped(), Point(), Point()
    run = True
    init = True
    # Node initiation
    rospy.init_node(NODE_NAME)
    rospy.loginfo('node initializeed')
    time.sleep(1)
    # setting up the pins for electromagnet
    wpi.wiringPiSetup()
    wpi.pinMode(0,1)
    # Publishers, subscribers and services
    pose_sub        = rospy.Subscriber('/mavros/local_position/pose', PoseStamped, Pose_Callback)
    state_sub       = rospy.Subscriber('/mavros/state', State, State_Callback)
    rospy.wait_for_service('mavros/set_mode')
    set_mode_client = rospy.ServiceProxy('mavros/set_mode', SetMode)
    rospy.wait_for_service('mavros/cmd/arming')
    arming_client   = rospy.ServiceProxy('mavros/cmd/arming', CommandBool)
    # Thread to send setpoints - mission execution
    tSetPoints = Thread(target=sendSetpoint,args=(mission,)).start()
    # Monitor security
    while not rospy.is_shutdown():
        InterfaceKeyboard()
Beispiel #3
0
def Change_Gpio_Mode(pin, mode):
    wiringpi.wiringPiSetup()
    if mode == 1:
        wiringpi.pinMode(pin, wiringpi.OUTPUT)
    else:
        wiringpi.pinMode(pin, wiringpi.INPUT)
    return (0)
    def __init__(self, gpio=0):
        global _linearEncoder

        # singleton
        if _linearEncoder is not None:
            raise Exception("Already created!")

        _linearEncoder = weakref.ref(self)

        # safety
        self.lock = threading.Lock()

        # tracking
        self.prevSampleTime = 0
        self.prevNumPulses = 0
        self.numPulses = 0

        # calibrations
        self.Calibration = calibration_pb2.Calibration()
        self.calMiles = None
        self.calDurationSec = None
        self.calRevolutions = None
        self.calRevToMilesScale = 0.0

        # GPIO
        wiringpi.wiringPiSetup()
        self.gpio = gpio
        wiringpi.wiringPiISR(self.gpio, wiringpi.INT_EDGE_FALLING,
                             LinearEncoder._myInterrupt)
        wiringpi.piHiPri(99)
Beispiel #5
0
def main():
    # setup wiringpi
    wipi.wiringPiSetup()

    # wPi 9 corresponds to Pin 5
    WPI_PORT = 9

    # time delay in milliseconds
    T = 0.05  # 0.05 ~ 50 ms

    # '1' means output
    wipi.pinMode(WPI_PORT, 1)

    # initial state
    state = 1
    print("blinking Pin 5")
    while True:
        # blink
        wipi.digitalWrite(WPI_PORT, state)

        # waiting
        time.sleep(T)

        # switch state
        state = not state
Beispiel #6
0
    def __init__(self, bname, bport, num_channels):
        super(mcp23017, self).__init__(bname, bport, num_channels)

        # set the pin base for this i2c device, it doesn't matter which
        # mcp device get which set of pin numbers- it's all internal to
        # this driver.  externally, we use 0-15
        global pin_base
        self.pin_base = pin_base
        pin_base += 16

        # convert the 'port' to the device i2c address
        # port should be defined with leading '0x'
        i2c_addr = int(bport, 0)

        # initialise wiringpi and setup mcpdriver for device
        wiringpi.wiringPiSetup()
        wiringpi.mcp23017Setup(self.pin_base, i2c_addr)

        self.channel_dirs = dict()
        self.channel_sense = dict()
        self.channel_configured = dict()

        # initialise all gpio as inputs first of all
        for pin in range(self.pin_base, 16):
            wiringpi.pinMode(pin, INPUT_PIN)
Beispiel #7
0
def Init_Drive_ESC():
    global l_drive
    l_drive = 0
    global r_drive
    r_drive = 0
    wiringpi.wiringPiSetup()
    global Motor1PWM
    Motor1PWM = 1  # gpio pin 12 = wiringpi no 1   (BCM 18)
    global Motor1AIN1
    Motor1AIN1 = 4  # gpio pin 16 = wiringpi no. 4  (BCM 23)
    global Motor1AIN2
    Motor1AIN2 = 5  # gpio pin 18 = wiringpi no. 5  (BCM 24)
    global MotorStandby
    MotorStandby = 6  # gpio pin 22 = wiringpi no. 6  (BCM 25)
    global Motor2PWM
    Motor2PWM = 23  # gpio pin 33 = wiringpi no. 23 (BCM 13)
    global Motor2AIN1
    Motor2AIN1 = 21  # gpio pin 29 = wiringpi no. 21 (BCM 5)
    global Motor2AIN2
    Motor2AIN2 = 22  # gpio pin 31 = wiringpi no. 22 (BCM 6)

    wiringpi.pinMode(Motor1PWM, 2)  # PWM mode
    wiringpi.pinMode(Motor1AIN1, 1)  # Digital out mode
    wiringpi.pinMode(Motor1AIN2, 1)  # Digital out mode
    # wiringpi.pinMode(MotorStandby, 	    1) 	# Ditial out mode
    wiringpi.pinMode(Motor2PWM, 2)  # PWM mode
    wiringpi.pinMode(Motor2AIN1, 1)  # Digital out mode
    wiringpi.pinMode(Motor2AIN2, 1)  # Digital out mode
def main():
    plogger = init_logger('rasptea1.player')
    # init WiringPi
    wp.wiringPiSetup()
    # set pin 4 to input mode
    wp.pinMode(4, 0)
    # keep player status
    playerActive = False
    # infinite loop
    while True:
        try:
            # read sensor state
            motionState = wp.digitalRead(4)
            if motionState == 1 and not playerActive:
                player = subprocess.Popen(
                    ['omxplayer', '-o', 'local', AUDIOFILE],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE)
                plogger.info('Player started')
                playerActive = True
                # wait for audio played completely
                player.wait()
                plogger.info('Player stopped')
                playerActive = False
        except Exception as e:
            plogger.error('Player error in loop occured %s' % (e, ))
    # wait for 100 ms
    wp.delay(100)
Beispiel #9
0
def gpioSetup():
    # Access global variables
    global dcRange
    global clockDivisor
    global pwm
    global pwm2

    try:
        # Setup board pin layout
        wiringpi.wiringPiSetup()
        wiringpi.pinMode(1, wiringpi.PWM_OUTPUT)
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(13, GPIO.OUT)
        GPIO.setup(19, GPIO.OUT)
        pwm = GPIO.PWM(13, 1000)

        # Set output to mark:space mode (to avoid frequency change)
        wiringpi.pwmSetMode(wiringpi.PWM_MODE_MS)

        # Set output to approximately 100 kHz
        wiringpi.pwmSetClock(2)
        wiringpi.pwmSetRange(dcRange)

        # Initialize duty cycles
        wiringpi.pwmWrite(1, 0)
        pwm.start(50)
        # pwmWrite requires numbers in range [0, dcRange]
    finally:
        print("Completed setup")
    def __init__(self):
        if GpioController.__instance != None:
            raise Exception('Do not call GpioController() directly. Use static get_instance')
        else:
            GpioController.__instance = self

        wpi.wiringPiSetup()
Beispiel #11
0
def main():
    delay = 1E-2 # seconds

    # set up pins
    wiringpi.wiringPiSetup()
    for pin in pinsA:
        wiringpi.pinMode( pin, 1 )
    for pin in pinsB:
        wiringpi.pinMode( pin, 1 )
    for pin in pinsOut:
        wiringpi.pinMode( pin, 0 )
    wiringpi.pinMode( isSignedPin, 1 )
    wiringpi.pinMode( isSupportedPin, 0 )
    
    numFails = testUnsigned(delay)
    numFails += testSigned(delay)

    # magic for coloured printing from https://pythonadventures.wordpress.com/2011/03/16/print-colored-text-in-terminal/
    colorred = "\033[01;31m{0}\033[00m"
    colorgrn = "\033[1;36m{0}\033[00m"
    
    if numFails > 0:
        print colorred.format("%d tests were failed" % numFails)
    else:
        print colorgrn.format("All tests passed")
Beispiel #12
0
def setupPWM(motor11, motor12, motor21, motor22, motor31, motor32, motor41, motor42):

    # setup wiringpi and pwm outputs
    wiringpi.wiringPiSetup()

    wiringpi.pinMode(motor11, 1)
    wiringpi.pinMode(motor12, 1)
    wiringpi.pinMode(motor21, 1)
    wiringpi.pinMode(motor22, 1)
    wiringpi.pinMode(motor31, 1)
    wiringpi.pinMode(motor32, 1)
    wiringpi.pinMode(motor41, 1)
    wiringpi.pinMode(motor42, 1)

    wiringpi.pwmSetMode(wiringpi.PWM_MODE_MS)
    wiringpi.pwmSetClock(2)
    wiringpi.pwmSetRange(1000)

    wiringpi.softPwmCreate(motor11, 0, 100)
    wiringpi.softPwmCreate(motor12, 0, 100)
    wiringpi.softPwmCreate(motor21, 0, 100)
    wiringpi.softPwmCreate(motor22, 0, 100)
    wiringpi.softPwmCreate(motor31, 0, 100)
    wiringpi.softPwmCreate(motor32, 0, 100)
    wiringpi.softPwmCreate(motor41, 0, 100)
    wiringpi.softPwmCreate(motor42, 0, 100)

    wiringpi.softPwmWrite(motor11, 100)
    wiringpi.softPwmWrite(motor12, 100)
    wiringpi.softPwmWrite(motor21, 100)
    wiringpi.softPwmWrite(motor22, 100)
    wiringpi.softPwmWrite(motor31, 100)
    wiringpi.softPwmWrite(motor32, 100)
    wiringpi.softPwmWrite(motor41, 100)
    wiringpi.softPwmWrite(motor42, 100)
def setup():
    wpi.wiringPiSetup()
    wpi.pinMode(pCLK, wpi.INPUT)
    wpi.pinMode(pDT, wpi.INPUT)
    wpi.pinMode(pSW, wpi.INPUT)
    wpi.pullUpDnControl(pSW, wpi.PUD_UP)
    rotaryClear()
def setup():
    wiringpi.wiringPiSetup()

    global boiler
    global tr2 
    global valves
    global call_for_heats
    global ufh_pump

    boiler = Boiler.Boiler()
    tr2 = TR2.TR2()
    zv1 = zonevalve.ZoneValve(1, zone_valve_state_changed)
    zv2 = zonevalve.ZoneValve(2, zone_valve_state_changed)
    zv3 = zonevalve.ZoneValve(3, zone_valve_state_changed)
    valves = {'ufh': zv1, 'downstairs':zv2, 'upstairs': zv3}

    cfh1 = cfh.CFH(1,cfh_state_changed)
    cfh2 = cfh.CFH(2,cfh_state_changed)
    cfh3 = cfh.CFH(3,cfh_state_changed)
    call_for_heats = {'kitchen':cfh1, 'lounge': cfh2, 'landing': cfh3}


    ufh_pump = relays.Relay(0)

    # boiler.set_temp(2000) 
    boiler.off()
   
    for v in valves:
        valves[v].close()
 def output_to_MC(self, data=list, baudrate=int):
     length = len(data)
     #Checks if the list is of length 4. If it isn't, immediately return
     if(length!=4):
         print("Invalid list size. Needed size of 4, you provided a list whose size is {}".format(length))
         return
     wiringpi.wiringPiSetup()
     #opens the Raspberry Pi's UART port, w/ a data transfer rate of
     #115200 bits/s
     serial = wiringpi.serialOpen('/dev/ttyS0', baudrate)
     #sleep a few seconds to make sure the port opens and sets connections
     #properly
     sleep(2)
    #signals to start data transmission, uses start of header char
     wiringpi.serialPuts(serial, chr(1).encode('ascii'))
     wiringpi.serialPuts(serial, data[0].encode('ascii'))
     for index in range(1, length, 1):
         #signals that the next data is being sent, uses start of text char
         wiringpi.serialPuts(serial, chr(2).encode('ascii'))
         #write the string data, as ascii, to the Raspberry Pi
         wiringpi.serialPuts(serial, data[index].encode('ascii'))
     #signals that data transmission is ending, uses end of transmission char
     wiringpi.serialPuts(serial, chr(4).encode('ascii'))
     #closes the serial port
     wiringpi.serialClose(serial)
     return
Beispiel #16
0
    def __init__(self, dev=(0,0),speed=4000000, brightness=256, contrast=CONTRAST):
        self.spi = spidev.SpiDev()
        self.speed = speed
        self.dev = dev
        self.spi.open(self.dev[0],self.dev[1])
        self.spi.max_speed_hz=self.speed

        # Set pin directions.
        self.dc = DC
        self.rst = RST
        wiringpi.wiringPiSetup()
        for pin in [self.dc, self.rst]:
            wiringpi.pinMode(pin, 1)

        self.contrast=contrast
        self.brightness=brightness
        
        # Toggle RST low to reset.
        wiringpi.digitalWrite(self.rst, OFF)
        time.sleep(0.100)
        wiringpi.digitalWrite(self.rst, ON)
        # Extended mode, bias, vop, basic mode, non-inverted display.
        wiringpi.digitalWrite(self.dc, OFF)
        self.spi.writebytes([0x21, 0x14, self.contrast, 0x20, 0x0c])
        # cls()

        self.ledpin = LED
        if self.ledpin == 1:
            wiringpi.pinMode(self.ledpin, 2)
            wiringpi.pwmWrite(self.ledpin, self.brightness)
        else:
            wiringpi.pinMode(self.ledpin, 1)
            wiringpi.digitalWrite(self.ledpin, ON)
Beispiel #17
0
def io_setup():
    wiringpi.wiringPiSetup()  # initialise wiringpi in native pin mode

    # bteak beam sensor
    wiringpi.pinMode(15, 0)  # sets GPIO14 to input
    wiringpi.pullUpDnControl(15, 2)  # set internal pull-up

    # Relay boards
    wiringpi.pinMode(0, 1)  # sets GPIO0 to output
    wiringpi.pinMode(2, 1)  # sets GPIO2 to output
    wiringpi.pinMode(3, 1)  # sets GPIO3 to ouput

    # expander IO
    pin_base = 65  # lowest available starting number is 65
    i2c_addr = 0x20  # A0, A1, A2 pins all wired to GND

    wiringpi.mcp23017Setup(pin_base, i2c_addr)  # set up the pins and i2c address

    # Note: MCP23017 has no internal pull-down, so we use pull-up instead and a NC contact to GND
    wiringpi.pinMode(65, 0)  # sets GPA0 to input
    wiringpi.pullUpDnControl(65, 2)  # set internal pull-up
    wiringpi.pinMode(66, 0)  # sets GPA1  to input
    wiringpi.pullUpDnControl(66, 2)  # set internal pull-up

    # Our second chip is now ready to use pins 81 (GPA0) – 96 (GPB7).
    wiringpi.mcp23017Setup(81, 0x21)
    def __init__(self, gpioexp_address=GPIO_EXPANDER_DEFAULT_I2C_ADDRESS):

        # Setup I2C interface for accelerometer and magnetometer.
        wp.wiringPiSetup()
        self._i2c = wp.I2C()
        self._io = self._i2c.setupInterface(
            '/dev/i2c-' + str(getPiI2CBusNumber()), gpioexp_address)
Beispiel #19
0
    def raspberry_node1_moving(self):
        wiringpi.wiringPiSetup()
        wiringpi.pinMode(1, 1)
        wiringpi.pinMode(2, 1)
        wiringpi.pinMode(3, 1)
        wiringpi.pinMode(4, 1)
        #wiringpi.softPwmCreate(2, 0, 100);wiringpi.softPwmCreate(3, 0, 100);wiringpi.softPwmCreate(4, 0, 100)

        while not rospy.is_shutdown():
            if self.X == 1:
                wiringpi.digitalWrite(1, 1)
                wiringpi.digitalWrite(2, 0)
                wiringpi.digitalWrite(3, 1)
                wiringpi.digitalWrite(4, 0)
                self.pub.publish(
                    "From Raspberry_node1: Forward Done with success")

            elif self.X == -1:
                wiringpi.digitalWrite(1, 0)
                wiringpi.digitalWrite(2, 1)
                self.pub.publish(
                    "From Raspberry_node1: Backward Done with success")
                #print("hi")
            if self.X_angular == 1:
                #wiringpi.softPwmWrite(1, 100)  # Change PWM duty cycle
                self.pub.publish("From Raspberry_node1: Done with success")
            self.rate.sleep()
Beispiel #20
0
def init_steppers():

    #current_units.x = 0.0;
    #current_units.y = 0.0;
    #current_units.z = 0.0;
    #target_units.x = 0.0;
    #target_units.y = 0.0;
    #target_units.z = 0.0;

    #-----------引脚初始化--------#
    gpio.wiringPiSetup()  #初始化

    gpio.pinMode(X_STEP_PIN, GPIO.OUTPUT)  # 把pin25设置为输出模式
    gpio.pinMode(X_DIR_PIN, GPIO.OUTPUT)  # 把pin25设置为输出模式
    gpio.pinMode(X_ENABLE_PIN, GPIO.OUTPUT)  # 把pin25设置为输出模式
    gpio.pinMode(X_MIN_PIN, GPIO.INPUT)  # 把pin25设置为输入模式
    gpio.pinMode(X_MAX_PIN, GPIO.INPUT)  # 把pin25设置为输入模式

    gpio.pinMode(Y_STEP_PIN, GPIO.OUTPUT)  # 把pin25设置为输出模式
    gpio.pinMode(Y_DIR_PIN, GPIO.OUTPUT)  # 把pin25设置为输出模式
    gpio.pinMode(Y_ENABLE_PIN, GPIO.OUTPUT)  # 把pin25设置为输出模式
    gpio.pinMode(Y_MIN_PIN, GPIO.INPUT)  # 把pin25设置为输入模式
    gpio.pinMode(Y_MAX_PIN, GPIO.INPUT)  # 把pin25设置为输入模式

    gpio.pinMode(Z_STEP_PIN, GPIO.OUTPUT)  # 把pin25设置为输出模式
    gpio.pinMode(Z_DIR_PIN, GPIO.OUTPUT)  # 把pin25设置为输出模式
    gpio.pinMode(Z_ENABLE_PIN, GPIO.OUTPUT)  # 把pin25设置为输出模式
    gpio.pinMode(Z_MIN_PIN, GPIO.INPUT)  # 把pin25设置为输入模式
    gpio.pinMode(Z_MAX_PIN, GPIO.INPUT)  # 把pin25设置为输入模式

    gpio.digitalWrite(X_ENABLE_PIN, GPIO.LOW)  #pin25输出为高电平
    gpio.digitalWrite(Y_ENABLE_PIN, GPIO.LOW)  #pin25输出为高电平
    gpio.digitalWrite(Z_ENABLE_PIN, GPIO.LOW)  #pin25输出为高电平
Beispiel #21
0
    def __init__(self, connector):
        # *** User variables ***
        self.drive_motor_forward_pin = 5
        self.drive_motor_reverse_pin = 6
        self.turn_motor_left_pin = 2
        self.turn_motor_right_pin = 3
        self.pwm0_pin = 1
        self.clock_pin = 7
        self.led_one_pin = 4
        # Serial depends on how PyBluez sets it up, but it's usually this
        self.serial_dev = "/dev/ttyAMA0"
        self.serial_baud = 9600

        # Internal setup
        self.rc = connector
        self.rc.setBlocking(True)
        wiringpi.wiringPiSetup()
        self.serial = wiringpi.serialOpen(self.serial_dev, self.serial_baud)
        wiringpi.pinMode(self.drive_motor_forward_pin, 1)
        wiringpi.pinMode(self.drive_motor_reverse_pin, 1)
        wiringpi.pinMode(self.turn_motor_left_pin, 1)
        wiringpi.pinMode(self.turn_motor_right_pin, 1)

        # Just output a constant high on drive PWM for now...
        wiringpi.pinMode(self.pwm0_pin, 1)
        wiringpi.digitalWrite(self.pwm0_pin, 1)
Beispiel #22
0
def initialize():
    """Set pins as outputs and start all lights in the off state."""
    wiringpi.wiringPiSetup()
    enable_device()
    set_pins_as_outputs()

    turn_off_lights()
Beispiel #23
0
def init(HOSTNAME):
    global main
    # setup LED control and door sensor
    #io_init()
    wpi.wiringPiSetup()
    # global network
    network = network_init(
        hostname=HOSTNAME,
        role="server",
        discovery_multicastGroup=settings.discovery_multicastGroup,
        discovery_multicastPort=settings.discovery_multicastPort,
        discovery_responsePort=settings.discovery_responsePort,
        pubsub_pubPort=settings.pubsub_pubPort,
        message_callback=network_message_handler,
        status_callback=network_status_handler)
    network.subscribe_to_topic("system")  # subscribe to all system messages
    network.subscribe_to_topic("found_beer")
    network.subscribe_to_topic("update_complete")
    network.subscribe_to_topic("image_capture_from_camera_unit")
    network.subscribe_to_topic("client_monitor_response")
    network.subscribe_to_topic("receive_image_overlay")
    network.subscribe_to_topic("receive_image_data")
    network.subscribe_to_topic("classification_data_to_conductor")

    main = Main(network)
    return main
 def __init__(self, оctoliner_address=OCTOLINER_DEFAULT_I2C_ADDRESS):
     # Setup I2C interface for accelerometer and magnetometer.
     wp.wiringPiSetup()
     self._i2c = wp.I2C()
     self._io = self._i2c.setupInterface(
         '/dev/i2c-' + str(getPiI2CBusNumber()), оctoliner_address)
     self._i2c.write(self._io, OCTOLINER_RESET)
Beispiel #25
0
    def run(self):            
        logging.info(__name__ + ":initializing WiringPi2")
        wiringpi.wiringPiSetup()

        localNode = Node.local
        localEvent = Event(0,localNode.id,localNode.devStr,localNode.devNum,[])
        localEvent.values = [0]*len(Sensor.instances)
        lastReport = time.time()
        lastRead = 0.0
        sigChange = False
        needToReport = False
        while not self.cancelled:
            now = time.time()
            if now - lastRead > localNode.monitorInterval:
                #Read all sensors and schedule their updates and reporting
                lastRead = now
                for key in Sensor.instances:
                    sigChange |= Sensor.instances[key].update()   # read sensor
            if sigChange or (now - lastReport) > localNode.reportInterval:
                for i,sensor in enumerate(self.sensors):
                    localEvent.values[i] = round(sensor.report()*10)
                localEvent.time = now
                evt = localEvent.tuple()
                logging.debug(__name__ + "Local event:" + str(evt))
                localNode.eventlog.qEvent(evt)
                needToReport = True
                sigChange = False
            if needToReport and (now - lastReport) > localNode.minServerEventInterval:
                localNode.server.qEvent(evt)
                logging.debug(__name__+":logged event for-"+str(evt))
                lastReport = now
                needToReport = False
            time.sleep(max(0, min(2,
                                  lastRead + localNode.monitorInterval - now,
                                  lastReport + localNode.reportInterval - now)))
Beispiel #26
0
	def __init__(self,i1,i2,i3,i4):
		w.wiringPiSetup()
		self.inp=[i1,i2,i3,i4]
		w.pinMode(i1,w.OUTPUT)
		w.pinMode(i2,w.OUTPUT)
		w.pinMode(i3,w.OUTPUT)
		w.pinMode(i4,w.OUTPUT)
		w.digitalWrite(i1,0)
		w.digitalWrite(i2,0)
		w.digitalWrite(i3,0)
		w.digitalWrite(i4,0)
		self.numstep=0
		self.half=[]
		self.half.append([1,0,0,1]) # setp 0
		self.half.append([1,0,0,0]) # step 1
		self.half.append([1,1,0,0]) # step 2
		self.half.append([0,1,0,0]) # step 3
		self.half.append([0,1,1,0]) # step 4
		self.half.append([0,0,1,0]) # step 5
		self.half.append([0,0,1,1]) # step 6
		self.half.append([0,0,0,1]) # step 7
		self.acc= 500  # passi
		self.dec= 500  # passi 
		self.actspeed=0
		self.t=threading.Thread(target=self.update_pos)
		self.t.start()
		time.sleep(1)
		self.update=False
Beispiel #27
0
    def getval(self):
        tl = []
        tb = []
        wiringpi.wiringPiSetup()
        wiringpi.pinMode(self.owpin, 1)
        wiringpi.digitalWrite(self.owpin, 1)
        wiringpi.delay(1)
        wiringpi.digitalWrite(self.owpin, 0)
        wiringpi.delay(25)
        wiringpi.digitalWrite(self.owpin, 1)
        wiringpi.delayMicroseconds(20)
        wiringpi.pinMode(self.owpin, 0)
        while (wiringpi.digitalRead(self.owpin) == 1):
            pass

        for i in range(45):
            tc = wiringpi.micros()

            while (wiringpi.digitalRead(self.owpin) == 0):
                pass
            while (wiringpi.digitalRead(self.owpin) == 1):
                if wiringpi.micros() - tc > 500:
                    break
            if wiringpi.micros() - tc > 500:
                break
            tl.append(wiringpi.micros() - tc)

        tl = tl[1:]
        for i in tl:
            if i > 100:
                tb.append(1)
            else:
                tb.append(0)

        return tb
Beispiel #28
0
    def __init__(self, LATCH, CLCK, SER, PWM1=None, PWM2=None, PWM3=None, PWM4=None):
        wiringpi.wiringPiSetup()
        self.LATCH = LATCH
        wiringpi.pinMode(self.LATCH, 1)
        self.CLCK = CLCK
        wiringpi.pinMode(self.CLCK, 1)
        self.SER = SER
        wiringpi.pinMode(self.SER, 1)

        self.pwmPins = []
        self.pwmPins.append(PWM1)  # index 0
        self.pwmPins.append(PWM2)
        self.pwmPins.append(PWM3)
        self.pwmPins.append(PWM4)

        self.motors = []
        for motorNum in range(0, 4):
            if self.pwmPins[motorNum] is not None:
                self.motors.append(Motor(motorNum+1, 0, None, self.pwmPins[motorNum]))
            else:
                self.motors.append(None)
        self.allDirections = 0

        if PWM1 is not None:
            self.PWM1 = PWM1
            wiringpi.pinMode(self.PWM1, 1)
        if PWM2 is not None:
            self.PWM2 = PWM2
            wiringpi.pinMode(self.PWM2, 1)
        if PWM3 is not None:
            self.PWM3 = PWM3
            wiringpi.pinMode(self.PWM3, 1)
        if PWM4 is not None:
            self.PWM4 = PWM4
            wiringpi.pinMode(self.PWM4, 1)
Beispiel #29
0
 def __init__(self):
     print "Hello from ccraspberry"
     wiringpi.wiringPiSetup()
     wiringpi.pinMode(self.pinDC, GPIO.OUTPUT)
     wiringpi.pinMode(self.pinDD, GPIO.OUTPUT)
     wiringpi.pinMode(self.pinRST, GPIO.OUTPUT)
     wiringpi.pinMode(self.pinSEND, GPIO.OUTPUT)
     wiringpi.digitalWrite(self.pinDC, GPIO.LOW)
     wiringpi.digitalWrite(self.pinDD, GPIO.LOW)
     wiringpi.digitalWrite(self.pinRST, GPIO.LOW)
     wiringpi.digitalWrite(self.pinSEND, GPIO.HIGH)
     # Default CCDebug instruction set for CC254x
     self.instr[INSTR_VERSION] = 1
     self.instr[I_HALT] = 0x40
     self.instr[I_RESUME] = 0x48
     self.instr[I_RD_CONFIG] = 0x20
     self.instr[I_WR_CONFIG] = 0x18
     self.instr[I_DEBUG_INSTR_1] = 0x51
     self.instr[I_DEBUG_INSTR_2] = 0x52
     self.instr[I_DEBUG_INSTR_3] = 0x53
     self.instr[I_GET_CHIP_ID] = 0x68
     self.instr[I_GET_PC] = 0x28
     self.instr[I_READ_STATUS] = 0x30
     self.instr[I_STEP_INSTR] = 0x58
     self.instr[I_CHIP_ERASE] = 0x10
     self.enter()
Beispiel #30
0
def main ():
    # states
    STATES = {'OFF': 0, 'ON': 1 }

    # wPi 9 corresponds to Pin 5
    WPI_PORT = 9;

    # time delay in milliseconds
    T = 0.05 	# 0.05 ~ 50 ms

    wipi.wiringPiSetup ()

    # '1' means output 
    wipi.pinMode ( WPI_PORT, 1 )

    # initial state
    state = STATES [ 'ON' ]

    print ( "blinking pin 5" )
    print ( "To finish press: 'Ctrl + c'" )
    try:
        while True:
            # blink
            wipi.digitalWrite ( WPI_PORT, state )

            # waiting
            time.sleep ( T )
    
            # switch state
            state = not state

    except KeyboardInterrupt:
        wipi.digitalWrite ( WPI_PORT, STATES [ 'OFF' ]  )
        print ( "\nprogram is closing..." )
        sys.exit ( 0 )
Beispiel #31
0
def main():
    """ Main function """
    wp.wiringPiSetup()
    datasocket = DateDataPullSocket('furnaceroom_controller',
                                    ['temperature', 'setpoint', 'dutycycle', 'pid_p', 'pid_i'],
                                    timeouts=999999, port=9000)
    datasocket.start()

    pushsocket = DataPushSocket('furnaceroom_push_control', action='store_last')
    pushsocket.start()

    power_calculator = PowerCalculatorClass(datasocket, pushsocket)
    power_calculator.daemon = True
    power_calculator.start()

    heater = HeaterClass(power_calculator, datasocket)
    heater.start()

    tui = CursesTui(heater)
    tui.daemon = True
    tui.start()
    # make sure tui close down properly and the T setpoint is put low.
    try:
        while not heater.quit:
            time.sleep(1)
    except KeyboardInterrupt:
        print("Keyboard Interrupt detected, closing program")
        heater.quit = True
    finally:
        power_calculator.quit = True
        time.sleep(0.1)
        tui.stop()
Beispiel #32
0
 def setup(self):
     GPIO.setup(self.GPIO_PWM, GPIO.OUT)
     GPIO.setup(self.GPIO_control1, GPIO.OUT)
     GPIO.setup(self.GPIO_control2, GPIO.OUT)
     wiringpi.wiringPiSetup()
     wiringpi.pinMode(self.WIRING_PIN, 1)
     wiringpi.softPwmCreate(self.WIRING_PIN, 0, 100)
Beispiel #33
0
def init_wiringpi(sCon):

    wiringpi.wiringPiSetup()

    wiringpi.pinMode(sCon.mosipin, 1)
    wiringpi.pinMode(sCon.misopin, 0)
    wiringpi.pinMode(sCon.clkpin,  1)
    wiringpi.pinMode(sCon.cspin,   1)
    wiringpi.pullUpDnControl(sCon.misopin, 0)
Beispiel #34
0
def init():

    GPIO.wiringPiSetup()  
    GPIO.pinMode(pinLed, 0) # sets WP pin 6 to input  
    GPIO.pinMode(pinPwr, 1) 
    GPIO.pinMode(pin1Cup, 1) 
    GPIO.pinMode(pin2Cup, 1) 
    # mise à 1 de tous les boutons
    GPIO.digitalWrite(pinPwr, GPIO.GPIO.HIGH)
    GPIO.digitalWrite(pin1Cup, GPIO.GPIO.HIGH)
    GPIO.digitalWrite(pin2Cup, GPIO.GPIO.HIGH)
def setup():
  # Set pin directions.
  wiringpi.wiringPiSetup()
  for pin in [DC, RST]:
    wiringpi.pinMode(pin, ON)

  wiringpi.pinMode(LED,2)
  wiringpi.pwmWrite(LED,128)

  spi.open(0,0)
  spi.max_speed_hz=5000000
Beispiel #36
0
 def setup(self):
     """
     Setup to use the GPIO. 
     """
     wiringpi.wiringPiSetup()                # setup the wiringPi library 
     self.A     = self.DigitalInputPin(0)    # the rotary encorder A
     self.B     = self.DigitalInputPin(1)    # the rotary encorder B
     self.RED   = self.LED(2)                # the LED on the rotary encorder RED
     self.GREEN = self.LED(3)                # the LED on the rotary encorder GREEN
     self.SW    = self.DigitalInputPin(4)    # the push switch on the rotary encorder
     self.A.pullUp()                         # set default level HIGH
     self.B.pullUp()                         # set default level HIGH
     self.SW.pullUp()                        # set default level HIGH
Beispiel #37
0
    def __init__(self, valves, pullsocket, pushsocket):
        threading.Thread.__init__(self)
        wp.wiringPiSetup()
        time.sleep(1)
        for index in range(0, 21):  # Set GPIO pins to output
            wp.pinMode(index, 1)
            wp.digitalWrite(index, 0)
        # Now that all output are low, we can open main safety output
        wp.digitalWrite(20, 1)

        self.pullsocket = pullsocket
        self.pushsocket = pushsocket
        self.running = True
        self.valves = valves
Beispiel #38
0
	def create( self ):
		# Addresses: 0x20, 0x21, 0x22
		# Setup WIRING PI in Pin Mode
		wiringpi.wiringPiSetup()

		# Setup the chips
		wiringpi.mcp23017Setup( 65, 0x20 )
		wiringpi.mcp23017Setup( 81, 0x21 )
		wiringpi.mcp23017Setup( 97, 0x22 )

		# Setup pins on the I2C Controller chip
		for x in range( 65, 114 ):
			wiringpi.pinMode( x, 1 ) # Set pin to output
			wiringpi.digitalWrite( x, 1 ) # Set pin to off
Beispiel #39
0
def main():
    if wp.wiringPiSetup() == -1:
        print ("Unable to start wiringPi")
        sys.exit(1)

    if wp.wiringPiSPISetup(SPI_CHANNEL, SPI_SPEED) == -1:
        print ("wiringPiSPISetup Failed")
        sys.exit(1)

    wp.pinMode(CS_MCP3208, wp.OUTPUT)

    while 1:
        t = time.time()

        vt = read_adc(0)
        R = (10000*vt)/(5-vt)
        vt = 5*R/(R+10000)
        temp = -0.3167*(vt**6) + 4.5437*(vt**5) - 24.916*(vt**4) + 63.398*(vt**3) - 67.737*vt*vt - 13.24*vt + 98.432

        vh = read_adc(1)
        humidity = (((vh/5.0)-0.16)/0.0062)/(1.0546-0.00216*temp)

        print('{} Temp={}C, Humid={}%'.format(t, temp, humidity))
        data = 'rasptest temp={},hum={} {:d}'.format(temp, humidity, int(t * (10**9)))
        print("Send data to DB")
        r = requests.post('http://192.168.1.231:8086/write', auth=('mydb', 'O7Bf3CkiaK6Ou8eqYttU'), params={'db': 'mydb'}, data=data)
        print("Return status: {}", r.status_code)

        time.sleep(30)
Beispiel #40
0
def setup_gpio():
  wiringpi.wiringPiSetup()
  # Set pin directions.
# outputs :
  for pin in [DIN, SCLK, DC, RST, SCE]:
    wiringpi.pinMode(pin, OUT)
# inputs :
  for pin in [UP, RIGHT, DOWN, LEFT, SELECT]:
    wiringpi.pinMode(pin, IN)
 
# enable pull downs for the switches
  wiringpi.pullUpDnControl(UP, wiringpi.PUD_DOWN)
  wiringpi.pullUpDnControl(RIGHT, wiringpi.PUD_DOWN)
  wiringpi.pullUpDnControl(DOWN, wiringpi.PUD_DOWN)
  wiringpi.pullUpDnControl(LEFT, wiringpi.PUD_DOWN)
  wiringpi.pullUpDnControl(SELECT, wiringpi.PUD_DOWN)
 
  wiringpi.pinMode(LED,2) # pwm mode
  wiringpi.pwmWrite(LED,128) # mid-level
Beispiel #41
0
	def __init__(self, CS1, CS2, E, RS, D0, D1, D2, D3, D4, D5, D6, D7, PWM):
		self.CS1 = CS1
		self.CS2 = CS2
		self.E = E
		self.RS = RS
		self.D0 = D0
		self.D1 = D1
		self.D2 = D2
		self.D3 = D3
		self.D4 = D4
		self.D5 = D5
		self.D6 = D6
		self.D7 = D7
		self.PWM = PWM
		
		# initialize new framebuffer
		self.myFrameBuffer = Framebuffer()
		
		# setup wiringPi for backlight PWM
		wiringpi.wiringPiSetup()
		wiringpi.pinMode(self.PWM,2) # setup wiringPi pin for PWM		   
		
		GPIO.setmode(GPIO.BCM)
		
		GPIO.setup(self.CS1, GPIO.OUT, initial=0)
		GPIO.setup(self.CS2, GPIO.OUT, initial=0)
		GPIO.setup(self.E, GPIO.OUT, initial=0)
		GPIO.setup(self.RS, GPIO.OUT, initial=1)
		GPIO.setup(self.D0, GPIO.OUT, initial=0)
		GPIO.setup(self.D1, GPIO.OUT, initial=0)
		GPIO.setup(self.D2, GPIO.OUT, initial=0)
		GPIO.setup(self.D3, GPIO.OUT, initial=0)
		GPIO.setup(self.D4, GPIO.OUT, initial=0)
		GPIO.setup(self.D5, GPIO.OUT, initial=0)
		GPIO.setup(self.D6, GPIO.OUT, initial=0)
		GPIO.setup(self.D7, GPIO.OUT, initial=0)
		
		sleep(self.DELAY_E)
		self.turnOn()
		self.setStartLine(0)
		self.clearScreen()
		self.setPage(0) # start on top left
		self.setAddress(1)
def main():
    context = zmq.Context()
    socket = context.socket(zmq.SUB)
    socket.setsockopt(zmq.SUBSCRIBE, '')
    socket.connect('tcp://192.168.2.1:7777')

    wiringpi.wiringPiSetup()
    wiringpi.softPwmCreate(RED_PIN, 0, 255)
    wiringpi.softPwmCreate(GREEN_PIN, 0, 255)
    wiringpi.softPwmCreate(BLUE_PIN, 0, 255)

    while True:
        rgb = int(socket.recv())
        red = (rgb >> 16) & 0xFF
        green = (rgb >> 8) & 0xFF
        blue = rgb & 0xFF

        wiringpi.softPwmWrite(RED_PIN, red)
        wiringpi.softPwmWrite(GREEN_PIN, green)
        wiringpi.softPwmWrite(BLUE_PIN, blue)
Beispiel #43
0
	def __init__(self, dev=(0,0),speed=5000000, brightness=256, contrast=0xc0):
		self.spi = spidev.SpiDev()
		self.speed = speed
		self.dev = dev
		self.spi.open(self.dev[0],self.dev[1])
		self.spi.max_speed_hz=self.speed
		spiConfig()

		# Set pin directions.
		self.dc = DC
		self.rst = RST
		wiringpi.wiringPiSetup()
		for pin in [self.dc, self.rst]:
			wiringpi.pinMode(pin, 1)

		self.contrast=contrast
		self.brightness=brightness

		# Toggle RST low to reset.
		wiringpi.digitalWrite(self.rst, OFF)
		time.sleep(0.100)
		wiringpi.digitalWrite(self.rst, ON)
		# Initialise LCD
		# 0x21 = Function set (0x20) + Power-down mode (0x04) + Vertical addressing (0x02) + Extended instruction set (0x01)
		# 0x14 = Bias system (0x10) + BS2 (0x04) + BS1 (0x02) + BS0 (0x01)
		# 0xXX = Vop (Operation Voltage) = 0x80 + 7 bits
		# 0x20 = Back to basic instruction set
		# 0x0c = Display Control = 0x08 + 3 bits: D,0,E. 0x04 = Normal mode
		self.lcd_cmd([0x21, 0x14, self.contrast, 0x20, 0x0c])

		self.row = -1
		self.col = -1
		# Clear the screen. This will also initialise self.row and self.col
		self.cls()

		self.ledpin = LED
		if self.ledpin == 1:
			wiringpi.pinMode(self.ledpin, 2)
		else:
			wiringpi.pinMode(self.ledpin, 1)
		self.set_brightness(self.brightness)
def main():
    """ Main function """
    wp.wiringPiSetup()
    datasocket = DateDataPullSocket('furnaceroom_controller',
                                    ['temperature', 'setpoint', 'dutycycle', 'pid_p', 'pid_i'],
                                    timeouts=999999, port=9000)
    datasocket.start()

    pushsocket = DataPushSocket('furnaceroom_push_control', action='store_last')
    pushsocket.start()

    power_calculator = PowerCalculatorClass(datasocket, pushsocket)
    power_calculator.daemon = True
    power_calculator.start()

    heater = HeaterClass(power_calculator, datasocket)
    heater.start()

    tui = CursesTui(heater)
    tui.daemon = True
    tui.start()
Beispiel #45
0
	def __init__(self, keyPad=default.defaultKeyPad, row=default.row, col=default.col):
		# wiringPi instance creation
		# (print SETUP for debugging, success value is SETUP=1) 
		self.SETUP=wiringpi.wiringPiSetup()
		
		# keypad dimension vs assigned GPIO checking
		# (must be of the same m x n size)
		self.__matrixSanity(keyPad, row, col)
		
		# in class 'global' constants
		self.keyPad = keyPad
		self.row = row
		self.col = col
Beispiel #46
0
	def __init__(self, ssr):
		
		self.verbose = False
		
		self.ssr = ssr
		
		threading.Thread.__init__(self)
		
		# set up the pin in out mode
		if wiringpi_available:
			#call(["/usr/local/bin/gpio", "mode", str(ssr.pin), "out"])
			#wiringpi.wiringPiSetupSys()
			
			#rasp numbering
			wiringpi.wiringPiSetup()
			
			#gpio numbering
			#wiringpi.wiringPiSetupGpio()
			
			#set the pinmode
			wiringpi.pinMode(int(ssr.pin), 1)
		elif bbb_available:
			GPIO.setup(ssr.pin, GPIO.OUT)
			#GPIO.cleanup()

		self.daemon = True
		self.duty_cycle = 0
		self.cycle_time = 0
		self.power = 100
		self.enabled = False
		self._On = False
		
		self.pid_controller = pid_controller.pidpy(ssr.pid)
		
		#create an event so we can stop
		self._stop = threading.Event()
def RFIDSetup():
    # setup up the serial port and the wiringpi software for use
    # call setup for the wiringpi2 software
    response = wiringpi2.wiringPiSetup()
    # set the GPIO pin for input
    wiringpi2.pinMode(GPIO_PIN, 0)
    # open the serial port and set the speed accordingly
    fd = wiringpi2.serialOpen('/dev/serial0', 9600)

    # clear the serial buffer of any left over data
    wiringpi2.serialFlush(fd)
    
    if response == 0 and fd >0:
        # if wiringpi is setup and the opened channel is greater than zero (zero = fail)
        print ("PI setup complete on channel %d" %fd)
    else:
        print ("Unable to Setup communications")
        sys.exit()
        
    return fd
Beispiel #48
0
sensor_name = collections.OrderedDict()
sensor_name["041637c1bcff"]="AlexanderBedroom"
sensor_name["041637f543ff"]="GuestBedroom"
sensor_name["041637bd5bff"]="NikitaBedroom"
sensor_name["041637ffddff"]="DanielBedroom"
sensor_name["0416380260ff"]="UpstairsHall"
sensor_name["80000027968e"]="KitchenDiningRoomTheatre"
sensor_name["800000046e8c"]="GreatRoomOffice"

thermostat = { "UpstairsHall", "KitchenDiningRoomTheatre", "GreatRoomOffice", "MasterBedroom" }

sensor_avg = {}
sensor_current = {}
temp_target = {}

wpi.wiringPiSetup()
CALL_HEAT_COOL_PIN=1
HEAT_COOL_PIN=2
FAN_PIN=3

thermostat_pinlist={}
thermostat_pinlist[("GreatRoomOffice",CALL_HEAT_COOL_PIN)]=21 # brown/white
thermostat_pinlist[("GreatRoomOffice",HEAT_COOL_PIN)]=22      # orange/white
thermostat_pinlist[("GreatRoomOffice",FAN_PIN)]=23            # green/white

thermostat_pinlist[("UpstairsHall",CALL_HEAT_COOL_PIN)]=12    # brown/white
thermostat_pinlist[("UpstairsHall",HEAT_COOL_PIN)]=13         # orange/white
thermostat_pinlist[("UpstairsHall",FAN_PIN)]=14               # green/white

thermostat_pinlist[("KitchenDiningRoomTheatre",CALL_HEAT_COOL_PIN)]=6 # brown/white
thermostat_pinlist[("KitchenDiningRoomTheatre",HEAT_COOL_PIN)]=10     # orange/white
        elif shutdownBtn.is_pressed:
            shutdown()
        elif monitorBtn.is_pressed:
            toggleState()
        elif wifiBtn.is_pressed:
            wifiToggle()
        elif bluetoothBtn.is_pressed:
            bluetoothToggle()
        elif cheatBtn.is_pressed:
            showCheat()


# Initial File Setup
try:
    comboStates = readData(statePath)
    wiringpi.wiringPiSetup()
    wiringpi.pinMode(led, 2)
    wiringpi.pwmWrite(led, comboStates['brightness'])
    os.system("amixer sset -q 'PCM' " + str(comboStates['volume']) + "%")
    if comboStates['wifi'] == 1:
        os.system("sudo rfkill unblock wifi")
    else:
        os.system("sudo rfkill block wifi")
    if comboStates['bluetooth'] == 1:
        os.system("sudo rfkill unblock bluetooth")
    else:
        os.system("sudo rfkill block bluetooth")
except:
    writeData(statePath)
    wiringpi.wiringPiSetup()
    wiringpi.pinMode(led, 2)
Beispiel #50
0
import wiringpi as wiringpi
from time import sleep

pin_base = 65  # lowest available starting number is 65
i2c_addr = 0x20  # A0, A1, A2 pins all wired to GND

wiringpi.wiringPiSetup()  # initialise wiringpi
wiringpi.mcp23017Setup(pin_base, i2c_addr)  # set up the pins and i2c address

wiringpi.pinMode(65, 1)  # sets GPA0 to output
wiringpi.digitalWrite(65, 0)  # sets GPA0 to 0 (0V, off)

wiringpi.pinMode(80, 0)  # sets GPB7 to input
wiringpi.pullUpDnControl(80, 2)  # set internal pull-up

# Note: MCP23017 has no internal pull-down, so I used pull-up and inverted
# the button reading logic with a "not"

try:
    while True:
        wiringpi.digitalWrite(65, 1)  # sets port GPA1 to 1 (3V3, on)
        sleep(1)
        wiringpi.digitalWrite(65, 0)  # sets port GPA1 to 0 (0V, off)
        sleep(1)
finally:
    wiringpi.digitalWrite(65, 0)  # sets port GPA1 to 0 (0V, off)
    wiringpi.pinMode(65, 0)  # sets GPIO GPA1 back to input Mode
    # GPB7 is already an input, so no need to change anything
Beispiel #51
0
def Init():
 global timeDelay
 global theTotalDistance
 global theTotalDistanceToday
 global counter
 global theGPSDevice
 global previousGeoPoint
 global currentGeoPoint
 global previousTime
 global theVelocity
 global theBearing
 global theDate
 global previousDate
 global theTotalDistance
 global theTotalDistanceToday
 global currentTime
 global previousTime
 global mesur_dist
 global Generator_Time
 global CRPO

 CRPO = 1

#----------------------------------------------------------------#
# Init Serial port
#----------------------------------------------------------------#
 timeDelay = 10

 signal.signal(signal.SIGINT, signal_handler)
 signal.signal(signal.SIGTERM, signal_handler)

 wiringpi.wiringPiSetup()
 wiringpi.pinMode(21, 0)
 wiringpi.pinMode(22, 0)
 wiringpi.pinMode(26, 1)

 thePortNumber = ''  # hopefully this will become non-empty later
 listOfCOMPorts = list(serial.tools.list_ports.comports())
 for i in range(len(listOfCOMPorts)):
    if listOfCOMPorts[i][1][0:12] == 'USB-Serial C':
      thePortNumber = listOfCOMPorts[i][0]      # get the active/used port number
 if thePortNumber == '':
    log.info('Sorry but the GPS device is not plugged in')
    sys.exit()
 if len(sys.argv) == 1 or  len(sys.argv) == 3:
 	theGPSDevice = serial.Serial(port=thePortNumber, baudrate=4800, bytesize=8, stopbits=1, parity='N', xonxoff=False, timeout=0)
 if len(sys.argv) == 2:
 	theGPSDevice = open('/home/pi/GPS/testgps.txt', 'r')
 log.info(str_color("blue", thePortNumber))
#-----------------------------------------------#
#  Read retain from file
#-----------------------------------------------#
 try:
  outputFile_dist = open('/home/pi/GPS/retain', 'r')  # open log file
  line = outputFile_dist.readline()
  theTotalDistance = float(line)
  line = outputFile_dist.readline()
  mesur_dist = ast.literal_eval(line)
  line = outputFile_dist.readline()
  Generator_Time = ast.literal_eval(line)
  outputFile_dist.close()
  log.info("RETAIN : Get Distance from saved file " + str(theTotalDistance))
  log.info("RETAIN : Get mesure from saved file " + str(mesur_dist))
  log.info("RETAIN : Get Generator_Time from saved file " + str(Generator_Time))
 except:
  log.info("Error not get Retain")
Beispiel #52
0
import time
import wiringpi as wp # pylint: disable=F0401
from qhue import Bridge

BRIDGE_ADRESS = '192.168.1.3'
USERNAME = '******'

def main():
    bridge = Bridge(BRIDGE_ADRESS, USERNAME)

    lights = bridge.lights
    vindue = lights[14]
    print(vindue())
    #vindue.state(bri=255)
    vindue.state(on=False)
if __name__ == '__main__':

    wp.wiringPiSetup()
    while wp.digitalRead(0) == 0:
        time.sleep(0.1)
    main()
Beispiel #53
0
 def turn_on_alarm_mode(self):
     """ Keep an eye on movement and turn on all lights """
     wp.wiringPiSetup()
     self.alarm_mode = True
     print('Alarm mode_activated')
Beispiel #54
0
# ch02_04.py file

import wiringpi
import time

# initialize
wiringpi.wiringPiSetup()  # WiPi mode

# define shift reg pins
DATA = 6
LATCH = 5
CLK = 4

OUTPUT = 1
LOW = 0
HIGH = 1

# common anode digital tube 16 BCD code
LED_BCD = [0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90, 0x88, 0x83, 0xc6, 0xa1, 0x86, 0x8e]

wiringpi.pinMode(DATA, OUTPUT)
wiringpi.pinMode(LATCH, OUTPUT)
wiringpi.pinMode(CLK, OUTPUT)

# initialization
print("Initialization...")
wiringpi.digitalWrite(LATCH, LOW)
wiringpi.digitalWrite(CLK, LOW)


def LED_display(LED_number, LED_display, LED_dp):
Beispiel #55
0
#Thermostat test script This tests all functionality
import wiringpi as io
import time
import Adafruit_CharLCD as LCD
import sht31
sht31 = sht31.SHT31(0)
LOW = 0
HIGH = 1
OUTPUT = 1
RELAY = 7

io.wiringPiSetup()
io.pinMode(RELAY,OUTPUT)

lcd = LCD.Adafruit_CharLCDPlate()

# Test Relay
io.digitalWrite(RELAY,HIGH)
time.sleep(1)
io.digitalWrite(RELAY,LOW)
time.sleep(1)

# activate screen
lcd.set_color(1,1,1)
lcd.clear()
time.sleep(1)
lcd.message('Hello!')
time.sleep(1)

# initialize temp
temperature, humidity = sht31.get_temp_and_humidity()
Beispiel #56
0
    parser.add_argument("-k", "--key", help="Private key file path")

    parser.add_argument("-p", "--pin", help="gpio pin (using BCM numbering)", type=int, required=True)

    parser.add_argument("-t", "--topic", help="MQTT topic(s)", nargs='+', required=True)
    parser.add_argument("-f", "--input_file", help="input file (yaml format)", default=None)

    parser.add_argument("-l", "--log_level", help="Log Level", default=logging.INFO)

    args = parser.parse_args()

    logging.basicConfig(filename=LOG_FILE, level=args.log_level)

    subscriber = Subscriber(args.endpoint, args.rootCA, args.key, args.cert, args.clientID)

    relay.wiringPiSetup()

    # Load configuration file
    if args.input_file is not None:
        f = open(args.input_file)
        topics = yaml.safe_load(f)
        for t in topics[args.endpoint]:
            logging.info("Subscribing to {}".format(t))
            subscriber.subscribe(t, my_callback)
            time.sleep(2)  # pause between subscribes (maybe not needed?)

    for t in args.topic:
        logging.info("Subscribing to {}".format(t))
        subscriber.subscribe(t, my_callback)
        time.sleep(2)  # pause
Beispiel #57
0
    def __init__(self, communication_style = "WIFI"):
        # parameters
        self.communication_style = communication_style
        self.HOST = ''
        self.CONNECTION_PORT = 2525


        self.DRIVING_PORT = 2526
        self.DRIVING_SERVICE_UUID = "94f39d29-7d6d-437d-973b-fba39e49d4ed"

        self.SONAR_PORT = 2527

        self.CAMERA_PORT = 2528

        self.CAMERA_DRIVING_PORT = 2529
        self.CAMERA_DRIVING_SERVICE_UUID = "94f39d29-7d6d-437d-973b-fba39e49d4ec"


        # MOTORS' PINS ----> still to be set correctly
        # Nomenclature: _F : forward     _B : backward
        self.MOTOR_LEFT_F = 7
        self.MOTOR_LEFT_B = 11
        self.MOTOR_RIGHT_F = 15
        self.MOTOR_RIGHT_B = 13
        # we know map them to the wiringPi gpio map
        # http://wiringpi.com/pins/
        self.MOTOR_LEFT_F = mapGPIO2WIRINGPI(self.MOTOR_LEFT_F)
        self.MOTOR_LEFT_B = mapGPIO2WIRINGPI(self.MOTOR_LEFT_B)
        self.MOTOR_RIGHT_F = mapGPIO2WIRINGPI(self.MOTOR_RIGHT_F)
        self.MOTOR_RIGHT_B = mapGPIO2WIRINGPI(self.MOTOR_RIGHT_B)


        # STATE OF THE ROBOT
        # The possible states are:
        # IDLE : don't move
        # FORWARD : moving forward
        # BACKWARD : moving backward
        # TURNING_LEFT : turning left
        # TURNING_RIGHT : turning right
        self.state = 'IDLE'
        # Then these states are enriched by the velocity for each well
        self.MAX_SPEED = 100
        self.MIN_SPEED = 70
        self.velocity_left_weel = 0
        self.velocity_right_weel = 0

        # The "connection socket" is the one with the only aim to establish a connection to the computer
        if self.communication_style == "WIFI":
            self.connection_socket = udpsocket.UDPSocket()
            # We make all the sockets as servers here for the robot. Once they have binded they can be used for normal communication
            self.connection_socket.bind(self.CONNECTION_PORT, self.HOST)
        else:
            self.connection_socket = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
            # bind the socket to an address, this format bounds the socket to any port and any address. You can bound the socket to a specific address and a specific port.
            self.connection_socket.bind(("", bluetooth.PORT_ANY))
            # Listen to connections made to the socket. The argument specified the maximum number of queded connections. It has to be at least 0 but in that case it does not listen anyone.
            self.connection_socket.listen(1)

        # The "driving socket" has the aim to receive data regarding the driving of the robot (direction and velocity)
        if self.communication_style == "WIFI":
            self.driving_socket = udpsocket.UDPSocket()
            self.driving_socket.bind(self.DRIVING_PORT, self.HOST)
        else:
            self.driving_socket = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
            # bind the socket to an address, this format bounds the socket to any port and any address. You can bound the socket to a specific address and a specific port.
            self.driving_socket.bind(("", bluetooth.PORT_ANY))
            # Listen to connections made to the socket. The argument specified the maximum number of queded connections. It has to be at least 0 but in that case it does not listen anyone.
            self.driving_socket.listen(1)

        # The "driving socket" has the aim to receive data regarding the driving of the robot (direction and velocity)
        if self.communication_style == "WIFI":
            self.camera_driving_socket = udpsocket.UDPSocket()
            self.camera_driving_socket.bind(self.CAMERA_DRIVING_PORT, self.HOST)
        else:
            self.camera_driving_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
            # bind the socket to an address, this format bounds the socket to any port and any address. You can bound the socket to a specific address and a specific port.
            self.camera_driving_socket.bind(("", bluetooth.PORT_ANY))
            # Listen to connections made to the socket. The argument specified the maximum number of queded connections. It has to be at least 0 but in that case it does not listen anyone.
            self.camera_driving_socket.listen(1)




        # The "sonar socket" send data regarding the measurement of the SONAR
        self.sonar_socket = udpsocket.UDPSocket()
        self.sonar_socket.bind(self.SONAR_PORT, self.HOST)

        # The "picamera socket" send data regarding the picamera
        self.picamera_socket = udpsocket.UDPSocket()
        self.picamera_socket.bind(self.CAMERA_PORT, self.HOST)

        # set up the wiringPi library
        wiringpi.wiringPiSetup()
        wiringpi.pinMode(self.MOTOR_LEFT_F, 1)
        wiringpi.pinMode(self.MOTOR_LEFT_B, 1)
        wiringpi.pinMode(self.MOTOR_RIGHT_F, 1)
        wiringpi.pinMode(self.MOTOR_RIGHT_B, 1)
        wiringpi.softPwmCreate(self.MOTOR_LEFT_F, 0, 100)
        wiringpi.softPwmCreate(self.MOTOR_LEFT_B, 0, 100)
        wiringpi.softPwmCreate(self.MOTOR_RIGHT_F, 0, 100)
        wiringpi.softPwmCreate(self.MOTOR_RIGHT_B, 0, 100)

        # CAMERA SERVO MOTORS -----------------------------------
        # set pwm for servo motors (motor for the camera)
        self.yaw_motor_pin = 12
        self.pitch_motor_pin = 16
        self.PWM_FREQUENCY = 50 # Hz
        self.camera_motors_max_time = 0.3 #sec  - Maximum time to send a pwm (for noise reduction)
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(self.yaw_motor_pin, GPIO.OUT)
        GPIO.setup(self.pitch_motor_pin, GPIO.OUT)
        self.yaw_motor_pwm = GPIO.PWM(self.yaw_motor_pin,self.PWM_FREQUENCY )
        self.yaw_motor_pwm.start(0.0)
        self.pitch_motor_pwm = GPIO.PWM(self.pitch_motor_pin, self.PWM_FREQUENCY)
        self.pitch_motor_pwm.start(0.0)

        # initial angle
        self.yaw_angle = 0
        self.pitch_angle = 0
        self.PULSES2DEGREE = 180/200 # 180 degree/ 200 pulses
        self.yaw_angle_old = self.yaw_angle
        self.pitch_angle_old = self.pitch_angle
        self.new_yaw_angle = False # this is set to true when tehre is a new yaw angle
        self.new_yaw_angle_arrived = time.time() # time at which the new yaw angle arrived
        self.new_pitch_angle = False
        self.new_pitch_angle_arrived = time.time()


        # the servo motors are controlled with pulses, from 50 to 250
        # we use the term pulse because it refers to the pwm with (50=0.5ms,250=2.5ms)
        # we are going to set the zero value of the servo with the central pulse
        # ideally 50 is -90 degree and 250 is + 90 degree (- is on the rigth for the yaw, and down for the pitch)
        self.yaw_angle_zero_pulse = 140
        self.pitch_angle_zero_pulse = 145
        # iF the zero values are not perfectly calibrated to 150 we are going to center with saturation values
        self.yaw_range_pulse = min( self.yaw_angle_zero_pulse - 50, 250 - self.yaw_angle_zero_pulse)
        self.yaw_max_pulse = self.yaw_angle_zero_pulse + self.yaw_range_pulse + 50
        self.yaw_min_pulse = self.yaw_angle_zero_pulse - self.yaw_range_pulse
        self.pitch_range_pulse = min(self.pitch_angle_zero_pulse - 50, 250 - self.pitch_angle_zero_pulse)
        self.pitch_max_pulse = self.pitch_angle_zero_pulse + self.pitch_range_pulse + 50
        self.pitch_min_pulse = self.pitch_angle_zero_pulse - self.pitch_range_pulse

        # 180degree/200pulses = degree/pulses is the resolution
        self.yaw_range_degree = 180/200 * 2 * self.yaw_range_pulse
        self.pitch_range_degree = 180/200 * 2 * self.pitch_range_pulse
        self.yaw_max_angle = self.yaw_range_degree/2
        self.yaw_min_angle = - self.yaw_max_angle
        self.pitch_max_angle = self.pitch_range_degree / 2
        self.pitch_min_angle = - self.pitch_max_angle
        print "YAW/PITCH RANGES [+/-degree]: ", self.yaw_range_degree/2, "/",self.pitch_range_degree/2

        # let's give the motors 0.3s to set to the zero position
        # we have to give it some times to reach a certain position
        # but we have to stop after sometime the motors because of noise problem
        t_start = time.time()
        yaw_duty_cycle = (self.yaw_angle_zero_pulse / 1000) * self.PWM_FREQUENCY
        pitch_duty_cycle = (self.pitch_angle_zero_pulse / 1000) * self.PWM_FREQUENCY
        while time.time() - t_start <= 0.3:
            #self.yaw_motor_pwm.ChangeDutyCycle(yaw_duty_cycle)
            self.yaw_motor_pwm.ChangeDutyCycle(self.yawDegreeToDutyCycle(0.0))
            self.pitch_motor_pwm.ChangeDutyCycle(self.pitchDegreeToDutyCycle(0.0))
            #self.pitch_motor_pwm.ChangeDutyCycle(pitch_duty_cycle)
        self.yaw_motor_pwm.ChangeDutyCycle(0.0)
        self.pitch_motor_pwm.ChangeDutyCycle(0.0)
Beispiel #58
0
	def __init(self):
		self.gpio = wiringpi.wiringPiSetup()		
		wiringpi.softPwmCreate(PIN_RED,   0, LED_MAX)
		wiringpi.softPwmCreate(PIN_GREEN, 0, LED_MAX)
		wiringpi.softPwmCreate(PIN_BLUE,  0, LED_MAX)
		self.off()
Beispiel #59
0
	def __init__(self):
		self.port = None
		wiringpi.wiringPiSetup()
		wiringpi.pinMode(5,INPUT)  #Physical pin 18, BCM GPIO 24
		wiringpi.pinMode(6,OUTPUT)	#Physical pin 22, BCM GPIO 25
		wiringpi.digitalWrite(6,1)  #Set output high