def do_measurement(): ### STEP 1: Initialise ADC object: ads = ADS1256(conf) n_loop = 1000 ### STEP 2: Gain and offset self-calibration: ads.cal_self() timestamp1 = time.time() for a in range(1, n_loop): ### STEP 3: Get data: raw_channels = ads.read_continue(CH_SEQUENCE) # raw_channels = ads.read_sequence(CH_SEQUENCE) timestamp2 = time.time() voltages = [i * ads.v_per_digit for i in raw_channels] nice_output(raw_channels, voltages) # Timing info print("\n"*9) delta = timestamp2 - timestamp1 print("Delta seconds: {}".format(delta)) per_sample = 1.0E6*delta/(n_loop*len(CH_SEQUENCE)) print("Per sample microseconds: {}".format(per_sample)) overhead = per_sample - 1.0e6/n_loop print("Overhead per sample microseconds: {}".format(overhead))
def do_measurement(): ### STEP 1: Initialise ADC object: ads = ADS1256() ### STEP 2: Gain and offset self-calibration: ads.cal_self() while True: ### STEP 3: Get data: global in0_vAnt global in1_vAnt global in2_vAnt global in3_vAnt global corrienteSensor_vAnt raw_channels = ads.read_sequence(CH_SEQUENCE) voltages = [i * ads.v_per_digit for i in raw_channels] ### STEP 4: DONE. Have fun! #nice_output(raw_channels, voltages) #print('Voltajes ') #print(voltages) ### Almacenar la informacion de los datos en el servidor: almacenarVariable(voltages[0],in0_vAnt,'voltaje_potenciometro','nodo_prueba_ADC') almacenarVariable(voltages[1],in1_vAnt,'voltaje_LDR','nodo_prueba_ADC') almacenarVariable(voltages[2],in2_vAnt,'voltaje_potenciometro_externo','nodo_prueba_ADC') almacenarVariableBM(voltages[3],in3_vAnt,'voltaje_sensor_corriente','nodo_prueba_ADC',0.01) corrienteSensor=voltages[3]*12.0-30.0 almacenarVariableBM(corrienteSensor,corrienteSensor_vAnt,'corriente','sensor_corriente_1',0.02) ### Valores anteriores para la banda muerta in0_vAnt=voltages[0] in1_vAnt=voltages[1] in2_vAnt=voltages[2] in3_vAnt=voltages[3] corrienteSensor_vAnt=corrienteSensor
def measurement(plotData,C_save,C_Drate): # 描画するデータ now = datetime.datetime.now()#get time plotData.append(['{0:%Y-%m-%d }'.format(now), 'Magnetic force(nT)_1ch','Magnetic force(nT)_2ch', 'Magnetic force(nT)_3ch','Magnetic force(nT)_4ch']) ads = ADS1256() ads.drate = (DRATE_100 if C_Drate == 100 else DRATE_500 if C_Drate == 500 else DRATE_1000 if C_Drate == 1000 else DRATE_2000) ads.pga_gain = 1 ads.cal_self() """データを一定間隔で追加するスレッドの処理""" counter = 0 while True: now = datetime.datetime.now() # get data raw_channels = ads.read_sequence(CH_SEQUENCE) voltages = [(i * ads.v_per_digit) for i in raw_channels] plotData.append(['{0:%H:%M:%S.%f}'.format(now),voltages[0],voltages[1],voltages[2],voltages[3]]) # MagneticF = [(i * 1000 / 0.16) for i in voltages] # plotData.append(['{0:%H:%M:%S.%f}'.format(now), MagneticF[0], MagneticF[1], MagneticF[2], MagneticF[3]]) counter += 1 if counter >= PLOT_DATA_NUM: plotData.pop(1) counter -= 1
def measurement(plotData, C_save, C_Drate): #1007B:1029A:1024A:LM60 slope = [6.041297912, 6.032822234, 6.024782582, 1.004970735] intercept = [-15.21584595, -15.20405742, -15.17129194, -0.000415594] transform = [0.16 * 0.001, 0.16 * 0.001, 0.16 * 0.001, 6.25 * 0.001] off_set = [0, 0, 0, 424 * 0.001] # 描画するデータ now = datetime.datetime.now(timezone.utc) plotData.append([ '{0:%Y-%m-%d }'.format(now), 'Magnetic force(nT)_1ch', 'Magnetic force(nT)_2ch', 'Magnetic force(nT)_3ch', 'Magnetic force(nT)_4ch' ]) ads = ADS1256() ads.drate = (DRATE_100 if C_Drate == 100 else DRATE_500 if C_Drate == 500 else DRATE_1000 if C_Drate == 1000 else DRATE_2000) ads.pga_gain = 1 ads.cal_self() with open('./data/MI{0:%y-%m-%d_%Hh%Mm%Ss}.csv'.format(now), 'w', newline="") as f: saveData = [ '{0:%Y-%m-%d }'.format(now), 'Magnetic force(nT)_1ch', 'Magnetic force(nT)_2ch', 'Magnetic force(nT)_3ch', 'Magnetic force(nT)_4ch' ] writer = csv.writer(f) writer.writerow(saveData) counter = 0 while True: now = datetime.datetime.now(timezone.utc) #### get data #### raw_channels = ads.read_sequence(CH_SEQUENCE) # raw_channels = ads.read_continue(CH_SEQUENCE) voltages = [i * ads.v_per_digit for i in raw_channels] voltages_15 = [(voltages[i] * slope[i] + intercept[i]) for i in range(4)] MagF = [((voltages_15[i] - off_set[i]) / transform[i]) for i in range(4)] #### test #### #sleep(0.1) #MagF = [8 + random.random(),8 + random.random(),8 + random.random(),2 + random.random()] ############## plotData.append([ '{0:%H:%M:%S.%f}'.format(now), MagF[0], MagF[1], MagF[2], MagF[3] ]) saveData = [ '{0:%H:%M:%S.%f}'.format(now), MagF[0], MagF[1], MagF[2], MagF[3] ] writer = csv.writer(f) writer.writerow(saveData) counter += 1 if counter >= PLOT_DATA_NUM: plotData.pop(1) counter -= 1
def __init__(self): from pipyadc import ADS1256 POTI = POS_AIN0 | NEG_AINCOM EXT2, EXT3, EXT4 = POS_AIN2 | NEG_AINCOM, POS_AIN3 | NEG_AINCOM, POS_AIN4 | NEG_AINCOM EXT5, EXT6, EXT7 = POS_AIN5 | NEG_AINCOM, POS_AIN6 | NEG_AINCOM, POS_AIN7 | NEG_AINCOM self.CH_SEQUENCE = (EXT2, EXT3, EXT4, EXT5, EXT6, EXT7) self.ads = ADS1256() self.ads.cal_self() print("Sensor Init")
def do_measurement(): ### STEP 1: Initialise ADC object: ads = ADS1256() ### STEP 2: Gain and offset self-calibration: ads.cal_self() ### STEP 3: Get data: adsread = ads.read_oneshot(EXT3) voltage = adsread * ads.v_per_digit return voltage
def prepare_data_acquisition(self): POTI, LDR, EXT2, EXT3 = ( POS_AIN0 | NEG_AINCOM, POS_AIN1 | NEG_AINCOM, POS_AIN2 | NEG_AINCOM, POS_AIN3 | NEG_AINCOM, ) self.CH_SEQUENCE = (POTI, LDR, EXT2, EXT3) self.ads = ADS1256(pipyadc.ADS1256_default_config) self.ads.cal_self()
def do_measurement(): ### STEP 1: Initialise ADC object: ads = ADS1256() ### STEP 2: Gain and offset self-calibration: ads.cal_self() while True: ### STEP 3: Get data: raw_channels = ads.read_sequence(new_seq) voltages = [i * ads.v_per_digit for i in raw_channels] print(voltages)
def do_measurement(): ### STEP 1: Initialise ADC object: ads = ADS1256() ### STEP 2: Gain and offset self-calibration: ads.cal_self() ### STEP 3: Get data: raw_channels = ads.read_sequence(CH_SEQUENCE) voltages = [i * ads.v_per_digit for i in raw_channels] ### STEP 4: DONE. Have fun! #print('Voltajes ') #print(voltages) return voltages[0], voltages[1]
def PWM_Measure_Voltage(Measurement): ads = ADS1256() ads.cal_self() if Measurement == 'DC_Link': adsread = ads.read_oneshot(EXT3) DCVolts = adsread * ads.v_per_digit elif Measurement == 'Solar': adsread = ads.read_oneshot(EXT4) DCVolts = adsread * ads.v_per_digit else: UPS_Error('Error_Voltage_Measurement') return DCVolts
def write(): ### STEP 1: Initialise ADC object using default configuration: # (Note1: See ADS1256_default_config.py, see ADS1256 datasheet) # (Note2: Input buffer on means limited voltage range 0V...3V for 5V supply) ads = ADS1256() ### STEP 2: Gain and offset self-calibration: ads.cal_self() while True: for x in range(5000000): ## time.sleep(1) ads.write_reg(0x30,0xFF) print(x)
def do_measurement(): ### STEP 1: Initialise ADC object: ads = ADS1256() ### STEP 2: Gain and offset self-calibration: ads.cal_self() while True: ### STEP 3: Get data: raw_channels = ads.read_sequence(CH_SEQUENCE) voltages = [i * ads.v_per_digit for i in raw_channels] ### STEP 4: DONE. Have fun! nice_output(raw_channels, voltages)
def do_measurement(): ### STEP 1: Initialise ADC object using default configuration: # (Note1: See ADS1256_default_config.py, see ADS1256 datasheet) # (Note2: Input buffer on means limited voltage range 0V...3V for 5V supply) ads = ADS1256() ### STEP 2: Gain and offset self-calibration: ads.cal_self() while True: ### STEP 3: Get data: raw_channels = ads.read_sequence(CH_SEQUENCE) voltages = [i * ads.v_per_digit for i in raw_channels] print("Data is " + str(voltages[0]))
def Run_Initialization(): # Water # Solar PWM.PWM_Write(Parameters.PWMPin, Parameters.PID_OLD_INIT * Parameters.Range) # VFD Connection Initialization # VFD.VFDInit("/dev/ttyAMA0".encode('ascii'),9600,8,1,1) VFD.VFDInit(Parameters.Device.encode('ascii'), Parameters.Baud, Parameters.Data, Parameters.Stop, Parameters.ID) VFD.VFDWrite( reg.get("WriteFunc", {}).get("Frequency_Set"), Parameters.VFD_Freq_Init) # Set initial frequency VFD.VFDWrite( reg.get("WriteFunc", {}).get("Frequency_Acc"), Parameters.VFD_Acc_Rate) # Set acceleration rate # PWM Setup PWM.PWM_Setup() PWM.PWM_Pin_Mode(Parameters.PWMPin) PWM.PWM_Set_Mode() PWM.PWM_Set_Clock(Parameters.Divisor) PWM.Pin_Mode_Output(Paramters.AC_DigitalPin) PWM.Pin_Mode_Output(Paramters.DC_DigitalPin) PWM.PWM_Set_Range(Parameters.Range) # # Connect to ADS1256 chip ads = ADS1256() # Calibrate gain and offset ads.cal_self() # SQL Database Setup try: conn = sqlite3.connect('UPS_DB.db') c = conn.cursor() c.execute( '''CREATE TABLE UPS_DB(Date text,Solar_Voltage real, DC_Link_Voltage real, VFD_Freq real, VFD_Volt real, VFD_Amps real, VFD_Power real, VFD_BusVolt real, VFD_Temp real)''' ) conn.commit() except: conn.rollback() print("Database already created") finally: conn.close() print("Database connection closed")
def handle_accept(self): ads = ADS1256() ads.cal_self() global data client, addr = self.accept() print("Connected to " + str(addr)) while (1): try: raw_channels = ads.read_sequence(CH_SEQUENCE) voltages = [i * ads.v_per_digit for i in raw_channels] ferguso = ','.join(map(str, voltages)) client.send((ferguso + '\n').encode()) data = np.roll(data, 1) time.sleep(0.05) except Exception as e: print(e) return
def do_measurement(): ### STEP 1: Initialise ADC object using default configuration: # (Note1: See ADS1256_default_config.py, see ADS1256 datasheet) # (Note2: Input buffer on means limited voltage range 0V...3V for 5V supply) ads = ADS1256() ### STEP 2: Gain and offset self-calibration: ads.cal_self() while True: ### STEP 3: Get data: raw_channels = ads.read_sequence(CH_SEQUENCE) # voltages = [i * ads.v_per_digit for i in raw_channels] ### STEP 4: DONE. Have fun! # sys.stdout.write( ", ".join(["{: 8d}".format(i) for i in raw_channels]) + "\n") sys.stdout.write( "{: d}".format(raw_channels[0]) + "\n")
def do_measurement(): ### STEP 1: Initialise ADC object using default configuration: # (Note1: See ADS1256_default_config.py, see ADS1256 datasheet) # (Note2: Input buffer on means limited voltage range 0V...3V for 5V supply) #create a new class following class rule ADS1256, named ads ads = ADS1256() #if you want to set v_ref, use ads.v_ref(5) ### STEP 2: Gain and offset self-calibration: ads.cal_self() while True: ### STEP 3: Get data: raw_channels = ads.read_sequence(CH_SEQUENCE) voltages = [i * ads.v_per_digit for i in raw_channels] ### STEP 4: DONE. Have fun! nice_output(raw_channels, voltages)
def PWM_Measure_Voltage(Measurement): # Connect to ADS1256 chip ads = ADS1256() # Calibrate gain and offset #ads.cal_self() # Measure DC link or solar voltage if Measurement == 'DC_Link': adsread = ads.read_oneshot(EXT3) DCVolts = adsread * ads.v_per_digit elif Measurement == 'Solar': adsread = ads.read_oneshot(EXT4) DCVolts = adsread * ads.v_per_digit else: UPS_Messages('Error_Voltage_Measurement') return DCVolts
def do_measurement(): ### STEP 1: Initialise ADC object using default configuration: # (Note1: See ADS1256_default_config.py, see ADS1256 datasheet) # (Note2: Input buffer on means limited voltage range 0V...3V for 5V supply) ads = ADS1256() ### STEP 2: Gain and offset self-calibration: ads.cal_self() while True: ### STEP 3: Get data: raw_channels = ads.read_sequence(CH_SEQUENCE) voltages = [i * ads.v_per_digit for i in raw_channels] sql = "INSERT INTO dbo.voltages (CustomerID, Voltage) VALUES (?, ?)" val = (1, voltages[0]) cursor.execute(sql, val) conn.commit()
def PWM_Measure_Voltage(Measurement): CH_SEQ = (EXT3, EXT4) # Connect to ADS1256 chip ads = ADS1256() # Calibrate gain and offset ads.cal_self() Volts = ads.read_sequence(CH_SEQ) # Measure DC link or solar voltage if Measurement == 'DC_Link': #adsread = ads.read_oneshot(EXT3) DCVolts = Volts[0] * ads.v_per_digit elif Measurement == 'Solar': #adsread = ads.read_oneshot(EXT4) DCVolts = Volts[1] * ads.v_per_digit else: logger.info('Error reading voltage measurement') return DCVolts
def _measurement(C_Drate, C_save): ads = ADS1256() ads.drate = (DRATE_100 if C_Drate == 100 else DRATE_500 if C_Drate == 500 else DRATE_1000 if C_Drate == 1000 else DRATE_2000) ads.pga_gain = 1 ads.cal_self() """データを一定間隔で追加するスレッドの処理""" counter = 0 while True: now = datetime.datetime.now() # get data raw_channels = ads.read_sequence(CH_SEQUENCE) voltages = [(i * ads.v_per_digit * 6.970260223 - 15.522769516) for i in raw_channels] MagneticF = [(i * 1000 / 0.16) for i in voltages] data.append([ '{0:%H:%M:%S.%f}'.format(now), MagneticF[0], MagneticF[1], MagneticF[2], MagneticF[3] ]) counter += 1 if counter > 1000: data.pop(1) counter -= 1
def setup(self, frequency, averaging=False): """Configure ADS1256 ADC converter Arguments: frequency {double} -- Frequency for reading data, in data/min. Keyword Arguments: averaging {boolean} -- If True, data will be read every 2 seconds, but returned averaged every 1/frequency (default: {False}) """ # --------------------------------------------------------------- # ADS Configuration # --------------------------------------------------------------- try: ads = ADS1256() ads.cal_self() self.ads = ads except Exception as e: self.logger.error("Error setting up ads1256 ADC converter : " + str(e)) return False self.frequency = frequency self.avg = averaging #Setup Base de Donnee connection_status = self.database.connection() if connection_status == "Connection failed": return connection_status table_status = self.database.create_table(TABLE_NAME, COL) if table_status == "Error date": return table_status self.logger.debug("Sensor is setup") return True
def do_measurement(): ### STEP 1: Initialise ADC object using default configuration: # (Note1: See ADS1256_default_config.py, see ADS1256 datasheet) # (Note2: Input buffer on means limited voltage range 0V...3V for 5V supply) ads = ADS1256() # サンプリング・レートの設定 # REG_DRATE: Sample rate definitions: # DRATE_30000 = 0b11110000 # 30,000SPS (default) # DRATE_15000 = 0b11100000 # 15,000SPS # DRATE_7500 = 0b11010000 # 7,500SPS # DRATE_3750 = 0b11000000 # 3,750SPS # DRATE_2000 = 0b10110000 # 2,000SPS # DRATE_1000 = 0b10100001 # 1,000SPS # DRATE_500 = 0b10010010 # 500SPS # DRATE_100 = 0b10000010 # 100SPS # DRATE_60 = 0b01110010 # 60SPS # DRATE_50 = 0b01100011 # 50SPS # DRATE_30 = 0b01010011 # 30SPS # DRATE_25 = 0b01000011 # 25SPS # DRATE_15 = 0b00110011 # 15SPS # DRATE_10 = 0b00100011 # 10SPS # DRATE_5 = 0b00010011 # 5SPS # DRATE_2_5 = 0b00000011 # 2.5SPS ads.drate = DRATE_1000 # gainの設定 ads.pga_gain = 1 ### STEP 2: Gain and offset self-calibration: ads.cal_self() # 1009B:1015A:1007A:LM60 slope = [5.983008908, 5.986294071, 5.969294712, 0.996870146] intercept = [-15.2799896, -15.24849903, -15.22909284, 0] transform = [0.16 * 0.001, 0.16 * 0.001, 0.16 * 0.001, 6.25 * 0.001] off_set = [0.30, -0.34, -0.10, 424 * 0.001] while True: now = datetime.datetime.now(timezone.utc) #get time today = '{0:%Y-%m-%d}'.format(now) counter = 0 while True: now = datetime.datetime.now(timezone.utc) # get data # raw_channels = ads.read_sequence(CH_SEQUENCE) raw_channels = ads.read_continue(CH_SEQUENCE) #voltages = [(i * ads.v_per_digit * 6.970260223 - 15.522769516) for i in raw_channels] #MagneticF = [(i * 1000 / 0.16) for i in voltages] voltages = [i * ads.v_per_digit for i in raw_channels] # voltages = [2.5,2.5,2.5,0] voltages_15 = [(voltages[i] * slope[i] + intercept[i]) for i in range(4)] # voltages_15 = [0,0,0,0] MagneticF = [(voltages_15[i] - off_set[i]) / transform[i] for i in range(4)] # MagneticF = [voltages[i] for i in range(4)] print('{0:%Y-%m-%d %H:%M:%S}'.format(now)) print('X [nT]= ' + '{:.4f}'.format(MagneticF[0])) print('Y [nT]= ' + '{:.4f}'.format(MagneticF[1])) print('Z [nT]= ' + '{:.4f}'.format(MagneticF[2])) print('Temperature [C]= ' + '{:.2f}'.format(MagneticF[3])) print("\33[6A") counter += 1 if '{0:%Y-%m-%d}'.format(now) != today: break today = '{0:%Y-%m-%d}'.format(now)
def logger(channels, outfile, rate=1, n_digits=3, mode='s', show_data=False): """ Method to log the data read back from a ADS1256 ADC to a file. Default is to read from positive AD0-AD7 pins from 0 to 7 for single- ended measurement. For differential measurement pin i and i + 1 are selected as inputs. Only as many channels are read as there are names in the channel list. Parameters ---------- channels: list list of strings with names of channels outfile: str string of output file location rate: int Logging rate in Hz n_digits: int number of decimal places to be logged into the outfile mode: 's' or 'd' or str of combination of both string character(s) describing the measurement mode: single-endend (s) or differential (d) show_data: bool whether or not to show the data every second on the stdout Returns ------- """ # get instance of ADC Board adc = ADS1256() # self-calibration adc.cal_self() # channels TODO: represent not only positive channels _all_channels = [ POS_AIN0, POS_AIN1, POS_AIN2, POS_AIN3, POS_AIN4, POS_AIN5, POS_AIN6, POS_AIN7 ] # gnd _gnd = NEG_AINCOM # get actual channels by name if len(channels) > 8 and mode == 's': raise ValueError('Only 8 single-ended input channels exist') elif len(channels) > 4 and mode == 'd': raise ValueError('Only 4 differential input channels exist') else: # only single-ended measurements if mode == 's': actual_channels = [ _all_channels[i] | _gnd for i in range(len(channels)) ] # only differential measurements elif mode == 'd': actual_channels = [ _all_channels[i] | _all_channels[i + 1] for i in range(len(channels)) ] # mix of differential and single-ended measurements elif len(mode) > 1: # get configuration of measurements channel_config = [ 1 if mode[i] == 's' else 2 for i in range(len(mode)) ] # modes are known and less than 8 channels in total if all(m in ['d', 's'] for m in mode) and sum(channel_config) <= 8: i = j = 0 actual_channels = [] while i != sum(channel_config): if channel_config[j] == 1: actual_channels.append(_all_channels[i] | _gnd) else: actual_channels.append(_all_channels[i] | _all_channels[i + 1]) i += channel_config[j] j += 1 if len(actual_channels) != len(channels): raise ValueError( 'Number of channels (%i) not matching measurement mode ("%s" == %i differential & %i single-ended channels)!' % (len(channels), mode, mode.count('d'), mode.count('s'))) else: raise ValueError( 'Unsupported number of channels! %i differential (%i channels) and %i single-ended (%i channels) measurements but only 8 channels total.' % (mode.count('d'), mode.count('d') * 2, mode.count('s'), mode.count('s'))) else: raise ValueError( 'Unknown measurement mode %s. Supported modes are "d" for differential and "s" for single-ended measurements.' % mode) # open outfile with open(outfile, 'w') as out: # write info header out.write('# Date: %s \n' % time.asctime()) out.write('# Measurement in %s mode.\n' % ('differential' if mode == 'd' else 'single-ended' if mode == 's' else mode)) out.write('# Timestamp / s\t' + ' \t'.join('%s / V' % c for c in channels) + '\n') # try -except clause for ending logger try: print 'Start logging channel(s) %s to file %s.\nPress CTRL + C to stop.\n' % ( ', '.join(channels), outfile) start = time.time() while True: readout_start = time.time() # get current channels raw = adc.read_sequence(actual_channels) volts = [b * adc.v_per_digit for b in raw] readout_end = time.time() # write timestamp to file out.write('%f\t' % time.time()) # write voltages to file out.write('\t'.join('%.{}f'.format(n_digits) % v for v in volts) + '\n') # wait time.sleep(1. / rate) # User feedback about logging and readout rates every second if time.time() - start > 1: # actual logging and readout rate logging_rate = 1. / (time.time() - readout_start) readout_rate = 1. / (readout_end - readout_start) # print out with flushing log_string = 'Logging rate: %.2f Hz' % logging_rate + ',\t' + 'Readout rate: %.2f Hz for %i channel(s)' % ( readout_rate, len(actual_channels)) # show values if show_data: # print out with flushing log_string += ': %s' % ', '.join( '{}: %.{}f V'.format(channels[i], n_digits) % volts[i] for i in range(len(volts))) # print out with flushing sys.stdout.write('\r' + log_string) sys.stdout.flush() # overwrite start = time.time() except KeyboardInterrupt: print '\nStopping logger...\nClosing %s...' % str(outfile) print 'Finished'
from ADS1256_definitions import * from pipyadc import ADS1256 # In this example, we pretend myconfig_2 was a different configuration file # named "myconfig_2.py" for a second ADS1256 chip connected to the SPI bus. import ADS1256_default_config as myconfig_2 SHORT_CIRCUIT = POS_AIN0|NEG_AIN0 EXT2 = POS_AIN2|NEG_AINCOM CH_OFFSET = np.array((0, 0), dtype=np.int) GAIN_CAL = np.array((1.0, 1.0), dtype=np.float) CH_SEQUENCE = (EXT2, SHORT_CIRCUIT) #begin ads2 = ADS1256(myconfig_2) ads2.drate = DRATE_30000 ads2.cal_self() chip_ID = ads2.chip_ID print("\nADC No. 2 reported a numeric ID value of: {}.".format(chip_ID)) # When the value is not correct, user code should exit here. if chip_ID != 3: print("\nRead incorrect chip ID for ADS1256. Is the hardware connected?") CH_GAIN = ads2.v_per_digit * GAIN_CAL time_read = 1 data_array = np.empty([1, 30000], dtype=int)
yield MA(values) if not os.path.exists("/dev/spidev0.1"): raise IOError("Error: No SPI device. Check settings in /boot/config.txt") #differential channels on the ADS1256 DIFF1 = POS_AIN0|NEG_AIN1 #LOX1 DIFF2 = POS_AIN2|NEG_AIN3 #LOX2 DIFF3 = POS_AIN4|NEG_AIN5 #RP11 DIFF4 = POS_AIN6|NEG_AIN7 #RP12 #post read processing global CHANNELS global CALIBRATION global ADS ADS = ADS1256() ADS.cal_self() CHANNELS = (DIFF1, DIFF2, DIFF3, DIFF4) CALIBRATION = [0,0] #(m, b) in y = mx+b CALIBRATE = lambda val: CALIBRATION[0]*val + CALIBRATION[1] CALIBRATE_MAP = lambda vals: map(CALIBRATE, vals) def read_pressure(ch = CHANNELS, keys = ["LOX_1", "LOX_2", "RP1_1", "RP1_2"]): global ADS readings = map(MAFilter, CALIBRATE_MAP(ADS.read_sequence(ch))) if readings[0] ==None: return None data = dict.fromkeys(keys) for reading, key in zip(readings, keys): data[key] = reading return data
import time import json import wiringpi as wp import mohm_definitions from mohm_definitions import * from ADS1256_definitions import * from pipyadc import ADS1256 ads = ADS1256() # Definitions TEMPERATURE_CHANNEL = (POS_AIN0 | NEG_AIN1) RESISTANCE_CHANNELS_20_VOLTAGE_GAIN = (POS_AIN4 | NEG_AIN5, POS_AIN6 | NEG_AIN7) RESISTANCE_CHANNELS_1000_VOLTAGE_GAIN = (POS_AIN2 | NEG_AIN3, POS_AIN6 | NEG_AIN7) class OHMIMETRO(object): def __init__(self, conf=mohm_definitions): # Set up the wiringpi object to use physical pin numbers wp.wiringPiSetupPhys() # Config and initialize the SPI and GPIO pins used by the ADC. # The following four entries are actively used by the code: self.ESC1_PIN = conf.ESC1_PIN self.ESC2_PIN = conf.ESC2_PIN self.ESC3_PIN = conf.ESC3_PIN self.GAIN_PIN = conf.GAIN_PIN self.INPUT1 = conf.INPUT1 self.INPUT2 = conf.INPUT2 self.INPUT3 = conf.INPUT3
def do_measurement(): ### STEP 1: Initialise ADC object using default configuration: # (Note1: See ADS1256_default_config.py, see ADS1256 datasheet) # (Note2: Input buffer on means limited voltage range 0V...3V for 5V supply) ads = ADS1256() # サンプリング・レートの設定 # REG_DRATE: Sample rate definitions: # DRATE_30000 = 0b11110000 # 30,000SPS (default) # DRATE_15000 = 0b11100000 # 15,000SPS # DRATE_7500 = 0b11010000 # 7,500SPS # DRATE_3750 = 0b11000000 # 3,750SPS # DRATE_2000 = 0b10110000 # 2,000SPS # DRATE_1000 = 0b10100001 # 1,000SPS # DRATE_500 = 0b10010010 # 500SPS # DRATE_100 = 0b10000010 # 100SPS # DRATE_60 = 0b01110010 # 60SPS # DRATE_50 = 0b01100011 # 50SPS # DRATE_30 = 0b01010011 # 30SPS # DRATE_25 = 0b01000011 # 25SPS # DRATE_15 = 0b00110011 # 15SPS # DRATE_10 = 0b00100011 # 10SPS # DRATE_5 = 0b00010011 # 5SPS # DRATE_2_5 = 0b00000011 # 2.5SPS ads.drate = DRATE_1000 # gainの設定 ads.pga_gain = 1 ### STEP 2: Gain and offset self-calibration: ads.cal_self() now = datetime.datetime.now() #get time data = [[ '{0:%Y-%m-%d }'.format(now), 'Magnetic force(nT)_1ch', 'Magnetic force(nT)_2ch', 'Magnetic force(nT)_3ch', 'Magnetic force(nT)_4ch' ]] counter = 0 while True: now = datetime.datetime.now() # get data raw_channels = ads.read_sequence(CH_SEQUENCE) voltages = [(i * ads.v_per_digit * 6.970260223 - 15.522769516) for i in raw_channels] MagneticF = [(i * 1000 / 0.16) for i in voltages] data.append([ '{0:%H:%M:%S.%f}'.format(now), MagneticF[0], MagneticF[1], MagneticF[2], MagneticF[3] ]) if counter == 1000: print('{0:%Y-%m-%d %H:%M:%S}'.format(now) + ' Magnetic force(nT)==' + str(MagneticF[0])) fig_plot(data, "OVER", 200) data.clear() now = datetime.datetime.now() #get time data = [[ '{0:%Y-%m-%d }'.format(now), 'Magnetic force(nT)_1ch', 'Magnetic force(nT)_2ch', 'Magnetic force(nT)_3ch', 'Magnetic force(nT)_4ch' ]] counter = 0 counter += 1
def do_measurement(): ### STEP 1: Initialise ADC objects for two chips connected to the SPI bus. # In this example, we pretend myconfig_2 was a different configuration file # named "myconfig_2.py" for a second ADS1256 chip connected to the SPI bus. # This file must be imported, see top of the this file. # Omitting the first chip here, as this is only an example. #ads1 = ADS1256(myconfig_1) # (Note1: See ADS1256_default_config.py, see ADS1256 datasheet) # (Note2: Input buffer on means limited voltage range 0V...3V for 5V supply) ads2 = ADS1256(myconfig_2) # Just as an example: Change the default sample rate of the ADS1256: # This shows how to acces ADS1256 registers via instance property ads2.drate = DRATE_100 ### STEP 2: Gain and offset self-calibration: ads2.cal_self() ### Get ADC chip ID and check if chip is connected correctly. chip_ID = ads2.chip_ID print("\nADC No. 2 reported a numeric ID value of: {}.".format(chip_ID)) # When the value is not correct, user code should exit here. if chip_ID != 3: print("\nRead incorrect chip ID for ADS1256. Is the hardware connected?") # Passing that step because this is an example: # sys.exit(1) # Channel gain must be multiplied by LSB weight in volts per digit to # display each channels input voltage. The result is a np.array again here: CH_GAIN = ads2.v_per_digit * GAIN_CAL # Numpy 2D array as buffer for raw input samples. Each row is one complete # sequence of samples for eight input channel pin pairs. Each column stores # the number of FILTER_SIZE samples for each channel. rows, columns = FILTER_SIZE, len(CH_SEQUENCE) filter_buffer = np.zeros((rows, columns), dtype=np.int) # Fill the buffer first once before displaying continuously updated results print("Channels configured: {}\n" "Initializing filter (this can take a minute)...".format( len(CH_SEQUENCE))) for row_number, data_row in enumerate(filter_buffer): # Do the data acquisition of eight multiplexed input channels. # The ADS1256 read_sequence() method automatically fills into # the buffer specified as the second argument: ads2.read_sequence(CH_SEQUENCE, data_row) # Depending on aquisition speed and filter lenth, this can take long... sys.stdout.write( "\rProgress: {:3d}%".format(int(100*(row_number+1)/FILTER_SIZE))) sys.stdout.flush() # From now, update filter_buffer cyclically with new ADC samples and # calculate results with averaged results. print("\n\nOutput values averaged over {} ADC samples:".format(FILTER_SIZE)) # The following is an endless loop! timestamp = time.time() # Limit output data rate to fixed time interval for data_row in itertools.cycle(filter_buffer): # # Do the data acquisition of eight multiplexed input channels # # The result channel values are directy read into the array specified # as the second argument, which must be a mutable type. ads2.read_sequence(CH_SEQUENCE, data_row) elapsed = time.time() - timestamp if elapsed > 1: timestamp += 1 # Calculate moving average of input samples, subtract offset ch_unscaled = np.average(filter_buffer, axis=0) - CH_OFFSET ch_volts = ch_unscaled * CH_GAIN nice_output([int(i) for i in ch_unscaled], ch_volts)
from bottle import route, run, template, request import plotly.offline as po import plotly.graph_objs as go import atexit CIRCUIT_R1 = 0.27 # Ohms; shunt resistor in series to load # Change this to the local DNS name of your Pi (often raspberrypi.local, if you have changed it) or # make it blank to connect to localhost. #PI_HOST = 'klabs.local' ### STEP 1: Initialise ADC object using default configuration: # (Note1: See ADS1256_default_config.py, see ADS1256 datasheet) # (Note2: Input buffer on means limited voltage range 0V...3V for 5V supply) ads = ADS1256() #pi=io.pi(PI_HOST)) ads.drate = DRATE_30000 ### STEP 2: Gain and offset self-calibration: ads.cal_self() #initialize PWM GPIO.setmode(GPIO.BCM) pwmpin = 12 GPIO.setup(pwmpin, GPIO.OUT) pwm = GPIO.PWM(pwmpin, 100) pwm.start(50.0) def exit_handler():