Exemplo n.º 1
0
    def __init__(self, serialport, romcode=''):
        '''
		temperaturesensor_MAXIM.__init__( serialport , romcode)
		
		Initialize TEMPERATURESENSOR object (MAXIM), configure serial port / 1-wire bus for connection to DS18B20 temperature sensor chip
		
		INPUT:
		serialport: device name of the serial port for 1-wire connection to the temperature sensor, e.g. serialport = '/dev/ttyUSB3'
		romcode: ROM code of the temperature sensor chip (you can find the ROM code using the digitemp program or using the pydigitemp package). If there is only a single temperature sensor connected to the 1-wire bus on the given serial port, romcode can be left empty.
		
		OUTPUT:
		(none)
		'''

        try:

            # configure 1-wire bus for communication with MAXIM temperature sensor chip
            r = AddressableDevice(
                UART_Adapter(serialport)).get_connected_ROMs()

            if r is None:
                logger.error('Couldn not find any 1-wire devices on ' +
                             serialport)
            else:
                bus = UART_Adapter(serialport)
                if romcode == '':
                    if len(r) == 1:
                        self._sensor = DS18B20(bus)
                        self._ROMcode = r[0]
                    else:
                        logger.error(
                            'Too many 1-wire devices to choose from! Try again with specific ROM code...'
                        )
                        for i in range(1, len(r)):
                            logger.info('Device ' + i + ' ROM code: ' +
                                        r[i - 1] + '\n')
                else:
                    self._sensor = DS18B20(bus, rom=romcode)
                    self._ROMcode = romcode

                self._UART_locked = False

            if not hasattr(self, '_sensor'):
                self.warning(
                    'Could not initialize MAXIM DS1820 temperature sensor.')

        except:
            self.error(
                'An error occured during configuration of the temperature sensor at serial interface '
                + serialport + '. The temperature sensor cannot be used.')
Exemplo n.º 2
0
from digitemp.master import UART_Adapter

bus = UART_Adapter('/dev/ttyS0')

for rom in bus.get_connected_ROMs():
    print(rom)

bus.close()
Exemplo n.º 3
0
    def __init__(self,
                 dout_pin,
                 pd_sck_pin,
                 gain_channel_A=128,
                 select_channel='A',
                 tempsens_serialport='',
                 TZero=[1.0,0.0],
                 TRatio=0.0):
        """
        Init a new instance of load cell (HX711+DS18B20)

        INPUT:
        dout_pin: GPIO pin at Raspberry Pi used for DOUT of HX711
        pd_sck_pin: GPIO pin at Raspberry Pi used for SCK of HX711
        gain_channel_A: gain setting for input channel A of HX711 (64 or 128, default: 128)
        select_channel: HX711 input channel used to read the load cell (A or B, default: A)
        tempsens_serialport (optional): serial port of the temperature sensor (Maxim DS18B20) used for temperature compensation of the load cell reading. If tempsens_serialport is empty, the r$
        TZero and TRatio: coefficients used for temperature compensation (default: TZero=[1.0,0.0] and TRatio=0.0)

        OUTPUT:
        (none)
        """


        # set up HX711 load cell sensor:
        if (isinstance(dout_pin, int)):
            if (isinstance(pd_sck_pin, int)):
                self._pd_sck = pd_sck_pin
                self._dout = dout_pin
            else:
                raise TypeError('pd_sck_pin must be type int. '
                                'Received pd_sck_pin: {}'.format(pd_sck_pin))
        else:
            raise TypeError('dout_pin must be type int. '
                            'Received dout_pin: {}'.format(dout_pin))

        self._gain_channel_A = 0
        self._offset_A_128 = 0  # offset for channel A and gain 128
        self._offset_A_64 = 0  # offset for channel A and gain 64
        self._offset_B = 0  # offset for channel B
        self._last_raw_data_A_128 = 0
        self._last_raw_data_A_64 = 0
        self._last_raw_data_B = 0
        self._wanted_channel = ''
        self._current_channel = ''
        self._scale_ratio_A_128 = 1  # scale ratio for channel A and gain 128
        self._scale_ratio_A_64 = 1  # scale ratio for channel A and gain 64
        self._scale_ratio_B = 1  # scale ratio for channel B
        self._debug_mode = False
        self._data_filter = outliers_filter  # default it is used outliers_filter

        GPIO.setup(self._pd_sck, GPIO.OUT)  # pin _pd_sck is output only
        GPIO.setup(self._dout, GPIO.IN)  # pin _dout is input only
        self.select_channel(select_channel)
        self.set_gain_A(gain_channel_A)

        # set up DS18B20 temperature sensor (optional):
        self._T0 = None
        self._TZero = TZero
        self._TRatio = TRatio
        if tempsens_serialport:
            from digitemp.master import UART_Adapter
            from digitemp.device import AddressableDevice
            from digitemp.device import DS18B20

            r = AddressableDevice(UART_Adapter(tempsens_serialport)).get_connected_ROMs()
            if r is None:
                print ('Couldn not find any 1-wire devices on ' + serialport)
            else:
                    bus = UART_Adapter(tempsens_serialport)
                    if len(r) == 1:
                        self._T_sensor = DS18B20(bus)
                        self._T_ROMcode = r[0]
                    else:
                        print ('Too many 1-wire devices to choose from! Try again with specific ROM code...')
                        for i in range(1,len(r)):
                            print ('Device ' + i + ' ROM code: ' + r[i-1] +'\n')
            if hasattr(self,'_T_sensor'):
                print ('Successfully configured DS18B20 temperature sensor (ROM code ' + self._T_ROMcode + ')' )
            else:
                self.warning('Could not initialize MAXIM DS1820 temperature sensor.')
Exemplo n.º 4
0
    def __init__(self,
                 serialport,
                 romcode='',
                 label='TEMPERATURESENSOR',
                 plot_title=None,
                 max_buffer_points=500,
                 fig_w=6.5,
                 fig_h=5,
                 has_plot_window=True,
                 has_external_plot_window=None):
        '''
		temperaturesensor_MAXIM.__init__( serialport , romcode, label = 'TEMPERATURESENSOR' , plot_title = None , max_buffer_points = 500 , fig_w = 6.5 , fig_h = 5 , has_plot_window = True , has_external_plot_window = None )
		
		Initialize TEMPERATURESENSOR object (MAXIM), configure serial port / 1-wire bus for connection to DS18B20 temperature sensor chip
		
		INPUT:
		serialport: device name of the serial port for 1-wire connection to the temperature sensor, e.g. serialport = '/dev/ttyUSB3'
		romcode: ROM code of the temperature sensor chip (you can find the ROM code using the digitemp program or using the pydigitemp package). If there is only a single temperature sensor connected to the 1-wire bus on the given serial port, romcode can be left empty.
		label (optional): label / name of the TEMPERATURESENSOR object (string) for data output. Default: label = 'TEMPERATURESENSOR'
		plot_title (optional): title string for use in plot window. If plot_title = None, the sensor label is used. Default: label = None
		max_buffer_points (optional): max. number of data points in the PEAKS buffer. Once this limit is reached, old data points will be removed from the buffer. Default value: max_buffer_points = 500
		fig_w, fig_h (optional): width and height of figure window used to plot data (inches)
		has_external_plot_window (optional): flag to indicate if there is a GUI system that handles the plotting of the data buffer on its own. This flag can be set explicitly to True of False, or can use None to ask for automatic 'on the fly' check if the has_external_plot_window = True or False should be used. Default: has_external_plot_window = None
		
		OUTPUT:
		(none)
		'''

        self._label = label

        # Check for has_external_plot_window flag:
        if has_external_plot_window is None:
            has_external_plot_window = misc.have_external_gui()

        # Check plot title:
        if plot_title == None:
            self._plot_title = self._label
        else:
            self._plot_title = plot_title

        # data buffer for temperature values:
        self._tempbuffer_t = numpy.array([])
        self._tempbuffer_T = numpy.array([])
        self._tempbuffer_unit = ['x'] * 0  # empty list
        self._tempbuffer_max_len = max_buffer_points
        self._tempbuffer_lastupdate_timestamp = -1

        # set up plotting environment
        if has_external_plot_window:
            # no need to set up plotting
            self._has_external_display = True
            self._has_display = False
        else:
            self._has_external_display = False
            self._has_display = misc.plotting_setup(
            )  # check for graphical environment, import matplotlib

        try:

            # configure 1-wire bus for communication with MAXIM temperature sensor chip
            r = AddressableDevice(
                UART_Adapter(serialport)).get_connected_ROMs()

            if r is None:
                print('Couldn not find any 1-wire devices on ' + serialport)
            else:
                bus = UART_Adapter(serialport)
                if romcode == '':
                    if len(r) == 1:
                        # print ('Using 1-wire device ' + r[0] + '\n')
                        self._sensor = DS18B20(bus)
                        self._ROMcode = r[0]
                    else:
                        print(
                            'Too many 1-wire devices to choose from! Try again with specific ROM code...'
                        )
                        for i in range(1, len(r)):
                            print('Device ' + i + ' ROM code: ' + r[i - 1] +
                                  '\n')
                else:
                    self._sensor = DS18B20(bus, rom=romcode)
                    self._ROMcode = romcode

                self._UART_locked = False

            if self._has_display:  # prepare plotting environment and figure

                import matplotlib.pyplot as plt

                # set up plotting environment
                self._fig = plt.figure(figsize=(fig_w, fig_h))
                t = 'MAXIM DS1820'
                if self._plot_title:
                    t = t + ' (' + self._plot_title + ')'
                self._fig.canvas.set_window_title(t)

                # set up panel for temperature history plot:
                self._tempbuffer_ax = plt.subplot(1, 1, 1)
                t = 'TEMPBUFFER'
                if self._plot_title:
                    t = t + ' (' + self._plot_title + ')'
                self._tempbuffer_ax.set_title(t, loc="center")
                self._tempbuffer_ax.set_xlabel('Time (s)')
                self._tempbuffer_ax.set_ylabel('Temperature')

                # add (empty) line to plot (will be updated with data later):
                self._tempbuffer_ax.plot([], [], 'ko-', markersize=10)

                # get some space in between panels to avoid overlapping labels / titles
                self._fig.tight_layout()

                # enable interactive mode:
                plt.ion()

                self._figwindow_is_shown = False

            if hasattr(self, '_sensor'):
                print(
                    'Successfully configured DS18B20 temperature sensor (ROM code '
                    + self._ROMcode + ')')
            else:
                self.warning(
                    'Could not initialize MAXIM DS1820 temperature sensor.')

        except:
            # print ( '\n**** WARNING: An error occured during configuration of the temperature sensor at serial interface ' + serialport + '. The temperature sensor cannot be used.\n' )
            self.warning(
                'An error occured during configuration of the temperature sensor at serial interface '
                + serialport + '. The temperature sensor cannot be used.')
Exemplo n.º 5
0
#
import time
from digitemp.master import UART_Adapter
from digitemp.device import TemperatureSensor
from digitemp.exceptions import DeviceError, AdapterError

bus = None
device = "/dev/ttyS0"
sensID = "10A75CA80208001A"

# infinite device loop
while True:
    try:
        time.sleep(3)
        print(f"Connecting to '{device}'...")
        bus = UART_Adapter(device)
        print("Connected to '%s'..." % device)

        sensor = TemperatureSensor(bus, rom=sensID)
        # infinite reading loop
        while True:
            try:
                temp = sensor.get_temperature()
                print(f"{temp}ºC")
            except AdapterError:
                print("U")
            time.sleep(3)

    except AssertionError:
        bus.close()
        bus = None
    p2.communicate()


def read_cpu_temperature():
    try:
        region0_temperature = subprocess.check_output(
            ["cat", "/etc/armbianmonitor/datasources/soctemp"])
        return float(region0_temperature)
    except:
        return float(-1)


if __name__ == '__main__':
    start = timer()

    bus = UART_Adapter('/dev/ttyUSB0')
    stats = StatsClient('statsd', 8125, 'readtemp')
    try:
        with open('/boot/id.txt', 'r') as f:
            sensor_id = f.readline().strip()
    except:
        sensor_id = 'unknown'

    stats.gauge('online.%s' % sensor_id, 1)
    led_toggle(1)
    for rom in get_roms():
        read_temperature(rom)
    led_toggle(0)

    elapsed_time = timer() - start
    stats.timing('runtime.%s.elapsed' % sensor_id, int(1000 * elapsed_time))
Exemplo n.º 7
0
	def __init__( self , serialport , romcode = '', label = 'TEMPERATURESENSOR' , max_buffer_points = 500 , fig_w = 6.5 , fig_h = 5):
		'''
		temperaturesensor_MAXIM.__init__( serialport , romcode, label = 'TEMPERATURESENSOR' , max_buffer_points = 500 , fig_w = 6.5 , fig_h = 5 )
		
		Initialize TEMPERATURESENSOR object (MAXIM), configure serial port / 1-wire bus for connection to DS18B20 temperature sensor chip
		
		INPUT:
		serialport: device name of the serial port for 1-wire connection to the temperature sensor, e.g. serialport = '/dev/ttyUSB3'
		romcode: ROM code of the temperature sensor chip (you can find the ROM code using the digitemp program or using the pydigitemp package). If there is only a single temperature sensor connected to the 1-wire bus on the given serial port, romcode can be left empty.
		label (optional): label / name of the TEMPERATURESENSOR object (string). Default: label = 'TEMPERATURESENSOR'
		max_buffer_points (optional): max. number of data points in the PEAKS buffer. Once this limit is reached, old data points will be removed from the buffer. Default value: max_buffer_points = 500
		fig_w, fig_h (optional): width and height of figure window used to plot data (inches)
		
		OUTPUT:
		(none)
		'''
		
		# configure 1-wire bus for communication with MAXIM temperature sensor chip
		r = AddressableDevice(UART_Adapter(serialport)).get_connected_ROMs()
		
		if r is None:
			print ( 'Couldn not find any 1-wire devices on ' + serialport )
		else:
			bus = UART_Adapter(serialport)
			if romcode == '':
				if len(r) == 1:
					# print ('Using 1-wire device ' + r[0] + '\n')
					self._sensor = DS18B20(bus)
					self._ROMcode = r[0]
				else:
					print ( 'Too many 1-wire devices to choose from! Try again with specific ROM code...' )
					for i in range(1,len(r)):
						print ( 'Device ' + i + ' ROM code: ' + r[i-1] +'\n' )
			else:
				self._sensor = DS18B20(bus, rom=romcode)
				self._ROMcode = romcode
		
		self._label = label

		# data buffer for temperature values:
		self._tempbuffer_t = numpy.array([])
		self._tempbuffer_T = numpy.array([])
		self._tempbuffer_unit = ['x'] * 0 # empty list
		self._tempbuffer_max_len = max_buffer_points
	
		# set up plotting environment
		self._has_display = havedisplay
		if self._has_display: # prepare plotting environment and figure

			# set up plotting environment
			self._fig = plt.figure(figsize=(fig_w,fig_h))
			t = 'MAXIM DS1820'
			if self._label:
				t = t + ' (' + self.label() + ')'
			self._fig.canvas.set_window_title(t)

			# set up panel for temperature history plot:
			self._tempbuffer_ax = plt.subplot(1,1,1)
			self._tempbuffer_ax.set_title('TEMPBUFFER (' + self.label() + ')',loc="center")
			self._tempbuffer_ax.set_xlabel('Time (s)')
			self._tempbuffer_ax.set_ylabel('Temperature')
			
			# add (empty) line to plot (will be updated with data later):
			self._tempbuffer_ax.plot( [], [] , 'ko-' , markersize = 10 )

			# get some space in between panels to avoid overlapping labels / titles
			self._fig.tight_layout()
			
			# enable interactive mode:
			plt.ion()

			self._figwindow_is_shown = False


		if hasattr(self,'_sensor'):
			print ( 'Successfully configured DS18B20 temperature sensor (ROM code ' + self._ROMcode + ')' )
		else:
			self.warning( 'Could not initialize MAXIM DS1820 temperature sensor.' )
import time
from digitemp.master import UART_Adapter
from digitemp.device import TemperatureSensor
from digitemp.exceptions import OneWireException

bus = UART_Adapter('/dev/ttyS0')

sensors = []
for rom in bus.get_connected_ROMs():
    try:
        sensors.append(TemperatureSensor(bus, rom))
    except OneWireException:
        pass

print(55 * "=")
for sensor in sensors:
    sensor.info()
    print(55 * "=")

# Instead of calling sensor.get_temperature() for each sensor we call bus.measure_temperature_all() once
# and then do sensor.read_temperature() for each sensor.

try:
    while True:
        measurements = []
        bus.measure_temperature_all()
        for sensor in sensors:
            try:
                measurements.append("%3.02fºC" % sensor.read_temperature())
            except OneWireException:
                measurements.append("  error")