def readTemperature(self): max102 = self.max102 # Step 1: Config die temperature register to take 1 temperature sample max102.write_byte_data(self, self.MAX30102_ADDRESS, self.MAX30102_DIETEMPCONFIG, 0x01) # Poll for bit to clear, reading is then complete # Timeout after 100 ms startTime = wiry.millis() while wiry.millis() - startTime < 100: response = max102.read_byte_data(self.MAX30102_ADDRESS, self.MAX30102_DIETEMPCONFIG) if (response & 0x01) == 0: break wiry.delay(1) # if (millis() - startTime >= 100) return (-999) # Step 2: Read die temperature register (integer) tempInt = max102.read_byte_data(self, self.MAX30102_ADDRESS, self.MAX30102_DIETEMPCONFIG) tempFrac = max102.read_byte_data(self, self.MAX30102_ADDRESS, self.MAX30102_DIETEMPFRAC) # Step 3: Calculate temperature (datasheet pg. 22) return tempInt + tempFrac * 0.0625
def __getTemperature(self, dataType): timeout = wp.millis() + self.__IRTEMP_TIMEOUT self.__sensorEnable(True) while True: data = [0] * self.__IRTEMP_DATA_SIZE for data_byte in range(0, self.__IRTEMP_DATA_SIZE, 1): for data_bit in range(7, -1, -1): # Clock idles high, data changes on falling edge, sample on rising edge while wp.digitalRead( self.__pinClock) == 1 and wp.millis() < timeout: pass # Wait for falling edge while wp.digitalRead( self.__pinClock) == 0 and wp.millis() < timeout: pass # Wait for rising edge to sample if wp.digitalRead(self.__pinData): data[data_byte] |= 1 << data_bit if wp.millis() >= timeout: self.__sensorEnable(False) return float('nan') if data[0] == dataType and self.__validData(data): self.__sensorEnable(False) temperature = self.__decodeTemperature(data) if self.__scale == "FAHRENHEIT": temperature = self.__convertFahrenheit(temperature) return temperature
def safeCheck(self, maxTimetoCheck): markTime = wiry.millis() while True: if wiry.millis() - markTime > maxTimetoCheck: return False if self.check(): return True
def getECG(self, numSeconds): sampleRate = 250 starTime = wiringpi.millis() while wiringpi.millis()-starTime < numSeconds*1000: Ecg = round((mcp.read_adc(1)*3.3)/1024,3) self.ecgValues = np.append(self.ecgValues,Ecg) wiringpi.delayMicroseconds(200)
def callback_sensor_action(self, sensor_num): reading = pin_read(self.sensor_state[sensor_num].pin) logging.info("\nGPIO_CALLBACK! - {} action = {}".format( self.sensor_state[sensor_num].name, reading)) if reading != self.sensor_state[sensor_num].button_state: special = 'GOOD' if (wpi.millis() - self.flap_time) < FLAP_THRESHOLD: special = 'TOO SOON' logging.info( '- too soon since last state change, ignoring this event') return self.flap_time = wpi.millis() logging.info('- Check for flap = {} : ({} - {}) < {}'.format( special, wpi.millis(), self.flap_time, FLAP_THRESHOLD)) self.door_state[sensor_num] = self.sensor_state[ sensor_num].update_door_sensor_state(reading) self.sensor_state[sensor_num].dump_state() send_email = False if self.sensor_state[sensor_num].button_state == 0: logging.info('- new state LOW') if sensor_num == Common.SENSOR_CLOSED: send_email = True action = 'CLOSED' else: action = 'OPENED' self.notify_email('take a photo, door is Opened', 'need text', delay=3) else: logging.info('- new state HIGH') if sensor_num == Common.SENSOR_CLOSED: send_email = True action = 'opening' else: action = 'closing' text = '- last state change occured {} ago'.format( Nutil.get_time_delta(self.last_door_state_change)) logging.info(text) self.update_door_state_change_time() # Example: LED Test #self.led_status(reading) subject = 'G.Door is {} : {}'.format(action, special) logging.info('- Subject: {}'.format(subject)) if send_email: self.notify_email(subject, text) self.notify_mqtt(subject)
def getECG(self, numSeconds, sampleRate): print "Begin ECG measure" samplerate = sampleRate samplePeriod = (1 / samplerate) * 1000 starTime = wiringpi.millis() while wiringpi.millis() - starTime < numSeconds * 1000: Ecg = round((self.mcp.read_adc(1) * 3.3) / 1024, 3) self.ecgValues = np.append(self.ecgValues, Ecg) wiringpi.delay(int(samplePeriod))
def getSpo2(self,numSeconds, samplerate): print "begin measure" startTime = wiringpi.millis() Spo2 = Sp2.Spo2Sensor(sampleAvg= 8,sampleRate=samplerate) newSample = False AFthreshold= 17 Spo2.enableAfull() Spo2.setFIFOAF(AFthreshold) interrupt = Button(7) while wiringpi.millis()-startTime < numSeconds*1000: interrupt.when_activated = Spo2.sampleAvailable() if Spo2.newSample == True: Spo2.readSample() Spo2.newSample = False print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" print "Buffer IR: ", len(Spo2.buffer_ir) print "Buffer Red: ", len(Spo2.buffer_red) pro = pr.Processing() #get Red and Ir buffers self.IR = Spo2.buffer_ir self.Red = Spo2.buffer_red #Delay Signal to avoid start overshoot #self.Red = pro.delaySignal(self.Red) #self.IR = pro.delaySignal(self. IR) #Median filter to the signals self.IR = sp.medfilt(self.IR) self.Red = sp.medfilt(self.Red) #low pass filter at 60hz #self.IR = pro.NotchFilter(self.IR, 60,samplerate) #self.Red = pro.NotchFilter(self.Red, 60,samplerate) #lowpass filter at 6Hz: #self.IR = pro.lowPasFIRFilter(self.IR, 6,samplerate) #self.Red = pro.lowPasFIRFilter(self.Red, 6,samplerate) #Compute Spo2Value: self.Spo2Value = pro.calcSpO2(self.Red,self.IR) print "Spo2: ", Spo2Value, "%" #get AC componente to plot the signal: self.Red = pro.getACcomponent(self.Red) self.IR = pro.getACcomponent(self.IR) self.IR = pro.Normalize(self.IR)
def softReset(self): max102 = self.max102 wirp = wiry.millis() self.bitmask(self.MAX30102_MODECONFIG, self.MAX30102_RESET_MASK, self.MAX30102_RESET) #Poll for bit to clear, reset is then complete #time out after 100ms startTIme = wirp while wiry.millis() - startTIme < 100: response = max102.read_byte_data(self.MAX30102_ADDRESS, self.MAX30102_MODECONFIG) if (response & self.MAX30102_RESET) == 0: break wiry.delay(1) return True
def poll(self): self._now = wiringpi.millis() if self._running: passed = self._now - self._time if passed > self._period: self._time += self._period self._eventHandler()
def incline_sense_callback(): global last_change_at global incline_pulses incline_pulses += 1 current = wiringpi.millis() diff = current - last_change_at last_change_at = current print("Incline changing! Time: %d, diff: %d, pulse: %d" % (current, diff, incline_pulses))
def getSpo2read(self, numSeconds): print "begin SPO2 measure" startTime = wiringpi.millis() newSample = False interrupt = Button(7) while wiringpi.millis() - startTime < numSeconds * 1000: interrupt.when_activated = self.Spo2.sampleAvailable() if self.Spo2.newSample == True: self.Spo2.readSample() self.Spo2.newSample = False #print (wiringpi.millis()-startTime)/1000 print "Spo2 measure ready" pro = pr.Processing() #get Red and Ir buffers self.IR = self.Spo2.buffer_ir self.Red = self.Spo2.buffer_red # #Normalize Red and IR signals self.Red = pro.Normalize(self.Red) self.IR = pro.Normalize(self.IR) #Butterword 4th order bandpass filter .5-6Hz self.IR = pro.BPButterFilter(self.IR, 0.5, 4.0, self.samplerateSpo2, 4) self.Red = pro.BPButterFilter(self.Red, 0.5, 4.0, self.samplerateSpo2, 4) #fft filtered dignal self.IR_Filtered_FFT = spfft.fft(self.IR) self.Red_Filtered_FFT = spfft.fft(self.Red) #Mean filter widnow = 4 # self.IR = pro.movMean(self.IR,4) # self.Red = pro.movMean(self.Red,4) self.Red = sp.medfilt(self.Red, 3) * -1 self.IR = sp.medfilt(self.IR, 3) * -1 self.Spo2Value = pro.calcSpO2(self.Red, self.IR) print "Spo2: ", self.Spo2Value, "%" self.HR = pro.heartRateCalc(self.IR)
def read_ATR(serial): wiringpi.pinMode(TX, INPUT) wiringpi.pullUpDnControl(TX, PUD_UP) first = wiringpi.millis() data_str = '' while (wiringpi.millis() - first) < 100: if wiringpi.serialDataAvail(serial) > 0: first = wiringpi.millis() data = wiringpi.serialGetchar(serial) if (data < 16): data *= 16 data_str += ('{:02x}'.format(data)) + ' ' wiringpi.pullUpDnControl(TX, PUD_OFF) wiringpi.pinModeAlt(TX, 4) data_str = data_str.lstrip('00') return data_str
def read_response(serial, ser, length): wiringpi.pinMode(TX, INPUT) wiringpi.pullUpDnControl(TX, PUD_UP) first = wiringpi.millis() wiringpi.delay(50) ## Save all the data from RX excluding bounced data data_list = [] num_ser = wiringpi.serialDataAvail(serial) while (wiringpi.millis() - first) < 100: if wiringpi.serialDataAvail(serial) > 0: first = wiringpi.millis() data = wiringpi.serialGetchar(serial) if (wiringpi.serialDataAvail(serial) < (num_ser - length)): data_list.append('{:02x}'.format(data)) wiringpi.pullUpDnControl(TX, PUD_OFF) wiringpi.pinModeAlt(TX, 4) return data_list
def wait_for_incline_stop(): global last_change_at global incline_pulses done = False while not done: wiringpi.delay(250) current = wiringpi.millis(); diff = current - last_change_at print('Checking if we should stop at %d, diff %d' % (current, diff)) if diff > 1200: done = True print('Incline change stopped after %d pulses' % incline_pulses) incline_pulses = 0
def calibrate_incline(): global last_change_at print('Incline up...') wiringpi.digitalWrite(INCLINE_UP_PIN, 1) wait_for_incline_stop() print('Incline stop') wiringpi.digitalWrite(INCLINE_UP_PIN, 0) print('Incline down') wiringpi.digitalWrite(INCLINE_DOWN_PIN, 1) last_change_at = wiringpi.millis() wait_for_incline_stop() print('Incline stop') wiringpi.digitalWrite(INCLINE_DOWN_PIN, 0)
def setup(): global rs_morse_bit, rs_morse_char, space_in_progress, tone_in_progress if HAMSHIELD_RST: wiringpi.pinMode(RESET_PIN, wiringpi.OUTPUT) wiringpi.digitalWrite(RESET_PIN, wiringpi.LOW) print("type any character and press enter to begin...") while (not inputAvailable()): pass inputFlush() if HAMSHIELD_RST: # if you're using a standard HamShield (not a Mini) # you have to let it out of reset wiringpi.digitalWrite(RESET_PIN, wiringpi.HIGH) wiringpi.delay(5) # wait for device to come up print("beginning radio setup") # initialize device radio.initialize() # verify connection --- this does the part of "initialize serial communication" print("Testing device connections...") if (radio.testConnection()): print("HamShield connection successful") else: print("HamShield connection failed") print("setting Radio configuration") radio.setRfPower(0) # Set the morse code characteristics radio.setMorseFreq(MORSE_FREQ) radio.setMorseDotMillis(MORSE_DOT) radio.lookForTone(MORSE_FREQ) # Configure the HamShield to operate on 438.000MHz radio.frequency(438000) radio.setModeReceive() print("Radio configured") last_tone_check = wiringpi.millis() space_in_progress = 0 tone_in_progress = 0 rx_morse_bit = 1 bits_to_process = False radio.bypassPreDeEmph()
def loop(): global muted, currently_tx, rssi_timeout # handle CTCSS tone detection if not currently_tx: # check for CTCSS tone if radio.getCtcssToneDetected(): if muted: muted = False radio.setUnmute() print("tone") elif not muted: muted = True radio.setMute() print("no tone") # handle serial commands if inputAvailable(): if inputPeek() == 't' or inputPeek() == 'T': c = inputReadChar() if c == 't': radio.setModeReceive() currently_tx = False print('RX') elif c == 'T': radio.setModeTransmit() currently_tx = True print('TX') freq = inputParseInt() inputFlush() if freq != 0: radio.frequency(freq) print("set frequency: " + str(freq)) if (not currently_tx and (wiringpi.millis() - rssi_timeout) > RSSI_REPORT_RATE_MS): print(radio.readRSSI()) rssi_timeout = wiringpi.millis()
def loop(): global rssi_timeout, currently_tx if inputAvailable(): if inputPeek() == 't' or inputPeek() == 'T': c = inputReadChar() if c == 't': radio.setModeReceive() currently_tx = False print('RX') elif c == 'T': radio.setModeTransmit() currently_tx = True print('TX') freq = inputParseInt() inputFlush() if freq != 0: radio.frequency(freq) print("set frequency: " + str(freq)) if (not currently_tx and (wiringpi.millis() - rssi_timeout) > RSSI_REPORT_RATE_MS): print(radio.readRSSI()) rssi_timeout = wiringpi.millis()
def getMsTicks(): """ Get number of milliseconds """ return wiringpi.millis()
def loop(): timer = 0 cmdbuff = [None]*32 repeater = 0 ctcssin = 0 cdcssin = 0 cdcssout = 0 if inputAvailable(): text = inputReadChar() if state == 10: if text == 32: timer = wiringpi.millis() return elif state == 0: if text == 32: # space - transmit if repeater == 1: radio.frequency(tx) radio.setModeTransmit() state = 10 print("#TX, ON;") timer = wiringpi.millis() return elif text == 63: # ? - RSSI print(":") print(radio.readRSSI(), DEC) print(";") return elif text == 65: # A - CTCSS In getValue() ctcssin =float(cmdbuff) radio.setCtcss(ctcssin) return elif text == 66: # B - CTCSS Out return elif text == 67: # C - CTCSS Enable return elif text == 68: # D - CTCSS Enable return elif text == 70: # F - frequency getValue() freq = float(cmdbuff) if radio.frequency(freq): print("@") print(freq, DEC) print(";!;") else: print("X1;") return elif text == 'M': getValue() radio.setModeTransmit() wiringpi.delay(300) radio.morseOut(cmdbuff) state = 10 return elif text == 80: # P - power level getValue() temp = float(cmdbuff) radio.setRfPower(temp) return elif text == 82: # R - repeater offset mode getValue() temp = float(cmdbuff) if temp == 0: repeater = 0 if temp == 1: repeater = 1 return elif state == 83: # S - squelch getValue() temp = float(cmdbuff) radio.setSQLoThresh(temp) return elif state == 84: # T - transmit offset getValue() tx = float(cmdbuff) return elif state == 94: # ^ - VSSI (voice) level print(":") print(radio.readVSSI(), DEC) print(";") else: return if state == 10: if wiringpi.millis() > (timer + 500): print("#TX,OFF;") radio.setModeReceive() if repeater == 1: radio.frequency(freq) state = 0 txcount = 0
def millis(): return wiringpi.millis()
print("set frequency: " + str(freq)) """ if inputAvailable(): if inputPeek() == 'r': c = inputReadChar() wiringpi.delay(1000) radio.initialize() else: freq = inputParseInt() inputFlush() if freq != 0: radio.frequency(freq) print("set frequency: " + str(freq)) """ if (not currently_tx and (wiringpi.millis() - rssi_timeout) > RSSI_REPORT_RATE_MS): print(radio.readRSSI()) rssi_timeout = wiringpi.millis() ######################################### # main and safeExit def safeExit(signum, frame): radio.setModeReceive() wiringpi.delay(25) sys.exit(1)
def loop(): # are we receiving anything rx_msg = [] if radio.toneDetected(): space_in_progress = 0 if tone_in_progress == 0: # start a new tone tone_in_progress = wiringpi.millis() # print('t') else: # keep track of how long the silence is if space_in_progress == 0: space_in_progress = wiringpi.millis() # we wait for a bit of silence before ending the last # symbol in order to smooth out the detector if (wiringpi.millis() - space_in_progress) > SYMBOL_END_TIME: if tone_in_progress != 0: # end the last tone tone_time = wiringpi.millis() - tone_in_progress tone_in_progress = 0 handleTone(tone_time) # we might be done with a character if the space is long enough if ((wiringpi.millis() - space_in_progress) > CHAR_END_TIME) and bits_to_process: m = parseMorse() bits_to_process = False if m != 0: rx_msg.append(m) # we might be done with a message if the space is long enough if (wiringpi.millis() - space_in_progress) > MESSAGE_END_TIME: if len(rx_msg) > 0: # we got a message, print it now rx_msg.append(None) # null terminate print(''.join(rx_msg)) rx_msg = [] rx_morse_char = 0 rx_morse_bit = 1 # should we send anything if inputAvailable(): print("checking channel") # We'll wait up to 30 seconds for a clear channel, # requiring that the channel is clear for 2 seconds before we transmit if radio.waitForChannel(30000, 2000, -5): # If we get here, the channel is clear. # Start transmitting by putting the radio into transmit mode. radio.setModeTransmit() MORSE_BUF_SIZE = 128 morse_buf = [' '] # start with space to let PA come up while inputAvailable() and len(morse_buf) < MORSE_BUF_SIZE: morse_buf.append(inputReadChar()) morse_buf.append(None) # Send a message out in morse code radio.morseOut(''.join(morse_buf)) # We're done sending the message, set the radio back into recieve mode. radio.setModeReceive() radio.lookForTone(MORSE_FREQ) print("sent") else: # If we get here, the channel is busy. Let's also print out the RSSI. print("The channel was busy. RSSI: ") print(radio.readRSSI())