def lecture_son(signal):
    for i in range(33984/Fe):
        if signal[i]>0:
            GPIO.output("P9_22", GPIO.HIGH)
        else:
            GPIO.output("P9_22", GPIO.LOW)
        time.sleep(1/Fe)
    def on_success(self, data):
        if 'text' in data:
	    print data['text'].encode('utf-8')
	    print
	    GPIO.output(LED, GPIO.HIGH)
	    time.sleep(0.5)
	    GPIO.output(LED, GPIO.LOW)
Example #3
0
 def __init__(self, pin, name=None):
     self._pin = pin
     if name:
         self._name = name
     else:
         self._name = self._pin
     GPIO.setup(self._pin, GPIO.IN)
Example #4
0
def init_LEDs():
    PWM.start(RED, 100)         # red
    PWM.start(GREEN, 100)       # green
    PWM.start(BLUE, 100)		# blue

    GPIO.setup(DOORPORT, GPIO.OUT)   # LockPort
    GPIO.output(DOORPORT, GPIO.LOW)  # Default low: locked
Example #5
0
def main():
	GPIO.setup(LED_PIN, GPIO.OUT)
	GPIO.output(LED_PIN, GPIO.LOW)
	radio = rfm69.RFM69()
	radio.initialize(FREQUENCY,NODEID,NETWORKID)
	radio.readAllRegs();
	if IS_RFM69HW:
		radio.setHighPower(IS_RFM69HW) #uncomment only for RFM69HW!

	radio.setEncryptionKey(ENCRYPTKEY)
	print "Transmitting at {} Mhz...".format(433 if FREQUENCY==rfm69.RF69_433MHZ else (868 if FREQUENCY==rfm69.RF69_868MHZ else 915))
	
	lastPeriod = 0
	sendSize = 0

	while True:
		#check for any received packets
		if (radio.receiveDone()):
			print "[{}] {} [RX_RSSI: {}]".format(radio.SENDERID, radio.DATA, radio.RSSI)
			if (radio.ACKRequested()):
				radio.sendACK()
				print " - ACK sent"
				Blink(LED_PIN, .003)

		currPeriod = radio._millis()/TRANSMITPERIOD
		if (currPeriod != lastPeriod):
			lastPeriod = currPeriod
			s = "Sending[{}]: {} ".format(sendSize, payload[:sendSize])
			if (radio.sendWithRetry(GATEWAYID, payload, sendSize, retries=RETRIES, retryWaitTime=ACK_TIME)):
				s += "ok!"
			else:
				s += "nothing..."
			print s
			sendSize = (sendSize + 1) % 31
			Blink(LED_PIN, .003)
Example #6
0
def callRight(data):
	#gets time
    time = rospy.get_time()
	#reads encoder inputs
    channelA = GPIO.input("P8_17")
    channelB = GPIO.input("P8_26")

	#puts inputs into the quadrature decoder program
    quadCalcR.update(channelA, channelB, time)
	 
	#creates messages
    rightFMSG = JointState()
    rightRMSG = JointState()
    header = Header()

    #appends velocity and position data to the joinstate message
	#front wheel
    rightFMSG.header.stamp.secs = rospy.get_time()
    rightFMSG.name.append('front_right_wheel')
    rightFMSG.position.append(quadCalcL.position)
	#rear wheel
    rightRMSG.header.stamp.secs = rospy.get_time()
    rightRMSG.name.append('rear_right_wheel')
    rightRMSG.position.append(quadCalcL.position)

	#publishes message
    pubFR.publish(rightFMSG)
    pubRR.publish(rightRMSG)
Example #7
0
    def turn_on(self):
        self._state['lastchange'] = str(datetime.datetime.today())
        print 'vars pin on', self._pin,self._on
        GPIO.output(self._pin, self._on)
        log.info('Turning {pin} on...',pin=self._pin)

        self._event_bus.publish_command(self.state)
Example #8
0
    def run(self):
        # Create new threads
        self.dialer.start()
        self.dialer.spawn()

        print 'Linphone Running: ' + str(self.dialer.isrunning())
        self.inUse = False
        while True:
            feedback = self.dialer.getLineStatus()
            if feedback == 'Incoming Call' and self.inUse is False:
                self.answerIncoming()
            elif feedback == 'Call ended':
                self.inUse = False
            else:
                pass

            if gpio.input(self.hook3) and self.dialer.isOnCall() is False and self.inUse is False and self.prevHookState == 'Low':
                self.inUse = True
                self.prevHookState = 'High'
                success = False
                while not success and gpio.input(self.hook3):
                    success = self.makeCall()
            elif not gpio.input(self.hook3) and self.prevHookState == 'High':
                if self.dialer.isOnCall():
                    self.dialer.terminateCall()
            else:
                pass
Example #9
0
def callLeft(data):
	#gets time
    time = rospy.get_time()
	#reads encoder inputs
    channelA = GPIO.input("P9_23")
    channelB = GPIO.input("P9_30")

	#puts inputs into the quadrature decoder program
    quadCalcL.update(channelA, channelB, time)
	
	#creates messages
    leftFMSG = JointState()
    leftRMSG = JointState()
    header = Header()
	
    #appends velocity and position data to the joinstate message
	#front wheel
    leftFMSG.header.stamp.secs = rospy.get_time()
    leftFMSG.name.append('front_left_wheel')
    leftFMSG.position.append(quadCalcL.position)
	#rear wheel
    leftRMSG.header.stamp.secs = rospy.get_time()
    leftRMSG.name.append('rear_left_wheel')
    leftRMSG.position.append(quadCalcL.position)
	
	#publishes message
    pubFL.publish(leftFMSG)
    pubRL.publish(leftRMSG)
Example #10
0
def display_char(char, font=FONT):
    try:
        GPIO.output(DC, GPIO.HIGH)
        writebytes(font[char]+[0])

    except KeyError:
        pass # Ignore undefined characters.
Example #11
0
 def __init__(self , note2buttons , actuatorno , isinv , chan): #initialize con lista de notas (en notacion anglosajona), numero de puchabotones necesarios, si se usa logica negada y el canal MIDI a escuchar
     self.actuatorno = actuatorno
     self.isinv = isinv
     self.chan=chan #Not implemented
     self.mid2gpio = self.__convert2Gpios(note2buttons) #obtener los gpios necesarios a encender o apagar cuando llega un msg de noteOn o noteOff
     for i in range(0 , actuatorno):
         GPIO.setup(self.bbb_gpios[i], GPIO.OUT)
Example #12
0
def selectDigit(digitArr, display):
    for i in range(0, len(digitArr)):
        comPinId = display[1][i]
        if digitArr[i] == 1:
            GPIO.output(comPinId, GPIO.LOW)
        else:
            GPIO.output(comPinId, GPIO.HIGH)
Example #13
0
    def irqWait(self):
        # A race condition may occur here.
        # TODO: Should set a timeout
        if GPIO.input(self.irq_pin) == 0:
            return

        GPIO.wait_for_edge(self.irq_pin, GPIO.FALLING)
Example #14
0
	def set_state(self, state):

		self._On = state
		_state = 0
		if state:
			_state = 1
				
		if self.verbose:
			print str(self.ssr.name) + " digitalWrite: " + str(self.ssr.pin) + " " + str(_state)
		
		#save the state
		if self.ssr.state != _state:
			self.ssr.state = _state
			self.ssr.save()

		#reverse if needed
		if self.ssr.reverse_polarity and self.enabled:
			_state = not _state

		if wiringpi2_available:
			wiringpi2.digitalWrite(int(self.ssr.pin), _state)

		elif bbb_available:
			if _state:
				GPIO.output(self.ssr.pin, GPIO.HIGH)
			else:
				GPIO.output(self.ssr.pin, GPIO.LOW)
Example #15
0
def displayDigit(segmentArr, display):
    for i in range(0, len(segmentArr)):
        pinId = display[0][i]
        if segmentArr[i] == 1:
            GPIO.output(pinId, GPIO.HIGH)
        else:
            GPIO.output(pinId, GPIO.LOW)
Example #16
0
    def tx_start(self):
        if not self.ptt_pin:
            return

        GPIO.setup(self.ptt_pin, GPIO.OUT)
        GPIO.output(self.ptt_pin, GPIO.HIGH)
        time.sleep(self.ptt_high)
def new_msg():

	pygame.display.init()
	print_echo("new CLP command")

	screen = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
	pygame.mouse.set_visible(0)
	x = 8*GPIO.input("P8_18")+4*GPIO.input("P8_16")+2*GPIO.input("P8_14")+GPIO.input("P8_12")

	# Tenta carregar a imagem do diretorio compartilhado. Caso nao consiga, carrega do diretorio interno
    	try:
        	directory_shared = "/home/debian/Desktop/shared/" + str(x) + ".png"
        	image = pygame.image.load(directory_shared)
        	print_echo(directory_shared)
    	except:
        	directory_interno = "/home/debian/Desktop/Project_display/images/" + str(x) + ".png"
        	image = pygame.image.load(directory_interno)
        	print_echo(directory_interno)

	image = pygame.transform.scale(image, (screen.get_size()[0], screen.get_size()[1]))
	back = pygame.Surface(screen.get_size())
	back = back.convert()
	back.blit(image,(0,0))
	screen.blit(back,(0,0))
	while GPIO.input("P8_11"):
		pygame.display.flip()
	#time.sleep(0.5)
	print_echo("end of command")
	pygame.display.quit()
Example #18
0
def enable(parameters = None):
    """
        Name:   enable
        Desc:   This enables the Main Power for the board.
                The board is powered on with AUX enabled.
        Params: parameters (list)
                    None
    """
    global EN

    for key in PINS.keys():
        GPIO.output(PINS[key], GPIO.LOW)
    
    GPIO.output(PINS["MAINPW_EN"], GPIO.HIGH)

    with open("EN", "wb") as ENFile:
        ENFile.write("1")

    EN = True

    time.sleep(1)

    aux([1])
    i2c = Adafruit_I2C(address, busNum)
    pll = si5338POST(i2c = i2c, regs = VCOREGS)
    
    pll._init()

    print "Main Power Enabled"
    print "Note: When finished use 'disable' or 'quit'"
Example #19
0
def setup_input(pin, pull_mode):
    """Set up a GPIO as input."""
    # pylint: disable=import-error
    from Adafruit_BBIO import GPIO
    GPIO.setup(pin, GPIO.IN,
               GPIO.PUD_DOWN if pull_mode == 'DOWN'
               else GPIO.PUD_UP)
Example #20
0
def testSwitch():
    t0 = time.time()
    GPIO.output(O_TEST, GPIO.HIGH)
    GPIO.output(O_TEST, GPIO.LOW)
    t1 = time.time()
    t2 = time.time()
    print(t1-t0, t2-t1)
Example #21
0
    def __init__(self, node_name_override = 'read_encoders'):
		#
        rospy.init_node(node_name_override)
        self.nodename = rospy.get_name()
        rospy.loginfo("Node starting with name %s", self.nodename) 
        self.rate = float(rospy.get_param("rate", 10))
        # Pines de los encoders
        self.cs1 = "P9_31"
        self.cs2 = "P9_29"
        self.do  = "P9_25"
        self.clk = "P9_23"
        #
        GPIO.cleanup()
        GPIO.setup(self.cs1, GPIO.OUT)
        GPIO.setup(self.cs2, GPIO.OUT)
        GPIO.setup(self.do,  GPIO.IN)
        GPIO.setup(self.clk, GPIO.OUT)
        #
        self.closeComm(self.cs1)
        self.closeComm(self.cs2)
        #
        self.e1val = 0
        self.e2val = 0
        #
        self.e1Pub = rospy.Publisher("e1", Int16)
        self.e2Pub = rospy.Publisher("e2", Int16)
Example #22
0
def setup_input(pin, pull_mode):
    """Setup a GPIO as input."""
    # pylint: disable=import-error,undefined-variable
    import Adafruit_BBIO.GPIO as GPIO
    GPIO.setup(pin, GPIO.IN,                            # noqa: F821
               GPIO.PUD_DOWN if pull_mode == 'DOWN'     # noqa: F821
               else GPIO.PUD_UP)                        # noqa: F821
Example #23
0
 def _setup_gpio(self):
     """Initialize GPIO pins"""
     GPIO.setup(self.dir1Pin[LEFT], GPIO.OUT)
     GPIO.setup(self.dir2Pin[LEFT], GPIO.OUT)
     GPIO.setup(self.dir1Pin[RIGHT], GPIO.OUT)
     GPIO.setup(self.dir2Pin[RIGHT], GPIO.OUT)
     GPIO.setup(self.led, GPIO.OUT)
Example #24
0
def screenInit():
    #GPIO.output(SCE, GPIO.LOW)
    time.sleep(0.050)
    # Toggle RST low to reset.
    GPIO.output(RST, GPIO.LOW)
    time.sleep(0.100)
    GPIO.output(RST, GPIO.HIGH)
Example #25
0
    def __init__(self, baseIP, robotIP):

        # Initialize GPIO pins
        GPIO.setup(self.dir1Pin[LEFT], GPIO.OUT)
        GPIO.setup(self.dir2Pin[LEFT], GPIO.OUT)
        GPIO.setup(self.dir1Pin[RIGHT], GPIO.OUT)
        GPIO.setup(self.dir2Pin[RIGHT], GPIO.OUT)

        GPIO.setup(self.ledPin, GPIO.OUT)

        # Initialize PWM pins: PWM.start(channel, duty, freq=2000, polarity=0)
        PWM.start(self.pwmPin[LEFT], 0)
        PWM.start(self.pwmPin[RIGHT], 0)

        # Set motor speed to 0
        self.setPWM([0, 0])

        # Initialize ADC
        ADC.setup()
        self.encoderRead = encoderRead(self.encoderPin)

        # Set IP addresses
        self.baseIP = baseIP
        self.robotIP = robotIP
        self.robotSocket.bind((self.robotIP, self.port))
Example #26
0
 def moveUP(self):
     PWM.start(self.pwmPIN, self.duty, self.freq, 0)
     GPIO.output(self.upDIR, GPIO.HIGH)
     status = 1
     print "Moving motor UP"
     time.sleep(1.5)
     return status
Example #27
0
 def moveDOWN(self):
     PWM.start(self.pwmPIN, self.duty, self.freq, 0)
     GPIO.output(self.downDIR, GPIO.HIGH)
     status = 0
     print "Moving motor DOWN"
     time.sleep(1.5)
     return status
def ButtonFunction(void):
    global alertFlag
    print "ButtonFunction"
    if alertFlag == 0:
        alertFlag = 1
        alertTime = time.time()+60
        GPIO.output(led,GPIO.LOW)
Example #29
0
 def set_beeper(self, value):
     if value:
         if gpio_available:
             GPIO.output(config.gpio_beeper, GPIO.HIGH)
     else:
         if gpio_available:
             GPIO.output(config.gpio_beeper, GPIO.LOW)
def hold():
  GPIO.output(ledPin, GPIO.HIGH)
  printer.printImage(Image.open('gfx/goodbye.png'), True)
  printer.feed(3)
  subprocess.call("sync")
  subprocess.call(["shutdown", "-h", "now"])
  GPIO.output(ledPin, GPIO.LOW)
Example #31
0
import Adafruit_BBIO.PWM as PWM
import Adafruit_BBIO.GPIO as GPIO
import time

GPIO.setup("P8_12", GPIO.IN)
old_switch_state = 0
servo_pin = "P8_19"
duty_min = 3
duty_max = 14.5
duty_span = duty_max - duty_min
flag = 0
PWM.start(servo_pin, (100 - duty_min), 60.0, 1)

while True:
    new_switch_state = GPIO.input("P8_12")
    if new_switch_state == 1 and old_switch_state == 0:
        time.sleep(0.2)
        flag = flag + 1
        print(flag)
    angle = flag * 45

    angle_f = float(angle)
    duty = 100 - ((angle_f / 180) * duty_span + duty_min)
    PWM.set_duty_cycle(servo_pin, duty)
Example #32
0
def disp2(t):
    if (t == 1):
        GPIO.output(disp21, GPIO.LOW)
        GPIO.output(disp22, GPIO.LOW)
        GPIO.output(disp23, GPIO.LOW)
        GPIO.output(disp24, GPIO.HIGH)
    elif (t == 2):
        GPIO.output(disp21, GPIO.LOW)
        GPIO.output(disp22, GPIO.LOW)
        GPIO.output(disp23, GPIO.HIGH)
        GPIO.output(disp24, GPIO.LOW)
    elif (t == 3):
        GPIO.output(disp21, GPIO.LOW)
        GPIO.output(disp22, GPIO.LOW)
        GPIO.output(disp23, GPIO.HIGH)
        GPIO.output(disp24, GPIO.HIGH)
    elif (t == 4):
        GPIO.output(disp21, GPIO.LOW)
        GPIO.output(disp22, GPIO.HIGH)
        GPIO.output(disp23, GPIO.LOW)
        GPIO.output(disp24, GPIO.LOW)
    elif (t == 5):
        GPIO.output(disp21, GPIO.LOW)
        GPIO.output(disp22, GPIO.HIGH)
        GPIO.output(disp23, GPIO.LOW)
        GPIO.output(disp24, GPIO.HIGH)
    elif (t == 6):
        GPIO.output(disp21, GPIO.LOW)
        GPIO.output(disp22, GPIO.HIGH)
        GPIO.output(disp23, GPIO.HIGH)
        GPIO.output(disp24, GPIO.LOW)
    elif (t == 7):
        GPIO.output(disp21, GPIO.LOW)
        GPIO.output(disp22, GPIO.HIGH)
        GPIO.output(disp23, GPIO.HIGH)
        GPIO.output(disp24, GPIO.HIGH)
    elif (t == 8):
        GPIO.output(disp21, GPIO.HIGH)
        GPIO.output(disp22, GPIO.LOW)
        GPIO.output(disp23, GPIO.LOW)
        GPIO.output(disp24, GPIO.LOW)
    elif (t == 9):
        GPIO.output(disp21, GPIO.HIGH)
        GPIO.output(disp22, GPIO.LOW)
        GPIO.output(disp23, GPIO.LOW)
        GPIO.output(disp24, GPIO.HIGH)
    elif (t == 0):
        GPIO.output(disp21, GPIO.LOW)
        GPIO.output(disp22, GPIO.LOW)
        GPIO.output(disp23, GPIO.LOW)
        GPIO.output(disp24, GPIO.LOW)
    elif (t == 10):
        GPIO.output(disp11, GPIO.HIGH)
        GPIO.output(disp12, GPIO.HIGH)
        GPIO.output(disp13, GPIO.HIGH)
        GPIO.output(disp14, GPIO.HIGH)
    return
Example #33
0
disp34 = "P8_19"  #LSB

disp41 = "P9_21"  #MSB
disp42 = "P9_16"
disp43 = "P9_15"
disp44 = "P9_14"  #LSB

x = 0
#This is the value of state
t = 0
#This is the value to be displayed
st = 5
#This is the time for each signal state

#Setup mode for leds of particular mode
GPIO.setup(road1r, GPIO.OUT)
GPIO.setup(road1y, GPIO.OUT)
GPIO.setup(road1g, GPIO.OUT)
GPIO.setup(road2r, GPIO.OUT)
GPIO.setup(road2y, GPIO.OUT)
GPIO.setup(road2g, GPIO.OUT)
GPIO.setup(road3r, GPIO.OUT)
GPIO.setup(road3y, GPIO.OUT)
GPIO.setup(road3g, GPIO.OUT)
GPIO.setup(road4r, GPIO.OUT)
GPIO.setup(road4y, GPIO.OUT)
GPIO.setup(road4g, GPIO.OUT)
#Setup mode for displays
GPIO.setup(disp11, GPIO.OUT)
GPIO.setup(disp12, GPIO.OUT)
GPIO.setup(disp13, GPIO.OUT)
Example #34
0
def teardown_module(module):
    GPIO.cleanup()
Example #35
0
 def test_direction_readback(self):
     GPIO.setup("P8_10", GPIO.IN)
     direction = GPIO.gpio_function("P8_10")
     assert direction == GPIO.IN
Example #36
0
 def release_pump(self):
     GPIO.cleanup()
Example #37
0
 def cleanup(self):
     GPIO.cleanup()
Example #38
0
def step(pin):
    GPIO.output(pin, GPIO.HIGH)
    time.sleep(1E-3)
    GPIO.output(pin, GPIO.LOW)
    time.sleep(1E-3)
Example #39
0
def do_tck(state):
    global TCK
    GPIO.output(TCK, state)
Example #40
0
THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------

UPDATES THIS PART

--------------------------------------------------------------------------
"""

# ------------------------------------------------------------------------
# Constants
# ------------------------------------------------------------------------

import Adafruit_BBIO.GPIO as GPIO
import time

# ------------------------------------------------------------------------
# Global variables
# ------------------------------------------------------------------------

GPIO.setup("USR3", GPIO.OUT)

# ------------------------------------------------------------------------
# Main script
# ------------------------------------------------------------------------

while True:
        GPIO.output("USR3", GPIO.HIGH)
        time.sleep(0.1)
        GPIO.output("USR3", GPIO.LOW)
        time.sleep(0.1)
Example #41
0
def do_tdo():
    global TDO
    return '0' if GPIO.input(TDO) == GPIO.LOW else '1'
Example #42
0
#!/usr/bin/python
import serial
import Adafruit_BBIO.GPIO as GPIO
import time
import math

# initialize serial port
# ser1 = serial.Serial('/dev/ttyUSB0', 9600)
# ser2 = serial.Serial('/dev/ttyUSB1', 9600)
# wrong usb ports, dont replug, reboot and pray
ser2 = serial.Serial('/dev/ttyUSB0', 9600)
ser1 = serial.Serial('/dev/ttyUSB1', 9600)

# initialize GPIOs
# Motor1 step
GPIO.setup("P8_8", GPIO.OUT)
# Motor1 direction
GPIO.setup("P8_10", GPIO.OUT)
# Motor2 step
GPIO.setup("P8_12", GPIO.OUT)
# Motor2 direction
GPIO.setup("P8_14", GPIO.OUT)

# some variables
delta = 100


# single step on rising edge
def step(pin):
    GPIO.output(pin, GPIO.HIGH)
    time.sleep(1E-3)
Example #43
0
"""
# UART TX (GPIO_15) / RX (GPIO_14)
config-pin P9.24 uart
config-pin P9.26 uart
# GPIO
config-pin P8.07 gpio
config-pin P8.08 gpio
config-pin P8.09 gpio
config-pin P8.10 gpio
"""
TDI = "P8_7"  # GPIO_66 / A4
TDO = "P8_8"  # GPIO_67 / A5
TCK = "P8_9"  # GPIO_69 / A2
TMS = "P8_10"  # GPIO_68 / A3

GPIO.setup(TDI, GPIO.OUT)
GPIO.setup(TDO, GPIO.IN)
GPIO.setup(TCK, GPIO.OUT)
GPIO.setup(TMS, GPIO.OUT)

PASSWORD_FILE = 'passwords'


def cleanup(signal, frame):
    global STOP
    STOP = True


signal.signal(signal.SIGINT, cleanup)

Example #44
0
def do_tms(low):
    global TMS
    GPIO.output(TMS, GPIO.LOW if low else GPIO.HIGH)
import Adafruit_BBIO.GPIO as GPIO
import time
import signal
import sys
import multiprocessing
import random

pins = [7, 8, 9, 10, 11, 12, 14, 16]
processes = []

for pin in pins:
    GPIO.setup("P8_%s" % pin, GPIO.OUT)
    GPIO.output("P8_%s" % pin, GPIO.HIGH)


def signal_handler(signal, frame):
    print '\nCaught interrupt, cleaning up...'
    for process in processes:
        process.terminate()
    for pin in pins:
        GPIO.output("P8_%s" % pin, GPIO.HIGH)
    sys.exit(0)


signal.signal(signal.SIGINT, signal_handler)


def pin_process(pin):
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    while 1:
        rand_time = random.random()
Example #46
0
def do_tdi(b):
    global TDI
    GPIO.output(TDI, GPIO.LOW if b == '0' else GPIO.HIGH)
Example #47
0
import Adafruit_BBIO.GPIO as GPIO 
import time 
import requests 
import json 

stationID = "123"
url = "http://192.168.1.79:5000/api/stationstate/" + stationID

GPIO.setup("PB_1O", GPIO.OUT) # GPIO - 68 

onStatus = False 

while True:
	r = requests.get(url)
	r = str(r.text)
	result = json.loads(r)

	if (onStatus == False):
		if (results[0] == True):
			print "Switch ON"
			onStatus = True 
			GPIO.output("PB_1O", GPIO.LOW)
	elif (onStatus == True):
		if (result[0] == True):
			print "Switch OFF"
			onStatus = False
			GPIO.output("PB_1O", GPIO.HIGH)

	time.sleep(2)
Example #48
0
import Adafruit_BBIO.GPIO as GPIO
from flask import Flask, render_template, request
app = Flask(__name__)
led = "P8_10"
GPIO.setup(led, GPIO.OUT)


@app.route('/switch.html', methods=['GET', 'POST'])
def change_LED_state():
    if request.method == 'POST':
        current_state = request.form['state']
        print current_state
        if (current_state == 'on'):
            GPIO.output(led, GPIO.HIGH)
        elif (current_state == "off"):
            GPIO.output(led, GPIO.LOW)
    return render_template('switch.html')


app.run('0.0.0.0', 3005)
Example #49
0
 def __init__(self):
     GPIO.setup(self.M1_IN1, GPIO.OUT)
     GPIO.setup(self.M1_IN2, GPIO.OUT)
     GPIO.setup(self.MLeft_IN1, GPIO.OUT)
     GPIO.setup(self.MLeft_IN2, GPIO.OUT)
     GPIO.setup(self.MRight_IN1, GPIO.OUT)
     GPIO.setup(self.MRight_IN2, GPIO.OUT)
     print("UAV __init__ has been executed!")
Example #50
0
 def power_off(self=None):
     logging.debug("[ADC] Powering the ADC off")
     GPIO.output("P9_18", GPIO.LOW)
     self.close_file()
     self.stop_gps_polling()
Example #51
0
def main():
    GPIO.setup(leds, GPIO.OUT)
    GPIO.output(leds, GPIO.HIGH)

    lcm_.subscribe("/rgb_leds", rgb_led_callback)
    run_coroutines(lcm_.loop(), publish_rgb_readings())
from flask_cors import CORS


def convertToU16(value, little_endian=True):
    value = value & 0xFFFF

    if not little_endian:
        value = ((value << 8) & 0xFF00) + (value >> 8)
    return value


workshop.setPinMux("P9_29", "gpio")
workshop.setPinMux("P9_19", "i2c")
workshop.setPinMux("P9_20", "i2c")
GPIO.setup("P9_29", GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

ADC.setup()

bus = smbus.SMBus(2)  ## Solution

TSL2561_I2C_ADDR = (0x29)  # Default address (pin left floating)

TSL2561_COMMAND_BIT = (0x80)  # Must be 1
TSL2561_WORD_BIT = (0x20)  # 1 = read/write word (rather than byte)

TSL2561_CONTROL_POWERON = (0x03)
TSL2561_CONTROL_POWEROFF = (0x00)

TSL2561_REGISTER_CONTROL = 0x00
Example #53
0
    def __init__(self, PORT, SPI):
        #Configurações iniciais
        self.spi = SPI
        self.port = PORT
        GPIO.setup(self.port, GPIO.OUT)
        GPIO.output(self.port, 1)

        #Configuração do ADC
        GPIO.output(self.port, 0)
        self.spi.xfer2([0xff, 0xff])
        GPIO.output(self.port, 1)

        #Envio de setup inicial
        GPIO.output(self.port, 0)
        self.spi.xfer2([0x83, 0x10])
        GPIO.output(self.port, 1)
Example #54
0
    def __stop(self):
        GPIO.cleanup()

        self.serialPort.close()
Example #55
0
import time
import dac
#-------------------------------------------------------
# initialize the bus and device /dev/spidev1.0
spi0 = SPI(0, 0)
#defining mode (CPOL = 0; CPHA = 1)
spi0.mode = 1
#defining speed (in bps)
spi0.msh = 10000000
#-------------------------------------------------------
# mnemonics for GPIO
BUSY = "P9_20"
CNV = "P9_23"
#-------------------------------------------------------
# defining outputs
GPIO.setup(CNV, GPIO.OUT)
#-------------------------------------------------------
# defining inputs
GPIO.setup(BUSY, GPIO.IN)
#-------------------------------------------------------
# initialization of outputs
GPIO.output(CNV, GPIO.LOW)
#=======================================================
#    ADC calibration parameters
#=======================================================
# global variables
global GAIN
global OFFSET
global REFERENCE
#REFERENCE = 13107
#GAIN = 1
Example #56
0
def commandlistener(cmdmessage):
    GPIO.setup(OUT_PIN, GPIO.OUT)
    GPIO.setup(IN_PIN, GPIO.IN)
    rospy.sleep(2)
    msg = EFStatus()
    msg.status = msg.EF_BUSY
    pub.publish(msg)

    if (cmdmessage.command == cmdmessage.CMD_GRAB):
        #initialize suckage
        GPIO.output(OUT_PIN, GPIO.HIGH)
        #reset servo just in case
        angle = 0.0
        #move in to grab
        while ((not GPIO.input(IN_PIN)) and (angle < ANGLE_LOWERED)):
            dutycyc = MINDUT + (MAXDUT - MINDUT) * (angle / SERVOMAX)
            PWM.start(SERVO_PIN, dutycyc, SERVO_FREQUENCY, 0)
            angle += 5
            rospy.sleep(0.25)
        if GPIO.input(IN_PIN):
            #we have contacted something
            #carefully retract
            while ((angle > ANGLE_RAISED)):
                dutycyc = MINDUT + (MAXDUT - MINDUT) * (angle / SERVOMAX)
                PWM.start(SERVO_PIN, dutycyc, SERVO_FREQUENCY, 0)
                angle -= 5
                rospy.sleep(0.5)
        if not (GPIO.input(IN_PIN)):
            #we dropped it or never got it in the first place
            while ((angle > ANGLE_RAISED)):
                dutycyc = MINDUT + (MAXDUT - MINDUT) * (angle / SERVOMAX)
                PWM.start(SERVO_PIN, dutycyc, SERVO_FREQUENCY, 0)
                angle -= 5
                rospy.sleep(0.5)
            #for now, retract as usual
        #we made it this far, this probably still have it
        msg = EFStatus()
        msg.status = msg.EF_READY
        pub.publish(msg)
    else:
        #kinda like in reverse
        GPIO.output(OUT_PIN, GPIO.LOW)  #end suckage
        #reset angle
        angle = 0.0
        dutycyc = MINDUT + (MAXDUT - MINDUT) * (angle / SERVOMAX)
        PWM.start(SERVO_PIN, dutycyc, SERVO_FREQUENCY, 0)
        msg = EFStatus()
        msg.status = msg.EF_READY
        pub.publish(msg)
Example #57
0
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# Toggeln des GPIO P9_25 (GPIO 117) ueber die Adafruit_BBIO-Bibliothek.

# S. Mack, 5.3.20

import Adafruit_BBIO.GPIO as GPIO
import time
import sys

print("Python-Interpreter: {}\n".format(sys.version))

pin = "P9_25"

GPIO.setup(pin, GPIO.OUT)
print("Pin enabled...")

try:
    while True:
        GPIO.output(pin, GPIO.HIGH)
        time.sleep(0.5)
        GPIO.output(pin, GPIO.LOW)
        time.sleep(0.5)
except KeyboardInterrupt:
    print("")
    GPIO.output(pin, GPIO.LOW)
    print("...Pin disabled.")
    print("Byebye...")
Example #58
0
def calibration():
    # global variables
    global GAIN, OFFSET, REFERENCE
    # set up DAC
    dac.config()
    calibration = [-9, 9]
    total_measures = 10000
    # defining variables for MAX, MIN and MEAN (ADC measure)
    min_adc = [0] * 5
    max_adc = [0] * 5
    mean_adc = [0] * 5
    std_var = [0] * 5
    i = 0
    j = 0
    ############################################################
    interval = []
    for x in calibration:
        measure = []
        #print "  ============================================================================"
        #print "  |                           CALIBRATION:                                   |"
        #print "  ============================================================================"

        # select DAC and write correspondent value
        base = int(((x + 10) / (20 / float(262144))))
        interval.append(base)
        dac.write(base)
        time.sleep(30)
        measure = []
        for i in range(total_measures):
            #------------------------------------------------------
            # "adc_value = read()" without considering previous calibration
            # CNVST = 0 --> start conversion
            GPIO.output(CNV, GPIO.LOW)
            # bring CNVST back to "1" state
            GPIO.output(CNV, GPIO.HIGH)
            # read three bytes
            data = spi0.readbytes(3)
            adc_value = (data[0] << 10) + (data[1] << 2) + (data[2] >> 6)
            #------------------------------------------------------
            measure.append(adc_value)
            # check if it is the first measure
            if (i == 0):
                min_adc[j] = measure[0]
                max_adc[j] = measure[0]
                mean_adc[j] = measure[0] * 1.0
            # if not, calculate max, min and mean
            else:
                if (measure[i] < min_adc[j]):
                    min_adc[j] = measure[i]
                if (measure[i] > max_adc[j]):
                    max_adc[j] = measure[i]
                mean_adc[j] = (mean_adc[j] * i + measure[i]) / (i + 1)
            i += 1
            adc_volt = float(adc_value) / 262143 * 20 - 10
            adc_volt_str = str(adc_volt)
            adc_volt_str = adc_volt_str[0:adc_volt_str.find(".") + 8]
            #sys.stdout.write("  | " + str(adc_value) + "\t" + str(adc_value) + "\t\t\t\t\t\t\t" + "|" + "\n")
        j += 1
    REFERENCE = mean_adc[0]
    # calculating gain correction
    theoretical_step = 20.0 / 262143
    calibrated_step = 18.0 / (mean_adc[1] - mean_adc[0])
    GAIN = calibrated_step / theoretical_step
    # calculating offset correction (around code 131072, 0V)
    interval = 9.0 / theoretical_step
    OFFSET = 131072 - interval - mean_adc[0]
    # return two parameters: gain and offset
    #output = [REFERENCE, GAIN, OFFSET]
    print "\treference = " + str(REFERENCE)
    print "\tgain = " + str(GAIN)
    print "\toffset = " + str(OFFSET)
Example #59
0
import sys
import numpy as np
import Adafruit_BBIO.GPIO as GPIO
import time
import smbus

bus = smbus.SMBus(2)  # Use i2c bus 1
matrix = 0x70  # Use address 0x70

newcur_y = 1
newcur_x = 0
cur_x = 0
cur_y = 1

#setting up the GPIO pins that the buttons are using
GPIO.setup("P9_11", GPIO.IN)  #left
GPIO.setup("P9_13", GPIO.IN)  #right
GPIO.setup("P9_23", GPIO.IN)  #up
GPIO.setup("P9_17", GPIO.IN)  #down
GPIO.setup("P9_27", GPIO.IN)  #clear
GPIO.setup("P9_24", GPIO.IN)  #exit
#initilizing button events
GPIO.add_event_detect("P9_11", GPIO.FALLING)
GPIO.add_event_detect("P9_13", GPIO.FALLING)
GPIO.add_event_detect("P9_23", GPIO.FALLING)
GPIO.add_event_detect("P9_17", GPIO.FALLING)
GPIO.add_event_detect("P9_27", GPIO.FALLING)
GPIO.add_event_detect("P9_24", GPIO.FALLING)

print(
    "Welcome to Etch-A-Sketch! To start playing simply enter the dimensions ",
Example #60
0
    display(roundconfig['instructions'], 20, 0)
    for ctrlid in controlids:
        controlsetup = roundconfig[ctrlid]
        lcdwrite(controlsetup['name'], ctrlid)
        #there's more to setup of course


def displayBar(num):
    lcd[0].setCursor(0, 3)
    lcd[0].message(chr(255) * num + ' ' * (20 - num))


#LCDs share a data bus but have different enable pins
for i in range(3):
    lcd[i].pin_e = lcdpins[i]
    GPIO.setup(lcdpins[i], GPIO.OUT)
    GPIO.output(lcdpins[i], GPIO.LOW)

lcd[0].begin(20, 4)
display("Awaiting instructions!", 20, 0)
lcd[1].begin(16, 2)
display("Ready control 1!", 16, 1)
lcd[2].begin(16, 2)
display("Ready control 2!", 16, 2)

for i in range(21):
    displayBar(i)

for i in range(21):
    displayBar(20 - i)