def __init__(self): self.uart = 'uart.txt' self.params = 'params.txt' self.adc = Adafruit_ADS1x15.ADS1015(address=0x49, busnum=1) self.adc2 = Adafruit_ADS1x15.ADS1015() self.GAIN = 1 self.Xs = (207.0, 419.0, 619.0, 824.0, 1032.0, 1241.0, 1444.0, 1649.0)
def run(self): adc = Adafruit_ADS1x15.ADS1015() span = 6.144 * 2 states = 2048 + 2047 resolution = span / states if os.path.exists(self.file_location): f = open(self.file_location, 'a') else: f = open(self.file_location, 'w') moving = 5 * [5] loc = 0 while self.running and average(moving) > 4: self.delta = time.time() - self.start_time self.value = adc.read_adc_difference(0, 2 / 3) * resolution ## self.value=1 moving[loc] = self.value loc += 1 if loc == 4: loc = 0 self.values.emit('{:.4f}'.format(self.value)) self.timing.emit('{:.4f}'.format(self.delta)) f.write('{:.4f},{:.4f}\n'.format(self.delta, self.value)) time.sleep(self.polling_rate) # PlotCanvas(self.value, self.delta) f.close()
def __init__(self): # Create the I2C bus self.adc = Adafruit_ADS1x15.ADS1015() self.pub = rospy.Publisher('command', Int32MultiArray, queue_size=1) array = [] self.cmd = Int32MultiArray(data=array) self.cmd.data = [-1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1,-1]
def setup_rpi(registry): from controller.device import TempSensorDevice, TankSensorDevice, ArduinoDevice, EZOSensorDevice # Relay import RPi.GPIO as GPIO setup_gpio(registry, GPIO) # ADC import Adafruit_ADS1x15 adc = Adafruit_ADS1x15.ADS1015() # With a gain of 2/3 and a sensor output of 0.25V-5V, the values should be around 83 and 1665 registry.add_sensor(TankSensorDevice("tank", adc, 1, 2 / 3, 83, 1665)) # pH, ORP registry.add_sensor(EZOSensorDevice("ph", "/dev/ezo_ph")) registry.add_sensor(EZOSensorDevice("orp", "/dev/ezo_orp")) # Arduino (cover, water) registry.add_valve(ArduinoDevice("arduino", "/dev/arduino")) # 1-wire # 28-031634d04aff # 28-0416350909ff # 28-031634d54bff # 28-041635088bff registry.add_sensor(TempSensorDevice("temperature_pool", "28-031634d04aff")) registry.add_sensor(TempSensorDevice("temperature_air", "28-0416350909ff")) registry.add_sensor( TempSensorDevice("temperature_local", "28-031634d54bff")) registry.add_sensor(TempSensorDevice("temperature_ncc", "28-041635088bff"))
def SendPulse(): print 'Pulse request from server ' adc = Adafruit_ADS1x15.ADS1015() GAIN = 3/3 oldtime = 0 newtime = 0 counter = 0 tick = 0 i = 0 t = 0 mylist = [0 for k in range(181)] while tick < 15: newtime = strftime("%S", gmtime()) if oldtime != newtime : tick += 1 oldtime = newtime Signal = adc.read_adc(0, gain=GAIN) if i < 181: if Signal > 0: mylist[i] = Signal/22.333 if Signal<0: mylist[i] = Signal/-1543 i += 1 time.sleep(0.072 ) return mylist
def __init__(self, extcallback, pin1, analogPin=0, readinterval=80): self.lastvalue = 0 self.lastnumvalue = 0 self.lastalerttime = 0 self.pin1 = pin1 GPIO.setup(self.pin1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(self.pin1, GPIO.RISING, callback=extcallback) if (readinterval < 2): # self.readinterval = 2 self.readinterval = 1 else: self.readinterval = readinterval self.lastfinalread = time.time() self.calibrationinterval = 50000 self.apin = analogPin self.initialized = True self.lastcalibration = 0 try: self.adc = Adafruit_ADS1x15.ADS1015( address=self.ADS1015_I2C_ADDRESS, busnum=self.I2C_BUS) except: print('ADS1015 error') self.initialized = False self.readinterval = 99999 if self.initialized: self.Ro = self.calibration() self.getpinvalue(pin1)
def __init__(self, sensor_pin=0, gain=4, samples=200, decimal_places=2): self.adc = Adafruit_ADS1x15.ADS1015() self.sensor_pin = sensor_pin self.gain = gain self.samples = samples self.decimal_places = decimal_places
def adcGetData(adc0q, adc1q, adc2q, adc3q, adcGetDataFlag): #print 'ADC STARTED' sample_time = 0 #sample roughly every 25 msec run_time = 0.0 values = [0] * 4 GAIN = 1 adc = Adafruit_ADS1x15.ADS1015() while True: try: #adcGetDataFlag.isSet(): #break adcGetDataFlag.wait() start_time = time.time() for i in range(4): # Read the specified ADC channel using the previously set gain value. values[i] = adc.read_adc(i, gain=GAIN) end_time = time.time() - start_time run_time += end_time # Put adc values into queues at the sample_time if run_time > sample_time: adc0q.put(values[0]) adc1q.put(values[1]) adc2q.put(values[2]) adc3q.put(values[3]) run_time = 0.0 #reset run_time end_time = time.time() - start_time run_time += end_time except Exception as e: print e
def readThermo(): adc = Adafruit_ADS1x15.ADS1015() GAIN = 1 # see above while True: value = (((float(adc.read_adc(0, gain=GAIN)) / 2048.0) * 4.096) - 1.25) / 0.005 return (value) # for external applications
def setupAdc(): # Create an ADS1015 ADC (12-bit) instance. # Set the I2C address as its default (0x48), and the I2C # bus number as 1 (0 is default): ### When using >1 devices, use an array of addresses per ADS1015 specs. adc = Adafruit_ADS1x15.ADS1015(address=0x48, busnum=1) # Choose a gain of 1 for reading voltages from 0 to 4.09V. # Or pick a different gain to change the range of voltages that are read: # - 2/3 = +/-6.144V # - 1 = +/-4.096V # - 2 = +/-2.048V # - 4 = +/-1.024V # - 8 = +/-0.512V # - 16 = +/-0.256V # See table 3 in the ADS1015/ADS1115 datasheet for more info on gain. #GAIN = GAIN (2) # Data rate goes up to 3300 with ADS1015. Default is 1600. # DATA_RATE = DATA_RATE # Start continuous ADC conversions on selected channel using the previously set gain # value. Note you can also pass an optional data_rate parameter, see the simpletest.py # example and read_adc function for more infromation. print('CHANNEL = %d, gain = %d, data_rate = %d' % (CHANNEL, GAIN, DATA_RATE)) adc.start_adc(CHANNEL, gain=GAIN, data_rate=DATA_RATE) #adc.start_adc(CHANNEL, gain=GAIN) # Let data_rate default to 1600. # Once continuous ADC conversions are started you can call get_last_result() to # retrieve the latest result, or stop_adc() to stop conversions. return adc
def __init__(self, extcallback, pin1, batCh=0, pwrCh=1, readinterval=30): self.lastvalue = 0 self.lastalerttime = 0 self.init_ok = True self.pin1 = pin1 self.bch = batCh self.pch = pwrCh GPIO.setup(self.pin1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # power=1 or 0 GPIO.add_event_detect(self.pin1, GPIO.BOTH, callback=extcallback) if (readinterval < 2): self.readinterval = 2 else: self.readinterval = readinterval self.lastfinalread = time.time() try: self.adc = Adafruit_ADS1x15.ADS1015( address=self.ADS1015_I2C_ADDRESS, busnum=self.I2C_BUS) except Exception as e: print('ADS1015 error: ', e) self.init_ok = False self.readinterval = 99999 if self.init_ok: # print("init ok") self.getpinvalue(self.pin1)
def __init__(self, Ro=10, analogPin=0): self.Ro = Ro self.ADS_PIN = analogPin self.adc = Adafruit_ADS1x15.ADS1015() self.LPGCurve = [2.3, 0.21, -0.47] # two points are taken from the curve. # with these two points, a line is formed which is "approximately equivalent" # to the original curve. # data format:{ x, y, slope}; point1: (lg200, 0.21), point2: (lg10000, -0.59) self.COCurve = [2.3, 0.72, -0.34] # two points are taken from the curve. # with these two points, a line is formed which is "approximately equivalent" # to the original curve. # data format:[ x, y, slope]; point1: (lg200, 0.72), point2: (lg10000, 0.15) self.SmokeCurve = [2.3, 0.53, -0.44] # two points are taken from the curve. # with these two points, a line is formed which is "approximately equivalent" # to the original curve. # data format:[ x, y, slope]; point1: (lg200, 0.53), point2: (lg10000, -0.22) print("Calibrating...") self.Ro = self.ADSCalibration(ADS_PIN) print("Calibration is done...\n") print("Ro=%f kohm" % self.Ro)
def __init__(self, extcallback, pin1, analogPin=1, readinterval=80): self.lastvalue = 0 self.init_ok = True self.lastnumvalue = 0 self.lastalerttime = 0 self.pin1 = pin1 self.apin = analogPin GPIO.setup(self.pin1, GPIO.IN) GPIO.add_event_detect(self.pin1, GPIO.BOTH, callback=extcallback) if (readinterval < 2): self.readinterval = 2 else: self.readinterval = readinterval self.lastfinalread = time.time() self.calibrationinterval = 600 self.lastcalibration = 0 try: self.adc = Adafruit_ADS1x15.ADS1015( address=self.ADS1015_I2C_ADDRESS, busnum=self.I2C_BUS) except Exception as e: print('ADS1015 error: ', e) self.init_ok = False self.readinterval = 99999 if self.init_ok: self.Ro = self.calibration() self.getpinvalue(self.pin1)
def __init__(self, interval): super(Sampler, self).__init__(interval) self.knocker = Knocker(HEARTBEAT_GPIO) # self.recorder = Recorder(UPLOAD_URL, BASICAUTH_ID, BASICAUTH_PASS, \ # MINIMUM_UPLOAD_QUEUE_LENGTH) self.adc = Adafruit_ADS1x15.ADS1015(\ address=ADS1015_I2C_BASE_ADDRESS,busnum=I2C_BUSNUM) self.reset_valiables()
def checkThermo(): adc = Adafruit_ADS1x15.ADS1015() GAIN = 1 value = (( (float(adc.read_adc(0, gain=GAIN)) / 2048.0) * 4.096) - 1.25) / 0.005 if value < 300: ledSystem.tcGood() print('Thermocouple good!') # terminal feedback
def sample(q): adc = Adafruit_ADS1x15.ADS1015() GAIN = 8 adc.start_adc(0,gain=GAIN) # start continous sampling on pin 0 while True: val = adc.get_last_result() print("Sending {}".format(val)) q.put(val)
def __init__(self,config): #initialization self.__adc=Adafruit_ADS1x15.ADS1015() self.__cnfg = config headings = ["Time","Time Step","gain","Reading","adc Milli Volts","Input mv","I","Irms" ] self.__adc_buffer = class_text_buffer(headings,config) self.setup_data()
def __init__(self, io_client_conf="/etc/wxchip.cfg", io_client_type="mqtt"): # VARIABLES self.io_client = None self.io_client_conf = io_client_conf self.io_client_type = io_client_type self.io_key = None self.io_user = None self.io_update_rate = SLEEPTIME self.data = [["wxchip-BMP180-temp", -1], ["wxchip-BMP180-baro", -1], ["wxchip-lux", -1], ["wxchip-windspeed", -1], ["wxchip-AM2315-temp", -1], ["wxchip-AM2315-humidity", -1]] self.dead = False self.last_pres_avg = 0 self.pres_trending = "flat" # READ OUR CONFIG config = ConfigParser.ConfigParser() config.read(self.io_client_conf) self.io_key = config.get("aio", "key", None) self.io_user = config.get("aio", "username", None) # OVER-WRITE THE IO CLIENT TYPE WITH THE STUFF FROM THE CONFIG self.io_client_type = config.get("aio", "type", self.io_client_type) # GET THE UPDATE RATE FROM THE CONFIG self.io_update_rate = config.get("aio", "update_rate", self.io_update_rate) # GET THE BUS NUMBERS FOR THE DEVICES self.bmp180_bus = config.get("devices", "bmp180_bus", 1) self.ads1015_bus = config.get("devices", "ads1015_bus", 1) self.am2315_bus = config.get("devices", "am2315_bus", 1) if self.io_key == None: text = "No AIO Key found in %s" % self.io_client_conf raise ValueError(text) if self.io_user == None and self.io_client_type == "mqtt": text = "No AIO User found in %s" % self.io_client_conf raise ValueError(text) # NO ERROR CHECKING FOR THE TYPE AND UPDATE RATE AS THEY HAVE DEFAULTS # CREATE OUR IO_CLIENT if self.io_client_type == "mqtt": self.io_client = Adafruit_IO.MQTTClient(self.io_user, self.io_key) logging.debug('Setting up AIO callbacks') self.io_client.on_connect = io_connected self.io_client.on_disconnect = io_disconnected elif self.io_client_type == "rest": self.io_client = Adafruit_IO.Client(self.io_key) # CREATE OUR DEVICE OBJECTS logging.debug('Setting up objects') self.bmp180 = BMP085.BMP085(busnum=self.bmp180_bus) self.ads1015 = Adafruit_ADS1x15.ADS1015(busnum=self.ads1015_bus)
def activate(self): assert self.params['address'] assert self.params['bus'] if not 'driver' in self.params.keys(): self.params['driver'] = 'ads1115' if 'name' in self.params: self.name = self.params['name'] + ' %i:%s' % ( self.params['bus'], hex(self.params['address'])) if self.params['driver'] == 'ADS1115': self.ADC = Adafruit_ADS1x15.ADS1115(address=int( self.params['address'], 16), busnum=self.params['bus']) elif self.params['driver'] == 'ADS1015': self.ADC = Adafruit_ADS1x15.ADS1015(address=int( self.params['address'], 16), busnum=self.params['bus']) else: cprint("Error: unknown driver. Choices are ADS1015 or ADS1115", 'red', attrs=['bold']) return if not 'differential' in self.params.keys(): self.diffDefault = True self.diff = True else: self.diffDefault = False self.diff = self.params['differential'] if self.diff: self.params['n_channels'] = 2 if not 'channel_names' in self.config: self.config['channel_names'] = ['ChA', 'ChB'] else: self.params['n_channels'] = 4 if not 'channel_names' in self.config: self.config['channel_names'] = ['Ch1', 'Ch2', 'Ch3', 'Ch4'] self.params['raw_units'] = ['V'] * self.params['n_channels'] self.config['eng_units'] = ['V'] * self.params['n_channels'] self.config['scale'] = np.ones(self.params['n_channels'], ) self.config['offset'] = np.zeros(self.params['n_channels'], ) if 'gain' in self.params: self.config['gain'] = self.params['gain'] cprint( "Activating %s on i2c bus at %i:%s with %i channels" % (self.params['driver'], self.params['bus'], hex(self.params['address']), self.params['n_channels']), 'green') if self.diffDefault: print("\tDifferential mode (default)") elif self.diff: print("\tDifferential mode specified") else: print("\tSingle-ended mode") self.apply_config() self.driverConnected = True return
def initTempSensors(): adc = Adafruit_ADS1x15.ADS1015() while True: values = [0] * 4 for i in range(4): values[i] = adc.read_adc(i, gain=GAIN) print('{2:>4} {3:>4}'.format(*values)) # Pause for half a second. sleep(0.5)
def button_down_wait(self): adc = Adafruit_ADS1x15.ADS1015() printer("Waiting for button to be released...") value_0 = adc.read_adc(0) while value_0 > self.BUTTON_LO: value_0 = adc.read_adc(0) time.sleep(0.1) printer("...released")
def __init__(self, param_name, param_id, param_unit, dtype, channel): self.param_name = param_name self.param_id = param_id self.param_unit = param_unit self.dtype = dtype super(AdcPollSensor, self).__init__() self.channel = channel self.adc = Adafruit_ADS1x15.ADS1015()
def setup(): global adc # # Logging # -> Output will be logged to the syslog, if -b specified, otherwise output will be printed to console # global logger logger = logging.getLogger(LOGGER_NAME) logger.setLevel(logging.DEBUG) if args.b: logger = log_create_syslog_loghandler( logger, args.loglevel, LOG_TAG, address='/dev/log') # output to syslog else: logger = log_create_console_loghandler(logger, args.loglevel, LOG_TAG) # output to console # # Load configuration # global configuration if not args.port_publisher and not args.port_subscriber: configuration = load_zeromq_configuration() else: if args.port_publisher and args.port_subscriber: pass else: configuration = load_zeromq_configuration() # Pub/Sub port override if args.port_publisher: configuration['zeromq']['port_publisher'] = args.port_publisher if args.port_subscriber: configuration['zeromq']['port_subscriber'] = args.port_subscriber # # ZMQ # global messaging printer("ZeroMQ: Initializing") messaging = MqPubSubFwdController('localhost', DEFAULT_PORT_PUB, DEFAULT_PORT_SUB) printer("ZeroMQ: Creating Publisher: {0}".format(DEFAULT_PORT_PUB)) messaging.create_publisher() # # ADC # adc = Adafruit_ADS1x15.ADS1015() printer('Initialized [OK]')
def poll(sensor): log.debug("Reading channel "+str(sensor["plugin"]["channel"])+" from "+sensor["plugin"]["type"]+"("+str(sensor["plugin"]["address"])+") with gain "+sensor["plugin"]["gain"]+" ("+str(gain_ratio[sensor["plugin"]["gain"]])+"V) output "+sensor["plugin"]["output"]) # convert the address in hex address = int(sensor["plugin"]["address"][2:],16) # select the device if sensor["plugin"]["type"] == "ads1115": adc = Adafruit_ADS1x15.ADS1115(address=address) elif sensor["plugin"]["type"] == "ads1015": adc = Adafruit_ADS1x15.ADS1015(address=address) # read the value and return the raw value value = adc.read_adc(sensor["plugin"]["channel"], gain=int(sensor["plugin"]["gain"])) log.debug("Read "+str(value)) return value
def __init__(self, AtoDPin, volumeOffCallback, debugOn): self.gain = 1 self.thresh = .35 self.divisor = 32.96 self.val0 = 0 self.AtoDPin = AtoDPin self.offCallback = volumeOffCallback self.debugOn = debugOn # Create an ADS1015 ADC (12-bit) instance. self.adc = Adafruit_ADS1x15.ADS1015()
def __init__(self, asIntPin, enabledCams): #bus and hardware descriptors1 self.i2c = busio.I2C(board.SCL, board.SDA) self.lps35hw = adafruit_lps35hw.LPS35HW(self.i2c) self.si7021 = si(smb(self.bus)) #maybe add delay here? #self.lightningSensor = as3935.AS3935(asIntPin, self.bus, self.as3935Addr) #this uses a pigpio socket self.pi = pigpio.pi() #for general gpio, may not end up needing this #self.cam = multiCam(enabledCams, self.pi,[1]) #init camera board with a=fisheye, c = ir (this could go in main?) self.adc = Adafruit_ADS1x15.ADS1015() #init adc for wind speed+dir sensor, light intensity self.rgbSensor = isl29125.ISL29125([0x0d,0x3f,0])
def checkThermo(): adc = Adafruit_ADS1x15.ADS1015() global GAIN GAIN = 1 value = (( (float(adc.read_adc(0, gain=GAIN)) / 2048.0) * 4.096) - 1.25) / 0.005 if value < 300: print('Thermocouple good!\n') # terminal feedback with open("systemLog.txt", "a") as logFile: logMsg1 = "GPS Signal Aquired Successfully\n\n" logFile.write(logMsg1)
def __init__(self): # Create the I2C bus self.adc = Adafruit_ADS1x15.ADS1015() self.pub = rospy.Publisher('joint_states', JointState, queue_size=10) rospy.init_node('joint_state_publisher') self.rate = rospy.Rate(10) # 10Hz self.data = JointState() self.data.header = Header() self.data.name = ['link_01_name__link_02_name', 'link_02_name__link_03_name','not_used_3','not_used_4'] self.data.velocity = [] self.data.effort = [] self.data.position = [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]
def button_down_delay(self): adc = Adafruit_ADS1x15.ADS1015() press_count = 0 print("Waiting for button to be released/or max. press count reached") value_0 = adc.read_adc(0) while value_0 > self.BUTTON_LO and press_count < 2: press_count+=1 print(press_count) value_0 = adc.read_adc(0) time.sleep(0.1) print("...released/max. delay reached")
def data_reader(read_time, file_path, low_cut, high_cut): GAIN = 1 adc = Adafruit_ADS1x15.ADS1015() timestamp = time.asctime(time.localtime(time.time())) path = file_path + timestamp os.makedirs(path) readtime = 10 counter = 0 portnum = 1 samplrate = 256 while True: # Data File Read data = [] filepath = path + "/" + str(counter) + ".txt" # datafile = open( filepath ,"w") start = time.time() diff = time.time() - start # 10 Sec Loop Through while (diff < readtime): line = adc.read_adc(portnum, gain=GAIN, data_rate=samplrate) # datafile.write(data) np.append[data, line] diff = time.time() - start # datafile.close() # Numpy Array Creation # data = np.loadtxt(filepath) # Powerline Interference Frequency Filter # lowfiltered = butter_lowpass_filter(data, lowcut, samplingf, 5) # Filter Signal For Smoothing order = int(0.3 * samplrate) # Apply a notch filter for powerline interference noise filtered, _, _ = st.filter_signal(signal=lowfiltered, ftype='FIR', band='bandstop', order=order, frequency=[lowcut, highcut], sampling_rate=samplrate) # Normalization # filtered -= basedrift # filtered *= scalefactor # Save to TXT file np.savetxt(filepath, filtered)