Exemple #1
0
def Init_IOPi(): 
    global sensorbus    
    global buttonbus
    i2c_helper = ABEHelpers()
    i2c_bus = i2c_helper.get_smbus()
    sensorbus = IoPi(i2c_bus, 0x20) 
    # set both rows of pins to input mode
    sensorbus.set_port_direction(0, 0xFF)
    sensorbus.set_port_direction(1, 0xFF)
    #setup interrupts on bus 2, port 1
    buttonbus = IoPi(i2c_bus, 0x21)
    # Set all pins on the bus to be inputs with internal pull-ups enabled.
    buttonbus.set_port_pullups(1, 0xFF)
    buttonbus.set_port_direction(1, 0xFF)
    # Inverting the ports will allow a button connected to ground to register as 1 or on.
    buttonbus.invert_port(1, 0xFF)  # invert port 1 so a button press will register as 1
    # Set the interrupt polarity to be active low and mirroring enabled, so
    # INT A and INT B go low when an interrupt is triggered
    buttonbus.set_interrupt_polarity(0)
    #buttonbus.mirror_interrupts(1)
    # Set the interrupts default value to 0 so it will trigger when any of the pins on the bus change to 1
    buttonbus.set_interrupt_defaults(1, 0x00)
    # Set the interrupt type to be 0xFF for port B so an interrupt is
    # fired when the pin matches the default value
    buttonbus.set_interrupt_type(1, 0xFF)
    # Enable interrupts for all pins on the port
    buttonbus.set_interrupt_on_port(1, 0xFF)
    # reset the interrups on the IO Pi bus 
    buttonbus.reset_interrupts()

    GPIO.setmode(GPIO.BCM)
    # Set up GPIO 23 as an input. The pull-up resistor is disabled as the level shifter will act as a pull-up. 
    GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_OFF)
    # when a falling edge is detected on GPIO pin 23 the function button_pressed will be run  
    GPIO.add_event_detect(23, GPIO.FALLING, callback=hwbutton_pressed) 
 def __init__(self, datasocket=None):
     threading.Thread.__init__(self)
     if datasocket is not None:
         self.datasocket = datasocket
     else:
         self.datasocket = None    
     self.measured_voltage = 0
     self.filament = {}
     port = '/dev/serial/by-id/usb-TTI_CPX400_Series_PSU_C2F952E5-if00'
     self.filament['device'] = CPX.CPX400DPDriver(1, device=port)
     self.filament['voltage'] = 0
     self.filament['current'] = 0
     self.filament['idle_voltage'] = 3
     self.filament['device'].set_current_limit(4)
     self.filament['device'].output_status(True)
     self.bias = {}
     self.bias['device'] = CPX.CPX400DPDriver(2, device=port)
     self.bias['grid_voltage'] = 0
     self.bias['grid_current'] = 0
     self.bias['device'].output_status(True)
     self.looptime = 0
     self.update_setpoint(0.1)
     i2c_helper = ABEHelpers()
     bus = i2c_helper.get_smbus()
     self.adc = DeltaSigma(bus, 0x68, 0x69, 18)
     self.adc.set_pga(1)  # This shold be 8, but amplifier seems broken on the available device
     self.running = True
     self.wanted_voltage = 0
     self.emission_current = 999
     self.pid = pid.PID(2, 0.03, 0, 9)
     self.pid.update_setpoint(self.setpoint)
Exemple #3
0
    def __init__(self, room, direction):
	self.room = room
	self.direction = direction
	self.channel = self.channelRoomMappings[direction][room]
        
	i2c_helper = ABEHelpers()
	bus = i2c_helper.get_smbus()
	self.adc = DeltaSigma(bus, 0x68, 0x69, 18)
 def setup_adc(self, adr1, adr2, accu):
     print("setting up adc with accuracy <"
           + str(accu) + "> on addresses <"
           + str(adr1) + "> and <"
           + str(adr2) + ">")
     i2c_helper = ABEHelpers()
     bus = i2c_helper.get_smbus()
     adc = ADCPi(bus, adr1, adr2, accu)
     
     return adc
Exemple #5
0
   def __init__ (self, ph7, ph4, ds):
      self.ph7 = ph7
      self.ph4 = ph4
      self.ds  = ds

      i2c_helper = ABEHelpers()
      bus = i2c_helper.get_smbus()
      self.adc = ADCPi(bus, self.i2c1, self.i2c2, self.bitrate)

      self.calcpHSlope()
Exemple #6
0
    def __init__(self):

        i2c_helper = ABEHelpers()
        i2c_bus = i2c_helper.get_smbus()
        multibus = [IoPi(i2c_bus, 0x22), IoPi(i2c_bus, 0x23)]

        self.tenhome = Digit(multibus, 1, True)
        self.home = Digit(multibus, 8, True)
        self.tenguest = Digit(multibus, 17, True)
        self.guest = Digit(multibus, 24, True)
Exemple #7
0
	def __init__(self):

		i2c_helper = ABEHelpers()
		i2c_bus = i2c_helper.get_smbus()
		multibus = [ IoPi(i2c_bus, 0x20), IoPi(i2c_bus, 0x21)]

		self.tenminute = Digit(multibus, 1, True)
		self.minute = Digit(multibus, 8, True)
		self.tensecond = Digit(multibus, 17, True)
		self.second = Digit(multibus, 24, True)
Exemple #8
0
	def __init__(self, configfilename):

		config = ConfigParser.RawConfigParser()
		config.read(configfilename)
		inverted_logic = config.getboolean(self.__class__.__name__, 'inverted_logic')

		i2c_helper = ABEHelpers()
		i2c_bus = i2c_helper.get_smbus()
		multibus = [ IoPi(i2c_bus, 0x20), IoPi(i2c_bus, 0x21)]

		self.tendigit = Digit(multibus, 1, inverted_logic)
		self.digit = Digit(multibus, 8, inverted_logic)
    def __init__(self):
        self._a2d_chan_speed = a2d_chan_speed
        self._a2d_chan_direction = a2d_chan_direction
        self._a2d_chan_vcc = a2d_chan_vcc
        
        self._file_report_period = file_report_period

        self._i2c_helper = ABEHelpers()
        self._bus = self._i2c_helper.get_smbus()
        self._adc = ADCPi(self._bus, 0x68, 0x69, 12)

        self._CtrlPort = 8200
        self._IPAddr = self.get_local_ip()
        self._samples = list()
        self._samples_lock = threading.Lock()        
        self._display_lock = threading.Lock()        

        self._thread_sampling_obj = None
        self._thread_reporting_obj = None
        self._stop_requested = False

        self._dirs_stream = list() #stream of directions searched for callibration samples
        
        #calibrated directions
        self._dirs = list()
        self._dirs_volts = list()
        self._dirs_names = ("NN", "NE", "EE", "SE", "SS", "SW", "WW", "NW")
        self._dirs_file = "/home/pi/PyProj/dirs_calibration.txt"

        self._calibration_restore()
        self.files_to_compress = list()
        self.display = False
    def __init__(self, drive):
        """ Standard Constructor """
        logging.info("Three Point Turn constructor")
        # set up ADC
        self.i2c_helper = ABEHelpers()
        self.bus = self.i2c_helper.get_smbus()
        self.adc = ADCPi(self.bus, 0x6a, 0x6b, 12)

        # define fixed values
        # red is typically 3.5V
        self.red_min = 3
        self.red = 3.5
        self.stopped = 0
        self.full_forward = 0.4
        self.half_forward = 0.3
        self.slow_forward = 0.1
        self.full_reverse = -0.3
        self.half_reverse = -0.15
        self.slow_reverse = -0.1

        self.straight = 0
        self.full_left = -1
        self.slow_left = -0.5
        self.rear_line_sensor = 2
        # same sensor for now
        self.front_line_sensor = 2
        self.max_rate = 2

        # Drivetrain is passed in
        self.drive = drive

        self.killed = False
Exemple #11
0
    def __init__(self, drive):
        """ Standard Constructor """
        logging.info("Proximity constructor")
        # set up ADC
        self.i2c_helper = ABEHelpers()
        self.bus = self.i2c_helper.get_smbus()
        self.adc = ADCPi(self.bus, 0x6a, 0x6b, 12)

        # define fixed values
        self.stopped = 0
        self.full_forward = 0.4
        self.slow_forward = 0.3
        self.full_reverse = -0.5
        self.slow_reverse = -0.25

        self.left_steering = -0.25
        self.right_steering = 0.25
        self.straight = 0
        self.distance_sensor = 1

        # Voltage value we are aiming for (2 was close, 0.5 was further away)
        self.distance_threshold = 50.0
        self.distance_required = 17.0

        # Drivetrain is passed in
        self.drive = drive
        self.killed = False
Exemple #12
0
    def __init__(self, drive):
        """ Standard Constructor """
        logging.info("Straight Line Speed constructor")
        # set up ADC
        self.i2c_helper = ABEHelpers()
        self.bus = self.i2c_helper.get_smbus()
        self.adc = ADCPi(self.bus, 0x6a, 0x6b, 12)

        # define fixed values
        self.stopped = 0
        self.full_forward = 0.5
        self.slow_forward = 0.1
        self.full_reverse = -0.5
        self.slow_reverse = -0.1

        self.left_steering = -0.25
        self.right_steering = 0.25
        self.straight = 0
        self.distance_sensor = 1

        # Voltage value we are aiming for (2 was close, 0.5 was further away)
        self.nominal_voltage = 0.5
        self.min_dist_voltage = 2.0
        self.max_dist_voltage = 0.4

        # Drivetrain is passed in
        self.drive = drive
        self.killed = False
Exemple #13
0
def main():
    """ Main function """
    logging.basicConfig(filename="logger.txt", level=logging.ERROR)
    logging.basicConfig(level=logging.ERROR)

    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()
    adc_instance = ADCPi(bus, 0x68, 0x69, 18)

    pressurereader = PressureReader(adc_instance)
    pressurereader.daemon = True
    pressurereader.start()

    codenames = ['chemlab312_sample_storage_pressure']
    loggers = {}
    for i in range(0, 1):
        loggers[codenames[i]] = ValueLogger(pressurereader,
                                            comp_val=0.05,
                                            comp_type='log')
        loggers[codenames[i]].start()
    socket = DateDataPullSocket('chemlab312_sample_storage',
                                codenames,
                                timeouts=[2.0])
    socket.start()

    live_socket = LiveSocket('chemlab312_sample_storage', codenames, 2)
    live_socket.start()

    db_logger = ContinuousDataSaver(
        continuous_data_table='dateplots_chemlab312',
        username=credentials.user,
        password=credentials.passwd,
        measurement_codenames=codenames)
    db_logger.start()

    time.sleep(5)

    while True:
        time.sleep(0.5)
        for name in codenames:
            value = loggers[name].read_value()
            socket.set_point_now(name, value)
            live_socket.set_point_now(name, value)
            if loggers[name].read_trigged():
                print(value)
                db_logger.save_point_now(name, value)
                loggers[name].clear_trigged()
class dld_solar_window:
    _channel = 0
    _report_period = 5

    _thread = None
    _stop_requested = False

    _srv_ip_addr = "1.2.2.201"
    _srv_port = 8200

    def __init__(self, channel=0, report_period=the_report_period):
        self._channel = channel
        self._report_period = report_period
        self._i2c_helper = ABEHelpers()
        self._bus = self._i2c_helper.get_smbus()
        self._adc = ADCPi(self._bus, 0x68, 0x69, 12)

    def Start(self):
        self._stop_requested = False
        self._thread = threading.Thread(target=self.SamplingThread)
        self._thread.start()
        print("sampling thread initialized")

    def SamplingThread(self):
        print("sampling thread started")

        mc_socket = None

        time_last_report = time.time()
        connected = False
        while self._stop_requested != True:
            if connected == False:
                try:
                    # time.sleep(5)
                    mc_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    mc_socket.connect((self._srv_ip_addr, self._srv_port))
                    print("connected")
                    time.sleep(1)
                except Exception as e:
                    connected = False
                    continue

            time_now = time.time()
            voltage = self._adc.read_voltage(self._channel)

            try:
                mc_socket.send("Vout:%02f\n" % (voltage))
                print("Vout:%02f\n" % (voltage))
            except Exception as e:
                connected = False
            time.sleep(5.0)

    def Stop(self):
        if self._thread == None:
            return
        self._stop_requested = True
        if self._thread.isAlive():
            self._thread.join()
        self._thread = None
Exemple #15
0
def init_servos(address):
    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()
    pwm = PWM(bus, address)
    pwm.set_pwm_freq(60)
    pwm.output_enable()

    # cycle the arms on channels 0, 2, 4
    print("cycling through all valid positions")
    for x in (175, 300, 425, 550):
        pwm.set_pwm(0, 0, x)
        sleep(1)
        pwm.set_pwm(2, 0, x)
        sleep(1)
        pwm.set_pwm(4, 0, x)
        sleep(2)
    return pwm
def main():
    """ Main function """
    logging.basicConfig(filename="logger.txt", level=logging.ERROR)
    logging.basicConfig(level=logging.ERROR)

    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()
    adc_instance = DeltaSigma(bus, 0x68, 0x69, 18)

    tempreader = TemperatureReader(adc_instance)
    tempreader.daemon = True
    tempreader.start()

    codenames = ['cooling_water_hot', 'cooling_water_cold']
    loggers = {}
    for i in range(0, 2):
        loggers[codenames[i]] = ValueLogger(tempreader,
                                            comp_val=0.5,
                                            channel=i)
        loggers[codenames[i]].start()
    socket = DateDataPullSocket('hall_cooling_water_temp',
                                codenames,
                                timeouts=2.0)
    socket.start()

    live_socket = LiveSocket('hall_waterpressure', codenames)
    live_socket.start()

    db_logger = ContinuousDataSaver(continuous_data_table='dateplots_hall',
                                    username=credentials.user,
                                    password=credentials.passwd,
                                    measurement_codenames=codenames)
    db_logger.start()

    time.sleep(5)

    while tempreader.is_alive():
        time.sleep(0.25)
        for name in codenames:
            value = loggers[name].read_value()
            socket.set_point_now(name, value)
            live_socket.set_point_now(name, value)
            if loggers[name].read_trigged():
                print(value)
                db_logger.save_point_now(name, value)
                loggers[name].clear_trigged()
Exemple #17
0
def init_servos(address):
    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()
    pwm = PWM(bus, address)
    pwm.set_pwm_freq(60)
    pwm.output_enable()

    # cycle the arms on channels 0, 2, 4
    print('cycling through all valid positions')
    for x in (175, 300, 425, 550):
        pwm.set_pwm(0, 0, x)
        sleep(1)
        pwm.set_pwm(2, 0, x)
        sleep(1)
        pwm.set_pwm(4, 0, x)
        sleep(2)
    return pwm
	def run(self):
		global mph
		global flag
		t1 = 0
		t2 = 0
		flagMine = 0
		diameter = 14     # need to find the actual diameter !!!

		i2c_helper = ABEHelpers()
		bus = i2c_helper.get_smbus()
		adc = ADCDifferentialPi(bus, i2cAddr1, i2cAddr2, bitRate)
		while True:
			c.acquire()
			if flag == 1:
				flag = 0
				voltage = adc.read_voltage( channel )               # voltage output from hall sensor (either a pos. or neg. value)
				curTime = time.time() - initTime                    # calculates the current time from time acc. minus time started with

				if voltage < 0.0 and flagMine == 0:                     # if voltage is neg. and we have not passed by the magnet yet
					flagMine = 1
					t1 = t2                                             # stores the previous curent time from curTime
					t2 = curTime                                        # stores the current time in curTime
					rps = 1/(t2 - t1)                                   # revolutions per second
					mph = rps * (math.pi) * diameter * (3600/63360)     # conversion from rps to miles per second
					#mph = rps*60

					#print( str(curTime) + "," + str(voltage) + "," + str(mph) )
					#text_file.write( str(curTime) + "," + str(voltage) + "," + str(mph) + "\n" )

				elif voltage < 0.0 and flagMine == 1:                   # else if voltage is neg. but we are currently still passing by the magnet
					#print( str(curTime) + "," + str(voltage) )
					#text_file.write( str(curTime) + "," + str(voltage) + "\n" )
					temp = 1

				else:                                               # else the voltage is positive (meaning the magnet is not next the the hall sensor)
					flagMine = 0
					#print( str(curTime) + "," + str(voltage) )
					#text_file.write( str(curTime) + "," + str(voltage) + "\n" )

				#mph = mph + 1
				c.notify_all()
			else:
				c.wait()
			c.release()
		text_file.close()	
Exemple #19
0
    def __init__(self):
        """ Standard Constructor """
        logging.info("Three Point Turn constructor")
        # set up ADC
        self.i2c_helper = ABEHelpers()
        self.bus = self.i2c_helper.get_smbus()
        self.adc = ADCPi(self.bus, 0x6a, 0x6b, 12)

        self.killed = False
Exemple #20
0
def main():
    """ Main function """
    logging.basicConfig(filename="logger.txt", level=logging.ERROR)
    logging.basicConfig(level=logging.ERROR)

    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()
    adc_instance = ADCPi(bus, 0x68, 0x69, 18)

    pressurereader = PressureReader(adc_instance)
    pressurereader.daemon = True
    pressurereader.start()

    codenames = ["chemlab312_sample_storage_pressure"]
    loggers = {}
    for i in range(0, 1):
        loggers[codenames[i]] = ValueLogger(pressurereader, comp_val=0.05, comp_type="log")
        loggers[codenames[i]].start()
    socket = DateDataPullSocket("chemlab312_sample_storage", codenames, timeouts=[2.0])
    socket.start()

    live_socket = LiveSocket("chemlab312_sample_storage", codenames)
    live_socket.start()

    db_logger = ContinuousDataSaver(
        continuous_data_table="dateplots_chemlab312",
        username=credentials.user,
        password=credentials.passwd,
        measurement_codenames=codenames,
    )
    db_logger.start()

    time.sleep(5)

    while True:
        time.sleep(0.5)
        for name in codenames:
            value = loggers[name].read_value()
            socket.set_point_now(name, value)
            live_socket.set_point_now(name, value)
            if loggers[name].read_trigged():
                print(value)
                db_logger.save_point_now(name, value)
                loggers[name].clear_trigged()
Exemple #21
0
def main():
    """ Main function """
    logging.basicConfig(filename="logger.txt", level=logging.ERROR)
    logging.basicConfig(level=logging.ERROR)

    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()
    adc_instance = DeltaSigma(bus, 0x68, 0x69, 18)

    tempreader = TemperatureReader(adc_instance)
    tempreader.daemon = True
    tempreader.start()

    codenames = ["cooling_water_hot", "cooling_water_cold"]
    loggers = {}
    for i in range(0, 2):
        loggers[codenames[i]] = ValueLogger(tempreader, comp_val=0.5, channel=i)
        loggers[codenames[i]].start()
    socket = DateDataPullSocket("hall_cooling_water_temp", codenames, timeouts=2.0)
    socket.start()

    live_socket = LiveSocket("hall_waterpressure", codenames)
    live_socket.start()

    db_logger = ContinuousDataSaver(
        continuous_data_table="dateplots_hall",
        username=credentials.user,
        password=credentials.passwd,
        measurement_codenames=codenames,
    )
    db_logger.start()

    time.sleep(5)

    while tempreader.is_alive():
        time.sleep(0.25)
        for name in codenames:
            value = loggers[name].read_value()
            socket.set_point_now(name, value)
            live_socket.set_point_now(name, value)
            if loggers[name].read_trigged():
                print(value)
                db_logger.save_point_now(name, value)
                loggers[name].clear_trigged()
def main():
    """ Main function """
    logging.basicConfig(filename="logger.txt", level=logging.ERROR)
    logging.basicConfig(level=logging.ERROR)

    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()
    adc_instance = ADCPi(bus, 0x68, 0x69, 18)
    pressurereader = PressureReader(adc_instance)
    pressurereader.daemon = True
    pressurereader.start()

    logger = ValueLogger(pressurereader, comp_val=0.5)
    logger.start()

    socket = DateDataPullSocket('hall_n5_argon_pressure',
                                ['n5_argon_pressure'],
                                timeouts=[1.0])
    socket.start()

    live_socket = LiveSocket('hall_n5_argon_pressure', ['n5_argon_pressure'],
                             2)
    live_socket.start()

    db_logger = ContinuousDataSaver(
        continuous_data_table='dateplots_hall',
        username=credentials.user,
        password=credentials.passwd,
        measurement_codenames=['n5_argon_pressure'])
    db_logger.start()

    time.sleep(2)

    while True:
        time.sleep(0.25)
        value = logger.read_value()
        socket.set_point_now('n5_argon_pressure', value)
        live_socket.set_point_now('n5_argon_pressure', value)
        if logger.read_trigged():
            print(value)
            db_logger.save_point_now('n5_argon_pressure', value)
            logger.clear_trigged()
    def __init__(self, channel = 1, dir_channel = 2, wind_power_channel = 3, report_period = the_report_period):
        self._channel = channel
        self._dir_channel = dir_channel
        self._wind_power_channel = wind_power_channel
        self._temp_channel = 4
        self._report_period = report_period
        self._i2c_helper = ABEHelpers()
        self._bus = self._i2c_helper.get_smbus()
        self._adc = ADCPi(self._bus, 0x68, 0x69, 12)

        self._IPAddr = self.GetLocalIP()
	def set_robot(self, servo_configuration_robot):
		self.servo_robot = servo_configuration_robot
		
		
		
		self.i2c_helper = ABEHelpers()
		self.bus = self.i2c_helper.get_smbus()
		self.pwm = PWM(self.bus, 0x6f) # take care to know the real port
		
		self.pwm.output_enable()
		self.pwm.set_pwm_freq(60)
Exemple #25
0
def main():
    """ Main function """

    logging.basicConfig(filename="logger.txt", level=logging.ERROR)
    logging.basicConfig(level=logging.ERROR)

    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()
    adc_instance = DeltaSigma(bus, 0x68, 0x69, 18)
    pressurereader = PressureReader(adc_instance)
    pressurereader.daemon = True
    pressurereader.start()

    codenames = ['mr_iongauge_pressure']

    logger = ValueLogger(pressurereader, comp_val=0.5)
    logger.start()

    socket = DateDataPullSocket('Microreactor Ion Gauge', codenames, timeouts=[1.0])
    socket.start()

    live_socket = LiveSocket('Microreactor Ion Gauge', codenames)
    live_socket.start()

    db_logger = ContinuousDataSaver(continuous_data_table='dateplots_microreactor',
                                    username=credentials.user,
                                    password=credentials.passwd,
                                    measurement_codenames=codenames)
    db_logger.start()

    time.sleep(2)

    while True:
        time.sleep(0.25)
        value = logger.read_value()
        socket.set_point_now(codenames[0], value)
        live_socket.set_point_now(codenames[0], value)
        if logger.read_trigged():
            print(value)
            db_logger.save_point_now(codenames[0], value)
            logger.clear_trigged()
Exemple #26
0
def StrainGauge():
    text_file = open("strainGuage_Data.txt", "w")

    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()
    adc = ADCDifferentialPi(bus, i2cAddr1, i2cAddr2, bitRate)

    adc.set_pga(
        1)  # Set the gain of the PDA on the chip (Parameters: gain - 1,2,4,8)

    prev_voltage = 0

    for i in range(10000):
        voltage = adc.read_voltage(channel)  # voltage output from strain Gauge

        changeInVoltage = voltage - prev_voltage
        prev_voltage = voltage

        #print( str(changeInVoltage * 1000) )

        text_file.write(str(voltage) + "\n")
def main():
    monitor = PeakMonitor(SINK_NAME, METER_RATE)
    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()

    pwm = PWM(bus, 0x40)

    # Set PWM frequency to 60 Hz
    pwm.set_pwm_freq(60)
    pwm.output_enable()
    
    for sample in monitor:
        sample = sample >> DISPLAY_SCALE
        step = ((4000 - 0) / 100.0)
        sample = int(step * sample)

        print ' %3d' % sample

        sys.stdout.flush()

	pwm.set_pwm(8, 0, (randint(0,1) * sample))
	pwm.set_pwm(7, 0, (randint(0,1) * sample))
	pwm.set_pwm(6, 0, (randint(0,1) * sample))
Exemple #28
0
    def __init__(self,
                 bus=None,
                 address=None,
                 address2=None,
                 samplerate=None,
                 gain=None):
        from ABE_helpers import ABEHelpers
        from ABE_ADCDifferentialPi import ADCDifferentialPi

        if bus is None:
            i2c_helper = ABEHelpers()
            bus = i2c_helper.get_smbus()

        # Initialize the ADC device using the default addresses and sample rate 18.
        # Sample rate can be 12, 14, 16 or 18.
        self.adc = ADCDifferentialPi(bus,
                                     address=address,
                                     address2=address2,
                                     rate=samplerate)

        # Set amplifier gain to 8.
        if gain is not None:
            self.adc.set_pga(gain)
def main():

    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()
    adc = ADCPi(bus, 0x68, 0x69, 18)

    if not os.path.isfile(db_name):
        createdb()
 
    while (True):
        temp = 0
        light = 0
        moisture = 0

        for x in range(0, 60):
            # read from adc channels and write to the log file
            temp = temp + (adc.read_voltage(1) - 0.5) * 100
            light = light + adc.read_voltage(2)
            moisture = moisture + adc.read_voltage(3)
            time.sleep(0.4)

        # Average temp
        temp = temp / 60
        # Correct temp
        temp = temp - 1.2
	
        # Average light
        light = light / 60

        # Average moisture
        moisture =  moisture / 60

        print("temp,light,moisture")
        print(temp)
        print(light)
        print(moisture)
        writetodb("%02f" % temp, "%02f" % light, "%02f" % moisture)
    def __init__(self):
        self._a2d_chan_speed = a2d_chan_speed
        self._a2d_chan_direction = a2d_chan_direction
        self._a2d_chan_vcc = a2d_chan_vcc
        
        self._file_report_period = file_report_period

        self._i2c_helper = ABEHelpers()
        self._bus = self._i2c_helper.get_smbus()
        self._adc = ADCPi(self._bus, 0x68, 0x69, 12)

        self._CtrlPort = 8200
        self._IPAddr = self.get_local_ip()
        self._samples = list()
        self._samples_lock = threading.Lock()        

        self._thread_sampling = None
        self._thread_reporting = None
        self._stop_requested = False
Exemple #31
0
class line_test:
    def __init__(self):
        """ Standard Constructor """
        logging.info("Three Point Turn constructor")
        # set up ADC
        self.i2c_helper = ABEHelpers()
        self.bus = self.i2c_helper.get_smbus()
        self.adc = ADCPi(self.bus, 0x6a, 0x6b, 12)

        self.killed = False

    def run(self, line_sensor=None):
        logging.info("Started Looking")

        while not self.killed:
            # If we have a line sensor, check it here. Bail if necesary
            #if line_sensor and (self.adc.read_voltage(line_sensor) > self.red_min):
            #    logging.info("Line Detected")
            if line_sensor:
                logging.info(str(self.adc.read_voltage(line_sensor)))
            time.sleep(0.05)
Exemple #32
0
class line_test:
    def __init__(self):
        """ Standard Constructor """
        logging.info("Three Point Turn constructor")
        # set up ADC
        self.i2c_helper = ABEHelpers()
        self.bus = self.i2c_helper.get_smbus()
        self.adc = ADCPi(self.bus, 0x6a, 0x6b, 12)

        self.killed = False

    def run(self, line_sensor=None):
        logging.info("Started Looking")

        while not self.killed:
            # If we have a line sensor, check it here. Bail if necesary
            #if line_sensor and (self.adc.read_voltage(line_sensor) > self.red_min):
            #    logging.info("Line Detected")
            if line_sensor:
                logging.info( str(self.adc.read_voltage(line_sensor)) )
            time.sleep(0.05)
Exemple #33
0
class ThreePointTurn:
    def __init__(self, drive):
        """ Standard Constructor """
        logging.info("Three Point Turn constructor")
        # set up ADC
        self.i2c_helper = ABEHelpers()
        self.bus = self.i2c_helper.get_smbus()
        self.adc = ADCPi(self.bus, 0x6a, 0x6b, 12)

        # define fixed values
        # red is typically 3.5V
        self.red_min = 3
        self.red = 3.5
        self.stopped = 0
        self.full_forward = 0.5
        self.half_forward = 0.25
        self.slow_forward = 0.1
        self.full_reverse = -0.5
        self.half_reverse = -0.25
        self.slow_reverse = -0.1

        self.straight = 0
        self.full_left = -1
        self.slow_left = -0.5
        self.rear_line_sensor = 2
        # same sensor for now
        self.front_line_sensor = 2
        self.max_rate = 2

        # Drivetrain is passed in
        self.drive = drive

        self.killed = False

    def run(self):
        """ Main call to run the three point turn script """
        # initiate camera

        # initialise throttle to 0
        # forward to turning point
        logging.info("forward to turning point")
        self.move_segment(total_timeout=0.6,
                          line_sensor=self.rear_line_sensor,
                          throttle=self.full_forward,
                          steering=self.straight)
        # required slow speed braking
        logging.info("appling break")
        self.move_segment(total_timeout=0.4,
                          line_sensor=self.rear_line_sensor,
                          throttle=self.slow_forward,
                          steering=self.straight)
        # required slow speed braking
        logging.info("aggressive break")
        self.move_segment(total_timeout=0.25,
                          line_sensor=self.rear_line_sensor,
                          throttle=self.half_reverse,
                          steering=self.straight)
        # first left turn
        logging.info("first left turn")
        self.move_segment(total_timeout=0.1,
                          throttle=self.stopped,
                          steering=self.full_left)
        # Slow left turn (braking)
        #logging.info("first left turn")
        #self.move_segment(
        #    total_timeout=0.2,
        #    throttle=self.stopped,
        #    steering=self.slow_left
        # )
        # forward to first side line
        logging.info("forward to first side line")
        throttle = self.move_segment(total_timeout=0.2,
                                     line_sensor=self.front_line_sensor,
                                     throttle=self.full_forward,
                                     steering=self.straight)
        # required slow speed braking
        #logging.info("appling break")
        #self.move_segment(
        #    total_timeout=0.1,
        #    line_sensor=self.rear_line_sensor,
        #    throttle=self.slow_forward,
        #    steering=self.straight
        #)
        # reverse portion to second side line
        logging.info("reverse to second side line")
        throttle = self.move_segment(total_timeout=0.5,
                                     line_sensor=self.rear_line_sensor,
                                     throttle=self.full_reverse,
                                     steering=self.straight)
        # required slow speed braking
        logging.info("appling break")
        self.move_segment(total_timeout=0.1,
                          line_sensor=self.rear_line_sensor,
                          throttle=self.slow_forward,
                          steering=self.straight)

        # required slow speed braking
        #logging.info("appling break")
        #self.move_segment(
        #    total_timeout=0.1,
        #    line_sensor=self.rear_line_sensor,
        #    throttle=self.slow_reverse,
        #    steering=self.straight
        #)
        # throttle = self.move_segment(
        #     total_timeout=0.75,
        #     accelerating_time=0.3,
        #     line_sensor=self.rear_line_sensor,
        #     max_throttle=self.
        #     full_reverse,
        #     max_steering=self.
        #     straight,
        #     end_throttle=self.
        #     slow_reverse,
        #     end_steering=self.
        #     straight,
        #     start_throttle=throttle
        # )
        # # reverse portion to second side line
        # throttle = self.move_segment(
        #     total_timeout=0.4,
        #     accelerating_time=0.2,
        #     max_throttle=self.full_forward,
        #     max_steering=self.straight,
        #     end_throttle=self.slow_forward,
        #     end_steering=self.straight,
        #     start_throttle=throttle
        # )
        # # second left turn
        # throttle = self.move_segment(
        #     total_timeout=0.3,
        #     accelerating_time=0.15,
        #     max_throttle=self.stopped,
        #     max_steering=self.full_left,
        #     end_throttle=self.straight,
        #     end_steering=self.slow_forward,
        #     start_throttle=throttle
        # )
        # # return to start
        # throttle = self.move_segment(
        #     total_timeout=0.35,
        #     accelerating_time=0.35,
        #     line_sensor=self.front_line_sensor,
        #     max_throttle=self.full_forward,
        #     max_steering=self.straight,
        #     end_throttle=self.slow_forward,
        #     end_steering=self.straight
        # )
        # # enter start box
        # throttle = self.move_segment(
        #     total_timeout=0.4,
        #     accelerating_time=0.2,
        #     line_sensor=self.rear_line_sensor,
        #     max_throttle=self.slow_forward,
        #     max_steering=self.straight,
        #     end_throttle=self.stopped,
        #     end_steering=self.straight
        # )
        # Final set motors to neutral to stop
        self.drive.set_neutral()
        self.stop()

    def stop(self):
        """Simple method to stop the challenge"""
        self.killed = True

    def move_segment(self,
                     total_timeout=0,
                     line_sensor=None,
                     throttle=0,
                     steering=0):
        logging.info("move_segment called with arguments: {0}".format(
            locals()))
        # Note Line_sensor=0 if no line sensor exit required
        # calculate timeout times
        now = datetime.now()
        end_timeout = now + timedelta(seconds=total_timeout)

        last_throttle_update = None

        while not self.killed and (datetime.now() < end_timeout):
            logging.info("mixing channels: {0} : {1}".format(
                throttle, steering))
            # Swapped steering/throttle
            self.drive.mix_channels_and_assign(steering, throttle)
            # If we have a line sensor, check it here. Bail if necesary
            if line_sensor and (self.adc.read_voltage(line_sensor) >
                                self.red_min):
                logging.info("Line Detected")
                break

            # if now < acceleration_timeout:
            #     throttle, last_throttle_update = self.ease_value(
            #         start_throttle,
            #         max_throttle,
            #         self.max_rate,
            #         last_throttle_update
            #     )
            #     steering = max_steering
            # else:
            #     # easing needs adding
            #     throttle = end_throttle
            #     steering = end_steering
            time.sleep(0.05)

        logging.info("Finished manoeuvre")
        # must have got better than usual acceleration.
        # need to slow down before finishing
        # if throttle != end_throttle or steering != end_steering:
        #     # needs easing adding
        #     throttle = end_throttle
        #     # needs easing adding
        #     steering = end_steering
        #     self.drive.mix_channels_and_assign(throttle, steering)
        return throttle

    def ease_value(self, current_value, target, rate, last_update_time=None):
        now = datetime.now()
        if last_update_time is None:
            last_update_time = now
        # if variable is above target
        if current_value > target:
            new_value = max(
                target, current_value - rate * int(
                    (now - last_update_time).total_seconds()))
        # or variable is below target
        if current_value <= target:
            new_value = max(
                target, current_value + rate * int(
                    (now - last_update_time).total_seconds()))
        last_update_time = datetime.now()
        return new_value, last_update_time
class App:
    global i2c_helper
    global newbus
    global bus2

    def __init__(self, master):
        self.i2c_helper = ABEHelpers()
        self.newbus = self.i2c_helper.get_smbus()
        self.bus2 = IoPi(
            self.newbus, 0x21
        )  # create an instance of Bus 2 which is on I2C address 0x21 by default
        self.bus2.set_port_direction(
            0, 0x00)  # set pins 1 to 8 to be outputs and turn them off
        self.bus2.write_port(0, 0x00)

        self.bus2.set_port_direction(
            1, 0x00)  # set pins 9 to 16 to be outputs and turn them off
        self.bus2.write_port(1, 0x00)

        frame = Frame(master)  # create a frame for the GUI
        frame.pack()

        # create 16 buttons which run the togglepin function when pressed
        self.button = Button(frame,
                             text="Pin 1",
                             command=lambda: self.togglepin(1))
        self.button.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 2",
                             command=lambda: self.togglepin(2))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 3",
                             command=lambda: self.togglepin(3))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 4",
                             command=lambda: self.togglepin(4))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 5",
                             command=lambda: self.togglepin(5))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 6",
                             command=lambda: self.togglepin(6))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 7",
                             command=lambda: self.togglepin(7))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 8",
                             command=lambda: self.togglepin(8))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 9",
                             command=lambda: self.togglepin(9))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 10",
                             command=lambda: self.togglepin(10))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 11",
                             command=lambda: self.togglepin(11))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 12",
                             command=lambda: self.togglepin(12))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 13",
                             command=lambda: self.togglepin(13))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 14",
                             command=lambda: self.togglepin(14))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 15",
                             command=lambda: self.togglepin(15))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 16",
                             command=lambda: self.togglepin(16))
        self.slogan.pack(side=LEFT)

    def togglepin(self, pin):
        # read the status from the selected pin, invert it and write it back to the pin
        pinstatus = self.bus2.read_pin(pin)
        if (pinstatus == 1):
            pinstatus = 0
        else:
            pinstatus = 1
        self.bus2.write_pin(pin, pinstatus)
Exemple #35
0
class Proximity:
    def __init__(self, drive):
        """ Standard Constructor """
        logging.info("Proximity constructor")
        # set up ADC
        self.i2c_helper = ABEHelpers()
        self.bus = self.i2c_helper.get_smbus()
        self.adc = ADCPi(self.bus, 0x6a, 0x6b, 12)

        # define fixed values
        self.stopped = 0
        self.full_forward = 0.4
        self.slow_forward = 0.3
        self.full_reverse = -0.5
        self.slow_reverse = -0.25

        self.left_steering = -0.25
        self.right_steering = 0.25
        self.straight = 0
        self.distance_sensor = 1

        # Voltage value we are aiming for (2 was close, 0.5 was further away)
        self.distance_threshold = 50.0
        self.distance_required = 17.0

        # Drivetrain is passed in
        self.drive = drive
        self.killed = False

    def stop(self):
        """Simple method to stop the challenge"""
        self.killed = True

    def run(self):
        """ Main call to run the three point turn script """
        # Drive forward for a set number of seconds keeping distance equal
        logging.info("forward to turning point")
        self.move_segment()

        # Final set motors to neutral to stop
        logging.info("Finished Event")
        self.drive.set_neutral()

    def get_distance(self):
        distance = 0.0
        if self.distance_sensor:
            voltage = self.adc.read_voltage(self.distance_sensor)
            distance = 27.0 / voltage
        return distance

    def move_segment(self):
        logging.info("move_segment called with arguments: {0}".format(locals()))

        # Throttle is static and does not change
        throttle = self.full_forward
        # Steering starts at zero (straight forward)
        steering = self.straight

        # Drive forward at half speed until we get reasonably close
        distance = self.get_distance()
        logging.info("distance: {0}".format(distance))
        time.sleep(0.05)
        while not self.killed and (distance > self.distance_threshold):
            self.drive.mix_channels_and_assign(self.straight, self.full_forward)
            distance = self.get_distance()
            logging.info("F: distance: {0}".format(distance))
            time.sleep(0.05)

        self.drive.set_neutral()
        time.sleep(0.05)
        logging.info("Entering Half Speed")

        # Drive forward at slow/min speed until we get very close
        while not self.killed and (distance > self.distance_required):
            self.drive.mix_channels_and_assign(self.straight, self.slow_forward)
            distance = self.get_distance()
            logging.info("S: distance: {0}".format(distance))
            time.sleep(0.05)

        # Ever so slight brake
        self.drive.mix_channels_and_assign(self.straight, self.slow_reverse)
        time.sleep(0.05)
        self.drive.set_neutral()
        time.sleep(0.05)
        logging.info("Finished manoeuvre")
================================================
ABElectronics IO Pi 32-Channel Port Expander - Read Write Demo
Version 1.0 Created 29/02/2015

Requires python 3 smbus to be installed
run with: python3 demo-iopireadwrite.py
================================================

This example reads pin 1 of bus 1 on the IO Pi board and sets pin 1 of bus 2 to match.  
The internal pull-up resistors are enabled so the input pin will read as 1 unless
the pin is connected to ground. 

Initialise the IOPi device using the default addresses, you will need to
change the addresses if you have changed the jumpers on the IO Pi
"""
i2c_helper = ABEHelpers()
i2c_bus = i2c_helper.get_smbus()

# create two instances of the IoPi class called bus1 and bus2 and set the default i2c addresses

bus1 = IoPi(i2c_bus, 0x20)  # bus 1 will be inputs
bus2 = IoPi(i2c_bus, 0x21)  # bus 2 will be outputs

# Each bus is divided up two 8 bit ports.  Port 0 controls pins 1 to 8, Port 1 controls pins 9 to 16.
# We will read the inputs on pin 1 of bus 1 so set port 0 to be inputs and
# enable the internal pull-up resistors
bus1.set_port_direction(0, 0xFF)
bus1.set_port_pullups(0, 0xFF)

# We will write to the output pin 1 on bus 2 so set port 0 to be outputs and
# turn off the pins on port 0
Exemple #37
0
def init_nox():
    """ init the sensor reader """
    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()
    adc = ADCPi(bus, 0x6A, 0x6B, 12)
    return adc
Exemple #38
0
class Proximity:
    def __init__(self, drive):
        """ Standard Constructor """
        logging.info("Straight Line Speed constructor")
        # set up ADC
        self.i2c_helper = ABEHelpers()
        self.bus = self.i2c_helper.get_smbus()
        self.adc = ADCPi(self.bus, 0x6a, 0x6b, 12)

        # define fixed values
        self.stopped = 0
        self.full_forward = 0.5
        self.slow_forward = 0.1
        self.full_reverse = -0.5
        self.slow_reverse = -0.1

        self.left_steering = -0.25
        self.right_steering = 0.25
        self.straight = 0
        self.distance_sensor = 1

        # Voltage value we are aiming for (2 was close, 0.5 was further away)
        self.nominal_voltage = 0.5
        self.min_dist_voltage = 2.0
        self.max_dist_voltage = 0.4

        # Drivetrain is passed in
        self.drive = drive
        self.killed = False

    def stop(self):
        """Simple method to stop the challenge"""
        self.killed = True

    def run(self):
        """ Main call to run the three point turn script """
        # Drive forward for a set number of seconds keeping distance equal
        logging.info("forward to turning point")
        self.move_segment( total_timeout=10.0 )

        # Final set motors to neutral to stop
        self.drive.set_neutral()
        self.stop()

    def move_segment( self, total_timeout=0 ):
        logging.info("move_segment called with arguments: {0}".format(locals()))
        # Note Line_sensor=0 if no line sensor exit required
        # calculate timeout times
        now = datetime.now()
        end_timeout = now + timedelta(seconds=total_timeout)

        # Throttle is static and does not change
        throttle = self.full_forward
        # Steering starts at zero (straight forward)
        steering = self.straight

        while not self.killed and (datetime.now() < end_timeout):
            # If we have a line sensor, check it here. Bail if necesary
            if distance_sensor:
                voltage = self.adc.read_voltage(distance_sensor)
                voltage_diff = voltage - self.nominal_voltage
                steering = interp(
                        voltage_diff,
                        [self.min_dist_voltage, self.max_dist_voltage]
                        [self.left_steering, self.right_steering],
                    )
                )

            # Had to invert throttle and steering channels to match RC mode
            logging.info("mixing channels: {0} : {1}".format(throttle, steering))
            self.drive.mix_channels_and_assign(steering, throttle)
            time.sleep(0.05)

        logging.info("Finished manoeuvre")
Exemple #39
0
def hallSen():
    # ADC Setup
    channel = 1  # analog channel number (1-8 inclusive)
    bitRate = 12  # programmable data rate
    # 18 (3.75 SPS) less per sec. but more accurate
    # 16 (  15 SPS) --
    # 14 (  60 SPS) --
    # 12 ( 240 SPS) more per sec. but less accurate

    i2cAddr1 = 0x68  # these addresses are associated with the Address Config. 1
    i2cAddr2 = 0x69

    text_file = open("hallSensor_Data_1.txt", "w")
    initTime = time.time()

    text_file.write(str(globalValue))
    text_file.flush()

    global t1
    global t2
    flag = 0
    diameter = 14  # need to find the actual diameter !!!

    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()
    adc = ADCDifferentialPi(bus, i2cAddr1, i2cAddr2, bitRate)

    global mph
    global flagThread
    global killH

    while True:
        if killH == True:
            text_file.close()
            time.sleep(10)
        else:
            voltage = adc.read_voltage(
                channel
            )  # voltage output from hall sensor (either a pos. or neg. value)
            curTime = time.time(
            ) - initTime  # calculates the current time from time acc. minus time started with

            if voltage < 0.0 and flag == 0:  # if voltage is neg. and we have not passed by the magnet yet
                flag = 1
                t1 = t2  # stores the previous curent time from curTime
                t2 = curTime  # stores the current time in curTime
                rps = 1 / (t2 - t1)  # revolutions per second
                flagThread = 1
                mph = rps * (math.pi) * diameter * (
                    3600 / 63360)  # conversion from rps to miles per second
                rpm = rps * 60
                flagThread = 0
                #mph = rps*60

                #print( str(curTime) + "," + str(voltage) + "," + str(mph) )
                text_file.write(str(curTime) + "," + str(rpm) + "\n")
                text_file.flush()

            elif voltage < 0.0 and flag == 1:  # else if voltage is neg. but we are currently still passing by the magnet
                #print( str(curTime) + "," + str(voltage) )
                #text_file.write( str(curTime) + "," + str(voltage) + "\n" )
                filler = 0

            else:  # else the voltage is positive (meaning the magnet is not next the the hall sensor)
                flag = 0
                #print( str(curTime) + "," + str(voltage) )
                #text_file.write( str(curTime) + "," + str(voltage) + "\n" )

                #time.sleep( 0.0100 )

    text_file.close()
Exemple #40
0
import RPi.GPIO as GPIO
import LCD1602 
from ABE_ADCPi import ADCPi             	#import the ADCPi library
from ABE_helpers import ABEHelpers      	#import ABEHelpers for smbus
import time		                	#import time module for delay
import smbus		                	#import smbus for i2c
LCD1602.init(0x27, 1)                   	#Assign LCD i2c address

GPIO.setwarnings(False)                 #remove uncecessary warnings
GPIO.setmode(GPIO.BCM)                  #setting pin mode to BCM

i2c_helper=ABEHelpers()	       #Creating instance of ABEHelpers() for i2c_bus object
bus=i2c_helper.get_smbus()	 	#Creating instance of i2c_bus
ADC=ADCPi(bus, 0X69, 0X6f, 18)   	#Set the i2c configuration address and bit rate
time.sleep(0.2)
#########

#Keypad input/output pins
GPIO.setup(19, GPIO.IN, pull_up_down = GPIO.PUD_UP) 
GPIO.setup(20, GPIO.IN, pull_up_down = GPIO.PUD_UP) 
GPIO.setup(21, GPIO.IN, pull_up_down = GPIO.PUD_UP) 
GPIO.setup(22, GPIO.IN, pull_up_down = GPIO.PUD_UP) 

GPIO.setup(23, GPIO.OUT) 
GPIO.setup(24, GPIO.OUT) 
GPIO.setup(25, GPIO.OUT) 
GPIO.setup(26, GPIO.OUT)

#Initializing the GPIO pins for Ultrasound, Buzzer, motion sensor, and LED
GPIO.setmode(GPIO.BCM) 
TRIG=13 #ultrasonic
class WindSpeedMeter():
    _channel = 0
    _report_period = 5
    _pulses_counter = 0
    _last_sample_pulses = 0
    _last_sample_time = 0

    _thread = None
    _stop_requested = False

    _IPAddr = "127.0.0.1"
    _CtrlPort = 8200

    _tr = temperature_resolver()


    def GetLocalIP(self):
        ifconfig_cmd = commands.getoutput("ifconfig")
        patt = re.compile(r'inet\s*\w*\S*:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
        addr_list = patt.findall(ifconfig_cmd)
        for addr in addr_list:
            if addr == "127.0.0.1":
                continue
##            if(self._nettype == NETTYPE.CELL):
##                if(addr.find("192.168.") == 0):
##                    continue
            if(addr.find('.')>0):
                return addr
        return "127.0.0.1"

    def __init__(self, channel = 1, dir_channel = 2, wind_power_channel = 3, report_period = the_report_period):
        self._channel = channel
        self._dir_channel = dir_channel
        self._wind_power_channel = wind_power_channel
        self._temp_channel = 4
        self._report_period = report_period
        self._i2c_helper = ABEHelpers()
        self._bus = self._i2c_helper.get_smbus()
        self._adc = ADCPi(self._bus, 0x68, 0x69, 12)

        self._IPAddr = self.GetLocalIP()


    def Start(self):
        self._stop_requested = False
        self._thread = threading.Thread(target=self.SamplingThread)
        self._thread.start()
        print("sampling thread initialized")

    def SendMCStatus(self, msg):
        mc_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        #mc_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        mc_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 100)
        mc_socket.bind((self._IPAddr, 8100))
        #mreq = struct.pack('4sl', socket.inet_aton("224.0.0.1"), socket.INADDR_ANY)
        mreq = struct.pack('4sl', socket.inet_aton("224.0.0.1"), socket.INADDR_ANY)
        mc_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        #mc_socket.sendto("init", ("224.0.0.1", 8100))

        mc_socket.sendto(msg, ("224.0.0.1", 8200))
        mc_socket.close()
        
    def SamplingThread(self):
        print("sampling thread started")

        last_voltage = 0
        time_last_report = time.time()
        self._last_sample_pulses = 0
        wind_v = 0
        while(self._stop_requested != True):
            time_now = time.time()
            voltage = self._adc.read_voltage(self._channel)
            if( (voltage > 0) and (last_voltage == 0)):
                self._pulses_counter += 1
                #print("pulses: " + str(self._pulses_counter))

                curr_wind_v = self._adc.read_voltage(self._wind_power_channel)
                wind_v += curr_wind_v

            last_voltage = voltage


            if(time_now > time_last_report):
                if(time_now - time_last_report >= self._report_period):
                    pulses = (self._pulses_counter - self._last_sample_pulses)
                    speed = (pulses * 3.14159 * 2 * 0.09)/(time_now - time_last_report)
                    vcc = self._adc.read_voltage(8)
                    direction = self._adc.read_voltage(self._dir_channel)
                    if(pulses != 0):
                        wind_v = wind_v/pulses
                    temp_v = self._adc.read_voltage(self._temp_channel)
                    temp_c, temp_f = self._tr.temp_read()
                    try:
                        msg = "VCC: %02f, WS: %0.3f(%03d), WD: %0.3f WndV: %0.3f TmpV: %0.3f Tmp: %0.3f" % \
                        (vcc, speed, pulses, direction, wind_v, temp_v, temp_c)
                        print(msg)
                        self.SendMCStatus(msg)
                    except Exception:
                        pass
                    self._last_sample_pulses = self._pulses_counter

                    globals()["g_wind_speed"] = speed
                    globals()["g_wind_speed_pulses"] = pulses
                    globals()["g_wind_direction"] = direction
                    globals()["g_wind_v"] = wind_v
                    globals()["g_vcc"] = vcc
                    globals()["g_temp_v"] = temp_v
                    globals()["g_temp_c"] = temp_c
                    globals()["g_temp_f"] = temp_f
                    time_last_report = time_now
                    wind_v = 0
            else:
                time_last_report = time_now
            time.sleep(0.01)

    def Stop(self):
        if(self._thread == None):
            return
        self._stop_requested = True
        if(self._thread.isAlive()):
            self._thread.join();
        self._thread = None
class wind_speed_meter():
    def __init__(self):
        self._a2d_chan_speed = a2d_chan_speed
        self._a2d_chan_direction = a2d_chan_direction
        self._a2d_chan_vcc = a2d_chan_vcc
        
        self._file_report_period = file_report_period

        self._i2c_helper = ABEHelpers()
        self._bus = self._i2c_helper.get_smbus()
        self._adc = ADCPi(self._bus, 0x68, 0x69, 12)

        self._CtrlPort = 8200
        self._IPAddr = self.get_local_ip()
        self._samples = list()
        self._samples_lock = threading.Lock()        

        self._thread_sampling = None
        self._thread_reporting = None
        self._stop_requested = False


    def get_local_ip(self):
        ifconfig_cmd = commands.getoutput("ifconfig")
        patt = re.compile(r'inet\s*\w*\S*:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
        addr_list = patt.findall(ifconfig_cmd)
        for addr in addr_list:
            if addr == "127.0.0.1":
                continue
##            if(self._nettype == NETTYPE.CELL):
##                if(addr.find("192.168.") == 0):
##                    continue
            if(addr.find('.')>0):
                return addr
        return "127.0.0.1"

    def start(self):
        self._stop_requested = False
        self._thread_sampling = threading.Thread(target=self.thread_sampling)
        self._thread_sampling.start()
        self._thread_reporting = threading.Thread(target=self.thread_reporting)
        self._thread_reporting.start()
        
    def thread_reporting(self):
        print("reporting thread started")
        mc_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        #mc_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        mc_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 100)
        mc_socket.bind((self._IPAddr, 0))
        #mreq = struct.pack('4sl', socket.inet_aton("224.0.150.150"), socket.INADDR_ANY)
        mreq = struct.pack('4sl', socket.inet_aton("224.0.1.200"), socket.INADDR_ANY)
        mc_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        #mc_socket.sendto("init", ("224.0.150.150", 8100))

        time_last_report = time.time()
        while(self._stop_requested != True):
            time_now = time.time()

            if(time_now - time_last_report < self._file_report_period) or (time_now < time_last_report):
                time.sleep(0.2)
                continue

            if(len(self._samples) > 0):
                self._samples_lock.acquire()
                smpl = self._samples.pop(0)
                print("extracted speed: {} ({}). list len: {}".format(str(smpl.speed_m_per_sec), smpl.speed_pulses, len(self._samples)))
                self._samples_lock.release()
            time_last_report = time_now

    def thread_sampling(self):
        print("sampling thread started")
        speed_voltage_last = 0
        speed_pulses_counter = 0
        last_sample_timestamp = 0
        time_now = time.time()
        time_last_sampling = time_now
        while(self._stop_requested != True):
            time_now = time.time()

            #read voltage from speed sensor
            speed_voltage = self._adc.read_voltage(self._a2d_chan_speed)
            if( (speed_voltage > 0) and (speed_voltage_last == 0)):
                #count only transitions from low to high signal
                speed_pulses_counter += 1
                #print("pulses: " + str(speed_pulses_counter))
            speed_voltage_last = speed_voltage

            if(time_now - time_last_sampling < self._file_report_period) or (time_now < time_last_sampling):
  #              time.sleep(0.001)
                continue

            smpl = sample()
            smpl.sample_time_stamp = time_now
            smpl.sample_time_span = time_now - time_last_sampling
            smpl.speed_pulses = speed_pulses_counter
            smpl.speed_m_per_sec = (speed_pulses_counter*2*math.pi*wind_sensor_radius)/smpl.sample_time_span

            if(self._a2d_chan_vcc != -1):
                vcc = self._adc.read_voltage(self._a2d_chan_vcc)

            if(a2d_chan_direction != -1):    
                smpl.direction_voltage = self._adc.read_voltage(self._dir_channel)
                smpl.direction_code = ""

            self._samples_lock.acquire()
            self._samples.append(smpl)
            print("speed: {} ({}). list len: {}".format(str(smpl.speed_m_per_sec), smpl.speed_pulses, len(self._samples)))
            self._samples_lock.release()

            speed_pulses_counter = 0
            time_last_sampling = time.time()


    def Stop(self):
        if(self._thread == None):
            return
        self._stop_requested = True
        if(self._thread.isAlive()):
            self._thread.join();
        self._thread = None
This example shows how to use the interrupt methods on the IO Pi.
The interrupts will be enabled and set so that a voltage applied to
pins 1 and 16 will trigger INT A and B respectively.
using the read_interrupt_capture or read_port methods will
reset the interrupts


Initialise the IOPi device using the default addresses and set the
output of bank 1 on IC1 to the input of bank 1 on IC2
"""
from ABE_helpers import ABEHelpers
from ABE_IoPi import IoPi
import time

i2c_helper = ABEHelpers()
newbus = i2c_helper.get_smbus()

bus1 = IoPi(newbus, 0x20)
bus2 = IoPi(newbus, 0x21)

# Set all pins on bus 2 to be inputs with internal pull-ups disabled.

bus2.set_port_pullups(0, 0x00)
bus2.set_port_pullups(1, 0x00)
bus2.set_port_direction(0, 0xFF)
bus2.set_port_direction(1, 0xFF)

# Set the interrupt polarity to be active high and mirroring disabled, so
# pins 1 to 8 trigger INT A and pins 9 to 16 trigger INT B
bus2.set_interrupt_polarity(1)
    def __init__(self, master):
        self.i2c_helper = ABEHelpers()
        self.newbus = self.i2c_helper.get_smbus()
        self.bus2 = IoPi(
            self.newbus, 0x21
        )  # create an instance of Bus 2 which is on I2C address 0x21 by default
        self.bus2.set_port_direction(
            0, 0x00)  # set pins 1 to 8 to be outputs and turn them off
        self.bus2.write_port(0, 0x00)

        self.bus2.set_port_direction(
            1, 0x00)  # set pins 9 to 16 to be outputs and turn them off
        self.bus2.write_port(1, 0x00)

        frame = Frame(master)  # create a frame for the GUI
        frame.pack()

        # create 16 buttons which run the togglepin function when pressed
        self.button = Button(frame,
                             text="Pin 1",
                             command=lambda: self.togglepin(1))
        self.button.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 2",
                             command=lambda: self.togglepin(2))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 3",
                             command=lambda: self.togglepin(3))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 4",
                             command=lambda: self.togglepin(4))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 5",
                             command=lambda: self.togglepin(5))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 6",
                             command=lambda: self.togglepin(6))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 7",
                             command=lambda: self.togglepin(7))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 8",
                             command=lambda: self.togglepin(8))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 9",
                             command=lambda: self.togglepin(9))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 10",
                             command=lambda: self.togglepin(10))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 11",
                             command=lambda: self.togglepin(11))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 12",
                             command=lambda: self.togglepin(12))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 13",
                             command=lambda: self.togglepin(13))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 14",
                             command=lambda: self.togglepin(14))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 15",
                             command=lambda: self.togglepin(15))
        self.slogan.pack(side=LEFT)

        self.slogan = Button(frame,
                             text="Pin 16",
                             command=lambda: self.togglepin(16))
        self.slogan.pack(side=LEFT)
Exemple #45
0
def hallSen(hallSensor_Num, adcChannel_Num, adcBitRate_Num, i2cAddr1_Num,
            i2cAddr2_Num, outputFile_Name, diameter_Num, hallSensorActive):
    # ADC Setup
    channel = 1  # analog channel number (1-8 inclusive)
    bitRate = 12  # programmable data rate
    # 18 (3.75 SPS) less per sec. but more
    # 16 (  15 SPS) --
    # 14 (	60 SPS) --
    # 12 ( 240 SPS) more per sec. but less accurate

    i2cAddr1 = 0x68  # these address are associated with the Address Config. 1
    i2cAddr2 = 0x69

    text_file = open("hallSensor_Data1.txt", "w")
    initTime = time.time()

    t1 = 0
    t2 = 0

    flag = 0
    diameter = 14  # need to find the actual diameter !!!

    i2c_helper = ABEHelpers()
    bus = i2c_helper.get_smbus()
    adc = ADCDifferentialPi(bus, i2cAddr1, i2cAddr2, bitRate)

    global activeMphValues
    global flagThread

    global activeHallSensors
    activeHallSensors.append(hallSensorActive)

    mph = 0
    activeMphValues.append(mph)
    #activeMphValues[hallSensor_Num-1] = mph

    while activeHallSensors[hallSensor_Num - 1]:
        voltage = adc.read_voltage(
            channel
        )  # voltage output from hall sensor (either a pos. or neg. value)
        curTime = time.time(
        ) - initTime  # calculates the current time from time acc. minus time started with

        if voltage < 0.0 and flag == 0:  # if voltage is neg. and we have not passed by the magnet yet
            flag = 1
            t1 = t2  # stores the previous current time from curTime
            t2 = curTime  # stores the current time in curTime
            rps = 1 / (t2 - t1)  # revolutions per second
            activeMphValues[
                hallSensor_Num -
                1] = (rps * (math.pi) * diameter * (3600 / 63360)
                      ) / 11.5  # conversion from rps to miles per second
            #temp = rps * (math.pi) * diameter * (3600/63360)
            rpm = rps * 60
            #activeMphValues[hallsensor_Num-1] = rpm
            #mph = rps*60

            #print( str(curTime + "," + str(voltage) + "," + str(mph) )
            text_file.write(str(curTime) + "," + str(rpm) + "\n")
            text_file.flush()

        elif voltage < 0.0 and flag == 1:  # else if voltage is neg. but we are currently still passing by the magnet
            #print( str(curTime) + "," + str(voltage) )
            #text_file.write( str(curTime) + "," str(voltage) + "\n" )
            filler = 0

        else:  # else the voltage is positive (meaning the magnet is not next to the hall sensor)
            flag = 0
            #print( str(curTime) + "," + str(voltage) )
            #text_file.write( str(curTime) + "," + str(voltage) + "\n" )
            flag = 0  # added hopefully no problems, if problems comment this out

        #time.sleep( 0.0100 )

    text_file.close()
================================================
ABElectronics IO Pi 32-Channel Port Expander - Read Write Demo
Version 1.0 Created 29/02/2015

Requires python 3 smbus to be installed
run with: python3 demo-iopireadwrite.py
================================================

This example reads pin 1 of bus 1 on the IO Pi board and sets pin 1 of bus 2 to match.  
The internal pull-up resistors are enabled so the input pin will read as 1 unless
the pin is connected to ground. 

Initialise the IOPi device using the default addresses, you will need to
change the addresses if you have changed the jumpers on the IO Pi
"""
i2c_helper = ABEHelpers()
i2c_bus = i2c_helper.get_smbus()

# create two instances of the IoPi class called bus1 and bus2 and set the default i2c addresses

bus1 = IoPi(i2c_bus, 0x20) # bus 1 will be inputs
bus2 = IoPi(i2c_bus, 0x21) # bus 2 will be outputs

# Each bus is divided up two 8 bit ports.  Port 0 controls pins 1 to 8, Port 1 controls pins 9 to 16.
# We will read the inputs on pin 1 of bus 1 so set port 0 to be inputs and
# enable the internal pull-up resistors
bus1.set_port_direction(0, 0xFF)
bus1.set_port_pullups(0, 0xFF)

# We will write to the output pin 1 on bus 2 so set port 0 to be outputs and
# turn off the pins on port 0
class wind_speed_meter():
    def __init__(self):
        self._a2d_chan_speed = a2d_chan_speed
        self._a2d_chan_direction = a2d_chan_direction
        self._a2d_chan_vcc = a2d_chan_vcc
        
        self._file_report_period = file_report_period

        self._i2c_helper = ABEHelpers()
        self._bus = self._i2c_helper.get_smbus()
        self._adc = ADCPi(self._bus, 0x68, 0x69, 12)

        self._CtrlPort = 8200
        self._IPAddr = self.get_local_ip()
        self._samples = list()
        self._samples_lock = threading.Lock()        
        self._display_lock = threading.Lock()        

        self._thread_sampling_obj = None
        self._thread_reporting_obj = None
        self._stop_requested = False

        self._dirs_stream = list() #stream of directions searched for callibration samples
        
        #calibrated directions
        self._dirs = list()
        self._dirs_volts = list()
        self._dirs_names = ("NN", "NE", "EE", "SE", "SS", "SW", "WW", "NW")
        self._dirs_file = "/home/pi/PyProj/dirs_calibration.txt"

        self._calibration_restore()
        self.files_to_compress = list()
        self.display = False

    def log_at_display(self, log_msg):
        if(self.display == False):
            return
        
        self._display_lock.acquire()
        print(log_msg)
        self._display_lock.release()
        
        
    def _calibration_save(self):
        fl = open(self._dirs_file, "w")
        for dir_name, dir in itertools.izip(self._dirs_names, self._dirs_volts):
            self.log_at_display("{}: {} ({},{})".format(dir_name, dir.dir, dir._rg_low, dir._rg_high))
            line = "{},{}\n".format(dir_name, dir.dir)
            fl.write(line)
        fl.close()

    def _calibration_restore(self):
        try:
            fl = open(self._dirs_file, "r")
        except Exception as e:
            self.log_at_display("No callibration data to restore")
            return
        line = fl.readline()
        while line != "" :
            ln_split = line.split(",")
            self._dirs_volts.append(dir_range(float(ln_split[1].strip())))
            line = fl.readline()
            
        

    def get_local_ip(self):
        ifconfig_cmd = commands.getoutput("ifconfig")
        patt = re.compile(r'inet\s*\w*\S*:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
        addr_list = patt.findall(ifconfig_cmd)
        for addr in addr_list:
            if addr == "127.0.0.1":
                continue
##            if(self._nettype == NETTYPE.CELL):
##                if(addr.find("192.168.") == 0):
##                    continue
            if(addr.find('.')>0):
                return addr
        return "127.0.0.1"

    def start(self):
        self._stop_requested = False
        self._thread_sampling_obj = threading.Thread(target=self._thread_sampling)
        self._thread_sampling_obj.start()
        self._thread_reporting_obj = threading.Thread(target=self._thread_reporting)
        self._thread_reporting_obj.start()
        self._thread_compression_obj = threading.Thread(target=self._thread_compression)
        self._thread_compression_obj.start()

    def _dir_calibration(self, smpl):
        if(len(self._dirs_stream) == 0):
            self._dirs_stream.append((smpl.direction_voltage,0))
        else:
            delta_from_prev = 0
            smpl_last = self._dirs_stream[len(self._dirs_stream)-1]
            dir_last = smpl_last[0]

            #calculate delta drom previous direction sensor read
            if(smpl.direction_voltage > dir_last):
                delta_from_prev = smpl.direction_voltage - dir_last
            elif(smpl.direction_voltage > 0) and (smpl.direction_voltage <1) and (dir_last > 4):
                delta_from_prev = smpl.direction_voltage + (5.0 - dir_last)

            #append only changing directions 
            if(dir_last != smpl.direction_voltage):
                self._dirs_stream.append((smpl.direction_voltage,round(delta_from_prev,1)))
            
            
        if (len(self._dirs_stream) == 5):
            self._dirs_stream.pop(0)

        #check if callibration is activated
        self.log_at_display("dirs: " + str(self._dirs_stream))
        calibration_matches = 0
        for dir in self._dirs_stream:
            if(dir[1]) >= 1 and (dir[1])<1.6:
                    calibration_matches+=1
                    
        if(calibration_matches == 4):
            matches = 0
            self.log_at_display("Direction callibration is completed:\n"\
            "Four consequent directions are cptured for N/E/S/W")
            
            self._dirs = self._dirs_stream
            self._dirs_stream = list() #reset the stream of directions searched for callibration samples
            self._dirs_volts = list()

            #fill calibration lists
            for i in range(0,len(self._dirs)):
                v_direction_prev = self._dirs[i-1][0]
                if( i == 0):
                    #use WW for NN
                    v_direction_prev = self._dirs[3][0]
                v_direction = self._dirs[i][0]
                d_direction = self._dirs[i][1] #delta from previos v_direction
                middle_dir = v_direction_prev + round(d_direction/2,1)
                if(middle_dir > 5):
                    middle_dir -= 5
                dir = dir_range(middle_dir)
                self._dirs_volts.append(dir)
                self._dirs_volts.append(dir_range(v_direction))
                idx = len(self._dirs_volts)-1
                dir = self._dirs_volts[idx]

            #append last half-direction
            nw = self._dirs_volts.pop(0)
            self._dirs_volts.append(nw)
            self._calibration_save()
            
        
    def _thread_reporting(self):
        self.log_at_display("reporting thread started")
        mc_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        #mc_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        mc_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 100)
        mc_socket.bind((self._IPAddr, 0))
        #mreq = struct.pack('4sl', socket.inet_aton("224.0.150.150"), socket.INADDR_ANY)
        mreq = struct.pack('4sl', socket.inet_aton("224.0.1.200"), socket.INADDR_ANY)
        mc_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        #mc_socket.sendto("init", ("224.0.150.150", 8100))

        time_last_report = time.time()
        self._dirs_stream = list()
        fl_name = "{}wind_{}.csv".format(file_location, time.strftime("%Y%m%d_%H%M%S"))
        fl = open(fl_name, "w")
        lines_reported = 0
        while(self._stop_requested != True):
            time_now = time.time()

            if(time_now - time_last_report < self._file_report_period) or (time_now < time_last_report):
                time.sleep(0.2)
                continue

            if(len(self._samples) == 0):
                continue

            if(lines_reported >= file_length):
                #open new file if current is full 
                fl.close()
                self.files_to_compress.append(fl_name)
                fl_name = "{}wind_{}.csv".format(file_location, time.strftime("%Y%m%d_%H%M%S"))
                fl = open(fl_name, "w")
                lines_reported = 0
                
            self._samples_lock.acquire()
            smpl = self._samples.pop(0)
            self._samples_lock.release()
            if(len(self._dirs_volts)>0):
                for i in range(0, len(self._dirs_volts)):
                    if self._dirs_volts[i].is_in(smpl.direction_voltage):
                        smpl.direction_code = self._dirs_names[i]
                        break
            self.log_at_display("REPORTED: speed={}m/s Vspeed_avg={}V ({} reads) Vdir={}V DIr={}".format(smpl.speed_m_per_sec, smpl.sample_average_voltage, smpl.voltage_reads, smpl.direction_voltage, smpl.direction_code))
            fl.write("{},{}\n".format(smpl.direction_code, smpl.speed_m_per_sec))
            lines_reported+=1
            
            self._dir_calibration(smpl)
                
            time_last_report = time_now

    def _thread_compression(self):
        while(self._stop_requested != True):
            if(len(self.files_to_compress) == 0):
                continue
            f_name = self.files_to_compress.pop(0)
            f_in = open(f_name, 'rb')
            f_out = gzip.open(f_name + '.gz', 'wb')
            f_out.writelines(f_in)
            f_out.close()
            f_in.close()
            os.remove(f_name)

    def _thread_sampling(self):
        self.log_at_display("sampling thread started")
        speed_reads_counter = 0
        last_sample_timestamp = 0
        time_now = time.time()
        time_last_sampling = time_now
        speed_voltage_sum = 0.0
        while(self._stop_requested != True):
            time_now = time.time()

            # output voltage is proportional to the wind speed at the voltage read moment
            #read voltage from speed sensor
            speed_voltage_sum += self._adc.read_voltage(self._a2d_chan_speed)
            speed_reads_counter += 1

            if(time_now - time_last_sampling < self._file_report_period) or (time_now < time_last_sampling):
                time.sleep(0.01)
                continue

            smpl = sample()
            smpl.sample_time_stamp = time_now
            smpl.sample_time_span = time_now - time_last_sampling
            smpl.voltage_reads = speed_reads_counter
            smpl.sample_average_voltage = round(speed_voltage_sum/smpl.voltage_reads,2)

            #Vout may vary from 0 to 5V which linearry relates to 0.5 to 50M/s
            # Thus each 1V relates to 10M/s or 1 mV -> 0.01 M/s:  1mV means 1cm/s
            # smpl.sample_average_voltage is in volts
            # smpl.sample_average_voltage*1000 gives the value in milli-volts
            # from here smpl.speed_m_per_sec = (smpl.sample_average_voltage*1000)mV*0.01 (Ms/ per mV)
            # or smpl.speed_m_per_sec = smpl.sample_average_voltage*10
            smpl.speed_m_per_sec = round(smpl.sample_average_voltage*10, 2)

            if(self._a2d_chan_vcc != -1):
                vcc = self._adc.read_voltage(self._a2d_chan_vcc)

            if(a2d_chan_direction != -1):    
                smpl.direction_voltage = round(self._adc.read_voltage(self._a2d_chan_direction),1)
                smpl.direction_code = ""
                            
            self._samples_lock.acquire()
            self._samples.append(smpl)
            self.log_at_display("CAPTURED: speed={}m/s Vspeed_avg={}V ({} reads) Vdir={}V List_len={}".format(smpl.speed_m_per_sec, smpl.sample_average_voltage, smpl.voltage_reads, smpl.direction_voltage, len(self._samples)))
            self._samples_lock.release()

            speed_reads_counter = 0
            speed_voltage_sum = 0.0
            time_last_sampling = time.time()


    def Stop(self):
        self._stop_requested = True
        if(self._thread_sampling_obj.isAlive()):
            self._thread_sampling_obj.join();
        if(self._thread_reporting_obj.isAlive()):
            self._thread_reporting_obj.join();
        if(self._thread_compression_obj.isAlive()):
            self._thread_compressions_obj.join();