Beispiel #1
0
    def setup(self, opts):
        self.tz = opts.get('Timezone')
        self.rate = float(opts.get('Rate', 1))
        ADC.setup()

        self.add_timeseries('/humidityLO', 'V', data_type="double",timezone=self.tz)
        self.add_timeseries('/humidityHI', 'V', data_type="double",timezone=self.tz)
Beispiel #2
0
    def __init__(self, pins=["P9_27", "P8_15", "P8_11", "P8_12"]):

        # creates pins for the stepper motors
        self.pins = pins

        # initlizes the pins for stepper
        initialize_pins(self.pins)
        set_all_pins_low(self.pins)

        # sets angle to 0
        self.angle = 0

        # Initialize stepping mode
        self.drivemode = fullstep

        # sets up ADC
        ADC.setup()
        # cretes a value for the threshold
        self.threshold = 0.7
        # creates a variable for the distance measurment
        self.distance = 0
        # creates a variable for the last ir sensor read
        self.lastval = 1

        # creates a variable for the ROS message and initilizes constant parameters
        self.msg = LaserScan()
        self.header = Header()

        self.msg.angle_increment = 0.015708
        self.msg.range_min = 0
        self.msg.range_max = 10
Beispiel #3
0
    def __init__(self, data, write, cs, clk, a=1, debug=False):

        self.data = data
        self.write = write
        self.cs = cs
        self.clk = clk
        self.numdisp = a
        self.chip_max = 4 * self.numdisp

        self.y_max = 16
        self.x_max = 32*self.numdisp

        self.shadowram = np.zeros((64, 8), dtype=int)

        GPIO.setup(self.data, GPIO.OUT)
        GPIO.setup(self.write, GPIO.OUT)
        GPIO.setup(self.cs, GPIO.OUT)
        GPIO.setup(self.clk, GPIO.OUT)

        ADC.setup()

        self.debug = debug

        #GPIO.cleanup()
        if self.debug:
            print ("GPIOs exported!")

        self.setup()
def getVoltage():

    ADC.setup()
    adc = 0.0

    for i in range(MEASURE_POINTS) :
        adc = adc + ADC.read(voltagePin)

    adc /= MEASURE_POINTS

    if adc<0.405:
        return "low"
    if adc>0.565:
        return "high"

    adc = "{0:.2f}".format(adc)



    try:
        voltage = adcToVoltage[adc]
    except:
        return "error"


    return str(voltage)
Beispiel #5
0
def IR_call():
  #Sets up the ADC pins which we will need to read the raw voltage of the IR sensor
  ADC.setup()
  pub = rospy.Publisher('/range', Range, queue_size=10)
  rospy.init_node('Range_Finder')
  r = rospy.Rate(5) #Sets the code to be executed 5 times per second
  IR.header.frame.id = "inertial_link"
  # Radiation value is set to 1 because the SHARP sensor is an infared sensor
  IR.radiation_type = 1
  # the field of view was set to 20 degrees but the value ha to be provided in 
  IR.field_of_view = 3.14/9.0
  # Minimum distance is set to 15 cm in order to avoid confusion where voltage could have two corresponding distances
  IR.min_range = 0.15
  # Maximum distance is 150 cm as sepcified by the spec sheet
  IR.Max_range = 1.50
  #Initalize IR sensor to have no value 
  IR.range = None
  while not rospy.is_shutdown():
    # We are going to use pin P9_39 because it worked and was used in the last assignment
    # Want to store the data as a float so it can be used to find the distance
    value = float(ADC.read_raw("P9_39")) 
    # Converts the voltage to distance by using an equation derived from the IR spec sheet
    # Distance to voltage was best modeled as a 4th degree polynomial
    distance = (20.065 * (value ** 4) - 155.71 * (value ** 3) + 443.24 * (value ** 2) - 570.96 * value + 324.71) * 100
    # Stores the distance conversion as the range
    IR.range = distance 
    rospy.loginfo(IR)
    # Publishes the data of the IR sensor
    pub.publish(IR)
    r.sleep()
Beispiel #6
0
	def task(self):
		ADC.setup()
		while not self.stop.isSet():
			try: 				        
				value = ADC.read_raw(self.pin) 
				now = datetime.datetime.now()
				print  self.protocol + "%f : %d : %d : %d "%(value,now.minute,now.second,now.microsecond)
				val = str(value)
				date = str(now.minute) + ":" + str(now.second) + ":" + str(now.microsecond)
				
				data = {'data':val,'sensor_code':self.sensor_code, 'date':date}
				string_data = json.dumps(data)
				
				if global_module.mode == 0:
			            global_module.wifi_namespace_reference.on_send(data)
				else:
				    #print "usb is sending"
				    global_module.ep_out.write(string_data.encode('utf-8'),timeout=0)
				if self.isLogging:
					self.log_file.write(val + " : " + date + "\n")
				sleep(self.rate);
				
			except Exception as e:
				print e;
				self.log_file.write(e);
				self.log_file.close();
				e_msg = "Sorry! Unable to read Analog Data"
				print e_msg
				if global_module.mode == 0:
			            global_module.wifi_namespace_reference.on_error(e_msg)
				else:
				    global_module.ep_out.write(e_msg.encode('utf-8'),timeout=0)
Beispiel #7
0
    def __init__(self, probe_pin, sh_a, sh_b, sh_c):
        """
        Initializes the controller for a temperature probe

        :param probe_pin: The BBB ADC pin to use, e.g. P9_39
        :type probe_pin: str
        :param sh_a: The Steinhart-Hart A coefficient
        :type sh_a: float
        :param sh_b: The Steinhart-Hart B coefficient
        :type sh_b: float
        :param sh_c: The Steinhart-Hart C coefficient
        :type sh_c: float
        """
        self._sh_a = sh_a
        self._sh_b = sh_b
        self._sh_c = sh_c

        self._probe_pin = probe_pin
        self._ema_temp = None
        self._last_temp = None

        ADC.setup()

        # Take a temperature immediately
        self._take_temperature()

        # Setup a periodic call every 1 second to take the temperature
        self._periodic_temp = tornado.ioloop.PeriodicCallback(
            self._take_temperature,
            SAMPLE_PERIOD * 1000)
        self._periodic_temp.start()
Beispiel #8
0
    def __init__(self, leftMotorPinList, rightMotorPinList, irPinList):

        print 'Initializing QuickBot - Running directly on the BeagleBone'

        # Initialize GPIO pins
        print 'Initializing GPIO pins'

        self.leftMotorPinList = leftMotorPinList
        self.rightMotorPinList = rightMotorPinList
        self.irPinList = irPinList
        #        self.coeffs = [-274.082,467.0223,-270.152,61.9435]  #coeffs of dis-vol function of ir
        #	self.coeffs=[-549586.614410014,2408274.92579189,-4572372.37077631,4929699.72432297,-3323046.43395288,1452630.42510176,-412767.715611524,74027.2686432297,-3323046.43395288,1452630.42510176,-412767.715611524,74027.2686459216,-7743.85714142088,386.267432882943]
        self.coeffs = [
            -2440.04872226593, 6350.17325967952, -6443.65540697229,
            3219.06585379877, -818.085638692615, 97.2435572925929
        ]
        self.compass = Compass()

        GPIO.setup(self.leftMotorPinList[0], GPIO.OUT)  #set pin as output
        GPIO.setup(self.leftMotorPinList[1], GPIO.OUT)

        GPIO.setup(self.rightMotorPinList[0], GPIO.OUT)
        GPIO.setup(self.rightMotorPinList[1], GPIO.OUT)

        # set the dir pins low
        GPIO.output(self.leftMotorPinList[0], GPIO.LOW)  #set output value LOW
        GPIO.output(self.leftMotorPinList[1], GPIO.LOW)

        GPIO.output(self.rightMotorPinList[0], GPIO.LOW)
        GPIO.output(self.rightMotorPinList[1], GPIO.LOW)

        # setup ADC
        print 'Setting Up ADC'
        ADC.setup()
Beispiel #9
0
 def __init__(self,pin):
     
     # Initialize ADC
     ADC.setup()
     
     # Set pin
     self.pin = pin
def GPIOlightRead():
  ADC.setup() 
  value =  ADC.read("P9_33")
  if value >= 0.3: # state of turn on the romm's light
    return 1
  else:
    return 0
def monitor_sensor():
    """Read the sensor value and detect an alarm condition."""

    logger.info("Starting to monitor sensor")
    post_to_twitter("Door Entry Alarm: started")
    ADC.setup()

    # start with door in closed state
    is_open = False
    logger.info("Door closed")
    post_to_twitter("Door closed")

    samples_counter = 0
    while True:
        reading = ADC.read(SENSOR_PIN)
        if is_open == False:
            if reading > SENSOR_THRESHOLD:
                samples_counter += 1
                if samples_counter >= SAMPLES_REQUIRED:
                    is_open = True
                    logger.info("Door opened")
                    post_to_twitter("Door opened")
                    samples_counter = 0
            else:
                samples_counter = 0
        elif is_open == True:
            if reading <= SENSOR_THRESHOLD:
                is_open = False
                logger.info("Door closed")
                post_to_twitter("Door closed")
                samples_counter = 0
        time.sleep(SAMPLE_FREQUENCY)
def setup():
    """Performs basic setup for the daemon and ADC"""
    global exitLock
    logger.debug("Setting up ADC")
    try:
        ADC.setup()
    except RuntimeError as e:
        logger.critical(
            "Attempting to start the BBB GPIO library failed.  This can be "
            "due to a number of things, including:"
        )
        logger.critical(
            "- Too new a kernel.  Adafruit BBIO runs on 3.8.13.  Downgrades "
            "to the version this is tested with can be done easily via:")
        logger.critical(
            "  apt-get install linux-{image,headers}-3.8.13-bone79")
        logger.critical("- Not running on a BBB")
        logger.critical("- Conflicting capes")
        logger.critical("Raw exception: %s", str(e))
        return
    tstat = connect()  # TODO: retries
    logger.debug("Attaching signal handlers")
    signal.signal(signal.SIGINT, handle_exit)
    signal.signal(signal.SIGTERM, handle_exit)
    logger.debug("Building Lock for singal interrupts")
    exitLock = Lock()
    exitLock.acquire()
    logger.debug("Running main loop")
    return tstat
Beispiel #13
0
def setup():
    """Setup the hardware components."""
    

    # Initialize Button
    ADC.setup()
    GPIO.setup(BUTTON0, GPIO.IN)
Beispiel #14
0
    def __init__(self):
        ## Set up ROS Node
        rospy.init_node("motor_enc")
        self.nodename = rospy.get_name()
        self.rate = rospy.Rate(10)
        
        # Publish velocity of each wheel 
        self.pub_w_l = rospy.Publisher('enc/lwheel', Float32)
        self.pub_w_r = rospy.Publisher('enc/rwheel', Float32)
        # Publish distance traveled by each wheel
        self.pub_dist_l = rospy.Publisher('data/ldist', Float32)
        self.pub_dist_r = rospy.Publisher('data/rdist', Float32)

        # A map from motor names to their pin number on the BBB
        self.pin_map = {self.MOTOR_LEFT:self.PIN_LEFT_ENC,
                self.MOTOR_RIGHT:self.PIN_RIGHT_ENC,
                self.MOTOR_SHELL:self.PIN_SHELL_ENC}

        # Map from motor names to their direction pin number
        self.dir_map = {self.MOTOR_LEFT:self.PIN_LEFT_DIR,
                self.MOTOR_RIGHT:self.PIN_RIGHT_DIR,
                self.MOTOR_SHELL:self.PIN_SHELL_DIR}

        ## Set up IO
        ADC.setup()

        ## Initialize important values
        self.w_l = 0 # Left wheel angular velocity
        self.w_r = 0 # Right wheel angular velocity

        self.dist_l = 0 # 
        self.dist_r = 0 
        
        # Time management
        self.then = rospy.Time.now() 
Beispiel #15
0
	def __init__(self):
		#init signal for motor dirction
		GPIO.setup("P8_7", GPIO.OUT)
		GPIO.setup("P8_8", GPIO.OUT)
		GPIO.setup("P8_9", GPIO.OUT)
		GPIO.setup("P8_10", GPIO.OUT)
		#init signal for left, right brush
		GPIO.setup("P8_17", GPIO.OUT)
		GPIO.setup("P8_18", GPIO.OUT)
		#init signal for left, right encoder
		GPIO.setup("P9_15", GPIO.IN)
		GPIO.setup("P9_21", GPIO.IN)
		#set up ADC for IR sensor
		ADC.setup()
		#set up the camera and face cascade
		self.cam = cv2.VideoCapture(0)
		self.face_cascade = cv2.CascadeClassifier('/root/Ferriclean_Robot/haarcascade_frontalface_default.xml')
		self.face = False
		#the parameter of wheels direction and distance
		self.direction_right = True
		self.direction_left = True
		self.distance_right = 0
		self.distance_left = 0
		#the robot left and right wheels PWM duty
		self.lefd = 40
		self.rigd = 40
		#the robot desired speed, set point, unit: counts/ sec
		self.lefsp = 400
		self.rigsp = 400
Beispiel #16
0
def check_voltage():
    os.system("echo 59 > /sys/class/gpio/export")
    os.system("echo out > /sys/class/gpio/gpio59/direction")
    os.system("echo 1 > /sys/class/gpio/gpio59/value")

    VOLTAGES = [['AIN0', 0.30, 1.7],
                ['AIN2', 0.85, 0.95],
                ['AIN4', 1.14, 1.26],
                ['AIN6', 1.42, 1.58],
                ['AIN1', 1.04, 1.16], # VDD_3V3B / 3
                ['AIN3', 1.58, 1.75], # VDD_5V   / 3
                ['AIN5', 1.60, 1.70]] # SYS_5V   / 3
                
    ADC.setup()
    result = []
    status = 'ok'
    for v in VOLTAGES:
        ain = ADC.read(v[0])*1.8
        if ain < v[1] or ain > v[2]:
            result.append('%f (%s) is out of range: %f ~ %f.' % (ain, v[0], v[1], v[2]))
            status = 'error'
        else:
            result.append('%f (%s) is in of range: %f ~ %f.' % (ain, v[0], v[1], v[2]))

    return  status,result
Beispiel #17
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))
Beispiel #18
0
 def _init_BBB(self):
     self._mylogger("---------------------------Initializing BBB Hardware---------------------------", forceinfo=True)
     BADC.setup()
     duty = self._settings.getInt(['DefaultDuty'])
     for j in range(len(self.fan_definitions)):
         if self.fan_definitions[j]['fan_pin'] == 'None' : continue
         else: BPWM.start(self.fan_definitions[j]['fan_pin'], self._settings.getInt(['DefaultDuty']), 22000, 0)
Beispiel #19
0
def main():
    # TODO: move all this into a config file
    sleep_time = 5 * 60
    low_battery_threshold = 12.3
    critical_battery_threshold = 12.2  # 3 * 3.85 # we're using a 3s battery, looking for a cell voltage of less than 3.85
    pin = "P9_40"
    r1 = 7.85
    r2 = 0.987
    multiplier = ((r1 + r2) / r2)

    ADC.setup()

    while True:
        v = read_battery_voltage(pin, multiplier)
        print(v)
        syslog.syslog(syslog.LOG_INFO, f'Battery voltage = {v:.2f}')

        if v <= low_battery_threshold:
            syslog.syslog(
                syslog.LOG_WARN,
                f'Battery voltage is below alarm threshold ({low_battery_threshold:.2f}), sending alarm'
            )
            send_alarm()

        if v <= critical_battery_threshold:
            syslog.syslog(
                syslog.LOG_ERR,
                f'Battery voltage is below shutdown threshold ({critical_battery_threshold:.2f}), shutting down'
            )
            power_down()
            break

        time.sleep(sleep_time)

    daemon.exit()
Beispiel #20
0
    def __init__(self, shared_memory, rootLogger=None, camerasock=None):
        """ """
        threading.Thread.__init__(self)
        self.shared_memory = shared_memory

        self.ui_state = 'PAUSE'

        self.lastfun1 = time.time()
        self.lastfun2 = time.time()
        self.lastchange = time.time()
        self.fun1 = False
        self.fun2 = False

        self.user_pattern = False  # user defined pattern or default?
        self.ptrn_idx = 0
        self.last_process_time = time.time()
        self.process_time = 0

        self.rootLogger = rootLogger
        self.rootLogger.info('Initialize HUI Thread ...')

        self.camerasock = camerasock
        self.camidx = 0

        ADC.setup()

        for btn in BTNS:
            GPIO.setup(btn, GPIO.IN)
            GPIO.add_event_detect(btn, GPIO.RISING)
        for led in LEDS:
            GPIO.setup(led, GPIO.OUT)
        for idx in SWITCHES:
            GPIO.setup(SWITCHES[idx], GPIO.IN)
        ring_leds()
def IRread():
    # Useful Lists:
    IR1list = []

    # General purpose variables:
    count = 0
    samples = 20
    voltMulti = 5

    ADC.setup()

    # Reading analog inputs:
    IR1 = ADC.read("P9_33") * voltMulti  #added a voltage multiplier

    for i in range(samples):
        count = count + 1

        IR1list.append(IR1)

        if (count == samples):
            # Calculating the average of 20 readings:
            avgIR1 = round(sum(IR1list) / len(IR1list), 3)

            # Clearing each list:
            IR1list = []

            count = 0

    return (avgIR1)
Beispiel #22
0
    def __init__(self, name, pin_0):
        """
        Software Representation of a Pressure Sensor (MPX2200AP)

        1.8V is the maximum voltage. Do not exceed 1.8V on the AIN pins !!
        VDD_ADC (P9_32) provides 1.8V. Use GNDA_ADC (P9_34) as the ground.

        ref:
        http://forum.arduino.cc/index.php?topic=281908.0
        https://learn.adafruit.com/setting-up-io-python-library-on-beaglebone-black/adc

        Valid ADC Pins:
            AIN0 - P9_39
            AIN1 - P9_40
            AIN2 - P9_37
            AIN3 - P9_38
            AIN4 - P9_33
            AIN5 - P9_36
            AIN6 - P9_35

        *Initialize with*

        Args:
            name (str): The name of the sensor
            pin_0 (str): Input pin 0 for PressureSens
        """
        ADC.setup()
        self.PinVPlus = pin_0
        #        self.PinVMin = pin_1
        self.offset = 0.0  # to calibrate the sensor
        self.name = name
Beispiel #23
0
    def setup_analog_pin(self):
        """
        This method validates and configures a pin for analog input
        :return: None
        """
        # clear out any residual problem strings
        #

        self.last_problem = '2-0\n'
        pin = self.validate_pin(self.analog_pins)
        if pin == 99:
            self.last_problem = '2-1\n'
            return
        index = self.analog_pins.index(pin)
        pin_entry = self.analog_pin_states[index]

        if self.payload['enable'] == 'Enable':
            pin_entry['enabled'] = True
            pin_entry['mode'] = 'analog'
            self.analog_pin_states[index] = pin_entry
        else:
            pin_entry['enabled'] = False
            self.analog_pin_states[index] = pin_entry

        if not self.analog_reader:
            self.analog_reader = AnalogReader(self.board_num, self.analog_pin_states)

            ADC.setup()
            self.analog_reader.start()
Beispiel #24
0
def getVolt():
    ADC.setup()
    analogPin="P9_40"
    potVal=ADC.read(analogPin)
    potVolt=potVal*1.8
    time.sleep(0.01)  # 66次/s,不加它边存数据库和实时画图会有延迟
    return potVolt
def TempCalc():
    '''Define and print temperature from sensor'''
    #GPIOTurnOff()
    ADC.setup()
    TEMP = (ADC.read(tempsensor) * 1800 - 500) / 10
    print("tmp = %.2f" % TEMP)
    return TEMP
Beispiel #26
0
def ignite(debuglevel):
	threshold=340 #150mv threshold
	threshigh=1024 #450mv upper threshold
	ADC.setup()
	ADC.read_raw("AIN4") #Flush this
	baseline=ADC.read_raw("AIN4")
	GPIO.setup("P8_14",GPIO.OUT) #This pin fires the ignition
	GPIO.output("P8_14",GPIO.LOW)
	PWM.start("P8_19",15,49500) #works best with an 11 turn primary
	time.sleep(0.05) #50ms Settling time for the analogue front end
	ADC.read_raw("AIN4")
	selftest=ADC.read_raw("AIN4")
	if selftest>threshold and selftest<threshigh and baseline<128:
		GPIO.output("P8_14",GPIO.HIGH)
		if debuglevel:
			print "Igniting"
		time.sleep(2) #plenty of time for ignition
		failure=0		
	else:
		if debuglevel:
			print "Failed"
		failure=1
	GPIO.output("P8_14",GPIO.LOW)
	PWM.stop("P8_19")
	PWM.cleanup()
	#Debug output
	if debuglevel:
		print baseline
		print selftest
	return {'failure':failure, 'baseline':baseline ,'selftest':selftest }
Beispiel #27
0
    def setup(self, opts):
        #self.tz = opts.get('Properties/Timezone', 'America/Denver')
	#self.tz = 'America/Denver'
        self.rate = float(opts.get('Rate', 1))
        ADC.setup()

        self.add_timeseries('/soil_moistureLO', 'V', data_type="double")
        self.add_timeseries('/soil_moistureHI', 'V', data_type="double")
Beispiel #28
0
 def __init__(self,pin,beta=BETA,r0=R0,t0=T0):
     self.val = 0.0
     self.tempList = []
     self.pin=pin
     self.beta=beta
     self.r0=r0
     self.t0=t0
     ADC.setup()
Beispiel #29
0
def getVolt():
    ADC.setup()
    from time import sleep
    analogPin="P9_40"
    potVal=ADC.read(analogPin)
    potVolt=potVal*1.8
    sleep(0.01)
    return potVolt
Beispiel #30
0
def setup():
    GPIO.setup("P8_15", GPIO.OUT)
    GPIO.setup("P8_11", GPIO.OUT)
    GPIO.setup("P8_12", GPIO.OUT)
    GPIO.setup("P8_7", GPIO.OUT)
    GPIO.setup("P8_8", GPIO.OUT)
    GPIO.setup("P9_41", GPIO.OUT)
    ADC.setup()
 def __init__(self):
     threading.Thread.__init__(self)
     self.setDaemon(True)
     self.name = self.__class__.__name__
     self.q_out = Queue.Queue()
     self._kill = False
     if WORKING_ON_BEAGLEBONE:
         print("Setting up ADC for beaglebone...")
         ADC.setup()
Beispiel #32
0
 def get_analog(self, port):
     """ Reads an analog signal from the beagle board
 
     :param port: string identifying the port, for example "P9_40"
     :return: value of the signal
     """
     ADC.setup()
     value = ADC.read(port)
     return value
def read_distance():
    ADC.setup()  #set up ADC
    value = ADC.read("P9_39")  #setup pin p9_39 as an ADC pin
    voltage = value * 3.2  #1.8V
    distance = (
        25.36 /
        (voltage + .42)) / 100  #convert from voltage to distance in meters
    #distance = 0.01 DEBUG
    return distance
    def test_setup_adc(self):
        ADC.setup()

        files = os.listdir('/sys/devices')
        ocp = '/sys/devices/'+[s for s in files if s.startswith('ocp')][0]
        files = os.listdir(ocp)
        helper_path = ocp+'/'+[s for s in files if s.startswith('helper')][0]

        assert os.path.exists(helper_path + "/AIN1")
    def test_many_read_adc(self):
        import time

        ADC.setup()

        for x in range(0,10000):
            start = time.time() 
            value = -1
            value = ADC.read("AIN1")
            assert value != -1
Beispiel #36
0
def connectToGateway(moduleName):
    '''optional
        called when the system connects to the cloud.
        Always called first (before updateAssets) '''
    global _cloud, _pinLayouts
    _device = device.Device(moduleName, 'beagle')
    configs = config.loadConfig('beaglePins', True)
    _pinLayouts = configs['pinLayouts']
    ADC.setup()                                        # need to start the ADC driver as well
    setupGPIO()
Beispiel #37
0
def getVolt(NO):
    while True:
        ADC.setup()
        analogPin = "P9_40"
        potVal = ADC.read(analogPin)
        t = time.time()
        potVolt = potVal * 1.8
        msg = {"device_no": NO, "time": t, "voltage": potVal}
        trsq.put(msg)
        time.sleep(0.01)
Beispiel #38
0
 def __init__(self, pin, average_samples=None, mock_hardware=False):
     self.pin = pin
     self._value = 0.0
     self.average_samples = average_samples
     self.mock_hardware = mock_hardware
     if self.mock_hardware:
         self.path = "hardware_files/%s" % self.pin
     if not ADC.adc_subsystem_started and not self.mock_hardware:
         adc.setup()
         ADC.adc_subsystem_started = True
Beispiel #39
0
def connectToGateway(moduleName):
    '''optional
        called when the system connects to the cloud.
        Always called first (before updateAssets) '''
    global _cloud, _pinLayouts
    _device = device.Device(moduleName, 'beagle')
    configs = config.loadConfig('beaglePins', True)
    _pinLayouts = configs['pinLayouts']
    ADC.setup()  # need to start the ADC driver as well
    setupGPIO()
Beispiel #40
0
 def __init__(self, pin, muxedPin=None, muxName=None):
     """Device supports a pin."""
     self._pin = pin  # Set pin
     self._muxedPin = muxedPin  # Set muxed pin
     self._muxName = muxName  # Set mux name
     self._zeroCounter = 0  # Set zero counter to 0
     self._mode = self._settings['modes'][0]  # Set default mode
     self._flags = []  # Set default flag list
     self._values = []  # Set empty values array
     ADC.setup()  # Enable ADC readings
Beispiel #41
0
    def test_setup_adc(self):
        ADC.setup()

        files = os.listdir('/sys/devices')
        ocp = '/sys/devices/' + [s for s in files if s.startswith('ocp')][0]
        files = os.listdir(ocp)
        helper_path = ocp + '/' + [s
                                   for s in files if s.startswith('helper')][0]

        assert os.path.exists(helper_path + "/AIN1")
    def test_many_read_adc(self):
        import time

        ADC.setup()

        for x in range(0, 1000):
            start = time.time()
            value = -1
            value = ADC.read("AIN1")
            assert value != -1
Beispiel #43
0
def init():
 	#for starter in pwmarray:
	#	print starter
	#	PWM.start(starter,15,100,0)
	for starter in GPIOinArray:
		print starter
		GPIO.setup(starter, GPIO.IN)
	for starter in GPIOoutArray:
		print starter
		GPIO.setup(starter, GPIO.OUT)
	ADC.setup()	
Beispiel #44
0
    def _setup(self):
        """ Setup the hardware components."""

        # Initialize Button
        GPIO.setup(self.button, GPIO.IN)

        # Initialize Display
        self.display.update(0)

        # Initialize Joystick Inputs
        ADC.setup()
Beispiel #45
0
def talker():
    pub = rospy.Publisher('adc_val', UInt16, queue_size=10)
    rospy.init_node('ADCIntTalker', anonymous=False)
    rate = rospy.Rate(10)
    ADC.setup()
    print('ADC setup...')
    while not rospy.is_shutdown():
        adc_val = int(ADC.read_raw("P9_39"))
        #rospy.loginfo('Talker: ADC value = ' + str(adc_val))
        pub.publish(adc_val)
        rate.sleep()
Beispiel #46
0
def lig():
	import Adafruit_BBIO.ADC as ADC
	import time
	sensor_pin = 'P9_40'
	ADC.setup()
	print('Reading\t\tVolts')
	while True:
		reading = ADC.read(sensor_pin)
		volts = reading * 1.800
		print('%f\t%f' % (reading, volts))
		time.sleep(1)
Beispiel #47
0
def lig():
    import Adafruit_BBIO.ADC as ADC
    import time
    sensor_pin = 'P9_40'
    ADC.setup()
    print('Reading\t\tVolts')
    while True:
        reading = ADC.read(sensor_pin)
        volts = reading * 1.800
        print('%f\t%f' % (reading, volts))
        time.sleep(1)
    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))


        if DEBUG:
            ## Stats of encoder values while moving -- high, low, and all tick state
            self.encHighLowCntMin = 2**5  # Min number of recorded values to start calculating stats
            self.encHighMean = [0.0, 0.0]
            self.encHighVar = [0.0, 0.0]
            self.encHighTotalCnt = [0, 0]

            self.encLowMean = [0.0, 0.0]
            self.encLowVar = [0.0, 0.0]
            self.encLowTotalCnt = [0, 0]

            self.encNonZeroCntMin = 2**5
            self.encNonZeroMean = [0.0, 0.0]
            self.encNonZeroVar = [0.0, 0.0]
            self.encNonZeroCnt = [0, 0]

            # Record variables
            self.encRecSize = 2**13
            self.encRecInd = [0, 0]
            self.encTimeRec = np.zeros((2, self.encRecSize))
            self.encValRec = np.zeros((2, self.encRecSize))
            self.encPWMRec = np.zeros((2, self.encRecSize))
            self.encNNewRec = np.zeros((2, self.encRecSize))
            self.encPosRec = np.zeros((2, self.encRecSize))
            self.encVelRec = np.zeros((2, self.encRecSize))
            self.encTickStateRec = np.zeros((2, self.encRecSize))
            self.encThresholdRec = np.zeros((2, self.encRecSize))
def gp2y0a12():
    ADC.setup()
    pub = rospy.Publisher('ir_sharp_80cm', String)
    rospy.init_node('gp2y0a21yk0f')
    r = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        measure = str(ADC.read_raw("P9_40"))
        cad = "gp2y0a12: %s" % measure
        rospy.loginfo(cad)
        pub.publish(String(measure))
        #rospy.sleep(1.0)
        r.sleep()
Beispiel #50
0
	def __init__(self):
		raw = 0
		ADC.setup()
		while True:
			for x in range(0, 20):
				raw += ADC.read(configSub.depth_pin)
			raw = raw/20
			pressure = psi(raw)
			value = convert(pressure)
			depth = value.split(",")
			depth = "f:" + depth[0] + ";m:"+ depth[1]
			return depth
Beispiel #51
0
    def initHR_SC04(self):
        print "Initializing HR-SC04 sensor..."
        ADC.setup()
        time.sleep(0.25)

        DIO.setup(TRIG, DIO.OUT)
        time.sleep(0.1)
        DIO.setup(ECHO, DIO.IN)
        time.sleep(0.1)
        DIO.output(TRIG, DIO.LOW)

        return
Beispiel #52
0
def setup_io_init():
	logger.info("Initializing IO")
	PWM.start(PUMP, 0)
	PWM.set_frequency(PUMP, 1000)
	water_pump(0)
	GPIO.setup(HEATER,GPIO.OUT)
	GPIO.setup(LAMP_1,GPIO.OUT)
	GPIO.setup(LAMP_2,GPIO.OUT)	
	lamp(False, LAMP_1)
	lamp(False, LAMP_2)
	heater(False)
	ADC.setup()
Beispiel #53
0
	def task(self):
		ADC.setup()
		while not self.stop.isSet():
							        
			value = ADC.read_raw(self.pin) 
			now = datetime.datetime.now()
			print  self.protocol + "%f : %d : %d : %d "%(value,now.minute,now.second,now.microsecond)
			val = str(value) + " : " + str(now.minute) + " : " + str(now.second) + " : " + str(now.microsecond)+"\n"
			global_module.wifi_namespace_reference.on_send(val);
			if self.isLogging:
				self.log_file.write(val)
			sleep(1);
Beispiel #54
0
def read_temp():
    """
    Obtiene la temperatura desde el dispositivo
    """
    
    try:
        import Adafruit_BBIO.ADC as ADC  # @UnresolvedImport
        ADC.setup()
        return int((ADC.read('P9_40')*1800)/10)
        
    except:
        return 1000
Beispiel #55
0
def tmp(sensor_pin):
	import Adafruit_BBIO.ADC as ADC
	import time
	sensor_pin = 'P9_40'
	ADC.setup()
	while True:
		reading = ADC.read(sensor_pin)
		millivolts = reading * 1800 # 1.8V reference = 1800 mV
		temp_c = (millivolts - 500) / 10
		temp_f = (temp_c * 9/5) + 32
		print('mv=%d C=%d F=%d' % (millivolts, temp_c, temp_f))
		time.sleep(1)
Beispiel #56
0
def tmp(sensor_pin):
    import Adafruit_BBIO.ADC as ADC
    import time
    sensor_pin = 'P9_40'
    ADC.setup()
    while True:
        reading = ADC.read(sensor_pin)
        millivolts = reading * 1800  # 1.8V reference = 1800 mV
        temp_c = (millivolts - 500) / 10
        temp_f = (temp_c * 9 / 5) + 32
        print('mv=%d C=%d F=%d' % (millivolts, temp_c, temp_f))
        time.sleep(1)
	def task(self):
		print "offline log started"
		ADC.setup()
		while not self.stop.isSet():
			print type(self.log_file)			        
			value = ADC.read_raw(self.pin) 
			now = datetime.datetime.now()
			print  self.protocol + "%f : %d : %d : %d "%(value,now.minute,now.second,now.microsecond)
			val = str(value) + " : " + str(now.minute) + " : " + str(now.second) + " : " + str(now.microsecond)+"\n"
			if self.isLogging:
				self.log_file.write(val)
			sleep(1);