def _nibble(self, nibble): for i in range(6): if nibble & (1<<i): self.wf.append(pigpio.pulse(self.txbit, 0, self.mics)) else: self.wf.append(pigpio.pulse(0, self.txbit, self.mics))
def fill_wave(pulses_buffer, direction): for i in range(0, 4): pulses_buffer.append(pigpio.pulse(1<<GPIO, 0, 1500)) pulses_buffer.append(pigpio.pulse(0, 1<<GPIO, 500)) for i in range(0, signals[direction]): pulses_buffer.append(pigpio.pulse(1<<GPIO, 0, 500)) pulses_buffer.append(pigpio.pulse(0, 1<<GPIO, 500))
def update_waves(self): self.logger.debug("Updating channels {}".format(' '.join(str(s) for s in self.widths))) # calculate the next wave to be added wf =[] micros = 0 for i in self.widths: wf.append(pigpio.pulse(0, 1<<self.gpio, self.gap_us)) wf.append(pigpio.pulse(1<<self.gpio, 0, i)) micros += (i+self.gap_us) # off for the remaining frame period wf.append(pigpio.pulse(0, 1<<self.gpio, self.frame_us-micros)) # add it to our 2 element list try: self.pi.wave_add_generic(wf) wid = self.pi.wave_create() except: return # if there's already a wave in the list, pop it off, we only want max 1 wave in the list if len(self.waves) > 0: try: self.pi.wave_delete(self.waves[0]) self.waves.pop() except: pass self.waves.append(wid)
def transmit_string(pi, gpio, str): pi.wave_clear() # start a new waveform wf=[] for C in str: c=C.lower() print(c) if c in morse: k = morse[c] for x in k: if x == '.': wf.append(pigpio.pulse(1<<gpio, NONE, DOT * MICROS)) else: wf.append(pigpio.pulse(1<<gpio, NONE, DASH * MICROS)) wf.append(pigpio.pulse(NONE, 1<<gpio, GAP * MICROS)) wf.append(pigpio.pulse(NONE, 1<<gpio, LETTER_GAP * MICROS)) elif c == ' ': wf.append(pigpio.pulse(NONE, 1<<gpio, WORD_GAP * MICROS)) pi.wave_add_generic(wf) pi.wave_tx_start()
def do_wave(): square = [] # ON OFF MICROS\ to_on = 1 << step_out1 | 1 << step_out2 square.append(pigpio.pulse(to_on, 0, 10000)) square.append(pigpio.pulse(0, to_on , 10000)) pi.wave_add_generic(square) wid = pi.wave_create() try: if wid >= 0: pi.wave_send_repeat(wid) time.sleep(4) GPIO.output(dir_out, 1) time.sleep(60) pi.wave_tx_stop() pi.wave_delete(wid) except: pass pi.wave_tx_stop() pi.stop()
def ts_2_actuacion(self , tus): self.pi.wave_clear() self.pi.wave_add_generic([ pigpio.pulse(0,1<<self.gpio,tus), pigpio.pulse(1<<self.gpio,0,tus),]) wid = self.pi.wave_create() self.pi.wave_send_repeat(wid)
def start_pit(self, pit_type, gpio): self.logger.debug('Starte Pit ' + pit_type + ' auf GPIO' + str(gpio)) if pit_type == 'fan_pwm': # 25kHz PC-Lüfter self.pi.set_mode(gpio, pigpio.OUTPUT) fan_pwm_pulses = [] fan_pwm_pulses.append(pigpio.pulse(1<<gpio,0,1)) fan_pwm_pulses.append(pigpio.pulse(0,1<<gpio,46)) self.pi.wave_clear() self.pi.wave_add_generic(fan_pwm_pulses) self.fan_pwm = self.pi.wave_create() self.pi.wave_send_repeat(self.fan_pwm) self.pit_gpio = gpio self.pit_type = pit_type elif pit_type == 'fan': # Lüftersteuerung v3 self.pi.set_mode(gpio, pigpio.OUTPUT) self.pi.set_PWM_frequency(gpio, 500) if not self.pit_inverted: self.pi.set_PWM_dutycycle(gpio, self.pit_min * 2.55) else: self.pi.set_PWM_dutycycle(gpio, self.pit_max * 2.55) self.pit_gpio = gpio self.pit_type = pit_type elif pit_type == 'servo': # Servosteuerung (oder Lüfter über Fahrtenregler) self.pi.set_mode(gpio, pigpio.OUTPUT) if not self.pit_inverted: self.pi.set_servo_pulsewidth(gpio, self.pit_min) else: self.pi.set_servo_pulsewidth(gpio, self.pit_max) self.pit_gpio = gpio self.pit_type = pit_type elif pit_type == 'io_pwm': # PWM-modulierter Schaltausgang (Schwingungspaketsteuerung) self.pi.set_mode(gpio, pigpio.OUTPUT) self.pit_io_pwm_end.clear() self.pit_io_pwm_thread = threading.Thread(target=self.io_pwm, args=(gpio,)) self.pit_io_pwm_thread.daemon = True # Startwerte mitgeben (nicht 0/0 wg. CPU-Last) if not self.pit_inverted: self.pit_io_pwm_on = 1 self.pit_io_pwm_off = 1 else: self.pit_io_pwm_on = 1 self.pit_io_pwm_off = 1 self.pit_io_pwm_thread.start() self.pit_gpio = gpio self.pit_type = pit_type elif pit_type == 'io': self.pi.set_mode(gpio, pigpio.OUTPUT) # Schaltausgang if not self.pit_inverted: self.pi.write(gpio, 0) else: self.pi.write(gpio, 1) self.pit_gpio = gpio self.pit_type = pit_type
def _make_waveform(self, waveform): wf = [] # Bit mask for GPIO pin number pin = 1<<self._pin # Convert to waveformat required by pigpio for val, t in waveform: if val: wf.append(pigpio.pulse(pin, 0, t)) else: wf.append(pigpio.pulse(0, pin, t)) return wf
def put(self, data, repeat=1): """ Transmit a message repeat times 0 is returned if message transmission has successfully started. Negative number indicates an error. """ ret = 0 if len(data) <> MESSAGE_BYTES: ret = -1 else: self.cancel() self.txBusy = True #Set TX high and wait to get agc of RX trained self.pi.write(self.txgpio, 1) time.sleep(TX_GAP / 1000000) #Define a single message waveform self.wf = [] # Pre Message low gap self.wf.append(pigpio.pulse(0, self.txbit, TX_GAP)) # Message start pulse self.wf.append(pigpio.pulse(self.txbit, 0, TX_HIGH)) self.wf.append(pigpio.pulse(0, self.txbit, TX_HIGH)) for i in data: # Byte start pulse self.wf.append(pigpio.pulse(self.txbit, 0, TX_HIGH)) self.wf.append(pigpio.pulse(0, self.txbit, TX_HIGH)) self.byte = _SYMBOL[i & 0x0F] for j in range(8): if self.byte & (0x80>>j): self.wf.append(pigpio.pulse(self.txbit, 0, TX_HIGH)) self.wf.append(pigpio.pulse(0, self.txbit, TX_HIGH)) else: self.wf.append(pigpio.pulse(0, 0, TX_LOW)) # Message end pulse self.wf.append(pigpio.pulse(self.txbit, 0, TX_HIGH)) self.wf.append(pigpio.pulse(0, self.txbit, TX_HIGH)) self.pi.wave_add_generic(self.wf) self.wave_id = self.pi.wave_create() if self.wave_id >= 0: for r in range(repeat): self.pi.wave_send_once(self.wave_id) while self.pi.wave_tx_busy(): # wait for waveform to be sent time.sleep(0.001) else: ret = -2 self.txBusy = False return ret
def put(self, data): """ Transmit a message. If the message is more than MAX_MESSAGE_BYTES in size it is discarded. If a message is currently being transmitted it is aborted and replaced with the new message. True is returned if message transmission has successfully started. False indicates an error. """ if len(data) > MAX_MESSAGE_BYTES: return False self.wf = [] self.wf.append(pigpio.pulse(self.txbit, 0, 500)) self.wf.append(pigpio.pulse(0, self.txbit, 100)) self.cancel() for i in _HEADER: self._nibble(i) crc = self._byte(0xFFFF, len(data)+_CTL) for i in data: if type(i) == type(""): v = ord(i) else: v = i crc = self._byte(crc, v) crc = ~crc self._byte(0, crc&0xFF) self._byte(0, crc>>8) self.wf.append(pigpio.pulse(0, self.txbit, self.mics)) self.pi.wave_add_generic(self.wf) self.wave_id = self.pi.wave_create() if self.wave_id >= 0: self.pi.wave_send_once(self.wave_id) return True else: return False
def add_to_code(self, on_micros, off_micros): on = (on_micros + self.on_mics) / self.micros if (on*2) + 1 + len(self.wf) > 680: pulses = self.pi.wave_add_generic(self.wf) self.offset = self.pi.wave_get_micros() self.wf = [pigpio.pulse(0, 0, self.offset)] for x in range(on): self.wf.append(pigpio.pulse(1<<self.gpio, 0, self.on_mics)) self.wf.append(pigpio.pulse(0, 1<<self.gpio, self.off_mics)) self.wf.append(pigpio.pulse(0, 0, off_micros))
def wave_mnch(DATA, PIN): pi.set_mode(PIN, pigpio.OUTPUT) # set GPIO pin to output. # create msg # syntax: pigpio.pulse(gpio_on, gpio_off, delay us) msg = [] for i in bin(DATA)[2:]: # this is a terrible way to iterate over bits... but it works. if i=='1': msg.append(pigpio.pulse(0,1<<PIN,RC5_PER)) # L msg.append(pigpio.pulse(1<<PIN,0,RC5_PER)) # H else: msg.append(pigpio.pulse(1<<PIN,0,RC5_PER)) # H msg.append(pigpio.pulse(0,1<<PIN,RC5_PER)) # L msg.append(pigpio.pulse(0,1<<PIN,RC5_PER)) # return line to idle condition. pi.wave_add_generic(msg) wid = pi.wave_create() return wid
def add_to_code(self, on, off): # is there room for more pulses? if (on*2) + 1 + len(self.wf) > 680: # 682 is maximum pulses = self.pi.wave_add_generic(self.wf) print("waveform partial {} pulses".format(pulses)) self.offset = self.pi.wave_get_micros() # continue pulses from offset self.wf = [pigpio.pulse(0, 0, self.offset)] # add on cycles of carrier for x in range(on): self.wf.append(pigpio.pulse(1<<self.gpio, 0, self.on_mics)) self.wf.append(pigpio.pulse(0, 1<<self.gpio, self.off_mics)) # add off cycles of no carrier self.wf.append(pigpio.pulse(0, 0, off * self.micros))
def convertToTwoBinary(number): if number == 0: serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) elif number == 1: serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65))
def ppm_update(data): trame = [] transit =0; result = OK # ON OFF DELAY trame.append(pigpio.pulse(1<<P2,1<<P1,500)) # niveau bas de start current_lenght = 500; for i in range(NBR_CHANNEL): if data[i] <= MAX_IN and data[i] >= MIN_IN: transit=int(round((A*(data[i])+B))) trame.append(pigpio.pulse(1<<P1,1<<P2,transit)) current_lenght+=transit else: transit=int(round((A*(DEFAULT_DATA[i])+B))) trame.append(pigpio.pulse(1<<P1,1<<P2,transit)) current_lenght+=transit result = i # memorise quelle channel a leve l'erreur trame.append(pigpio.pulse(1<<P2,1<<P1,500))# niveau bas entre 2 channel current_lenght+=500; # fin boucle trame.append(pigpio.pulse(1<<P1,1<<P2,(TOTAL_LENGHT-current_lenght))) # delai final #print TOTAL_LENGHT-current_lenght # trame terminee pi.wave_clear() # on lance le nouveau signal PPM en etant sur de pas avoir coupe le precedent pi.wave_add_generic(trame) id_trame=pi.wave_create() if(id_trame >= 0): pi.wave_send_using_mode(id_trame, pigpio.WAVE_MODE_REPEAT_SYNC) print "PPM signal updated" else: result = WAVE_ERROR return result
def avance(self , tus , ): if not tus: self.parar() else : if tus< 0: direccion = 1 else: direccion = 0 self.pi.write(self.pin_direccion , direccion) tus = abs(int(tus)) self.pi.wave_add_generic([ pigpio.pulse(0,1<<self.pin_pulse,abs(tus)), pigpio.pulse(1<<self.pin_pulse,0,abs(tus)),]) wid = self.pi.wave_create() if self.wid_vieja is not None: self.pi.wave_send_using_mode(wid , pigpio.WAVE_MODE_REPEAT_SYNC) while self.pi.wave_tx_at() !=wid: pass self.pi.wave_delete(self.wid_vieja) else : self.pi.wave_send_repeat(wid) self.wid_vieja = wid
def play_tone(self): """ This method will play a tone using a wave. :return: None """ # clear out any residual problem strings self.last_problem = "5-0\n" pin = self.validate_pin() if pin == 99: self.last_problem = "5-1\n" return # get pin information pin_state = self.pins[pin] if pin_state["mode"] != pigpio.OUTPUT: self.last_problem = "5-2\n" return frequency = int((1000 / int(self.payload["frequency"])) * 1000) duration = int(self.payload["duration"]) tone = [pigpio.pulse(1 << pin, 0, frequency), pigpio.pulse(0, 1 << pin, frequency)] # flash every 100 ms self.pi.wave_clear() self.pi.wave_add_generic(tone) # 100 ms flashes tone_wave = self.pi.wave_create() # create and save id self.pi.wave_send_repeat(tone_wave) if duration == 0: return sleep_time = duration * 0.001 time.sleep(sleep_time) self.pi.wave_tx_stop() # stop waveform self.pi.wave_clear() # clear all waveforms
def set_status_LED_color(self, color1, color2, blink_rate): blink_flash = [] if blink_rate =="FAST": blink_ms = 100000 elif blink_rate == "SLOW": blink_ms = 500000 else: blink_ms = 1000000 color2 = color1 blink_rate = "OFF" step1_on_pins = self._status_LED_colors[color1] step1_off_pins = self._status_LED_colors[color1] ^ self._status_LED_colors["WHITE"] step2_on_pins = self._status_LED_colors[color2] step2_off_pins = self._status_LED_colors[color2] ^ self._status_LED_colors["WHITE"] blink_flash.append(pigpio.pulse(step1_on_pins,step1_off_pins,blink_ms)) blink_flash.append(pigpio.pulse(step2_on_pins,step2_off_pins,blink_ms)) self._pi.wave_add_generic(blink_flash) self._status_LED_wave = self._pi.wave_create() self._pi.wave_send_repeat(self._status_LED_wave) self._status_LED_state = [ color1, color2, blink_rate]
def _make_waves(self): wf = [pigpio.pulse(1 << self.gpio, 0, self.t_0), pigpio.pulse(0, 1 << self.gpio, self.gap)] self.pi.wave_add_generic(wf) self._amble = self.pi.wave_create() wf = [pigpio.pulse(1 << self.gpio, 0, self.t_0), pigpio.pulse(0, 1 << self.gpio, self.t_1)] self.pi.wave_add_generic(wf) self._wid0 = self.pi.wave_create() wf = [pigpio.pulse(1 << self.gpio, 0, self.t_1), pigpio.pulse(0, 1 << self.gpio, self.t_0)] self.pi.wave_add_generic(wf) self._wid1 = self.pi.wave_create()
def waveChunk(self,freq,steps,dir): t=500000/freq #time in micros lasting=steps*2*t print lasting wave=[] for i in range(steps): wave.append(pigpio.pulse(0, 1<<self.STEP_PIN, t)) wave.append(pigpio.pulse(1<<self.STEP_PIN, 0, t)) self.waveChunks.append(wave) dirwave=[] if dir>0: dirwave.append(pigpio.pulse(0,1<<self.DIR_PIN,t/2)) dirwave.append(pigpio.pulse(1<<self.DIR_PIN,0,lasting-t/2)) else: dirwave.append(pigpio.pulse(0,1<<self.DIR_PIN,t/2)) dirwave.append(pigpio.pulse(0,1<<self.DIR_PIN,lasting-t/2)) self.waveChunks.append(dirwave) print len(self.waveChunks)
def _make_waves(self): """ Generates the basic waveforms needed to transmit codes. """ wf = [] wf.append(pigpio.pulse(1 << self.gpio, 0, self.t0)) wf.append(pigpio.pulse(0, 1 << self.gpio, self.gap)) self.pi.wave_add_generic(wf) self._amble = self.pi.wave_create() wf = [] wf.append(pigpio.pulse(1 << self.gpio, 0, self.t0)) wf.append(pigpio.pulse(0, 1 << self.gpio, self.t1)) self.pi.wave_add_generic(wf) self._wid0 = self.pi.wave_create() wf = [] wf.append(pigpio.pulse(1 << self.gpio, 0, self.t1)) wf.append(pigpio.pulse(0, 1 << self.gpio, self.t0)) self.pi.wave_add_generic(wf) self._wid1 = self.pi.wave_create()
def moveSteppers(self, ramp1, ramp2): l1 = len(ramp1) wid1 = [-1] * l1 l2 = len(ramp2) wid2 = [-1] * l2 self.pi.set_mode(stepperPins[0], pigpio.OUTPUT) self.pi.set_mode(stepperPins[1], pigpio.OUTPUT) #generating a wave for frequency for ramp1 for i in range(l1): f1 = ramp1[i][0] micros = int(500000 / f1) #creates waveform array for each frequency wf = [] wf.append(pigpio.pulse(1 << stepperPins[0], 0, micros)) wf.append(pigpio.pulse(0, 1 << stepperPins[0], micros)) #adds wave component to waveform self.pi.wave_add_generic(wf) wid1[i] = self.pi.wave_create() for i in range(l2): f2 = ramp2[i][0] micros = int(500000 / f2) #creates waveform array for each frequency wf = [] wf.append(pigpio.pulse(1 << stepperPins[1], 0, micros)) wf.append(pigpio.pulse(0, 1 << stepperPins[1], micros)) #adds wave component to waveform self.pi.wave_add_generic(wf) wid2[i] = self.pi.wave_create() chain1 = [] #Creates a chain for each ramp wave for i in range(l1): steps = ramp1[i][1] x = steps & 255 y = steps >> 8 chain1 += [255, 0, wid1[i], 255, 1, x, y] print(chain1) chain2 = [] for i in range(l2): steps = ramp2[i][1] x = steps & 255 y = steps >> 8 chain2 += [255, 0, wid2[i], 255, 1, x, y] print(chain2) self.pi.wave_chain(chain1) while self.pi.wave_tx_busy(): time.sleep(0.1) self.pi.wave_chain(chain2) while self.pi.wave_tx_busy(): time.sleep(0.1) for i in range(l1): self.pi.wave_delete(wid1[i]) for i in range(l2): self.pi.wave_delete(wid2[i])
def add_wave(self, hi, lo): self.pi.wave_add_generic([pigpio.pulse(1<<self.pin, 0, hi * CYCLE), pigpio.pulse(0, 1<<self.pin, lo * CYCLE)]) return self.pi.wave_create()
if arg in records: code = records[arg] # Create wave marks_wid = {} spaces_wid = {} wave = [0]*len(code) for i in range(0, len(code)): ci = code[i] if i & 1: # Space if ci not in spaces_wid: pi.wave_add_generic([pigpio.pulse(0, 0, ci)]) spaces_wid[ci] = pi.wave_create() wave[i] = spaces_wid[ci] else: # Mark if ci not in marks_wid: wf = carrier(GPIO, FREQ, ci) pi.wave_add_generic(wf) marks_wid[ci] = pi.wave_create() wave[i] = marks_wid[ci] delay = emit_time - time.time() if delay > 0.0: time.sleep(delay) pi.wave_chain(wave)
pi.set_mode(GPIO_pin, pigpio.OUTPUT) pi = pigpio.pi() # connect to local Pi freq = 30000 # Hz period = 1.0 / freq * 10**6 print "period: %f" % period #ramp_time = 5 # sec #start_date = time.time() # final wave square = [] square.append(pigpio.pulse(1 << GPIO_pin, 0, period / 2.0)) square.append(pigpio.pulse(0, 1 << GPIO_pin, period / 2.0)) pi.wave_clear() pi.wave_add_generic(square) wid0 = pi.wave_create() square = [] steps = 200 for i in range(steps): #print "i : ", i # ON OFF MICROS square.append( pigpio.pulse(1 << GPIO_pin, 0, period / 2.0 * (steps / (i + 1.0))))
def generateW(): wave=[] for i in range(steps): wave.append(pigpio.pulse(0, 1<<STEP_PIN, t)) wave.append(pigpio.pulse(1<<STEP_PIN, 0, t)) pi.wave_add_generic(wave)
import time import pigpio WAVES = 20 GPIO = 2 wid = [0] * WAVES pi = pigpio.pi() # Connect to local Pi. pi.set_mode(GPIO, pigpio.OUTPUT) for i in range(WAVES): pi.wave_add_generic([ pigpio.pulse(1 << GPIO, 0, 20), pigpio.pulse(0, 1 << GPIO, (i + 1) * 200) ]) wid[i] = pi.wave_create() '''pi.wave_chain([ wid[4], wid[3], wid[2], # transmit waves 4+3+2 255, 0, # loop start wid[0], wid[0], wid[0], # transmit waves 0+0+0 255, 0, # loop start wid[0], wid[1], # transmit waves 0+1 255, 2, 0x88, 0x13, # delay 5000us 255, 1, 30, 0, # loop end (repeat 30 times) 255, 0, # loop start wid[2], wid[3], wid[0], # transmit waves 2+3+0 wid[3], wid[1], wid[2], # transmit waves 3+1+2
def playback(gpioNum, file, irCode): pi = pigpio.pi() # Connect to Pi. if not pi.connected: exit(0) try: f = open(file, "r") except: print("Can't open: {}".format(file)) exit(0) records = json.load(f) f.close() pi.set_mode(gpioNum, pigpio.OUTPUT) # IR TX connected to this GPIO. pi.wave_add_new() emit_time = time.time() if irCode in records: code = records[irCode] # Create wave marks_wid = {} spaces_wid = {} wave = [0] * len(code) for i in range(0, len(code)): ci = code[i] if i & 1: # Space if ci not in spaces_wid: pi.wave_add_generic([pigpio.pulse(0, 0, ci)]) spaces_wid[ci] = pi.wave_create() wave[i] = spaces_wid[ci] else: # Mark if ci not in marks_wid: wf = carrier(gpioNum, FREQ, ci) pi.wave_add_generic(wf) marks_wid[ci] = pi.wave_create() wave[i] = marks_wid[ci] delay = emit_time - time.time() if delay > 0.0: time.sleep(delay) pi.wave_chain(wave) while pi.wave_tx_busy(): time.sleep(0.002) emit_time = time.time() + GAP_S for i in marks_wid: pi.wave_delete(marks_wid[i]) marks_wid = {} for i in spaces_wid: pi.wave_delete(spaces_wid[i]) spaces_wid = {} else: print("Id {} not found".format(irCode)) pi.stop() # Disconnect from Pi.
def td(): print("Wavechains & filter tests.") tdcb = pi.callback(GPIO) pi.set_mode(GPIO, pigpio.OUTPUT) pi.write(GPIO, pigpio.LOW) e = pi.wave_clear() CHECK(13, 1, e, 0, 0, "callback, set mode, wave clear") wf = [] wf.append(pigpio.pulse(1<<GPIO, 0, 50)) wf.append(pigpio.pulse(0, 1<<GPIO, 70)) wf.append(pigpio.pulse(1<<GPIO, 0, 130)) wf.append(pigpio.pulse(0, 1<<GPIO, 150)) wf.append(pigpio.pulse(1<<GPIO, 0, 90)) wf.append(pigpio.pulse(0, 1<<GPIO, 110)) e = pi.wave_add_generic(wf) CHECK(13, 2, e, 6, 0, "pulse, wave add generic") wid = pi.wave_create() chain = [ 255, 0, wid, 255, 1, 128, 0, 255, 2, 0, 8, 255, 0, wid, 255, 1, 0, 1, 255, 2, 0, 4, 255, 0, wid, 255, 1, 0, 2] e = pi.set_glitch_filter(GPIO, 0) CHECK(13, 3, e, 0, 0, "clear glitch filter") e = pi.set_noise_filter(GPIO, 0, 0) CHECK(13, 4, e, 0, 0, "clear noise filter") tdcb.reset_tally() e = pi.wave_chain(chain) CHECK(13, 5, e, 0, 0, "wave chain") while pi.wave_tx_busy(): time.sleep(0.1) time.sleep(0.3) tally = tdcb.tally() CHECK(13, 6, tally, 2688, 2, "wave chain, tally") pi.set_glitch_filter(GPIO, 80) tdcb.reset_tally() pi.wave_chain(chain) while pi.wave_tx_busy(): time.sleep(0.1) time.sleep(0.3) tally = tdcb.tally() CHECK(13, 7, tally, 1792, 2, "glitch filter, wave chain, tally") pi.set_glitch_filter(GPIO, 120) tdcb.reset_tally() pi.wave_chain(chain) while pi.wave_tx_busy(): time.sleep(0.1) time.sleep(0.2) tally = tdcb.tally() CHECK(13, 8, tally, 896, 2, "glitch filter, wave chain, tally") pi.set_glitch_filter(GPIO, 140) tdcb.reset_tally() pi.wave_chain(chain) while pi.wave_tx_busy(): time.sleep(0.1) time.sleep(0.2) tally = tdcb.tally() CHECK(13, 9, tally, 0, 0, "glitch filter, wave chain, tally") pi.set_glitch_filter(GPIO, 0) pi.wave_chain(chain) pi.set_noise_filter(GPIO, 1000, 150000) tdcb.reset_tally() while pi.wave_tx_busy(): time.sleep(0.1) time.sleep(0.2) tally = tdcb.tally() CHECK(13, 10, tally, 1500, 2, "noise filter, wave chain, tally") pi.wave_chain(chain) pi.set_noise_filter(GPIO, 2000, 150000) tdcb.reset_tally() while pi.wave_tx_busy(): time.sleep(0.1) time.sleep(0.2) tally = tdcb.tally() CHECK(13, 11, tally, 750, 2, "noise filter, wave chain, tally") pi.wave_chain(chain) pi.set_noise_filter(GPIO, 3000, 5000) tdcb.reset_tally() while pi.wave_tx_busy(): time.sleep(0.1) time.sleep(0.2) tally = tdcb.tally() CHECK(13, 12, tally, 0, 2, "noise filter, wave chain, tally") pi.set_noise_filter(GPIO, 0, 0) e = pi.wave_delete(wid) CHECK(13, 13, e, 0, 0, "wave delete") tdcb.cancel()
def t5(): global t5_count BAUD=4800 TEXT=""" Now is the winter of our discontent Made glorious summer by this sun of York; And all the clouds that lour'd upon our house In the deep bosom of the ocean buried. Now are our brows bound with victorious wreaths; Our bruised arms hung up for monuments; Our stern alarums changed to merry meetings, Our dreadful marches to delightful measures. Grim-visaged war hath smooth'd his wrinkled front; And now, instead of mounting barded steeds To fright the souls of fearful adversaries, He capers nimbly in a lady's chamber To the lascivious pleasing of a lute. """ print("Waveforms & bit bang serial read/write tests.") t5cb = pi.callback(GPIO, pigpio.FALLING_EDGE, t5cbf) pi.set_mode(GPIO, pigpio.OUTPUT) e = pi.wave_clear() CHECK(5, 1, e, 0, 0, "callback, set mode, wave clear") wf = [] wf.append(pigpio.pulse(1<<GPIO, 0, 10000)) wf.append(pigpio.pulse(0, 1<<GPIO, 30000)) wf.append(pigpio.pulse(1<<GPIO, 0, 60000)) wf.append(pigpio.pulse(0, 1<<GPIO, 100000)) e = pi.wave_add_generic(wf) CHECK(5, 2, e, 4, 0, "pulse, wave add generic") wid = pi.wave_create() e = pi.wave_send_repeat(wid) if e < 14: CHECK(5, 3, e, 9, 0, "wave send repeat") else: CHECK(5, 3, e, 19, 0, "wave send repeat") oc = t5_count time.sleep(5) c = t5_count - oc CHECK(5, 4, c, 50, 1, "callback") e = pi.wave_tx_stop() CHECK(5, 5, e, 0, 0, "wave tx stop") e = pi.bb_serial_read_open(GPIO, BAUD) CHECK(5, 6, e, 0, 0, "serial read open") pi.wave_clear() e = pi.wave_add_serial(GPIO, BAUD, TEXT, 5000000) CHECK(5, 7, e, 3405, 0, "wave clear, wave add serial") wid = pi.wave_create() e = pi.wave_send_once(wid) if e < 6964: CHECK(5, 8, e, 6811, 0, "wave send once") else: CHECK(5, 8, e, 7116, 0, "wave send once") oc = t5_count time.sleep(3) c = t5_count - oc CHECK(5, 9, c, 0, 0, "callback") oc = t5_count while pi.wave_tx_busy(): time.sleep(0.2) time.sleep(0.2) c = t5_count - oc CHECK(5, 10, c, 1702, 0, "wave tx busy, callback") c, text = pi.bb_serial_read(GPIO) CHECK(5, 11, STRCMP(text, TEXT), True, 0, "wave tx busy, serial read"); e = pi.bb_serial_read_close(GPIO) CHECK(5, 12, e, 0, 0, "serial read close") c = pi.wave_get_micros() CHECK(5, 13, c, 6158148, 0, "wave get micros") CHECK(5, 14, 0, 0, 0, "NOT APPLICABLE") c = pi.wave_get_max_micros() CHECK(5, 15, c, 1800000000, 0, "wave get max micros") c = pi.wave_get_pulses() CHECK(5, 16, c, 3405, 0, "wave get pulses") CHECK(5, 17, 0, 0, 0, "NOT APPLICABLE") c = pi.wave_get_max_pulses() CHECK(5, 18, c, 12000, 0, "wave get max pulses") c = pi.wave_get_cbs() if c < 6963: CHECK(5, 19, c, 6810, 0, "wave get cbs") else: CHECK(5, 19, c, 7115, 0, "wave get cbs") CHECK(5, 20, 0, 0, 0, "NOT APPLICABLE") c = pi.wave_get_max_cbs() CHECK(5, 21, c, 25016, 0, "wave get max cbs") e = pi.wave_clear() CHECK(5, 22, e, 0, 0, "wave clear") e = pi.wave_add_generic(wf) CHECK(5, 23, e, 4, 0, "pulse, wave add generic") w1 = pi.wave_create() CHECK(5, 24, w1, 0, 0, "wave create") e = pi.wave_send_repeat(w1) if e < 14: CHECK(5, 25, e, 9, 0, "wave send repeat") else: CHECK(5, 25, e, 19, 0, "wave send repeat") oc = t5_count time.sleep(5) c = t5_count - oc CHECK(5, 26, c, 50, 1, "callback") e = pi.wave_tx_stop() CHECK(5, 27, e, 0, 0, "wave tx stop") e = pi.wave_add_serial(GPIO, BAUD, TEXT, 5000000) CHECK(5, 28, e, 3405, 0, "wave add serial") w2 = pi.wave_create() CHECK(5, 29, w2, 1, 0, "wave create") e = pi.wave_send_once(w2) if e < 6964: CHECK(5, 30, e, 6811, 0, "wave send once") else: CHECK(5, 30, e, 7116, 0, "wave send once") oc = t5_count time.sleep(3) c = t5_count - oc CHECK(5, 31, c, 0, 0, "callback") oc = t5_count while pi.wave_tx_busy(): time.sleep(0.2) time.sleep(0.2) c = t5_count - oc CHECK(5, 32, c, 1702, 0, "wave tx busy, callback") e = pi.wave_delete(0) CHECK(5, 33, e, 0, 0, "wave delete") t5cb.cancel()
def runSteps(self, pulseList, deltaX, deltaY, deltaZ, isProgram, controlClass): self.controlClass = controlClass self.deltaX = deltaX self.deltaY = deltaY self.deltaZ = deltaZ self.isProgram = isProgram self.totalPulses = len(pulseList) pulse_list = [] executions = 0 self.pulseCount = 0 pulses = 0 timeStart = self.pi.get_current_tick() for i, entry in enumerate(pulseList[:-1]): if entry[2] == 1: pulse_list.append( pigpio.pulse(1 << entry[1], 0, int(pulseList[i + 1][0] - entry[0]))) else: pulse_list.append( pigpio.pulse(0, 1 << entry[1], int(pulseList[i + 1][0] - entry[0]))) if i % 1000 == 0 and i > 0: #submit waveform in junks of 1000 pulses pulses += 1000 self.pi.wave_add_generic(pulse_list) pulse_list = [] pulse_list.append(pigpio.pulse(0, 0, self.pi.wave_get_micros())) if i % 11000 == 0 and i > 0: #submit waveform in junks of 11000 pulses #wait for last wave to finish if self.wave is not None: if self.waitForWaveToFinish(timeStart, executions - 1, 11000) == False: return False #increase execustions counter and reset pulses counter executions += 1 pulses = 0 if self.wave is not None: self.pi.wave_delete(self.wave) #create and submit new wave form self.pi.wave_add_generic(pulse_list) self.wave = self.pi.wave_create() #get wavelength and execute wave self.waveLength = self.pi.wave_get_micros() self.pi.wave_send_once(self.wave) timeStart = self.pi.get_current_tick() pulse_list = [] #reset pulselist #adds the last doubled zero step with zero length pulse_list.append(pigpio.pulse(0, 1 << pulseList[-1][1], 0)) if self.wave is not None: if self.waitForWaveToFinish(timeStart, executions - 1, 11000) == False: return False #create last wave if self.wave is not None: self.pi.wave_delete(self.wave) self.pi.wave_add_generic(pulse_list) self.wave = self.pi.wave_create() #execute last wave self.waveLength = self.pi.wave_get_micros() self.pi.wave_send_once(self.wave) if self.waitForWaveToFinish(self.pi.get_current_tick(), executions, len(pulse_list) + pulses) == False: return False self.pi.wave_delete(self.wave) self.pi.wave_clear() self.wave = None return True
def addGap(code, duration): code.append(pigpio.pulse(0, 0, duration)) return code
def append_null(self, usec): self.waveform.append(pigpio.pulse(0, 0, usec))
def _init_precompiled_frames(self): """ This function is not supposed to be called by user. It compute some "pre-compiled" waves. """ self.frame_preamble = [pigpio.pulse(1<<self.data_pin,0,1*PULSE_LEN), pigpio.pulse(0,1<<self.data_pin,14*PULSE_LEN)] self.frame_end = [pigpio.pulse(1<<self.data_pin,0,1*PULSE_LEN), pigpio.pulse(0,1<<self.data_pin,100*PULSE_LEN)] self.frame_bit_high = [pigpio.pulse(1<<self.data_pin,0,1*PULSE_LEN), pigpio.pulse(0,1<<self.data_pin,7*PULSE_LEN), pigpio.pulse(1<<self.data_pin,0,1*PULSE_LEN), pigpio.pulse(0,1<<self.data_pin,2*PULSE_LEN)] self.frame_bit_low = [pigpio.pulse(1<<self.data_pin,0,1*PULSE_LEN), pigpio.pulse(0,1<<self.data_pin,2*PULSE_LEN), pigpio.pulse(1<<self.data_pin,0,1*PULSE_LEN), pigpio.pulse(0,1<<self.data_pin,7*PULSE_LEN)]
def __synthesize_elements(self): # Generate waveforms as frame elements as follows # - Leader # - Data '0', mark: T, space: T # - Data '1', mark: T, space: 3T # - Trailer # Clear wave self.__pi.wave_clear() # Generate waveform of leader wb = [] for i in range(0, self.__MARK_CYCLES * self.__N_LEADER_ON): wb.append(pigpio.pulse(1 << self.__pin, 0, self.__T_CARRIER // 2)) wb.append(pigpio.pulse(0, 1 << self.__pin, self.__T_CARRIER // 2)) wb.append( pigpio.pulse( 0, 1 << self.__pin, self.__T_CARRIER * self.__MARK_CYCLES * self.__N_LEADER_OFF)) self.__pi.wave_add_generic(wb) self.__wave_leader = self.__pi.wave_create() if DEBUG: print('Waveform for leader pulses created') # Generate waveform of Data '0' wb = [] for i in range(0, self.__MARK_CYCLES): wb.append(pigpio.pulse(1 << self.__pin, 0, self.__T_CARRIER // 2)) wb.append(pigpio.pulse(0, 1 << self.__pin, self.__T_CARRIER // 2)) wb.append( pigpio.pulse(0, 1 << self.__pin, self.__T_CARRIER * self.__MARK_CYCLES)) self.__pi.wave_add_generic(wb) self.__wave_data_0 = self.__pi.wave_create() if DEBUG: print('Waveform for data \'0\' created') # Generate waveform of Data '1' wb = [] for i in range(0, self.__MARK_CYCLES): wb.append(pigpio.pulse(1 << self.__pin, 0, self.__T_CARRIER // 2)) wb.append(pigpio.pulse(0, 1 << self.__pin, self.__T_CARRIER // 2)) wb.append( pigpio.pulse( 0, 1 << self.__pin, self.__T_CARRIER * self.__MARK_CYCLES * self.__MARK_OFF)) self.__pi.wave_add_generic(wb) self.__wave_data_1 = self.__pi.wave_create() if DEBUG: print('Waveform for data \'1\' created') # Generate waveform of trailer wb = [] for i in range(0, self.__MARK_CYCLES): wb.append(pigpio.pulse(1 << self.__pin, 0, self.__T_CARRIER // 2)) wb.append(pigpio.pulse(0, 1 << self.__pin, self.__T_CARRIER // 2)) wb.append( pigpio.pulse(0, 1 << self.__pin, 8000 - self.__T_CARRIER * self.__MARK_CYCLES)) self.__pi.wave_add_generic(wb) self.__wave_trailer = self.__pi.wave_create() if DEBUG: print('Waveform for trailer created')
def handleMessage(self): # get command from Scratch2 payload = json.loads(self.data) print(payload) client_cmd = payload['command'] # When the user wishes to set a pin as a digital Input if client_cmd == 'input': pin = int(payload['pin']) self.pi.set_glitch_filter(pin, 20000) self.pi.set_mode(pin, pigpio.INPUT) self.pi.callback(pin, pigpio.EITHER_EDGE, self.input_callback) # when a user wishes to set the state of a digital output pin elif client_cmd == 'digital_write': pin = int(payload['pin']) self.pi.set_mode(pin, pigpio.OUTPUT) state = payload['state'] if state == '0': self.pi.write(pin, 0) else: self.pi.write(pin, 1) # when a user wishes to set a pwm level for a digital input pin elif client_cmd == 'analog_write': pin = int(payload['pin']) self.pi.set_mode(pin, pigpio.OUTPUT) value = int(payload['value']) self.pi.set_PWM_dutycycle(pin, value) elif client_cmd == 'servo': # HackEduca ---> When a user wishes to set a servo: # Using SG90 servo: # 180° = 2500 Pulses; 0° = 690 Pulses # Want Servo 0°-->180° instead of 180°-->0°: # Invert pulse_max to pulse_min # pulse_width = int((((pulse_max - pulse_min)/(degree_max - degree_min)) * value) + pulse_min) # Where: # Test the following python code to know your Pulse Range: Replace it in the formula # >>>>-----------------------> # import RPi.GPIO as GPIO # import pigpio # Pulse = 690 # 0° # Pulse = 2500 # 180° # pi = pigpio.pi() # pi.set_mode(23, pigpio.OUTPUT) # pi.set_servo_pulse_width(23, Pulse) # pi.stop() # <------------------------<<<<< pin = int(payload['pin']) self.pi.set_mode(pin, pigpio.OUTPUT) value = int(payload['value']) DegreeMin = 0 DegreeMax = 180 PulseMin = 2500 PulseMax = 690 Pulsewidth = int((((PulseMax - PulseMin) / (DegreeMax - DegreeMin)) * value) + PulseMin) self.pi.set_servo_pulsewidth(pin, Pulsewidth) time.sleep(0.01) # when a user wishes to output a tone elif client_cmd == 'tone': pin = int(payload['pin']) self.pi.set_mode(pin, pigpio.OUTPUT) frequency = int(payload['frequency']) frequency = int((1000 / frequency) * 1000) tone = [ pigpio.pulse(1 << pin, 0, frequency), pigpio.pulse(0, 1 << pin, frequency) ] self.pi.wave_add_generic(tone) wid = self.pi.wave_create() if wid >= 0: self.pi.wave_send_repeat(wid) time.sleep(1) self.pi.wave_tx_stop() self.pi.wave_delete(wid) elif client_cmd == 'ready': pass else: print("Comando recebido desconhecido", client_cmd)
def generate_wave(self, json_file_name, n_tones_limit=42, freq_limit=440, time_scale_factor=1.15): with open(json_file_name) as f: tone_json = json.load(f) tone_list = tone_json["sequence"] limit = min(n_tones_limit, len(tone_list)) freq_list = [tone["f"] for tone in tone_list[:limit]] duration_list = [ float(tone["l"] / 1000.0) * time_scale_factor for tone in tone_list[:limit] ] pause_list = [ float(tone["d"] / 1000.0) * time_scale_factor if "d" in tone else 0 for tone in tone_list[:limit] ] #print(freq_list) max_freq = max(freq_list) freq_limit = float(freq_limit) if max_freq > freq_limit: shift_factor = max_freq / freq_limit freq_list = [int(f / shift_factor) for f in freq_list] #print(freq_list) sq_wave = [] for freq, duration, pause in zip(freq_list, duration_list, pause_list): period = int((1.0 / freq) * 1e6) semiperiod = int(period / 2) remaining_steps = int(freq * duration) #print(freq, duration, period, semiperiod, remaining_steps) while remaining_steps > 0: #print("in while loop", remaining_steps, POSITION, "FWD" if DIRECTION == DIR_FWD else "BCK") tmp = [] if self.DIRECTION == self.DIR_FWD: tmp.append( pigpio.pulse((1 << self.STEP) | (0 << self.DIR), (0 << self.STEP) | (1 << self.DIR), semiperiod)) tmp.append( pigpio.pulse((0 << self.STEP) | (0 << self.DIR), (1 << self.STEP) | (1 << self.DIR), semiperiod)) else: tmp.append( pigpio.pulse((1 << self.STEP) | (1 << self.DIR), (0 << self.STEP) | (0 << self.DIR), semiperiod)) tmp.append( pigpio.pulse((0 << self.STEP) | (1 << self.DIR), (1 << self.STEP) | (0 << self.DIR), semiperiod)) # compute number of steps to take in current direction, based on current position tmp_steps = min( remaining_steps, 80 - self.POSITION if self.DIRECTION == self.DIR_FWD else self.POSITION) # add steps (pulses) to waveform sq_wave.extend(tmp_steps * tmp) # update number of residual steps remaining_steps -= tmp_steps # update current position self.POSITION = self.POSITION + tmp_steps if self.DIRECTION == self.DIR_FWD else self.POSITION - tmp_steps # if drive head has reached one of the boundaries (POSITION 0 or 80), invert direction if self.POSITION == 0: self.DIRECTION = self.DIR_FWD elif self.POSITION == 80: self.DIRECTION = self.DIR_BCK # pause # convert pause in us pause = int(pause * 1e6) tmp = [] tmp.append(pigpio.pulse(0, 0, pause)) sq_wave.extend(tmp) return sq_wave[:]
def playback(self, identification): if type(identification) == str: identification = [identification] try: f = open(self.FILE, "r") except FileNotFoundError: print("Can't open: {}".format(self.FILE)) exit(0) records = json.load(f) f.close() self.pi.set_mode(self.GPIO, pigpio.OUTPUT) # IR TX connected to this GPIO. self.pi.wave_add_new() emit_time = time.time() if self.VERBOSE: print("Playing") for arg in identification: if arg in records: self.code = records[arg] # Create wave marks_wid = {} spaces_wid = {} wave = [0] * len(self.code) for i in range(0, len(self.code)): ci = self.code[i] if i & 1: # Space if ci not in spaces_wid: self.pi.wave_add_generic([pigpio.pulse(0, 0, ci)]) spaces_wid[ci] = self.pi.wave_create() wave[i] = spaces_wid[ci] else: # Mark if ci not in marks_wid: wf = self.carrier(self.GPIO, self.FREQ, ci) self.pi.wave_add_generic(wf) marks_wid[ci] = self.pi.wave_create() wave[i] = marks_wid[ci] delay = emit_time - time.time() if delay > 0.0: time.sleep(delay) self.pi.wave_chain(wave) if self.VERBOSE: print("key " + arg) while self.pi.wave_tx_busy(): time.sleep(0.002) emit_time = time.time() + self.GAP_S for i in marks_wid: self.pi.wave_delete(marks_wid[i]) marks_wid = {} for i in spaces_wid: self.pi.wave_delete(spaces_wid[i]) spaces_wid = {} else: print("Id {} not found".format(arg))
#irDATA = [0x23, 0xCB, 0x26, 0x01, 0x00, 0x20, 0x18, 0x18, 0x80, 0x59, 0x83, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] CheckSum = sum(irDATA) - (math.floor(sum(irDATA)/256))*256 irDATA.append(CheckSum) #0x0C cycle_tx=[0] #This will hold one cycle of the carrier pi = pigpio.pi() # Connect to local Pi. pi.set_mode(GPIO, pigpio.OUTPUT);#Set the GPIO to OUTPUT pi.set_mode(23, pigpio.OUTPUT) pi.set_mode(25, pigpio.INPUT) #Create one period of carrier cycle_pulse = [ pigpio.pulse(1<<GPIO, 0, round(ir_tx_per/2)), pigpio.pulse(0, 1<<GPIO, round(ir_tx_per/2)) ] cur_data = [] for x in range (0, math.floor(HEADER_MARK/ir_tx_per)): cur_data.extend(cycle_pulse) #Add Modulated Header Mark cur_data.extend([ pigpio.pulse(1<<GPIO, 0, round(ir_tx_per/2)), pigpio.pulse(0, 1<<GPIO, math.floor(HEADER_SPACE)) ]) #Add Header Space pi.wave_add_generic(cur_data); header_pulse=[] header_pulse = pi.wave_create();#Store the wave
print("hour: %s, half period in us: %s" % (twelvehour, halfperiod)) print("minute: %s, half-period in us: %s" % (now.minute, minhalfperiod)) square = [] minsquare = [] # Duration of pulse train in us (1000000us = 1s) duration = 10000000 pi.wave_clear() # Build up 1s worth of pulses for the hour - do a simple integer division - this is # accurate enough for our use case for i in xrange(int(duration / (2 * halfperiod))): # ON OFF MICROS square.append(pigpio.pulse(1 << GPIO, 0, halfperiod)) square.append(pigpio.pulse(0, 1 << GPIO, halfperiod)) pi.wave_add_generic(square) if (minhalfperiod > 0): # Now build up 1s worth of pulses for the minute readout as above for i in xrange(int(duration / (2 * minhalfperiod))): minsquare.append( pigpio.pulse(1 << GPIOMIN, 0, minhalfperiod)) minsquare.append( pigpio.pulse(0, 1 << GPIOMIN, minhalfperiod)) else: # Minutes == 0 should mean a DC output (i.e. no ON pulse) for i in xrange(int(duration / (2 * halfperiod))): minsquare.append(
def __init__(self): #initialize user interface Gtk.Window.__init__(self, title="Hello World") grid = Gtk.Grid() self.add(grid) self.pi = pigpio.pi() #populate user interface # f = Figure(figsize=(5, 4), dpi=100) # a = f.add_subplot(3, 1, 1) # b = f.add_subplot(3, 1, 2) # c = f.add_subplot(3, 1, 3) # t = np.arange(0.0, 3.0, 0.01) # s = np.sin(2*np.pi*t) # a.set_title("Automated Indoor Greenhouse") # a.plot(t, s) # a.plot(t, -s) # b.plot(t, s) # c.plot(t, s) # self.plot1 = FigureCanvas(f) # self.lamp_button = Gtk.Button(label="Lamp On/Off") # self.lamp_button.connect("clicked", self.on_lamp_button_clicked) # self.lamp_button.set_hexpand(True) # self.lamp_button.set_vexpand(True) # Set up Lamp Buttons self.lamp_state = AUTO self.lamp_button_off = Gtk.RadioButton.new_with_label_from_widget( None, label="Lamp Off") self.lamp_button_off.set_active(False) self.lamp_button_off.set_size_request(-1, RADIO_BUTTON_HEIGHT) self.lamp_button_off.connect("toggled", self.on_lamp_button_toggled, OFF) self.lamp_button_on = Gtk.RadioButton.new_with_label_from_widget( self.lamp_button_off, label="Lamp On") self.lamp_button_on.set_active(False) self.lamp_button_on.set_size_request(-1, RADIO_BUTTON_HEIGHT) self.lamp_button_on.connect("toggled", self.on_lamp_button_toggled, ON) self.lamp_button_auto = Gtk.RadioButton.new_with_label_from_widget( self.lamp_button_off, label="Lamp Auto") self.lamp_button_auto.set_active(True) self.lamp_button_auto.set_size_request(-1, RADIO_BUTTON_HEIGHT) self.lamp_button_auto.connect("toggled", self.on_lamp_button_toggled, AUTO) # Set up Fan Buttons self.fan_state = AUTO self.fan_button_off = Gtk.RadioButton.new_with_label_from_widget( None, label="Fan Off") self.fan_button_off.set_active(False) self.fan_button_off.set_size_request(-1, RADIO_BUTTON_HEIGHT) self.fan_button_off.connect("toggled", self.on_fan_button_toggled, OFF) self.fan_button_on = Gtk.RadioButton.new_with_label_from_widget( self.fan_button_off, label="Fan On") self.fan_button_on.set_active(False) self.fan_button_on.set_size_request(-1, RADIO_BUTTON_HEIGHT) self.fan_button_on.connect("toggled", self.on_fan_button_toggled, ON) self.fan_button_auto = Gtk.RadioButton.new_with_label_from_widget( self.fan_button_off, label="Fan Auto") self.fan_button_auto.set_active(True) self.fan_button_auto.set_size_request(-1, RADIO_BUTTON_HEIGHT) self.fan_button_auto.connect("toggled", self.on_fan_button_toggled, AUTO) # Set up Pump Buttons self.pump_state = AUTO self.pump_button_off = Gtk.RadioButton.new_with_label_from_widget( None, label="Pump Off") self.pump_button_off.set_active(False) self.pump_button_off.set_size_request(-1, RADIO_BUTTON_HEIGHT) self.pump_button_off.connect("toggled", self.on_pump_button_toggled, OFF) self.pump_button_on = Gtk.RadioButton.new_with_label_from_widget( self.pump_button_off, label="Pump On") self.pump_button_on.set_active(False) self.pump_button_on.set_size_request(-1, RADIO_BUTTON_HEIGHT) self.pump_button_on.connect("toggled", self.on_pump_button_toggled, ON) self.pump_button_auto = Gtk.RadioButton.new_with_label_from_widget( self.pump_button_off, label="Pump Auto") self.pump_button_auto.set_active(True) self.pump_button_auto.set_size_request(-1, RADIO_BUTTON_HEIGHT) self.pump_button_auto.connect("toggled", self.on_pump_button_toggled, AUTO) self.door_button = Gtk.Button(label=OPEN_DOOR_BUTTON_LABEL) self.door_button.connect("clicked", self.on_door_button_clicked) self.door_button.set_hexpand(True) self.door_button.set_vexpand(True) self.moisture_levelbars = [] self.moisture_levelbars_labels = [] for i in range(8): self.moisture_levelbars.append( Gtk.LevelBar(min_value=0, max_value=1023)) # if i % 2 == 1: # position = "bottom" # elif i % 2 == 0: # position = "top" self.moisture_levelbars[i].set_size_request(-1, 20) if i % 2 == 0: self.moisture_levelbars_labels.append( Gtk.Label("Plant {} (top / bottom)".format(int(i / 2)))) self.last_read_dht11 = 0.0 self.inside_dht11 = DHT11(self.pi, PIN_DHT11_INSIDE) self.outside_dht11 = DHT11(self.pi, PIN_DHT11_OUTSIDE) self.inside_dht11_label = Gtk.Label("Inside Greenhouse:") self.inside_dht11_temp_label = Gtk.Label("") self.inside_dht11_humid_label = Gtk.Label("") self.outside_dht11_label = Gtk.Label("Outside Greenhouse:") self.outside_dht11_temp_label = Gtk.Label("") self.outside_dht11_humid_label = Gtk.Label("") self.lightgate_label = Gtk.Label("") self.pi.set_mode(PIN_LIGHTGATE, pigpio.INPUT) #self.plot1.set_size_request(480, 600) #grid.attach(self.plot1, left=0, top=0, width=2, height=1) total_num_cols = 3 for i in range(8): if i % 2 == 0: grid.attach(self.moisture_levelbars_labels[int(i / 2)], left=0, top=2 * i, width=total_num_cols, height=1) grid.attach(self.moisture_levelbars[i], left=0, top=2 * i + 1, width=total_num_cols, height=1) lightgate_row = 16 grid.attach(self.lightgate_label, left=0, top=lightgate_row, width=total_num_cols, height=1) sensor_row = 17 grid.attach(self.inside_dht11_label, left=0, top=sensor_row, width=1, height=1) grid.attach(self.inside_dht11_temp_label, left=1, top=sensor_row, width=1, height=1) grid.attach(self.inside_dht11_humid_label, left=2, top=sensor_row, width=1, height=1) grid.attach(self.outside_dht11_label, left=0, top=sensor_row + 1, width=1, height=1) grid.attach(self.outside_dht11_temp_label, left=1, top=sensor_row + 1, width=1, height=1) grid.attach(self.outside_dht11_humid_label, left=2, top=sensor_row + 1, width=1, height=1) button_row = 19 grid.attach(self.lamp_button_off, left=0, top=button_row, width=1, height=1) grid.attach(self.lamp_button_on, left=0, top=button_row + 1, width=1, height=1) grid.attach(self.lamp_button_auto, left=0, top=button_row + 2, width=1, height=1) grid.attach(self.fan_button_off, left=1, top=button_row, width=1, height=1) grid.attach(self.fan_button_on, left=1, top=button_row + 1, width=1, height=1) grid.attach(self.fan_button_auto, left=1, top=button_row + 2, width=1, height=1) grid.attach(self.pump_button_off, left=2, top=button_row, width=1, height=1) grid.attach(self.pump_button_on, left=2, top=button_row + 1, width=1, height=1) grid.attach(self.pump_button_auto, left=2, top=button_row + 2, width=1, height=1) grid.attach(self.door_button, left=0, top=button_row + 3, width=total_num_cols, height=1) self.fullscreen() #initialize wave form sequences for door accel_sequence = [] decel_sequence = [] const_sequence = [] current_velocity_ms = 0.0 current_steps = 0.0 current_height_m = 0.0 time_since_start_s = 0.001 while current_velocity_ms < MAX_VELOCITY_MS and current_steps < TOTAL_STEPS / 2: current_velocity_ms = ACCELERATION_MS2 * time_since_start_s delta_t_s = (1 / STEPS_PER_M) / current_velocity_ms # ON OFF DELAY accel_sequence.append( pigpio.pulse(1 << PIN_STEP, 0, int((1000000 * delta_t_s) / 2))) accel_sequence.append( pigpio.pulse(0, 1 << PIN_STEP, int((1000000 * delta_t_s) / 2))) decel_sequence.insert( 0, pigpio.pulse(0, 1 << PIN_STEP, int((1000000 * delta_t_s) / 2))) decel_sequence.insert( 0, pigpio.pulse(1 << PIN_STEP, 0, int((1000000 * delta_t_s) / 2))) current_steps += 1 time_since_start_s += delta_t_s print("accel/decel steps: {}".format(current_steps)) delta_t_s = (1 / STEPS_PER_M) / MAX_VELOCITY_MS const_sequence.append( pigpio.pulse(1 << PIN_STEP, 0, int((1000000 * delta_t_s) / 2))) const_sequence.append( pigpio.pulse(0, 1 << PIN_STEP, int((1000000 * delta_t_s) / 2))) self.num_steps_const_sequence = int(TOTAL_STEPS - (current_steps * 2)) if self.num_steps_const_sequence >= 0xffff: print("burp") #initialize door control self.pi.set_mode(PIN_STEP, pigpio.OUTPUT) self.pi.set_mode(PIN_ENN, pigpio.OUTPUT) self.pi.set_mode(PIN_DIR, pigpio.OUTPUT) self.pi.wave_clear() self.pi.wave_add_generic(accel_sequence) self.wid_accel = self.pi.wave_create() self.pi.wave_add_generic(decel_sequence) self.wid_decel = self.pi.wave_create() self.pi.wave_add_generic(const_sequence) self.wid_const = self.pi.wave_create() self.door_position = DOOR_CLOSED #initialize lamp control self.pi.set_mode(PIN_LAMP, pigpio.OUTPUT) self.lamp_state = 0 #initialize fan control self.pi.set_mode(PIN_FAN, pigpio.OUTPUT) self.fan_state = 0 #initialize pump control self.pi.set_mode(PIN_PUMP, pigpio.OUTPUT) self.pump_state = 0 #initialize moisture sensors # Open SPI bus self.spi = self.pi.spi_open(spi_channel=0, baud=1000000, spi_flags=0) # initialize timer to periodically read sensor data self.timeout_id = GLib.timeout_add(200, self.on_periodic_timer)
def _zero(self): return [ pigpio.pulse(1 << self.pin, 0, self.mark_length_micro), pigpio.pulse(0, 1 << self.pin, self.mark_length_micro) ]
def waveChunk(self): wave=[] lasting=TIMESLOT tmin=1 delta=self.betaTarget-self.beta if delta*self.dir<0: newtime=time.time() print self.name,"DIR change",newtime-self.old_time self.old_time=newtime dir_change=True self.steps_rest=-self.steps_rest self.dir=self.dir*-1 else: dir_change=False dir=self.dir if delta==0 or self.freq==0: steps=0 if delta==0: self.syncronized=True #print self.name,"Syncronize" wave.append(pigpio.pulse(0, 1<<self.STEP_PIN, tmin)) self.pi.wave_add_generic(wave) return self.beta steps_float=self.freq*lasting/1000000. steps=int(steps_float) self.steps_rest=self.steps_rest+(steps_float-steps) #print self.name,steps_float,steps,self.steps_rest if steps==0 and self.steps_rest<1: wave.append(pigpio.pulse(0, 1<<self.STEP_PIN, tmin)) self.pi.wave_add_generic(wave) return self.beta if self.steps_rest>=1: print "STEP REST",int(self.steps_rest),self.steps_rest steps=steps+int(self.steps_rest) self.steps_rest=self.steps_rest-int(self.steps_rest) t=0.5*lasting/steps #time in micros if abs(delta)<steps: pass #print "Delta",self.name,steps,delta,self.betaTarget,self.beta steps=int(abs(delta)) for i in range(steps): wave.append(pigpio.pulse(0, 1<<self.STEP_PIN, t)) wave.append(pigpio.pulse(1<<self.STEP_PIN, 0, t)) self.pi.wave_add_generic(wave) if dir_change: dirwave=[] dirwave.append(pigpio.pulse(0,1<<self.DIR_PIN,t/2)) if dir>0: pass #dirwave.append(pigpio.pulse(1<<self.DIR_PIN,0,lasting-t/2)) dirwave.append(pigpio.pulse(1<<self.DIR_PIN,0,t/2)) else: pass #dirwave.append(pigpio.pulse(0,1<<self.DIR_PIN,lasting-t/2)) dirwave.append(pigpio.pulse(0,1<<self.DIR_PIN,t/2)) pulses=self.pi.wave_add_generic(dirwave) #self.checkWaveBuffer() #print "Wave chunck lasting/cbs:",t*2.*steps/1000000,pulses self.beta=self.beta+steps*dir return self.beta
def sendCommand(self, shutterId, button, repetition): #Sending a frame # Sending more than two repetitions after the original frame means a button kept pressed and moves the blind in steps # to adjust the tilt. Sending the original frame and three repetitions is the smallest adjustment, sending the original # frame and more repetitions moves the blinds up/down for a longer time. # To activate the program mode (to register or de-register additional remotes) of your Somfy blinds, long press the # prog button (at least thirteen times after the original frame to activate the registration. self.LogDebug("sendCommand: Waiting for Lock") self.lock.acquire() try: self.LogDebug("sendCommand: Lock aquired") checksum = 0 teleco = int(shutterId, 16) code = int(self.config.Shutters[shutterId]['code']) # print (codecs.encode(shutterId, 'hex_codec')) self.config.setCode(shutterId, code + 1) pi = pigpio.pi() # connect to Pi if not pi.connected: exit() pi.wave_add_new() pi.set_mode(self.TXGPIO, pigpio.OUTPUT) self.LogInfo("Remote : " + "0x%0.2X" % teleco + ' (' + self.config.Shutters[shutterId]['name'] + ')') self.LogInfo("Button : " + "0x%0.2X" % button) self.LogInfo("Rolling code : " + str(code)) self.LogInfo("") self.frame[0] = 0xA7 # Encryption key. Doesn't matter much self.frame[ 1] = button << 4 # Which button did you press? The 4 LSB will be the checksum self.frame[2] = code >> 8 # Rolling code (big endian) self.frame[3] = (code & 0xFF) # Rolling code self.frame[4] = teleco >> 16 # Remote address self.frame[5] = ((teleco >> 8) & 0xFF) # Remote address self.frame[6] = (teleco & 0xFF) # Remote address outstring = "Frame : " for octet in self.frame: outstring = outstring + "0x%0.2X" % octet + ' ' self.LogInfo(outstring) for i in range(0, 7): checksum = checksum ^ self.frame[i] ^ (self.frame[i] >> 4) checksum &= 0b1111 # We keep the last 4 bits only self.frame[1] |= checksum outstring = "With cks : " for octet in self.frame: outstring = outstring + "0x%0.2X" % octet + ' ' self.LogInfo(outstring) for i in range(1, 7): self.frame[i] ^= self.frame[i - 1] outstring = "Obfuscated :" for octet in self.frame: outstring = outstring + "0x%0.2X" % octet + ' ' self.LogInfo(outstring) #This is where all the awesomeness is happening. You're telling the daemon what you wanna send wf = [] wf.append(pigpio.pulse(1 << self.TXGPIO, 0, 9415)) # wake up pulse wf.append(pigpio.pulse(0, 1 << self.TXGPIO, 89565)) # silence for i in range(2): # hardware synchronization wf.append(pigpio.pulse(1 << self.TXGPIO, 0, 2560)) wf.append(pigpio.pulse(0, 1 << self.TXGPIO, 2560)) wf.append(pigpio.pulse(1 << self.TXGPIO, 0, 4550)) # software synchronization wf.append(pigpio.pulse(0, 1 << self.TXGPIO, 640)) for i in range(0, 56): # manchester enconding of payload data if ((self.frame[int(i / 8)] >> (7 - (i % 8))) & 1): wf.append(pigpio.pulse(0, 1 << self.TXGPIO, 640)) wf.append(pigpio.pulse(1 << self.TXGPIO, 0, 640)) else: wf.append(pigpio.pulse(1 << self.TXGPIO, 0, 640)) wf.append(pigpio.pulse(0, 1 << self.TXGPIO, 640)) wf.append(pigpio.pulse(0, 1 << self.TXGPIO, 30415)) # interframe gap for j in range(1, repetition): # repeating frames for i in range(7): # hardware synchronization wf.append(pigpio.pulse(1 << self.TXGPIO, 0, 2560)) wf.append(pigpio.pulse(0, 1 << self.TXGPIO, 2560)) wf.append(pigpio.pulse(1 << self.TXGPIO, 0, 4550)) # software synchronization wf.append(pigpio.pulse(0, 1 << self.TXGPIO, 640)) for i in range(0, 56): # manchester enconding of payload data if ((self.frame[int(i / 8)] >> (7 - (i % 8))) & 1): wf.append(pigpio.pulse(0, 1 << self.TXGPIO, 640)) wf.append(pigpio.pulse(1 << self.TXGPIO, 0, 640)) else: wf.append(pigpio.pulse(1 << self.TXGPIO, 0, 640)) wf.append(pigpio.pulse(0, 1 << self.TXGPIO, 640)) wf.append(pigpio.pulse(0, 1 << self.TXGPIO, 30415)) # interframe gap time.sleep( 0.25) # small pause before repetition, see issue #45 pi.wave_add_generic(wf) wid = pi.wave_create() pi.wave_send_once(wid) while pi.wave_tx_busy(): pass pi.wave_delete(wid) pi.stop() finally: self.lock.release() self.LogDebug("sendCommand: Lock released")
def send_wave(self, msg: Message): w = [] if isinstance(msg, BaseStationKeypadMessage): syncs = 150 elif isinstance(msg, KeypadMessage): syncs = 40 elif isinstance(msg, SensorMessage): syncs = 20 else: raise TypeError next_bit = 0 for i in range(syncs): w.append(pigpio.pulse(0, self.tx, 1000)) w.append(pigpio.pulse(self.tx, 0, 1000)) wd = [] wd.append(pigpio.pulse(0, self.tx, 2000)) wd.append(pigpio.pulse(self.tx, 0, 2000)) next_bit = 0 for msg_byte in bytes(msg): for i in range(8): if msg_byte & (1 << i): d = 1000 else: d = 500 if next_bit == 1: wd.append(pigpio.pulse(self.tx, 0, d)) else: wd.append(pigpio.pulse(0, self.tx, d)) next_bit ^= 1 if isinstance(msg, BaseStationKeypadMessage): ds = [1000, 1000, 500, 500] for d in ds: if next_bit == 1: wd.append(pigpio.pulse(self.tx, 0, d)) else: wd.append(pigpio.pulse(0, self.tx, d)) next_bit ^= 1 for i in range(4): if next_bit == 1: wd.append(pigpio.pulse(self.tx, 0, 1000)) else: wd.append(pigpio.pulse(0, self.tx, 1000)) next_bit ^= next_bit if isinstance(msg, BaseStationKeypadMessage): ws = [] for i in range(18): ws.append(pigpio.pulse(0, self.tx, 1000)) ws.append(pigpio.pulse(self.tx, 0, 1000)) w = w + wd + ws + wd + ws + wd elif isinstance(msg, ComponentMessage): w = w + wd + wd else: raise TypeError self._pi.wave_clear() self._pi.wave_add_generic(w) wid = self._pi.wave_create() if wid < 0: raise Exception("Message wave creation failed!") self._pi.wave_send_once(wid) while self._pi.wave_tx_busy(): sleep(1) self._pi.wave_clear() self._pi.stop()
pi.bb_serial_read_close(RX) pigpio.exceptions = True pi.wave_clear() # Build wave to send #total = pi.wave_add_serial(TX, baud, msg, bb_bits=8, offset=(3.5*char_time), bb_stop=2) #pi.wave_add_new(TX, baud, msg, bb_bits=8, bb_stop=2) #pi.wave_add_new() bits = sys.argv[1] debug = "" for bit in range(0, len(bits)): if bit == "1": if DEBUG: debug = debug + "1" pi.wave_add_generic([pigpio.pulse(1 << TX, 1 << TX, 500000)]) else: # using RX to create 0 value pulses on the wave that hits our TX pin if DEBUG: debug = debug + "0" pi.wave_add_generic([pigpio.pulse(1 << RX, 1 << RX, 500000)]) print("debug: ", debug) #print str(total)+" bits in message...Sending" #pi.wave_add_serial(TX, baud, msg) wid = pi.wave_create() pi.wave_send_once(wid) while pi.wave_tx_busy(): pass # Receive mode
def convertToFourBinary(number): if number == 0: serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) elif number == 1: serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) elif number == 2: serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) elif number == 3: serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) elif number == 4: serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) elif number == 5: serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) elif number == 6: serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) elif number == 7: serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) elif number == 8: serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) elif number == 9: serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65))
def start_pit(self, pit_type, gpio, servo_gpio): self.logger.debug(_(u'Starting pit {pit_type} on GPIO {gpio}').format(pit_type=pit_type, gpio=str(gpio))) if pit_type == 'fan_pwm': # 25kHz PC-Lüfter self.pi.set_mode(gpio, pigpio.OUTPUT) fan_pwm_pulses = [] fan_pwm_pulses.append(pigpio.pulse(1 << gpio, 0, 1)) fan_pwm_pulses.append(pigpio.pulse(0, 1 << gpio, 46)) self.pi.wave_clear() self.pi.wave_add_generic(fan_pwm_pulses) self.fan_pwm = self.pi.wave_create() self.pi.wave_send_repeat(self.fan_pwm) self.pit_gpio = gpio self.pit_type = pit_type elif pit_type == 'fan': # Lüftersteuerung v3 self.pi.set_mode(gpio, pigpio.OUTPUT) self.pi.set_PWM_frequency(gpio, 500) if not self.pit_inverted: self.pi.set_PWM_dutycycle(gpio, self.pit_min * 2.55) else: self.pi.set_PWM_dutycycle(gpio, self.pit_max * 2.55) self.pit_gpio = gpio self.pit_type = pit_type elif pit_type == 'servo': # Servosteuerung (oder Lüfter über Fahrtenregler) self.pi.set_mode(servo_gpio, pigpio.OUTPUT) # Reset limiter self.pit_servo_current_width = 0 if not self.pit_servo_inverted: self.servo_limiter(self.pi.set_servo_pulsewidth(servo_gpio, self.pit_servo_min)) else: self.servo_limiter(self.pi.set_servo_pulsewidth(servo_gpio, self.pit_servo_max)) self.pit_servo_gpio = servo_gpio self.pit_type = pit_type elif pit_type == 'io_pwm': # PWM-modulierter Schaltausgang (Schwingungspaketsteuerung) self.pi.set_mode(gpio, pigpio.OUTPUT) self.pit_io_pwm_end.clear() self.pit_io_pwm_thread = threading.Thread(target=self.io_pwm, args=(gpio,)) self.pit_io_pwm_thread.daemon = True # Startwerte mitgeben (nicht 0/0 wg. CPU-Last) if not self.pit_inverted: self.pit_io_pwm_on = 1 self.pit_io_pwm_off = 1 else: self.pit_io_pwm_on = 1 self.pit_io_pwm_off = 1 self.pit_io_pwm_thread.start() self.pit_gpio = gpio self.pit_type = pit_type elif pit_type == 'io': self.pi.set_mode(gpio, pigpio.OUTPUT) # Schaltausgang if not self.pit_inverted: self.pi.write(gpio, 0) else: self.pi.write(gpio, 1) self.pit_gpio = gpio self.pit_type = pit_type elif pit_type == 'damper' and gpio != servo_gpio: # Lüftersteuerung für Damper self.pi.set_mode(gpio, pigpio.OUTPUT) self.pi.set_PWM_frequency(gpio, 500) if not self.pit_inverted: self.pi.set_PWM_dutycycle(gpio, self.pit_min * 2.55) else: self.pi.set_PWM_dutycycle(gpio, self.pit_max * 2.55) # Servosteuerung für Damper # Reset limiter self.pit_servo_current_width = 0 self.pi.set_mode(servo_gpio, pigpio.OUTPUT) if not self.pit_servo_inverted: self.servo_limiter(self.pi.set_servo_pulsewidth(servo_gpio, self.pit_servo_min)) else: self.servo_limiter(self.pi.set_servo_pulsewidth(servo_gpio, self.pit_servo_max)) self.pit_gpio = gpio self.pit_servo_gpio = servo_gpio self.pit_type = pit_type
def send(room, action): checksum = 0 #Defining button action if action == "open": bouton = btnUp elif action == "close": bouton = btnDown elif action == "stop": bouton = btnStop elif action == "register": bouton = btnProg else: print "Unknown action." print "Please use open, close, stop or register." sys.exit() print "Action : " + action #Defining room print "Room : " + room #Reading remote #The files are stored in a subfolder called "remotes" with open("remotes/" + room + ".txt", 'r') as file: data = file.readlines() remote = int(data[0], 16) code = int(data[1]) data[1] = str(code + 1) with open("remotes/" + room + ".txt", 'w') as file: file.writelines(data) #Connecting to Pi pi = pigpio.pi() if not pi.connected: exit() pi.wave_add_new() pi.set_mode(TXGPIO, pigpio.OUTPUT) print "Remote : " + "0x%0.2X" % remote print "Button : " + "0x%0.2X" % bouton print "Rolling code : " + str(code) frame[0] = 0xA7; # Encryption key. Doesn't matter much frame[1] = bouton << 4 # Which action did you chose? The 4 LSB will be the checksum frame[2] = code >> 8 # Rolling code (big endian) frame[3] = (code & 0xFF) # Rolling code frame[4] = remote >> 16 # Remote address frame[5] = ((remote >> 8) & 0xFF) # Remote address frame[6] = (remote & 0xFF) # Remote address print "Frame :", for octet in frame: print "0x%0.2X" % octet, print "" for i in range(0, 7): checksum = checksum ^ frame[i] ^ (frame[i] >> 4) checksum &= 0b1111; # We keep the last 4 bits only frame[1] |= checksum; print "With cks :", for octet in frame: print "0x%0.2X" % octet, print "" for i in range(1, 7): frame[i] ^= frame[i-1]; print "Obfuscated :", for octet in frame: print "0x%0.2X" % octet, print "" #Telling what you want to send wf=[] wf.append(pigpio.pulse(1<<TXGPIO, 0, 9415)) wf.append(pigpio.pulse(0, 1<<TXGPIO, 89565)) for i in range(2): wf.append(pigpio.pulse(1<<TXGPIO, 0, 2560)) wf.append(pigpio.pulse(0, 1<<TXGPIO, 2560)) wf.append(pigpio.pulse(1<<TXGPIO, 0, 4550)) wf.append(pigpio.pulse(0, 1<<TXGPIO, 640)) for i in range (0, 56): if ((frame[i/8] >> (7 - (i%8))) & 1): wf.append(pigpio.pulse(0, 1<<TXGPIO, 640)) wf.append(pigpio.pulse(1<<TXGPIO, 0, 640)) else: wf.append(pigpio.pulse(1<<TXGPIO, 0, 640)) wf.append(pigpio.pulse(0, 1<<TXGPIO, 640)) wf.append(pigpio.pulse(0, 1<<TXGPIO, 30415)) #1 for i in range(7): wf.append(pigpio.pulse(1<<TXGPIO, 0, 2560)) wf.append(pigpio.pulse(0, 1<<TXGPIO, 2560)) wf.append(pigpio.pulse(1<<TXGPIO, 0, 4550)) wf.append(pigpio.pulse(0, 1<<TXGPIO, 640)) for i in range (0, 56): if ((frame[i/8] >> (7 - (i%8))) & 1): wf.append(pigpio.pulse(0, 1<<TXGPIO, 640)) wf.append(pigpio.pulse(1<<TXGPIO, 0, 640)) else: wf.append(pigpio.pulse(1<<TXGPIO, 0, 640)) wf.append(pigpio.pulse(0, 1<<TXGPIO, 640)) wf.append(pigpio.pulse(0, 1<<TXGPIO, 30415)) #2 for i in range(7): wf.append(pigpio.pulse(1<<TXGPIO, 0, 2560)) wf.append(pigpio.pulse(0, 1<<TXGPIO, 2560)) wf.append(pigpio.pulse(1<<TXGPIO, 0, 4550)) wf.append(pigpio.pulse(0, 1<<TXGPIO, 640)) for i in range (0, 56): if ((frame[i/8] >> (7 - (i%8))) & 1): wf.append(pigpio.pulse(0, 1<<TXGPIO, 640)) wf.append(pigpio.pulse(1<<TXGPIO, 0, 640)) else: wf.append(pigpio.pulse(1<<TXGPIO, 0, 640)) wf.append(pigpio.pulse(0, 1<<TXGPIO, 640)) wf.append(pigpio.pulse(0, 1<<TXGPIO, 30415)) pi.wave_add_generic(wf) wid = pi.wave_create() pi.wave_send_once(wid) while pi.wave_tx_busy(): pass pi.wave_delete(wid) pi.stop()
def update(): currentTime = datetime.datetime.now() threading.Timer(1-(1/currentTime.microsecond), update).start() serialData[:]=[] hour = currentTime.hour minute = currentTime.minute second = currentTime.second #HOURS if hour >= 12: #PM serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 240)) serialData.append(pigpio.pulse(0, 1<<clockPin, 65)) if hour > 12: #Convert 24hr to 12hr hour = hour - 12 else: #AM serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) serialData.append(pigpio.pulse(1<<clockPin, 0, 65)) serialData.append(pigpio.pulse(0, 1<<clockPin, 240)) if hour >= 10: #First Digit convertToTwoBinary(1) #Second Digit convertToFourBinary(int(str(hour)[1])) else: #First Digit convertToTwoBinary(0) #Second Digit convertToFourBinary(hour) #MINUTES if minute < 10: #Third Digit convertToThreeBinary(0) #Fourth Digit convertToFourBinary(minute) else: #Third Digit convertToThreeBinary(int(str(minute)[0])) #Fourth Digit convertToFourBinary(int(str(minute)[1])) #SECONDS if second < 10: #Fith Digit convertToThreeBinary(0) #Sixth Digit convertToFourBinary(second) else: #Fith Digit convertToThreeBinary(int(str(second)[0])) #Sixth Digit convertToFourBinary(int(str(second)[1])) pi.wave_clear() # clear any existing waveforms pi.wave_add_generic(serialData) eseTime = pi.wave_create() pi.wave_send_once(eseTime)
def add_low(self, duration): self.pulseArray.append( pigpio.pulse(0, 1 << AC_Settings.GPIO_OUT, duration))
def _pause(self): return [ pigpio.pulse(1 << self.pin, 0, self.mark_length_micro), pigpio.pulse(0, 1 << self.pin, 40 * self.mark_length_micro) ]
def __synthesize_single(self, bits): # Define wave buffer wb = [] # Synthesize the leader pulses, mark: 8T, space: 4T # Mark, with the 38-kHz carrier for i in range(0, self.__MARK_CYCLES * self.__N_LEADER_ON): wb.append(pigpio.pulse(1 << self.__pin, 0, self.__T_CARRIER // 2)) wb.append(pigpio.pulse(0, 1 << self.__pin, self.__T_CARRIER // 2)) # Space wb.append( pigpio.pulse( 0, 1 << self.__pin, self.__T_CARRIER * self.__MARK_CYCLES * self.__N_LEADER_OFF)) if DEBUG: print('A pigpio waveform of leader pulses synthesized...') # Synthesize the data pulses for bit in bits: # Mark, for T, with the 38-kHz carrier for i in range(0, self.__MARK_CYCLES): wb.append( pigpio.pulse(1 << self.__pin, 0, self.__T_CARRIER // 2)) wb.append( pigpio.pulse(0, 1 << self.__pin, self.__T_CARRIER // 2)) # Space, for T if bit is '0' if bit == '0': wb.append( pigpio.pulse(0, 1 << self.__pin, self.__T_CARRIER * self.__MARK_CYCLES)) # Space, for 3T if bit is '1' elif bit == '1': wb.append( pigpio.pulse( 0, 1 << self.__pin, self.__T_CARRIER * self.__MARK_CYCLES * self.__MARK_OFF)) if DEBUG: print('A pigpio waveform of data pulses synthesized...') # Synthesize the trailer # Mark, for T, with the 38-kHz carrier for i in range(0, self.__MARK_CYCLES): wb.append(pigpio.pulse(1 << self.__pin, 0, self.__T_CARRIER // 2)) wb.append(pigpio.pulse(0, 1 << self.__pin, self.__T_CARRIER // 2)) # Space, for 8 ms - T wb.append( pigpio.pulse(0, 1 << self.__pin, 8000 - self.__T_CARRIER * self.__MARK_CYCLES)) if DEBUG: print('A pigpio waveform of trailer pulses synthesized...') # Create a waveform based on the list of pulses self.__pi.wave_clear() self.__pi.wave_add_generic(wb) wave = self.__pi.wave_create() if DEBUG: print(f'A pigpio wave_id = {wave} obtained...') print( f'Length of waveform in DMA control blocks: {self.__pi.wave_get_cbs()}/{self.__pi.wave_get_max_cbs()}' ) print( f'Length of the waveform in microseconds: {self.__pi.wave_get_micros()}/{self.__pi.wave_get_max_micros()}' ) print( f'Length of the waveform in number of pulses: {self.__pi.wave_get_pulses()}/{self.__pi.wave_get_max_pulses()}' ) # Create and return wavechain as a list of wave_id although there is only a single element wc = [wave] return wc
def carrierOff(self, durationNS): flash = [] flash.append(pulse(0, 1 << self.id, durationNS)) return flash
def frameToWave(frame): wave = [] for trit in frame: if trit == 0: # H L L L H L L L wave.append(pigpio.pulse(1<<pin, 0, period)) wave.append(pigpio.pulse(0, 1<<pin, period*3)) wave.append(pigpio.pulse(1<<pin, 0, period)) wave.append(pigpio.pulse(0, 1<<pin, period*3)) elif trit == 1: # H H H L H H H L wave.append(pigpio.pulse(1<<pin, 0, period*3)) wave.append(pigpio.pulse(0, 1<<pin, period)) wave.append(pigpio.pulse(1<<pin, 0, period*3)) wave.append(pigpio.pulse(0, 1<<pin, period)) elif trit == 2: # H L L L H H H L wave.append(pigpio.pulse(1<<pin, 0, period)) wave.append(pigpio.pulse(0, 1<<pin, period*3)) wave.append(pigpio.pulse(1<<pin, 0, period*3)) wave.append(pigpio.pulse(0, 1<<pin, period)) else: print("Invalid trit: "+trit) wave.append(pigpio.pulse(1<<pin, 0, period)) wave.append(pigpio.pulse(0, 1<<pin, period*31)) return(wave)
def set_pit(self, control_out): self.logger.debug('Setze Pit auf ' + str(control_out) + '%') if control_out > 100: self.logger.info('Steuergröße über Maximum, begrenze auf 100%') control_out = 100 elif control_out < 0: self.logger.info('Steuergröße unter Minimum, begrenze auf 0%') control_out = 0 # Startup-Funktion für Lüfteranlauf, startet für 0,5s mit 25% if self.pit_type in ['fan_pwm', 'fan', 'servo'] and control_out > 0: # Auch bei Servo, falls noch jemand Lüfter an Fahrtenregler betreibt. if self.pit_out <= self.pit_startup_threshold and control_out < self.pit_startup_min: self.logger.info('Lüfteranlauf, 0,5s 25%') self.set_pit(self.pit_startup_min) time.sleep(self.pit_startup_time) self.pit_out = self.pit_startup_min if self.pit_type == 'fan_pwm': # 25kHz PC-Lüfter # Puls/ Pause berechnen pulselength = 47.0 if not self.pit_inverted: if control_out < 0.1: # Zerocut width = 0 else: width = int(round(self.pit_min + ((self.pit_max - self.pit_min) * (control_out / 100.0))) / (100 / (pulselength - 1))) else: width = int(round(self.pit_max - ((self.pit_max - self.pit_min) * (control_out / 100.0))) / (100 / (pulselength - 1))) # Ohne Impuls = 100%, daher minimum 1! width = width + 1 pause = pulselength - width self.logger.debug('fan_pwm Pulsweite ' + str(width)) # Wellenform generieren fan_pwm_pulses = [] fan_pwm_pulses.append(pigpio.pulse(1<<self.pit_gpio,0,width)) fan_pwm_pulses.append(pigpio.pulse(0,1<<self.pit_gpio,pause)) self.pi.wave_clear() self.pi.wave_add_generic(fan_pwm_pulses) wave = self.pi.wave_create() # Neue Wellenform aktivieren, alte Löschen self.pi.wave_send_repeat(wave) self.pi.wave_delete(self.fan_pwm) self.fan_pwm = wave elif self.pit_type == 'fan': # Lüftersteuerung v3 if not self.pit_inverted: if control_out < 0.1: # Zerocut width = 0 else: width = int(round(self.pit_min + ((self.pit_max - self.pit_min) * (control_out / 100.0))) * 2.55) else: width = int(round(self.pit_max - ((self.pit_max - self.pit_min) * (control_out / 100.0))) * 2.55) self.pi.set_PWM_dutycycle(self.pit_gpio, width) self.logger.debug('fan PWM ' + str(width) + ' von 255') elif self.pit_type == 'servo': # Servosteuerung (oder Lüfter über Fahrtenregler) if not self.pit_inverted: width = self.pit_min + ((self.pit_max - self.pit_min) * (control_out / 100.0)) else: width = self.pit_max - ((self.pit_max - self.pit_min) * (control_out / 100.0)) self.pi.set_servo_pulsewidth(self.pit_gpio, width) self.logger.debug('servo Impulsbreite ' + str(width) + 'µs') elif self.pit_type == 'io_pwm': # PWM-modulierter Schaltausgang (Schwingungspaketsteuerung) # Zyklusdauer in s cycletime = 2 width = (self.pit_min / 100.0 + ((self.pit_max - self.pit_min) / 100.0 * (control_out / 100.0))) * cycletime if not self.pit_inverted: on = width off = cycletime - width else: on = cycletime - width off = width with self.pit_io_pwm_lock: self.pit_io_pwm_on = on self.pit_io_pwm_off = off self.logger.debug('io_pwm Impulsbreite ' + str(on) + 's von ' + str(cycletime) + 's') elif self.pit_type == 'io': # Schaltausgang if control_out >= 50.0: # Einschalten self.logger.debug('io Schalte ein!') if not self.pit_inverted: self.pi.write(self.pit_gpio, 1) else: self.pi.write(self.pit_gpio, 0) else: # Ausschalten self.logger.debug('io Schalte aus') if not self.pit_inverted: self.pi.write(self.pit_gpio, 0) else: self.pi.write(self.pit_gpio, 1) self.pit_out = control_out
import time import pigpio sq = 13 square = [] square.append(pigpio.pulse(1 << sq, 0, 4)) square.append(pigpio.pulse(0, 1 << sq, 4)) pi = pigpio.pi() pi.set_mode(sq, pigpio.OUTPUT) pi.wave_add_generic(square) wid = pi.wave_create() print("Here") if wid >= 0: pi.wave_send_repeat(wid) time.sleep(1) pi.wave_tx_stop() pi.wave_delete(wid) pi.stop()
def t5(): global t5_count BAUD = 4800 TEXT = """ Now is the winter of our discontent Made glorious summer by this sun of York; And all the clouds that lour'd upon our house In the deep bosom of the ocean buried. Now are our brows bound with victorious wreaths; Our bruised arms hung up for monuments; Our stern alarums changed to merry meetings, Our dreadful marches to delightful measures. Grim-visaged war hath smooth'd his wrinkled front; And now, instead of mounting barded steeds To fright the souls of fearful adversaries, He capers nimbly in a lady's chamber To the lascivious pleasing of a lute. """ print("Waveforms & serial read/write tests.") t5cb = pigpio.callback(GPIO, pigpio.FALLING_EDGE, t5cbf) pigpio.set_mode(GPIO, pigpio.OUTPUT) e = pigpio.wave_clear() CHECK(5, 1, e, 0, 0, "callback, set mode, wave clear") wf = [] wf.append(pigpio.pulse(1 << GPIO, 0, 10000)) wf.append(pigpio.pulse(0, 1 << GPIO, 30000)) wf.append(pigpio.pulse(1 << GPIO, 0, 60000)) wf.append(pigpio.pulse(0, 1 << GPIO, 100000)) e = pigpio.wave_add_generic(wf) CHECK(5, 2, e, 4, 0, "pulse, wave add generic") e = pigpio.wave_tx_repeat() CHECK(5, 3, e, 9, 0, "wave tx repeat") oc = t5_count time.sleep(5) c = t5_count - oc CHECK(5, 4, c, 50, 1, "callback") e = pigpio.wave_tx_stop() CHECK(5, 5, e, 0, 0, "wave tx stop") e = pigpio.serial_read_open(GPIO, BAUD) CHECK(5, 6, e, 0, 0, "serial read open") pigpio.wave_clear() e = pigpio.wave_add_serial(GPIO, BAUD, 5000000, TEXT) CHECK(5, 7, e, 3405, 0, "wave clear, wave add serial") e = pigpio.wave_tx_start() CHECK(5, 8, e, 6811, 0, "wave tx start") oc = t5_count time.sleep(3) c = t5_count - oc CHECK(5, 9, c, 0, 0, "callback") oc = t5_count while pigpio.wave_tx_busy(): time.sleep(0.1) time.sleep(0.1) c = t5_count - oc CHECK(5, 10, c, 1702, 0, "wave tx busy, callback") c, text = pigpio.serial_read(GPIO) CHECK(5, 11, TEXT == text, True, 0, "wave tx busy, serial read") e = pigpio.serial_read_close(GPIO) CHECK(5, 12, e, 0, 0, "serial read close") c = pigpio.wave_get_micros() CHECK(5, 13, c, 6158704, 0, "wave get micros") CHECK(5, 14, 0, 0, 0, "NOT APPLICABLE") c = pigpio.wave_get_max_micros() CHECK(5, 15, c, 1800000000, 0, "wave get max micros") c = pigpio.wave_get_pulses() CHECK(5, 16, c, 3405, 0, "wave get pulses") CHECK(5, 17, 0, 0, 0, "NOT APPLICABLE") c = pigpio.wave_get_max_pulses() CHECK(5, 18, c, 12000, 0, "wave get max pulses") c = pigpio.wave_get_cbs() CHECK(5, 19, c, 6810, 0, "wave get cbs") CHECK(5, 20, 0, 0, 0, "NOT APPLICABLE") c = pigpio.wave_get_max_cbs() CHECK(5, 21, c, 25016, 0, "wave get max cbs") e = pigpio.wave_clear() CHECK(5, 22, e, 0, 0, "wave clear") e = pigpio.wave_add_generic(wf) CHECK(5, 23, e, 4, 0, "pulse, wave add generic") w1 = pigpio.wave_create() CHECK(5, 24, w1, 0, 0, "wave create") e = pigpio.wave_send_repeat(w1) CHECK(5, 25, e, 9, 0, "wave send repeat") oc = t5_count time.sleep(5) c = t5_count - oc CHECK(5, 26, c, 50, 1, "callback") e = pigpio.wave_tx_stop() CHECK(5, 27, e, 0, 0, "wave tx stop") e = pigpio.wave_add_serial(GPIO, BAUD, 5000000, TEXT) CHECK(5, 28, e, 3405, 0, "wave add serial") w2 = pigpio.wave_create() CHECK(5, 29, w2, 1, 0, "wave create") e = pigpio.wave_send_once(w2) CHECK(5, 30, e, 6811, 0, "wave send once") oc = t5_count time.sleep(3) c = t5_count - oc CHECK(5, 31, c, 0, 0, "callback") oc = t5_count while pigpio.wave_tx_busy(): time.sleep(0.1) time.sleep(0.1) c = t5_count - oc CHECK(5, 32, c, 1702, 0, "wave tx busy, callback") e = pigpio.wave_delete(0) CHECK(5, 33, e, 0, 0, "wave delete")
def _agc(self): return [ pigpio.pulse(1 << self.pin, 0, 16 * self.mark_length_micro), pigpio.pulse(0, 1 << self.pin, 8 * self.mark_length_micro) ]