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
예제 #2
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() 
예제 #3
0
        def getVolumeAndStationValue():
            prevStation = 0
            while True:
                sample = 0
                volReading = 0
                statReading = 0
                while sample < 10:
                    volReading += adc.read(self.volumePot)
                    time.sleep(0.01)
                    statReading += adc.read(self.stationPot)
                    sample += 1
                    time.sleep(0.05)

                volReading = volReading / 10.0
                statReading = int(statReading * 100)

                station = statReading

                if station != prevStation:
                    # print prevStation, station
                    if self.have_stations:
                        print 'True'
                    prevStation = station

                volume = volReading
                volString = "%.2f" % round(volume, 2)

                previousVolume = self.player.get_property('volume')
                prevVolString = "%.2f" % round(previousVolume, 2)

                if volString != prevVolString:
                    # print previousVolume, volume
                    self.player.set_property('volume', volume)
예제 #4
0
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)
예제 #5
0
파일: 493.py 프로젝트: dgcarneiro/493
def avoid_():

	

def readfile_coordinates():
	global line
	f = open('temp.txt', 'r')
	temp = f.readlines(line)
	f.close()
	latitude = temp.split("")[0]
	longitude = temp.split("")[1]


while True:
	try:
		while True:
			readfile_coordinates(line)
			scheduler()
			arbiter()
			
	except KeyboardInterrupt: # pressing ctrl C stops operation and cleans up

		PWM.stop(left_wheel)	
		PWM.stop(right_wheel)
		PWM.cleanup()
		GPIO.cleanup()
		ADC.cleanup()
예제 #6
0
 def get_voltage(self):
    Vo = ADC.read("P9_39")* 1.8 
    Vo = ADC.read("P9_39") * 1.8 
    R1 = 10 * 1000
    R2 = 2.2 * 1000
    Vi = Vo * (R1 + R2) / R2
    return Vi
예제 #7
0
파일: xibb.py 프로젝트: MrYsLab/xideco
    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()
예제 #8
0
파일: xibb.py 프로젝트: MrYsLab/xideco
    def run(self):
        """
        Continuously monitor the A/D
        :return:
        """
        value = None
        while True:
            try:
                for entry in self.pin_states:
                    if entry['enabled']:
                        if entry['mode'] == 'analog':
                            value = ADC.read(entry['pin'])
                            value = round(value, 4)

                        elif entry['mode'] == 'sonar':
                            value = ADC.read_raw(entry['pin'])
                            value = self.convert_to_distance(value)

                        digital_reply_msg = umsgpack.packb({u"command": "analog_read", u"pin": entry['pin'],
                                                            u"value": str(value)})

                        envelope = ("B" + self.board_num).encode()
                        self.publisher.send_multipart([envelope, digital_reply_msg])
                time.sleep(0.05)
            except KeyboardInterrupt:
                sys.exit(0)
예제 #9
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()
예제 #10
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)
예제 #11
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)
예제 #12
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
예제 #13
0
	def read_IR(self):
		self.mid = ADC.read("P9_35")
        	self.lef = ADC.read("P9_33")
       		self.rig = ADC.read("P9_36")	
		self.mrig = ADC.read("P9_37")
		self.mlef = ADC.read("P9_39")
		self.value = [self.lef, self.mid, self.rig, self.mlef, self.mrig]
예제 #14
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
예제 #15
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()
예제 #16
0
파일: omega.py 프로젝트: yshao/weathergit
    def read(self):
        voltageHI = ADC.read("AIN0") * 1800 #1.8V
        voltageLO = ADC.read("AIN1") * 1800 #1.8V

        # print voltage
        self.add('/tempLO',voltageLO)
        self.add('/tempHI',voltageHI)
예제 #17
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()
예제 #18
0
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
예제 #19
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)
예제 #20
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
예제 #21
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))
예제 #22
0
 def __init__(self,pin):
     
     # Initialize ADC
     ADC.setup()
     
     # Set pin
     self.pin = pin
예제 #23
0
    def read(self):

        voltageLO = ADC.read("AIN2") * 1.8 #1.8V
        voltageHI = ADC.read("AIN3") * 1.8 #1.8V

        # print voltage
        self.add('/humidityLO',voltageLO)
        self.add('/humidityHI',voltageHI)
예제 #24
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")
예제 #25
0
    def read(self):

        voltageLO = ADC.read("AIN2") * 1.8 #1.8V
        voltageHI = ADC.read("AIN3") * 1.8 #1.8V

        # print voltage
        self.add('/soil_moistureLO',voltageLO)
        self.add('/soil_moistureHI',voltageHI)
    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
예제 #28
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()
예제 #29
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))


        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))
예제 #30
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()	
예제 #31
0
def adc_get_value(chan):
    return ADC.read(chan) * 1800
예제 #32
0
def ReadAdc(adc_pin):

    adc_rtat = []
    ADC.setup()
    adc_rtat.append(ADC.read(adc_pin))
    return adc_rtat
예제 #33
0
import Adafruit_BBIO.ADC as ADC

from time import sleep

ADC.setup()

pino = 'P9_36'

while True:
    v1 = ADC.read(pino)
    sleep(.01)
    v2 = ADC.read(pino)
    print '%s %10.3f |%20s| %10.3f |%20s|' % (pino, v1, int(v1 * 20) * '#', v2,
                                              int(v2 * 20) * '#'),
    print  # '*' * int(tempo*60)
    sleep(.01)
예제 #34
0
import Adafruit_BBIO.ADC as ADC
import Adafruit_BBIO.GPIO as GPIO
import time

RedLED = "P9_27"
GreenLED = "P9_30"

GPIO.setup(RedLED, GPIO.OUT)
GPIO.setup(GreenLED, GPIO.OUT)
GPIO.output(RedLED, GPIO.LOW)
GPIO.output(GreenLED, GPIO.LOW)

ADC.setup()
laststate = "Temperature High"

import smtplib
to = '*****@*****.**'
gmail_user = '******'
gmail_pwd = '##!$@%8'
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
try:
    while True:
        reading = ADC.read('P9_40')
        millivolts = reading * 1800
        temp_c = millivolts / 10
        if (temp_c > 50) and laststate == "Temperature Low":
            print "Temperature is high"
예제 #35
0
def front_sensor(front_threshold, ADC_INPUT):
    measured_value = ADC.read(ADC_INPUT)
    distance = 35 * math.exp(-0.0006 * measured_value * 4000)

    if (distance <= front_threshold): return 1
    if (distance > front_threshold): return 0
예제 #36
0

 # print(value*1.8)
  
#GPIO.output("P9_11",0)

#utilizando GPIO
#GPIO.setup("P9_23", GPIO.IN) #pin 23 es una entrada beagle, lee la senal digital
#GPIO.setup("P9_25", GPIO.OUT) #pin 25 salida beagle alimenta led

#GPIO.output("P9_25", 1) #prende led
#time.sleep(5)
#GPIO.output("P9_25", 0) #apaga led

#utilizando ADC (analogo)
ADC.setup()
analogPin="P9_39"
suma0,suma=0,0
for i in range(2000):
   soundVal=ADC.read(analogPin)*1.8 #*3.42*1000
   decibel=20*math.log10(soundVal/1.8)
   #s.append(soundVal)   #Creando una lsita
  # soundVolt=soundVal*1000 #*1.7*1000
  # print "The Voltage is: "+str(soundVal)+" V"
   #print "The decibel is: "+str(decibel)+" dB"
#print(round(ADC.read(analogPin),10),str(round(soundVal,2))+" ", str(decibel)+str(" dB"))
#   print(round(soundVolt,3))
   #time.sleep(0.5)
   #GPIO.output("P9_25",0)
   suma+=soundVal
   suma0+=decibel
예제 #37
0
def mapVals(val, inMin, inMax, outMin, outMax):
        toRet = float(outMin + (float(outMax - outMin) * (float(val - inMin) / float(inMax - inMin))))
        # print('turned %s into %s'%(val,toRet))
        toRet = clamp(toRet, outMin, outMax)
        return toRet

def clamp(val, tmin, tmax):
    if val > tmax:
        val = tmax
    if val < tmin:
        val = tmin
    return val


uart.setup("UART2")
adc.setup()
atexit.register(exit_handler)
printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5)
printer.begin()
printer.upsideDownOn()
printer.feed(3)
printer.print(parse('i am awake and I am APPLE (light)'))
printer.feed(1)
rPast = 0
rMax = 0 # all-time max sensor reading
rMin = 100000 # all-time min sensor reading
WINDOW_SIZE = 30 # size of moving-window avg
noop = 0 # number of intervals passed without a trigger
noop_threshold = 480
emission_threshold = 0.1 # changed this for vcnl4000, used to be 0.7
예제 #38
0
import time  #measure proceeding time to calculate Hz
import Adafruit_BBIO.ADC as ADC  #use analog read
ADC.setup()
import numpy as np
import requests  #connect IFTTT
from scipy import signal  #detect peak

# parameters
analogPin = "P9_39"
sample_number = 2000
repeat_number = 2

sound_data = []
Gx = []
Gy = []


# IFTTT_Webhook
def ifttt_webhook(eventid):
    payload = {"value1": Gx_i, "value2": Gy_i, "value3": freq[maximal_idx]}
    url = "https://maker.ifttt.com/trigger/" + eventid + "/with/key/xxxxxxxxxxxxxxxxxxx"
    response = requests.post(url, data=payload)


# Starting measurement sound data

for i in range(10000):  #cutting launch time peak? noise?
    sound_data_t = ADC.read(analogPin)
    sound_data.append(sound_data_t)
    sound_data = []  #sound_data resset
예제 #39
0
'''
Sensor test
'''
import Adafruit_BBIO.ADC as ADC
from SBE_functions import *

# serial input setup
ser = setupSerial()

poten_pin = "P9_33"
poten_value = 0 # input range 0 - 1.0
ADC.setup()

rval = 0.0

sen_gain = 0.003384*25.4 # converts sensor reading to mm
gained_val = 0.0 # sensor reading in mm


while True:
    try:
    	rval = ToughSonicRead(ser)
    	gained_val = rval * sen_gain # sensor reading in mm

    	poten_value = ADC.read(poten_pin)
    	poten_value = ADC.read(poten_pin) # read twice due to possible known ADC driver bug
    	print("Ultrasonic [mm]: ", int(gained_val), " Wand [0-1]: ", poten_value)
    except KeyboardInterrupt: # allows for easy program stop by tester
        break
    
# clean up
 def get_data(self):
     return ADC.read_raw(self.__pin)
 def __init__(self,pin):
     self.__pin = pin
     ADC.setup()
예제 #42
0
    def scan(self):
        #initilizes a count for number of datapoints
        count = 0
        #changes angle slightly so loop will run
        self.angle = .0001
        #creates a variable that returns 1 when the scan completes
        scanComplete = 0
        #records the start time
        self.startTime = rospy.get_time()
        #runs while there are less than 400 data points or the angle becomes is not 0
        while count < 400 and self.angle != 0:

            for pin_index in range(len(self.pins)):
                #gets time before first reading
                self.datatime1 = rospy.get_time()
                self.drivemode(self.pins, pin_index)

                #writes to the LIDAR to take a reading
                #writes to the register that takes measurment
                self.i2c.write8(self.distWriteReg, self.distWriteVal)
                #waits for 'x' seconds to control motor speed and prevent sensor overpolling(minimum sleep time is .0025)
                time.sleep(.01)

                #checks for when the sensor triggers 0 angle calibration
                #reads value from sensor
                rotateVal = ADC.read("P9_39")
                #checks if the sensor is over the threshold but the last value is under the threshold
                #if both are true the sensor has just been passe dan should now reset
                if rotateVal > self.threshold and self.lastval < self.threshold:
                    #sets angle before it gets reset
                    self.msg.angle_max = self.angle
                    self.angle = 0
                else:
                    self.angle = self.angle + .9
                    #sets max angle to the most recent angle
                    self.msg.angle_max = self.angle
                self.lastval = rotateVal
                #saves angle in a list so the first angle can be recalled
                self.angleR.append(self.angle)
                #reads distance from Lidar
                dist1 = self.i2c.readU8(self.distReadReg1)
                dist2 = self.i2c.readU8(self.distReadReg2)
                #shifts bits to get correct distance
                self.distance = (dist1 << 8) + dist2

                #writes dynamic data to msg
                #uses final data gathering time for the time increment between data readings
                #taking the average over the entire period would probably be more accurate
                self.msg.time_increment = (self.datatime1 - self.datatime2)
                self.msg.ranges.append(self.distance)
                #saves previous start time
                self.datatime2 = self.datatime1
                count = count + 1

        #sets pin low when scan completes
        set_all_pins_low(self.pins)

        #writes static data to laserscan message
        self.msg.angle_min = (self.angleR[0] * 0.0174533)
        #changes angle to radians
        self.msg.angle_max = (self.msg.angle_max * 0.0174533)

        #records final time
        self.finishTime = rospy.get_time()
        #calcualtes scan time
        self.msg.scan_time = (self.finishTime - self.startTime)

        #changes variable when scan is complete
        scanComplete = 1
        return scanComplete
예제 #43
0
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.ADC as ADC
ADC.setup()
from time import sleep
analogPin = "P9_40"
led1 = "P9_41"
led2 = "P9_30"
led3 = "P9_23"
led4 = "P8_11"

GPIO.setup(led1, GPIO.OUT)
GPIO.setup(led2, GPIO.OUT)
GPIO.setup(led3, GPIO.OUT)
GPIO.setup(led4, GPIO.OUT)
while (1):
    potval = ADC.read(analogPin) * 1000
    a = int(potval)
    print a
    sleep(0.5)
    if (a > 500 and a < 525):
        GPIO.output(led1, GPIO.HIGH)
        GPIO.output(led2, GPIO.LOW)
        GPIO.output(led3, GPIO.LOW)
        GPIO.output(led4, GPIO.LOW)
    elif (potval >= 525 and potval < 550):
        GPIO.output(led1, GPIO.LOW)
        GPIO.output(led2, GPIO.HIGH)
        GPIO.output(led3, GPIO.LOW)
        GPIO.output(led4, GPIO.LOW)
    elif (potval >= 550 and potval < 575):
        GPIO.output(led1, GPIO.LOW)
예제 #44
0
# Created by Carmelito Andrade for the DIY Drum kit project
#Based on Adafruit's python libary for 12-Key Capacitive Touch Sensor Breakout - MPR121
#clone the forked github repo from - https://github.com/adafruit/Adafruit_Python_MPR121
#git clone https://github.com/CJAndrade/DIY-Drum-Kit
#sudo python setup.py install

import sys
import time
import os
import subprocess
import Adafruit_MPR121.MPR121 as MPR121
import Adafruit_BBIO.ADC as ADC
import time

ADC.setup()
folderDial = "P9_33"
tuneDial = "P9_35"
tuneFileAt = '/root/soundFiles/tunes'
song1Poll = 0
song2Poll = 0
wavFileAt = '/root/soundFiles/basicDrum'
os.chdir(wavFileAt)

print 'Adafruit MPR121 Capacitive Touch Sensor Test'

# Create MPR121 instance.
cap = MPR121.MPR121()

# Initialize communication with MPR121 using default I2C bus of device, and
# default I2C address (0x5A).  On BeagleBone Black will default to I2C bus 0.
if not cap.begin(bus=1):
예제 #45
0
from gRPC import MessagesServices_pb2_grpc as ms_grpc
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.ADC as ADC



# Set up GPIO reading of the hall effect sensors. Need to do this using the logic level shifter because the sensors need and output 5V, while the BBB runs on 3V!!
# print("setting up GPIO")
GPIO.setup(CONST.HALL_STBD_PIN, GPIO.IN)
GPIO.setup(CONST.HALL_PORT_PIN, GPIO.IN)



# Set up the ADC for reading the pot that was in the plans, but never materialized due to campus closure.
# print("setting up ADC")
ADC.setup()



# Create a protobuf to store sensor values and fill it in with dummy values.
# NOTE: filling protobufs with 0s seems to result in a completely empty structure that will not be properly decoded on the other side.
sensor_msg = ms.BBBSersorData()
sensor_msg.hall_port = False
sensor_msg.hall_stbd = False
sensor_msg.pot_val = 0.5
sensor_msg.pot_centered = True



def readSensors(): # Call this with some regularity
    # Check if the pot is centered
예제 #46
0
DHT_PIN  = 'P8_11'

FREQUENCY_SECONDS      = 900

humidity, temp = Adafruit_DHT.read(DHT_TYPE, DHT_PIN)
if humidity is None or temp is None:
                time.sleep(2)
                continue

        print 'Temperature: {0:0.1f} F'.format((((temp*9)/5)+32))
        print 'Humidity:    {0:0.1f} %'.format(humidity)

print'\n'

ADC.setup()
soil_moisture = ADC.read("P9_36")
soil_moisture = ADC.read("P9_36")

if 1 > soil_moisture > .8 :
    print 'Low Soil Moisture: '
    print soil_moisture

elif .8> soil_moisture > .5 :
    print 'Medium Soil Moisture: '
    print soil_moisture
else :
    print 'High Soil Moisture: '
    print soil_moisture 
	
print '\n'	
예제 #47
0
import Adafruit_BBIO.ADC as ADC
import time
import datetime

#For reading analog data
ADC.setup()

f1 = open('pressure.csv', 'a')
f1.write("Month,Day,Hour,Minute,Second,Raw Pressure, Pressure (Hg)\n")

while 1:
    now = datetime.datetime.now()
    rawP = ADC.read("P9_39")
    #convert raw voltage to pressure in Hg - formula derived from data sheet, page 11: http://sensing.honeywell.com/index.php?ci_id=151133
    #p = ((rawP * 1.8 * 2 -.33)/1.65)*29.92
    #p = ((rawP * 1.8 * 2 -.33)/1.65)*100
    p = (1.6 * (rawP * 2.0 * 1.8 - 3.3 * 0.10)) / (0.8 * 3.3) * 100
    print str(rawP) + ' ' + str(p)
    #write to csv file
    f1.write(
        str(now.month) + ',' + str(now.day) + ',' + str(now.hour) + ',' +
        str(now.minute) + ',' + str(now.second) + ',' + str(rawP) + ',' +
        str(p) + '\n')
    time.sleep(1)
f1.close()
예제 #48
0
X_msb = 0x03
X_lsb = 0x04
Z_msb = 0x05
Z_lsb = 0x06
Y_msb = 0x07
Y_lsb = 0x08

i2c = Adafruit_I2C(mag_addr)

UART.setup("UART2")

ser = serial.Serial(port="/dev/ttyO2", baudrate=9600)
ser.close()
ser.open()

ADC.setup()

# Based on observation of high and low raw readings of the accelerometer X 3.6 V. Then took the average of each.
zeroOffsetZ = 1.672
zeroOffsetX = 1.595
zeroOffsetY = 1.614

#The sensitivity or conversion factor is the average for each axis of the accelerometer minus low raw reading.
conversionFactorZ = 0.322
conversionFactorY = 0.325
conversionFactorX = 0.319

# Values off of the datasheet for Thermistor, to calculate temp
Bvalue = 3348  #Beta
Ro = 1000  #Resistance at 25 C
To = 298.15  #Room temperature Kelvin
예제 #49
0
import Adafruit_BBIO.ADC as ADC
import time

#Connect Grove UV Sensor to P9_40

ADC.setup()

while True:
    value = ADC.read("P9_40")
    voltage = value * 1.8 #1.8V
    print "method_1:",voltage,"V"
    print "method_2:", ADC.read_raw("AIN1"),"mV"
    time.sleep(0.5)

예제 #50
0
#Written for the 135-102DAG-J01 Thermistor
import Adafruit_BBIO.ADC as ADC
import time
import datetime
import math as mt

ADC.setup()

#See June 4 comment on http://ealmberg.blogspot.com/2015/06/4-june-15.html

Bvalue = 3348  #Beta
Ro = 1000  #Resistance at 25 C
To = 298.15  #Room temperature in Kelvin

# Make sure the out file is opened properly
while 1:
    try:
        f1 = open('/media/CARD/temp2.csv', 'a')
        f2 = open('/media/CARD/temp_errors2.csv', 'a')
        print "Successfully opened", f1.name
        print "Successfully opened", f2.name
        f1.write(
            "Month,Day,Hour,Minute,Second,ADC,Resistance,Kelvin,Celsius,Fahrenheit\n"
        )
        f2.write("Month,Day,Hour,Minute,Second,Error\n")
        break
    except Exception as error1:
        print 'Error ' + str(error1)
        time.sleep(1)

# Get thermistor values and write them to file
예제 #51
0
#!/usr/bin/python

import Adafruit_BBIO.ADC as ADC
import time
import datetime
import numpy as np

ADC.setup()

# Based on observation of high and low raw readings X 3.6 V. Then took the average of each.
zeroOffsetX = 1.595
zeroOffsetY = 1.614
zeroOffsetZ = 1.672

#The sensitivity or conversion factor is the average for each axis minus low raw reading.
conversionFactorX = 0.319
conversionFactorY = 0.325
conversionFactorZ = 0.322

# Make sure the out file is opened properly
while 1:
    try:
        f1 = open('/media/CARD/acceleration2.csv', 'a')
        # raise IOError
        print "Successfully opened", f1.name
        f1.write("Month,Day,Hour,Minute,Second,Xraw,Yraw,Zraw,X,Y,Z,Norm\n")
        break

    except Exception as err:
        print 'Error:', err
        time.sleep(1)
예제 #52
0
def Temperatura(PinTemperatura):
    reading = ADC.read(PinTemperatura)
    milivolts = reading * 1800
    temp_c = (milivolts / 10.0) + 143.70 - 273.15
    return (round(temp_c, 0))
예제 #53
0
import Adafruit_BBIO.ADC as ADC
import Adafruit_BBIO.PWM as PWM
import time

sensor_pin = 'P9_40'
servo_pin = "P8_13"
duty_min = 3
duty_max = 14.5
duty_span = duty_max - duty_min

PWM.start(servo_pin, (100 - duty_min), 60.0, 1)
angle_f = float(90)
duty = 100 - ((angle_f / 180) * duty_span + duty_min)
duty_zero = 100 - (0 * duty_span + duty_min)
ADC.setup()

print('Reading\t\tVolts')

while True:
    reading = ADC.read(sensor_pin)
    print(reading)
    if reading >= 0.85:
        PWM.set_duty_cycle(servo_pin, duty)
    else:
        PWM.set_duty_cycle(servo_pin, duty_zero)

    time.sleep(1)
예제 #54
0
from Adafruit_BBIO import ADC
from time import sleep
from redis import *
import socket, sys

ADC.setup()
client = StrictRedis(host="127.0.0.1")

proportional = 12.2 / 2.2

VoltageFactor_ip = {
    '10.128.170.107': 100,
    '10.128.170.108': 1000,
    '10.128.170.109': 100,
    '10.128.170.110': 100,
    '10.128.170.111': 100,
    '10.128.170.112': 3000,
    '10.128.170.113': 1500,
    '10.128.170.116': 1500,
    '10.128.180.107': 1000,
    '10.128.180.108': 100,
    '10.128.180.109': 100,
    '10.128.180.110': 3000
}


def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    try:
        # doesn't even have to be reachable
예제 #55
0
import time
import math

import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.ADC as ADC

#To install...
#https://learn.adafruit.com/setting-up-io-python-library-on-beaglebone-black/installation-on-ubuntu

Range_pin = "P9_41"
GPIO.setup(Range_pin, GPIO.OUT)
GPIO.output(Range_pin, GPIO.HIGH)

#Starts ranging Ultrasonics
ADC.setup()
#Ultrasonics have to get the reading, scale up the voltage and then scale down to to the bealgebone logic
ultrasonic_frontLeft_data_pin = "P9_40"
ultrasonic_frontCenter_data_pin = "P9_36"
ultrasonic_frontRight_data_pin = "P9_38"

ultrasonic_frontLeft_value = ADC.read(ultrasonic_frontLeft_data_pin)
ultrasonic_frontLeft_value = ADC.read(
    ultrasonic_frontLeft_data_pin
)  #Bug in Adafruit Library. You need to read the alues twice to get the latest value
ultrasonic_frontLeft_voltage = ultrasonic_frontLeft_value * 1.8  #1.8V
ultrasonic_frontLeft_distance = ultrasonic_frontLeft_voltage / 0.00699

ultrasonic_frontCenter_value = ADC.read(ultrasonic_frontCenter_data_pin)
ultrasonic_frontCenter_value = ADC.read(
    ultrasonic_frontCenter_data_pin
)  #Bug in Adafruit Library. You need to read the alues twice to get the latest value
예제 #56
0
import Adafruit_BBIO.ADC as ADC
import Adafruit_BBIO.PWM as PWM
import Adafruit_BBIO.GPIO as GPIO
import time
from time import sleep

Enc1 = RotaryEncoder(eQEP1)
Enc1.enable()
Enc1.zero()
Enc1.setAbsolute()
Enc2 = RotaryEncoder(eQEP2)
Enc2.enable()
Enc2.zero()
Enc2.setAbsolute()

ADC.setup()  # setup BBB ADC
PWM1 = "P8_13"  # motor 1 signal
PWM2 = "P8_19"  # motor 2 signal
PWM.start(PWM1, 60)
PWM.start(PWM2, 60)
PWM.set_duty_cycle(PWM1, 69)
PWM.set_duty_cycle(PWM2, 71)

##### setup BBB GPIO pins
GPIO.setup("P8_37", GPIO.OUT)
GPIO.setup("P8_38", GPIO.OUT)
GPIO.setup("P8_31", GPIO.OUT)
GPIO.setup("P8_32", GPIO.OUT)


def back(slp):  ###BACK
예제 #57
0
def is_obstruction():
    #Analog read and time delay (Only front sensor)
    #There is currently a bug in the ADC driver.
    #You'll need to read the values twice in order to get the latest value.
    '''
	wait_pin_change(ADC.read("AIN2"))
	print "Front Detected"
	'''
    value = ADC.read("AIN2")  #"P9_37"
    value = ADC.read("AIN2")
    '''
	#wait_pin_change(ADC.read("AIN3"))
	#print "Right Detected"
	valRight = ADC.read("AIN3") #"P9_38"
	valRight = ADC.read("AIN3")
	
	#wait_pin_change(ADC.read("AIN0"))
	#print "Left Detected"
	valLeft = ADC.read("AIN0") #"P9_39"
	valLeft = ADC.read("AIN0")
	
	#wait_pin_change(ADC.read("AIN1"))
	#print "Back"
	valBack = ADC.read("AIN1") #"P9_40"
	valBack = ADC.read("AIN1")
	'''

    #POLL FOR INTERRUPT, range is 0-1.65V
    voltage = value * 1.8
    '''
	voltRight = valRight * 1.8
	voltLeft = valLeft * 1.8
	voltBack = valBack * 1.8
	'''

    voltRight = 0
    voltLeft = 0
    voltBack = 0

    sensorFlag = False
    voltArr = [voltage, voltRight, voltLeft, voltBack]
    count = 0
    for v in voltArr:
        #print (v)
        if v > 1.6:
            sensorFlag = True
            #Poll which sensor went off
            if count == 0:
                obsC = True
            elif count == 1:
                obsR = True
            elif count == 2:
                obsL = True
            elif count == 3:
                obsB = True
        else:
            if count == 0:
                obsC = False
            elif count == 1:
                obsR = False
            elif count == 2:
                obsL = False
            elif count == 3:
                obsB = False
        #increment
        count = count + 1

    return sensorFlag
예제 #58
0
# BeagleBone Black Health Sensors
# Autores: Mario Baldini, Joao Baggio, Raimes Moraes

import os
import time
import Adafruit_BBIO.ADC as ADC
from time import sleep
from Adafruit_I2C import Adafruit_I2C

ADC.setup()
adx1 = Adafruit_I2C(0x1d, 1)  #(device addr, i2c bus addr)
adx2 = Adafruit_I2C(0x53, 1)
adx3 = Adafruit_I2C(0x1d, 2)
adx4 = Adafruit_I2C(0x53, 2)

POWER_CTL_addr = 0x2D
#DATA_FORMAT_addr = 0x31;

adx1.write8(POWER_CTL_addr, 0x08)
adx2.write8(POWER_CTL_addr, 0x08)
adx3.write8(POWER_CTL_addr, 0x08)
adx4.write8(POWER_CTL_addr, 0x08)

while True:

    t_init = time.time()

    # solicita todos os valores em 1 comando
    # recomendacao do datasheet, para garantir sincronia

    #acc1 = adx1.readList(0x32,6)
예제 #59
0
    def calibrate(self, numsteps):
        """
            Calculates the coefficient and power terms for the sensor by recording
            voltage measurements at known distances and then performing an
            exponential curve fit on the data.
            
            numsteps: the number of measurements to take from min to max distance
                      more steps will give a more accurate curve
        """
        import numpy as np
        from scipy.optimize import curve_fit

        distances = range(self.min, self.max + 1,
                          (self.max - self.min) / numsteps)
        voltages = []

        def func(x, a, b):
            """
                Curve fitting function.  Used to fit data points to the curve
                y = a * x ^ b
            """
            return a * x**b

        print('IR Calibration')
        print('\nThe calibration process requires you to place an object ' \
              '(a flat piece of card is good) at a variety of distances from ' \
              'the minumum distance to the maximum distance.\n\n' \
              'Voltage readings will be taken at (cm):')
        print distances

        for d in distances:
            print("Measure @ %d cm" % (d))
            sleep(5)
            for x in range(5):
                sys.stdout.write("%d  " % (5 - x))
                sys.stdout.flush()
                sleep(1)

            print("\nReading @ %d cm" % (d))
            sleep(2)
            value = 0.0
            total = 0.0
            for x in range(5):
                value = ADC.read(self.AIN) * 1.8 * self.scale
                total = total + value
                print("#%d - %2.4f" % (x + 1, value))
                sleep(1)
            print("%d cm Average: %2.4f" % (d, total / 5))
            print "=" * 15
            voltages.append(total / 5)

        # fits measured voltages to y = a * x ^ B curve
        popt, pcov = curve_fit(func, np.array(voltages), np.array(distances))
        self.coeff = popt[0]
        self.power = popt[1]
        print "Calibration Data"
        print "-" * 15
        print "Coefficient  :", self.coeff
        print "Power        :", self.power
        print "Err 1 std dev:", np.sqrt(np.diag(pcov))
        print "\nEquation     : distance = %2.2f * scaled_voltage ** %2.2f" % (
            self.coeff, self.power)
        print "-" * 15
        print "Example use:"
        print '  IR = SharpIR("P9_36", scale=1560.0/560.0, coeff=%2.6f, power=%2.6f)' % (
            self.coeff, self.power)
        print "-" * 15
예제 #60
0
import Adafruit_BBIO.ADC as ADC
ADC.setup()
from time import sleep

sensorPin = "P9_40"

while(1):
	signal = ADC.read(sensorPin)
	voltage = 1.8 * signal
	distance = voltage/0.002441 # distance in cm in air
	distance /= 2.54 # distance in inches in air
	print "Distance: ",distance," in"
	sleep(0.025)