def testBuildCommands(self): expected_cmds = [u3.AIN(0), u3.AIN(1), u3.AIN(2)] commands, command_proto_field = self.labjack.BuildCommands() for command in commands: index = commands.index(command) self.assertEqual(command.positiveChannel, expected_cmds[index].positiveChannel) expected_mapping = { 0: 'fuel_level_voltage', 1: 'water_temp_voltage', 2: 'oil_pressure_voltage' } for command in command_proto_field: self.assertEqual(expected_mapping[command.positiveChannel], command_proto_field[command])
def ReadValues(self): """Reads the labjack voltages.""" try: if self.config.get('labjack'): point = gps_pb2.Point() point.labjack_temp_f = ( self.u3.getTemperature() * 9.0/5.0 - 459.67) for input_name, proto_field in self.config['labjack'].items(): if input_name.startswith('ain') or input_name.startswith('fio'): channel = int(input_name[-1]) # Note getFeedback(u3.AIN(4)) is reading voltage from FIO4. # Physically AIN4 and FIO4 are identical. AIN is for analog input # and FIO is flexible input/output. feedback = self.u3.getFeedback(u3.AIN(channel))[0] is_low_voltage = channel not in self.HIGH_VOLTAGE_CHANNELS voltage = self.u3.binaryToCalibratedAnalogVoltage( feedback, isLowVoltage=is_low_voltage, channelNumber=channel) if input_name in self.config['labjack'].get('tick_divider_10'): voltage = voltage * 10 setattr(point, proto_field, voltage) self.AddPointToQueue(point) except u3.LabJackException: stack_trace = ''.join(traceback.format_exception(*sys.exc_info())) logging.log_every_n_seconds(logging.ERROR, 'Error reading labjack values\n%s', 10, stack_trace)
def calcNoiseAndResolution(d, positiveChannel=0, negativeChannel=31): readings = [] cmd = u3.AIN(positiveChannel, negativeChannel, QuickSample=False, LongSettling=False) for i in range(128): readings.append(float(d.getFeedback(cmd)[0]) / 16.0) #print readings # Peak-To-Peak Noise p2pn = max(readings) - min(readings) # Noise-free resolution in bits if p2pn > 0: nfrbits = 12 - math.log(p2pn, 2) else: nfrbits = 12 # Noise-free resolution in millivolts if d.deviceName.endswith("HV") and positiveChannel < 4: vRange = 20.6 else: if negativeChannel != 31: vRange = 4.88 else: vRange = 2.44 nfrres = (vRange / (2**nfrbits)) * (10 ** 3) return p2pn, nfrbits, nfrres
def configureChannels(self, channels=None): # check if a list of channels has been provided. If not then just use # all channels. if channels: self.channels = channels else: self.channels = range(16) # make a list of read commands self.cmd = [] for ch in self.channels: self.cmd.append(u3.AIN(ch, 31, QuickSample = False, LongSettling = False))
#The following is implementation of the above ConfigIO config = D.configIO(FIOAnalog=0x1f, TimerCounterPinOffset=6, EnableCounter0=True, EnableCounter1=True) print(config) NHVs = 4 NLVs = 1 NDINs = 1 NCounters = 2 IsLV = [False] * NHVs + [True] * NLVs # Sensors/Actuators AINs = [ u3.AIN(i, NegativeChannel=31, LongSettling=False, QuickSample=True) for i in range(NHVs + NLVs) ] DINs = [u3.BitStateRead(i) for i in range(NHVs + NLVs, NHVs + NLVs + NDINs)] Counters = [u3.Counter(i, Reset=True) for i in range(NCounters)] def RGB(rgb): # RGB LED connected to EIO7, EIO5, EIO3 if rgb < 8: rgb += 8 threeBits = bin(rgb)[-3:] ch = (15, 13, 11) return [u3.BitStateWrite(ch[i], int(threeBits[i])) for i in range(3)] #````````````````````````````Helper functions````````````````````````````````` def printi(msg):
GUI.CurrentRate = CurrentRate GUI.RequiredPaymentAmount = RequiredPaymentAmount GUI.ChargeStartTime = ChargeStartTime GUI.Proximity = Proximity GUI.MaxAmps = MaxAmps if GUI._stop_event.is_set(): sys.exit() #not sure how to make ChargeNow perpetual, so just add an hour on every loop. TWCManager.master.setChargeNowTimeEnd( int(3600) ) #set how long to hold the current for, in seconds. need to refine this statement if have multiple wall units. ain0bits, = LabJack.getFeedback( u3.AIN(0) ) #channel 0, also note, the "," after "ain0bits" which is used to unpack the list returned by getFeedback() TheOutputVoltage = LabJack.binaryToCalibratedAnalogVoltage( ain0bits, isLowVoltage=False, channelNumber=0) #print TheOutputVoltage if (TheOutputVoltage > ProximityVoltage - 0.05) and (not Proximity): if ( time() > ProximityLostTime + 15 ): #wait at least 15 seconds after the plug was removed to start looking for proximity again if ProximityCheckStartTime == -1: ProximityCheckStartTime = time() TimeStampedPrint( "plug inserted"
d.getFeedback(u3.PortDirWrite(Direction=[0, 0, 0], WriteMask=[0, 0, 15])) feedbackArguments = [] feedbackArguments.append(u3.DAC0_8(Value=125)) feedbackArguments.append(u3.PortStateRead()) #Check if the U3 is an HV if d.configU3()['VersionInfo'] & 18 == 18: isHV = True else: isHV = False for i in range(numChannels): feedbackArguments.append( u3.AIN(i, 31, QuickSample=quickSample, LongSettling=longSettling)) #print feedbackArguments start = datetime.now() # Call Feedback 1000 times i = 0 while i < numIterations: results = d.getFeedback(feedbackArguments) #print results for j in range(numChannels): #Figure out if the channel is low or high voltage to use the correct calibration if isHV == True and j < 4: lowVoltage = False else: lowVoltage = True
_ratio = 1.9936 # Source: ardupilot AP_Airspeed_analog.cpp _airspeed0 = 0 _airspeed2 = 0 # Calibrate by taking 2000 measurements and taking simple average ain0offset = 0 ain2offset = 2 d = u3.U3() lc = lcm.LCM() CALIBRATION_TIME = 5 # desired calibration time in seconds SENSOR_FREQUENCY = 500 # in seconds for i in range(1, SENSOR_FREQUENCY * CALIBRATION_TIME): ain0bits, = d.getFeedback(u3.AIN(0)) # Read from raw bits from AIN0 ain0Value = d.binaryToCalibratedAnalogVoltage(ain0bits, isLowVoltage=False, channelNumber=0) ain0offset = (ain0offset * (i - 1) + ain0Value) / i ain2bits, = d.getFeedback(u3.AIN(2)) # Read from raw bits from AIN0 ain2Value = d.binaryToCalibratedAnalogVoltage(ain2bits, isLowVoltage=False, channelNumber=0) ain2offset = (ain2offset * (i - 1) + ain2Value) / i try: while True:
else: if prefix.upper() == 'E': AINbits = response["EIOAnalog"] elif prefix.upper() == 'F': AINbits = response["FIOAnalog"] else: return values for bit in range(8): bitvalue = 2**bit if prefix.upper() == 'E': bitID = bit + 8 else: bitID = bit if bitvalue & AINbits: values[prefix.upper() + 'AIN' + str(bit)] = self.getFeedback(u3.AIN(bitID)) return values def get_dir_bits(self): """ Get direction bits """ response = self.configU3() self.logger.debug("%s", response) return response["FIODirection"], \ response["EIODirection"], \ response["CIODirection"] def configureIO(self, config_dict): """ Configure the IO ports
# Python import u3 d = u3.U3() d.debug = True d.getCalibrationData() numsamples = 500 i = 0 fileName = 'testSignalGenData.dat' file = open(fileName, 'w') file.write("voltage,\n") while i < numsamples: voltageBits, = d.getFeedback(u3.AIN(1, 0)) print(voltageBits) voltage = d.binaryToCalibratedAnalogVoltage(voltageBits, isLowVoltage=True, isSingleEnded=True, isSpecialSetting=False, channelNumber=0) print(voltage) # print(d.getAIN(0)) file.write("{:10.7f},\n".format(voltage)) i += 1 ''' d.configIO(FIOAnalog = 0, EIOAnalog =0) # configures the FIOs and EIOs to digital state0 = d.getFIOState(0) # gives 0; means on? state1 = d.getFIOState(1) # gives 1; means off? state4 = d.getFIOState(4)
#!/usr/bin/python # LabJack demonstration # # Blink the U3's status LED until the AIN0 input exceeds a limit value. # # Source code from the book "Real World Instrumentation with Python" # By J. M. Hughes, published by O'Reilly. import u3 import time u3d = u3.U3() LEDoff = u3.LED(0) LEDon = u3.LED(1) AINcmd = u3.AIN(0, 31, False, False) toggle = 0 while True: # blink the LED while looping if toggle == 0: u3d.getFeedback(LEDon) toggle = 1 else: u3d.getFeedback(LEDoff) toggle = 0 inval = u3d.getFeedback(AINcmd)[0] print inval if inval > 40000:
fios = FIOEIOAnalog & 0xFF eios = FIOEIOAnalog // 256 LabJack.configIO(FIOAnalog=fios, EIOAnalog=eios) LabJack.getFeedback( u3.PortDirWrite(Direction=[0, 0, 0], WriteMask=[0, 0, 15])) FeedbackArguments = [] FeedbackArguments.append(u3.DAC0_8(Value=125)) FeedbackArguments.append(u3.PortStateRead()) if LabJack.configU3()['VersionInfo'] & 18 == 18: isHV = True # U3 is an HV else: isHV = False for Input in range(InputCount): FeedbackArguments.append( u3.AIN(Input, 31, QuickSample=QuickSample, LongSettling=LongSettling)) Time0 = time.time() Time1 = Time0 Path(SemaphoreFileName).touch() print(' time', end='') for Input in range(InputCount): if ChannelName[Input]: Name = ChannelName[Input] else: Name = '%02d' % (Input) print('%10s' % (Name), end='') print() print(' ------', end='') for Input in range(InputCount): print('%10s' % ('-' * 8), end='')