import Adafruit_ADS1x15 as ADS import serial from pathlib import Path #----> Machine learning Imports <---- # import pickle # import sklearn #################### Object Declaration #################### GPIO.setmode(GPIO.BOARD) # Linear Actuator pinLA = 8 pinEnable = 10 linearActuator = LinearActuator(pinLA, pinEnable) # Analog-Digital Converter #Darius Edit adc = ADS.ADS1115(0x49) adc2 = ADS.ADS1115(0x48) # MOS Sensor sensor1 = MOS(adc2, 0) # sensor2 = MOS(adc2, 1) sensor3 = MOS(adc2, 2) sensor4 = MOS(adc2, 3) all_sensors = all_sensors(sensor1,sensor2,sensor3,sensor4) # Temperature sensor #Darius Edit Temp_adc_channel = 1 #Darius Edit temperatureSensor = TemperatureSensor(adc, Temp_adc_channel) #Pressure Sensor #Press_adc_channel = 0 #pressureSensor = PressureSensor(adc,Press_adc_channel)
def __init__(self): # Create an ADS1115 ADC (16-bit) instance. self.adc = Adafruit_ADS1x15.ADS1115() self.GAIN = 1 self.aws_publisher = aws_publisher()
import I2C_LCD_driver import Adafruit_ADS1x15 import RPi.GPIO as GPIO from time import * mylcd = I2C_LCD_driver.lcd() mylcd.lcd_display_string("Hello World4!", 1) adc = Adafruit_ADS1x15.ADS1015() GAIN = 1 counter = 1 # start code voor encoder counter = 10 # starting point for the running directional counter Enc_A = 23 # Encoder input A: input GPIO 23 (active high) // 23 -> 13 Enc_B = 24 # Encoder input B: input GPIO 24 (active high) // 24 -> 19 KlepSensorPinOpen = 22 KlepSensorPinClosed = 27 def initEncoder(): global counter print "Rotary Encoder Test Program3" GPIO.setwarnings(True) GPIO.setmode(GPIO.BCM) GPIO.setup(Enc_A, GPIO.IN) # pull-ups are too weak, they introduce noise GPIO.setup(Enc_B, GPIO.IN) GPIO.add_event_detect(Enc_A, GPIO.RISING, callback=rotation_decode, bouncetime=2) # bouncetime in mSec return
def __init__(self): self.adc = Adafruit_ADS1x15.ADS1115() self.manager = multiprocessing.Manager() self.lock = self.manager.Lock() self.storage = Storage.Storage() self.measurement_list = []
CW = 0 CCW = 1 MVA = 10 * 20 # Number of degrees * number of steps for 1 degree step_count = 7200 # SPR delay = .002 #.005 # Set GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(DIRalt, GPIO.OUT) GPIO.setup(STEPalt, GPIO.OUT) GPIO.setup(DIRazi, GPIO.OUT) GPIO.setup(STEPazi, GPIO.OUT) GPIO.setup(16, GPIO.IN) adcqpd = Adafruit_ADS1x15.ADS1115(address=0x48, busnum=1) GAIN = 2 / 3 qpd_step_count = 1 #1 step is equal to .05 degree #======================start of while loop=========================# while True: values = [0] * 4 values[1] = adcqpd.read_adc(1, gain=GAIN) UDQ = (values[1] * 0.1875) / 1000 #alt # values[2] = adcqpd.read_adc(2, gain=GAIN) # LRQ = (values[2] * 0.1875)/1000
import Adafruit_ADS1x15 import sys try: adc = Adafruit_ADS1x15.ADS1015(address=0x48, busnum=3) except: sys.exit(1) try: bat_ext = adc.read_adc(1, gain=1) # Range is +/- 4.096V. except: sys.exit(1) #print(str(bat_ext)) if bat_ext >= 950: sys.exit(0) else: sys.exit(2)
# Created by Duje import Adafruit_ADS1x15 as ADS import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) ledPin = 27 adcAddress = 0x48 adcBusNumber = 1 adcRange = 32767 frequency = 500 GPIO.setup(ledPin, GPIO.OUT) adc = ADS.ADS1115(address=adcAddress, busnum=adcBusNumber) while True: adcRead = adc.read_adc(channel=0) dutyOn = adcRead / adcRange dutyOff = 1 - dutyOn GPIO.output(ledPin, 1) time.sleep(dutyOn / frequency) GPIO.output(ledPin, 0) time.sleep(dutyOff / frequency)
from RPLCD.i2c import CharLCD gpio.setwarnings(False) gpio.setmode(gpio.BOARD) db = firebase.FirebaseApplication('https://practica3-sd.firebaseio.com', None) def call(c): """Cambia el valor de on/off""" global on on = not on # Declaraciones de objetos y constantes lcd = CharLCD('PCF8574', 0x27) adc = analogo.ADS1115() GAIN = 1 maximaLuz = 26500 #Pines pir = 11 interruptor = 35 ledVentilacion = 13 ledIluminacion = 15 ledSistema = 19 #Setup gpio.setup(pir, gpio.IN, pull_up_down=gpio.PUD_DOWN) gpio.setup(interruptor, gpio.IN) gpio.setup(ledVentilacion, gpio.OUT) gpio.setup(ledIluminacion, gpio.OUT)
# continuous_read_adc.py - 12/9/2013. Written by David Purdie as part of the openlabtools initiative # Uses the adafruit python libraries to sample the ADS1115 at a user defined sampling frequency, # saving results to a .txt file import Adafruit_ADS1x15 import time import numpy as np import matplotlib.pyplot as plt GAIN = 1 #pga = 4096 # Set full-scale range of programable gain amplifier (page 13 of data sheet), change depending on the input voltage range ADS1115 = 0x00 # Specify that the device being used is the ADS1115, for the ADS1015 used 0x00 adc = Adafruit_ADS1x15.ADS1015( ) # Create instance of the class ADS1x15 called adc # Function to print sampled values to the terminal def logdata(): print "sps value should be one of: 8, 16, 32, 64, 128, 250, 475, 860, otherwise the value will default to 250" frequency = input("Input sampling frequency (Hz): " ) # Get sampling frequency from user #sps = input("Input sps (Hz) : ") # Get ads1115 sps value from the user time1 = input("Input sample time (seconds): " ) # Get how long to sample for from the user period = 1.0 / frequency # Calculate sampling period datapoints = int( time1 * frequency
class ADS(): ######################### Hardware Related Macros ######################### ADS_PIN = 0 # define which analog input channel you are going to use (MCP3008) RL_VALUE = 5 # define the load resistance on the board, in kilo ohms RO_CLEAN_AIR_FACTOR = 9.83 # RO_CLEAR_AIR_FACTOR=(Sensor resistance in clean air)/RO, # which is derived from the chart in datasheet GAIN = 2 adc = Adafruit_ADS1x15.ADS1015() ######################### Software Related Macros ######################### CALIBARAION_SAMPLE_TIMES = 50 # define how many samples you are going to take in the calibration phase CALIBRATION_SAMPLE_INTERVAL = 500 # define the time interal(in milisecond) between each samples in the # cablibration phase READ_SAMPLE_INTERVAL = 50 # define how many samples you are going to take in normal operation READ_SAMPLE_TIMES = 5 # define the time interal(in milisecond) between each samples in # normal operation ######################### Application Related Macros ###################### GAS_LPG = 0 GAS_CO = 1 GAS_SMOKE = 2 def __init__(self, Ro=10, analogPin=0): self.Ro = Ro self.ADS_PIN = analogPin # self.adc = Adafruit_ADS1x15.ADS1015() self.LPGCurve = [1.9,0.27,-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 = [5.1,1.5,-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 =[3.3,0.63,-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 this...") self.Ro = self.ADSCalibration(self.ADS_PIN) print("Calibration is done...\n") print("Ro=%f kohm" % self.Ro) def ADSPercentage(self): val = {} read =self.ADSRead(0) # print(read) val["GAS_LPG"] = self.ADSGetGasPercentage(read/self.Ro, 0) val["CO"] = self.ADSGetGasPercentage(read/self.Ro, 1) val["SMOKE"] = self.ADSGetGasPercentage(read/self.Ro, 2) return val ######################### ADSResistanceCalculation ######################### # Input: raw_adc - raw value read from adc, which represents the voltage # Output: the calculated sensor resistance # Remarks: The sensor and the load resistor forms a voltage divider. Given the voltage # across the load resistor and its resistance, the resistance of the sensor # could be derived. ############################################################################ def ADSResistanceCalculation(self): # print("Berekenen van sensor weerstand deel2...\n") voltage = 4.096 return float(self.RL_VALUE*(1023.0-voltage)/float(voltage)); ######################### ADSCalibration #################################### # Input: ads_pin - analog channel # Output: Ro of the sensor # Remarks: This function assumes that the sensor is in clean air. It use # ADSResistanceCalculation to calculates the sensor resistance in clean air # and then divides it with RO_CLEAN_AIR_FACTOR. ############################################################################ def ADSCalibration(self, ads_pin): val = 0.0 voltage = 4.096 print("Starten van calibratie clean air..\n") for i in range(50): # take multiple samples val += float(self.RL_VALUE*(1023.0-voltage)/float(voltage)) # print(val) time.sleep(500/1000.0) val = val/50 # calculate the average value val = val/9.83 print(val) return val; ######################### ADSRead ########################################## # Input: ads_pin - analog channel # Output: Rs of the sensor # Remarks: This function use ADSResistanceCalculation to caculate the sensor resistenc (Rs). # The Rs changes as the sensor is in the different consentration of the target # gas. The sample times and the time interval between samples could be configured # by changing the definition of the macros. ############################################################################ def ADSRead(self, ADS_PIN): rs = 0.0 # print("Bereken van sensor weerstand RS...\n") voltage = 4.096 for i in range(5): read = self.adc.read_adc(0) # print(read) # rs += float(self.RL_VALUE*(1023.0-voltage)/float(voltage)) # rs += self.ADSResistanceCalculation(read) rs += float(self.RL_VALUE*(1023.0-read)/float(read)) # print(rs) time.sleep(50/1000.0) rs = rs/5 # print(rs) return rs ######################### ADSGetGasPercentage ############################## # Input: rs_ro_ratio - Rs divided by Ro # gas_id - target gas type # Output: ppm of the target gas # Remarks: This function passes different curves to the ADSGetPercentage function which # calculates the ppm (parts per million) of the target gas. ############################################################################ def ADSGetGasPercentage(self, rs_ro_ratio, gas_id): # print("Starten van calibratie deel3..\n") if ( gas_id == 0 ): return self.ADSGetPercentage(rs_ro_ratio, self.LPGCurve) elif ( gas_id == 1 ): return self.ADSGetPercentage(rs_ro_ratio, self.COCurve) elif ( gas_id == 2 ): return self.ADSGetPercentage(rs_ro_ratio, self.SmokeCurve) return 0 ######################### ADSGetPercentage ################################# # Input: rs_ro_ratio - Rs divided by Ro # pcurve - pointer to the curve of the target gas # Output: ppm of the target gas # Remarks: By using the slope and a point of the line. The x(logarithmic value of ppm) # of the line could be derived if y(rs_ro_ratio) is provided. As it is a # logarithmic coordinate, power of 10 is used to convert the result to non-logarithmic # value. ############################################################################ def ADSGetPercentage(self, rs_ro_ratio, pcurve): # print("Starten van calibratie deel4..\n") return (math.pow(10,( ((math.log(rs_ro_ratio)-pcurve[1])/ pcurve[2]) + pcurve[0])))
def read_heart_data(): ADC = Adafruit_ADS1x15.ADS1015() GAIN = 2 / 3 THRESHOLD = 525 # mid point in the waveform PEAK = 512 TROUGH = 512 TIME_IN_MILLISECS = 0 TIME_OF_LAST_HEARTBEAT = 0 FIRST_HEARTBEAT = True SECOND_HEARTBEAT = False PULSE = False INTERBEAT_INTERVAL = 600 RATE = deque([0 for i in range(10)], maxlen=10) AMPLITUDE = 100 LAST_TIME = int(time.time() * 1000) print("Running Sensor...") while True: Signal = ADC.read_adc( 0, gain=GAIN) # First arg corresponds to ADC channel CURRENT_TIME = int(time.time() * 1000) TIME_IN_MILLISECS += CURRENT_TIME - LAST_TIME LAST_TIME = CURRENT_TIME TIME_SINCE_LAST_HEARTBEAT = TIME_IN_MILLISECS - TIME_OF_LAST_HEARTBEAT if Signal < THRESHOLD and TIME_SINCE_LAST_HEARTBEAT > ( INTERBEAT_INTERVAL / 5.0 ) * 3.0: # avoid dichrotic noise by waiting 3/5 of last INTERBEAT_INTERVAL if Signal < TROUGH: TROUGH = Signal # keep track of lowest point in pulse wave if Signal > THRESHOLD and Signal > PEAK: # THRESHOLD condition helps avoid noise PEAK = Signal # keep track of highest point in pulse wave # signal surges up in value every time there is a pulse if TIME_SINCE_LAST_HEARTBEAT > 250: # avoid high frequency noise if (Signal > THRESHOLD) and (PULSE == False) and ( TIME_SINCE_LAST_HEARTBEAT > INTERBEAT_INTERVAL / 5 * 3): PULSE = True INTERBEAT_INTERVAL = TIME_IN_MILLISECS - TIME_OF_LAST_HEARTBEAT TIME_OF_LAST_HEARTBEAT = TIME_IN_MILLISECS if SECOND_HEARTBEAT: SECOND_HEARTBEAT = False RATE.extend( [INTERBEAT_INTERVAL for i in range(10)] ) # seed the running total to get a realisitic BPM at startup if FIRST_HEARTBEAT: FIRST_HEARTBEAT = False SECOND_HEARTBEAT = True continue # INTERBEAT_INTERVAL value is unreliable so discard it # keep a running total of the last 10 INTERBEAT_INTERVAL values RUNNING_TOTAL = 0 RATE.popleft() RUNNING_TOTAL = sum(RATE) RATE.append(INTERBEAT_INTERVAL) RUNNING_TOTAL += INTERBEAT_INTERVAL RUNNING_TOTAL //= 10 BPM = 60000 // RUNNING_TOTAL #print('BPM: {}'.format(BPM)) yield (BPM, RATE) if Signal < THRESHOLD and PULSE == True: # when the values are going down, the beat is over PULSE = False AMPLITUDE = PEAK - TROUGH THRESHOLD = AMPLITUDE // 2 + TROUGH PEAK = THRESHOLD TROUGH = THRESHOLD if TIME_SINCE_LAST_HEARTBEAT > 2500: THRESHOLD = 512 PEAK = 512 TROUGH = 512 TIME_OF_LAST_HEARTBEAT = TIME_IN_MILLISECS FIRST_HEARTBEAT = True SECOND_HEARTBEAT = False
import numpy as np import time import Adafruit_ADS1x15 from numpy import genfromtxt import math import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure from matplotlib import style import numpy as np global positionSensor adc1 = Adafruit_ADS1x15.ADS1115(address=0x48) #adc2 = Adafruit_ADS1x15.ADS1115(address = 0x49) start_time = time.time( ) # capture the time at which the test began. All time values can use start_time as a reference dataVector1 = [] # data values to be returned from sensor 1 timeVector = [] # time values associated with data values count = 0 while (count < 2000): # print("Big Orange: ", adc1.read_adc(0, gain = 2/3)) # print ("Sensor 2 Val: ", adc1.read_adc(1, gain = 2/3)) # print("Pressure: ", adc1.read_adc(1, gain = 2/3)) dataVector1.append(adc1.read_adc(3, gain=2 / 3)) timeVector.append(time.time() - start_time) print("Sensor Val: ", (adc1.read_adc(3, gain=2 / 3)) / pow(2, 15) * 6.144)
import numpy as np import RPi.GPIO as GPIO from PyQt5 import QtWidgets, QtGui, QtCore from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import pyqtgraph as pg pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') import random import sys import time import datetime import Adafruit_ADS1x15 as ads adc = ads.ADS1115(0x48) global timeVector timeVector = [] global dataVector dataVector = [] global livegraph global app global startTime startTime = time.time() global mos class MOS: def __init__(self, adc, channel): # 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
import sys sys.path.append('/home/pi/DAM/gps-python3/gpspy3') sys.path.append('/home/pi/DAM/gps-python3') import spidev #library for spi communication from gps import * import time import Adafruit_ADS1x15 #Library for ADC initializations and functions spi = spidev.SpiDev() spi.open(0, 0) spi.max_speed_hz = 1000000 x = [0] * 88 gpsd = GPS(mode=WATCH_ENABLE | WATCH_NEWSTYLE) adc = Adafruit_ADS1x15.ADS1115() # initialize adc variable latval = 999 longval = 999 speedval = 999 GAIN = 2 # Print nice channel column headers. #print('| {0:>6} | {1:>6} | {2:>6} | {3:>6} |'.format(*range(4))) #print('-' * 37) try: while True: values = [0] * 88 for i in range(4): values[i] = adc.read_adc(i, gain=GAIN) #print('| {0:>6} | {1:>6} | {2:>6} | {3:>6} |'.format(*values)) report = gpsd.next()
import time #import maxSonarTTY import Adafruit_ADS1x15 import adafruit_ads1x15.ads1115 as ADS #import GPIO import csv import board import busio from adafruit_ads1x15.analog_in import AnalogIn #we will need to change the gain to 2/3 and find the factor to multiply the result by #we can compare with the adafruit stuff that returns a voltage #reference https://cdn-learn.adafruit.com/downloads/pdf/adafruit-4-channel-adc-breakouts.pdf?timestamp=1551486012 #Define all interfaces adc = Adafruit_ADS1x15.ADS1115() #may want to customize interface here serialPort = "dev/ttyAMA0" maxPress = 750.0 minPress = 10.0 vSource = 5.0 #voltage source to the adafruit thingy vSupplyPress = 5.0 #voltage supply to pressure sensor pressure = 0.0 temp = 0.0 vOut = 0.0 #calculated voltage that the pressure sensor returns maxNum = 32768 #upper end of what the adafruit thingy can return gain = 2 / 3 #Loop while True: values = [0] * 4
def main(duration=0, rate=3300, gain=16, verbose=False, **kwargs): """ Take data from the ADS1015 for duration seconds (or until stdin receives EOF, if duration is 0) at rate and gain. Default argument values may not be the same as for the command line arguments. See the ArgumentParser instance below. Kwargs: lc_channel = the channel of the ads1015 from which to read load cell data. comparator = Whether to use the ALERT/RDY pin instead of time.sleep(). This is highly recommended, provided the hardware is setup. comparator_pin = the GPIO pin from which to yoink the comparator. This is specified as a BCM number. battery_check_freq = frequency to check the battery level. Not exact! 1 Hz by default... but setting 2 Hz results in ~ 1 Hz measurements. battery_channel = obvious. Sends the data to stdout. We're using common mode, not differential mode. At 3300 samples per second, this generates 2.2 MB of ascii per minute, which is probably fine. """ if verbose: print("Debugging information:", file=stderr) for key in kwargs: print(key + ": {0}".format(kwargs[key]), file=stderr) adc = Adafruit_ADS1x15.ADS1015() lc_channel = kwargs['lc_channel'] if 'lc_channel' in kwargs else 0 use_comp = kwargs['comparator'] if 'comparator' in kwargs else False differential = kwargs['differential'] if 'differential' in kwargs else False battery_check_freq = (kwargs['battery_check_freq'] if 'battery_check_freq' in kwargs else 1) battery_channel = (kwargs['battery_channel'] if 'battery_channel' in kwargs else 1) battery_counter_limit = rate / battery_check_freq assert battery_counter_limit > 0 pretty_time = SimpleTimer() print(TITLE_LINE, file=stdout) if duration == 0: # The test will run until ctrl-D is sent end_condition = EndCondition() end_condition.start() keep_going = lambda: not end_condition.finished else: # The test will run for the specified number of seconds. time_stop = time.time() + duration keep_going = lambda: time.time() < time_stop # Setup the ADC. See ADS1015 datasheet, pages 12 and 17. # A couple things are different depending on whether we're measuring # between lc_channel and ground, or between lc_channel and some other # analogue input (i.e. kwargs['diff_channel']). if differential: print("Also differential mode", file=stderr) # lc_channel, until this next part executes, has represented a single analog # input pin on the ADS1015. To measure the difference between two analog inputs, # we need to change it into a special value that's meaningful only to the # ads_1015 hardware. See the ADS1015 data sheet, page 16. diff_channel = kwargs[ 'diff_channel'] if 'diff_channel' in kwargs else None assert 0 <= diff_channel <= 3 and diff_channel != lc_channel if lc_channel == 0 and diff_channel == 1: lc_channel = 0 elif lc_channel == 0 and diff_channel == 3: lc_channel = 1 elif lc_channel == 1 and diff_channel == 3: lc_channel = 2 elif lc_channel == 2 and diff_channel == 3: lc_channel = 3 else: raise ValueError() if use_comp: # if we're using the comparator lc_start_adc_function = adc.start_adc_difference_comparator else: lc_start_adc_function = adc.start_adc_difference else: # Single ended mode is the opposite of differential mode, of course. print("Also single-ended mode", file=stderr) if use_comp: lc_start_adc_function = adc.start_adc_comparator else: lc_start_adc_function = adc.start_adc if use_comp: # Set up the test, using the ALERT/RDY pin in "conversion-ready" mode. print("Comparator mode", file=stderr) ready_pin = kwargs['comparator_pin'] # Setup and fish for debilitating GPIO exceptions: GPIO.setup(ready_pin, Adafruit_GPIO.IN, pull_up_down=Adafruit_GPIO.PUD_OFF) wait_function = lambda: GPIO.wait_for_edge(ready_pin, Adafruit_GPIO. FALLING) # Set up the test, using the ALERT/RDY pin in "conversion-ready" mode. # We store these functions because we will need to switch modes # repeatedly in order to read both the start_lc = lambda: lc_start_adc_function( lc_channel, -1, 1, # Hi_thresh < 0 < Lo_thresh --> conversion ready mode data_rate=rate, gain=gain, latching=False, # latching is ignored num_readings=1, traditional=False, active_low=True, wait_function=wait_function) start_battery = lambda: adc.start_adc_comparator( battery_channel, -1, 1, # Same idea. data_rate=BATTERY_RATE, gain=BATTERY_GAIN, latching=False, # latching is ignored num_readings=1, traditional=False, active_low=True, wait_function=wait_function) do_cleanup = lambda: GPIO.cleanup(pin=ready_pin) else: # We have no ALERT/RDY pin, so set up the test to use # time.sleep() instead of GPIO interrupts. # TODO - test whether the logic to assign lc_start_adc_function # earlier is enough to make this code work with both differential # and non-differential measurements. sleeper = Sleeper(rate, lambda: (time.time(), adc.get_last_result())) wait_function = sleeper.sleep # sleeps roughly the right amount start_lc = lambda: lc_start_adc_function( lc_channel, gain=gain, data_rate=rate) start_battery = lambda: adc.start_adc( battery_channel, gain=gain, data_rate=BATTERY_RATE) do_cleanup = lambda: None # This is the main loop. All the lambdas and complicated stuff above # happened so that this loop could be clear and readable. start_lc() battery_check_counter = 0 try: while keep_going(): try: if battery_check_counter > battery_counter_limit: read_battery(adc, BATTERY_SAMPLE_SIZE, start_lc=start_lc, start_battery=start_battery, file=stdout, wait_function=wait_function, get_time=pretty_time) battery_check_counter = 0 battery_check_counter += 1 wait_function() print(LC_DATA_FORMAT.format(pretty_time(), adc.get_last_result()), file=stdout) except IOError: if verbose: traceback.print_exc() start_lc() continue finally: do_cleanup() adc.stop_adc() print("Cleaned up.", file=stderr)
def start(): adc = Adafruit_ADS1x15.ADS1115()
# Simple demo of reading each analog input from the ADS1x15 and printing it to # the screen. # Author: Tony DiCola # License: Public Domain import time # Import the ADS1x15 module. import Adafruit_ADS1x15 # Create an ADS1115 ADC (16-bit) instance. adc1 = Adafruit_ADS1x15.ADS1115(0x48) adc2 = Adafruit_ADS1x15.ADS1115(0x49) # Or create an ADS1015 ADC (12-bit) instance. #adc = Adafruit_ADS1x15.ADS1015() # Note you can change the I2C address from its default (0x48), and/or the I2C # bus by passing in these optional parameters: #adc = Adafruit_ADS1x15.ADS1015(address=0x49, 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 = 2 / 3 ADC_V = 0.1875 print('Reading ADS1x15 values, press Ctrl-C to quit...')
def init_adc(self): self.adc = Adafruit_ADS1x15.ADS1115()
import time import RPi.GPIO as GPIO import Adafruit_ADS1x15 THERMISTORVALUE 100000 SERIESRESISTOR 100000 #series resistor to thermistor BCOEFFICIENT 4072 thermistorR2Temp = {3.2575:0, 2.5348:5, 1.9876:10, 1.5699:15, 1.2488:20, 1.0000:25, 0.80594:30, 0.65355:35, 0.53312:40, 0.43735:45, 0.36074:50, 0.29911:55, 0.24925:60, 0.20872:65, 0.17558:70, 0.14837:75, 0.12592:80, 0.10731:85, 0.091816:90, 0.078862:95, 0.067988:100, 0.058824:105, 0.051071:110} GPIO.setmode(GPIO.BOARD) #pin numbering scheme uses board header pins GPIO.setup(19,GPIO.out) #pin 19, GPIO12 output GPIO.setup(26,GPIO.out) #pin 26, GPIO07 output adc = Adafruit_ADS1x15.ADS1015() #create an ADS1015 ADC (12-bit) instance. # 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 = 1 while True: reading = adc.read_adc(0, gain=GAIN) #read A0, 12 bit signed integer, -2048 to 2047 (0=GND, 2047=4.096*gain) voltReading = reading * 4.096 / 2047.0 #convert adc to voltage thermoR = SERIESRESISTOR / ((4.0/voltReading) - 1)#convert voltage to thermoster resistance #7002 thermistor
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ] # RainSensor Setting GPIO.setmode(GPIO.BCM) GPIO.setup(15, GPIO.IN) RAIN_REPE_NUM = 100 RAIN_REPE_TIME = 0.2 # TemperatureSensor Setting SENSOR_ID = "28-01191ed4dcbc" SENSOR_W1_SLAVE = "/sys/bus/w1/devices/" + SENSOR_ID + "/w1_slave" ERR_VAL = 85000 # DO,pH Setting ADC = Adafruit_ADS1x15.ADS1115() GAIN = 1 DOPH_REPE_NUM = 150 DOPH_REPE_TIME = 0.2 PH_MID = 25200 PH_SLOPE_LOW = 1192 PH_INTERCEPT_LOW = 17177 PH_SLOPE_HIGH = 1626 PH_INTERCEPT_HIGH = 14257 DO_SLOPE = 474 DO_INTERCEPT = -1312 # Gspread Setting SPREADSHEET_KEY = '18jf-W56QqMvjSUgvxBv76Hm3H-HEmgkUZTz-7_Qx1F8' # 共有設定したスプレッドシートキー
def onJoin(self, details): self._tick_sent = {} self._is_scrolling = False extra = self.config.extra self._serial = get_serial() self._my_ip = get_ip_address() self._joined_at = time.strftime("%H:%M") self._app_prefix = 'io.crossbar.demo.wpad' self._prefix = '{}.wpad.{}'.format(self._app_prefix, self._serial) self.log.info("Crossbar.io IoT Starterkit Serial No.: {serial}", serial=self._serial) self.log.info("WPad connected: {details}", details=details) # setup Neopixel LED strip self._ledstrip = Adafruit_NeoPixel( extra['led_count'], extra['led_pin'], extra['led_freq_hz'], extra['led_dma'], extra['led_invert'], extra['led_brightness']) self._ledstrip.begin() # setup GPIO GPIO.setwarnings(False) pinmode = extra.get("pin_mode", "bcm") if pinmode in WPad.PINMODES: GPIO.setmode(WPad.PINMODES[pinmode]) else: GPIO.setmode(GPIO.BCM) GPIO.cleanup() self._row_pins = extra.get("row_pins", []) for pin in self._row_pins: GPIO.setup(pin, GPIO.OUT) self._select_row(0) # setup ADC self._adc = Adafruit_ADS1x15.ADS1015() def log_adc(): # read values from ADC values = [] for i in range(4): values.append(self._adc.read_adc(i, gain=8)) # normalize values nvalues = [ round(100. * ((2048. - float(x)) / 2048.), 3) for x in values ] nvalues = [nvalues[2], nvalues[3], nvalues[1], nvalues[0]] # illuminate neopixel strip for i in range(4): col = int(round(255. * float(nvalues[i]) / 100.)) self._ledstrip.setPixelColorRGB(i * 2, col, col, col) self._ledstrip.setPixelColorRGB(i * 2 + 1, col, col, col) self._ledstrip.show() # publish WAMP event self.publish('{}.on_wpad'.format(self._prefix), nvalues) scan_rate = float(extra.get('scan_rate', 50)) self.log.info('Scanning sensors with {} Hz ..'.format(scan_rate)) LoopingCall(log_adc).start(1. / scan_rate) self._cpu_load = deque() for i in range(self._ledstrip.numPixels()): self._cpu_load.append(0) # our quad, alphanumeric display: https://www.adafruit.com/products/2157 self._disp = QuadAlphanum(extra['i2c_address']) self._disp.clear() self._disp.setBrightness(int(round(extra['brightness'] * 15))) @inlineCallbacks def displayNotice(): yield self.scroll_text( self._disp, "IP {} ({}) ".format(self._my_ip, self._joined_at).upper()) # every couple of secs, display a notice LoopingCall(displayNotice).start(53) def on_tick(tick_no): if tick_no in self._tick_sent: rtt = 1000. * (time.time() - self._tick_sent[tick_no]) del self._tick_sent[tick_no] else: rtt = None self.log.info('TICK received [tick {}, rtt {}]'.format( tick_no, rtt)) self.flash(r=0, g=255, b=0, repeat=1) yield self.subscribe(on_tick, '{}.on_alive'.format(self._prefix)) self._tick_no = 0 self._tick_loop = LoopingCall(self._tick) self._tick_loop.start(7) LoopingCall(self.show_load).start(1) # signal we are done with initializing our component self.publish('{}.on_ready'.format(self._prefix)) self.log.info("WPad ready.") self.flash()
import sys import Adafruit_ADS1x15 from pump import auto_water # 1 Define variables seconds_between_readings = 1800 # Reading frequency - 3600 seconds p/h count = 0 results = [] output_file_name = "results/plant_output %s.csv" % time.strftime( "%Y-%m-%d %H:%M") # 1.1 sMoisture sensor variables ADS1015 = 0x00 # 12-bit ADC gain = 4 adc = Adafruit_ADS1x15.ADS1015( ) # Initialise the ADC using the default mode (use default I2C address) # 2 Setup CSV file for output with open(output_file_name, 'a') as file: file.write( "Reading, Time, Green_Value, Red_Value, Blue_Value, Green_Percent, Volts - Higher is drier, Water Dispensed') " ) def write_result_csv(count, when, green, red, blue, green_percent, volts, water_dispensed): with open(output_file_name, 'a') as file: file.write("\n" + count + "," + when + "," + green + "," + red + "," + blue + "," + g_percent + "," + volts + "," + water_dispensed)
import Adafruit_ADS1x15 as ADS # Create an ADS1115 ADC (16-bit) instance. #adc = Adafruit_ADS1x15.ADS1115() # Or create an ADS1015 ADC (12-bit) instance. #adc = Adafruit_ADS1x15.ADS1015() # Note you can change the I2C address from its default (0x48), and/or the I2C # bus by passing in these optional parameters: #adc = ADS.ADS1115(address=0x49, busnum=1) #adc._data_rate_config(860) adc0 = ADS.ADS1115(address=0x49, busnum=1) adc0._data_rate_config(860) #adc1 = ADS.ADS1115(address=0x49, busnum=1) #adc1._data_rate_config(860) #adc = ADS.ADS1115(i2c, gain=1, data_rate=860) # 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
# Simple demo of reading each analog input from the ADS1x15 and printing it to # the screen. # Author: Tony DiCola # License: Public Domain import time # Import the ADS1x15 module. import Adafruit_ADS1x15 coeff = 76.29 # ADC 16 bits 76.29uv # Create an ADS1115 ADC (16-bit) instance. adc = Adafruit_ADS1x15.ADS1115(address=0x50, busnum=2) # 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 = 2 print('Reading ADS1x15 values, press Ctrl-C to quit...') # Print nice channel column headers. print('| {0:>6} | {1:>6} | {2:>6} | {3:>6} |'.format(*range(4))) print('-' * 37) # Main loop.
#! /usr/bin/python3 # -*- coding: utf-8 -*- #[email protected] import threading import time from statistics import mean from ringbuffer import RingBuffer #This version uses a circular buffer to avoid unwanted zero readings import Adafruit_ADS1x15 # Analogic digital conversor ADS 15 bit 2^15-1=32767 (needs to be installed using pip3) adc = Adafruit_ADS1x15.ADS1115( address=0x48, busnum=1) #address of ADC See in -- sudo i2cdetect -y 1 # Choose a gain of 1 for reading voltages from 0 to 6.14V. # 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 = 1 #2/3, 1, 2, 4 , 6 , 8, 16 DATA_RATE = 250 # 8, 16, 32, 64, 128, 250, 475, 860 samples/second max =860 the higher the number the higher the noise! class AnalogSensor(threading.Thread): def __init__(self, sleep, records): threading.Thread.__init__(self) self.sleep = sleep
import smbus from time import sleep import Adafruit_ADS1x15 # 2.97V = max output = 250psi # 2.97V / 4.096 V = 0.7251 # 250psi / 0.7251 = 344.781 psi # 344.781 psi / 4.096 V = 59.761 psi / V CONVERT = (4.096 / 32767) V2PSI = 59.761 GAIN = 1 ADDR = 0x48 ADC = Adafruit_ADS1x15.ADS1115(address=ADDR, busnum=1) bus = smbus.SMBus(1) try: bus.write_quick(ADDR) except: print("ERROR") if __name__ == '__main__': while True: try: pressure = ((ADC.read_adc(0, GAIN) * CONVERT) - 0.29) except IOError: pressure = 0 print("%.2f psi" % pressure) sleep(0.1)
import time PREVIOUS_LINE = "\x1b[1F" RED_BACK = "\x1b[41;37m" GREEN_BACK = "\x1b[42;30m" YELLOW_BACK = "\x1b[43;30m" RESET = "\x1b[0m" import Adafruit_ADS1x15 adc = Adafruit_ADS1x15.ADS1115() adc = Adafruit_ADS1x15.ADS1015(address=0x49, busnum=1) GAIN = 1 adc.start_adc(1, gain=GAIN) import os import sys import datetime from datetime import date import calendar tooday = date.today() sys.stdout = open( "/home/pi/Documents/Week1/Day: " + calendar.day_name[tooday.weekday()] + " " + str(tooday), "a") print('Reading ADS1x15 channel 1 for 5 seconds...') print("Date & Time: " + str(datetime.datetime.now())) start = time.time() while (time.time() - start) <= 10.0: value = adc.get_last_result() if value < 800: print('too_much_water {0}'.format(value)) elif value < 1000: print('ok {0}'.format(value)) elif value > 1350: print('Completly_dry! {0}'.format(value))
#!/usr/bin/python3 import time import RPi.GPIO as GPIO from http.server import BaseHTTPRequestHandler, HTTPServer from threading import Thread import Adafruit_ADS1x15 import json adc = Adafruit_ADS1x15.ADS1115() # Temp in °C coffee_temp = -1 # RPi pin numbers BTN_ONE = 11 # out BTN_TWO = 12 # out LED_ONE = 22 # in LED_TWO = 18 # in GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(LED_ONE, GPIO.IN) GPIO.setup(LED_TWO, GPIO.IN) GPIO.setup(BTN_ONE, GPIO.OUT) GPIO.setup(BTN_TWO, GPIO.OUT) # Ensure relais are open (active low) GPIO.output(BTN_ONE, GPIO.HIGH) GPIO.output(BTN_TWO, GPIO.HIGH)
import time import datetime import Adafruit_ADS1x15 device = Adafruit_ADS1x15.ADS1115() num = 0 while True: values = [0]*4 for i in range(4): values[i] = device.read_adc(i, gain=8) if values[0] > 3200: fo = open("writeTo.txt", "w") fo.write('{}'.format(num)) fo.write(' {0:6}'.format(*values)) ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S') fo.write(' {}\n'.format(st)) print('{}'.format(num)) print(' {0:6}'.format(*values)) print(' {}\n'.format(st)) num+=1 fo.close() time.sleep(0.0001)