Example #1
0
def main():
    pwm_timer = Timer(MOTOR_TIMER, freq=PWM_FREQ)

    ch1 = motorController(PIN_CH1, pwm_timer, 1)
    ch2 = motorController(PIN_CH2, pwm_timer, 2)

    adc = ADC(PIN_ADC)
    main_loop = loop(adc, ch1, ch2)

    event_timer = Timer(EVENT_TIMER, freq=1000)
    event_timer.freq(10)
    event_timer.callback(lambda t: next(main_loop))
Example #2
0
def music():
    global i
    x1 = Pin('X4', Pin.OUT_PP)
    tm3 = Timer(2, freq=MyScore[i][0])
    led3 = tm3.channel(4, Timer.PWM, pin=x1, pulse_width_percent=50)
    a = Pin.value(x1)
    for i in range(16):
        print(MyScore[i][0])
        tm3.freq(MyScore[i][0])
        pyb.delay(int(MyScore[i][1]))
        #i=i+1


#music()
Example #3
0
def main():
    pwm_timer = Timer(MOTOR_TIMER, freq=PWM_FREQ)

    ch1 = motorController(PIN_CH1, pwm_timer, 1)
    ch2 = motorController(PIN_CH2, pwm_timer, 2)
    ch3 = motorController(PIN_CH3, pwm_timer, 3)
    ch4 = motorController(PIN_CH4, pwm_timer, 4)

    adc = ADC(PIN_ADC)

    pb_in = Pin(PIN_PB_H, Pin.IN, Pin.PULL_UP)
    pb_out = Pin(PIN_PB_L, Pin.OUT_PP)
    pb_out.low()

    main_loop = loop(adc, ch1, ch2, ch3, ch4, pb_in)

    event_timer = Timer(EVENT_TIMER, freq=1000)
    event_timer.freq(10)
    event_timer.callback(lambda t: next(main_loop))
Example #4
0
class Music:
    def __init__(self,
                 pin_code="X1",
                 timer_no=5,
                 channel_id=1,
                 delay_period=150):
        self.p2 = Pin(pin_code)
        self.tim = Timer(timer_no, freq=3000)
        self.ch = self.tim.channel(channel_id, Timer.PWM, pin=self.p2)
        self.delay_period = delay_period

    def play(self, notes, volume=30):
        for i in notes:
            if i == 0:
                self.ch.pulse_width_percent(0)
            else:
                self.tim.freq(i)  # change frequency for change tone
                self.ch.pulse_width_percent(volume)

            pyb.delay(self.delay_period)
from pyb import Pin, ADC, Timer
from array import array

f = 500                           # Fréquence d'échantillonnage (750 kHz max.)
N = 20                            # Nombre de points
buffer = array("h", N*[0xFFFF])   # Tableau de N x 16 bit pour stocker les mesures
                                  # "h" pour signed short (int 2 octets)
                                        
adc = ADC(Pin('A0'))              # Déclaration du CAN sur la broche A0

tim = Timer(6, freq=f)            # Le timer 6 fixe la fréquence d'échantillonnage f

adc.read_timed(buffer, tim)       # Lancement des mesures

f = tim.freq()
t = [i*1/f     for i in range(N)]
y = [buffer[i] for i in range(N)]

print(t)
print(y)
Example #6
0
f = 750E3  # max = 750 kHz [84Mhz/4/(12+15) = 778 kHz]
nb = 1000  # Nombre de points de mesure

pinE = Pin('A2', Pin.OUT)  # Alimentation du circuit RC
adc = ADC(Pin('A3'))  # Activation du CAN
buf = array.array("h", nb * [0x0FFF])  # h = signed short (int 2 octets)
tim = Timer(6, freq=f)
#tim = Timer(6, prescaler=0, period=120)         # create a timer running at 10Hz

while True:
    pinE.on()  # Décharge du condensateur
    sleep_ms(100)  # Attendre 2 s
    pinE.off()  # Début de la charge
    adc.read_timed(buf, tim)  # Mesures

    seuil = buf[0] * 0.368
    for i in range(nb):
        if buf[i] < seuil:
            tau = i / tim.freq() * 1E6
            break
    R = 9.93
    C = tau / R  # nF
    h = round(1.56 * C - 33.7, 1)

    #print("C=", C, "h =", h)
    aff.fill(0)  # Efface l'affichage précédent
    aff.text(str(h))
    aff.show()
    sleep_ms(1000)
Example #7
0
class Buzzer(object):
    '''
    Plays sounds through the buzzer module
    '''
    def __init__(self, pin, timerId, channelId):
        '''
        Constructor
        
        @param pin: Pin where the module is attached to
        @param timerId: Timer associated to the pin
        @param channelId: Channel of the timer
        '''

        self._pin = pin
        #20200407 DPM: The timer must be initialized with a frequency, otherwise it won't beep.
        self._timer = Timer(timerId, freq=440)
        self._channel = self._timer.channel(channelId,
                                            Timer.PWM,
                                            pin=self._pin,
                                            pulse_width=0)

        self._buzzing = False

    def startBuzz(self, freq):
        '''
        Starts beeping. Use the stopBuzz method to finish.
        @see Buzzer.stopBuzz
        
        @param freq: Frequency of the sound
        '''

        if self._buzzing:
            self._timer.freq(freq)
        else:
            self._timer.init(freq=freq)
            self._buzzing = True

        self._channel.pulse_width_percent(50.0)

    def stopBuzz(self):
        '''
        Stops beeping.
        @see Buzzer.startBuzz
        '''

        self._channel.pulse_width(0)
        self._buzzing = False

    def buzz(self, freq, millisecs):
        '''
        Beeps a sound during a time
        
        @param freq: Frequency of the sound
        @param millisecs: Time to play
        '''

        self.startBuzz(freq)
        sleep_ms(millisecs)
        self.stopBuzz()

    def trill(self, freq, millisecs, playTime=10, muteTime=10):
        '''
        Makes a vibrating sound
        
        @param freq: Frequency of the sound
        @param millisecs: Duration of the sound
        @param playTime: (default=10) Time the buzzer beeps, as milliseconds
        @param muteTime: (default=10) Time the buzzer is muted, as milliseconds
        '''

        startTime = ticks_ms()

        while millisecs > ticks_diff(ticks_ms(), startTime):
            self.startBuzz(freq)
            sleep_ms(playTime)
            self.stopBuzz()
            sleep_ms(muteTime)

    def slide(self, freq1, freq2, millisecs):
        '''
        Slides sound between frequencies
        
        @param freq1: Starting frequency
        @param freq2: End frequency
        @param millisecs: Duration of the effect
        '''

        step = (freq2 - freq1) / millisecs
        freq = freq1
        t = 0
        while t < millisecs:
            self.startBuzz(freq)
            sleep_ms(1)
            t += 1
            freq += step

        self._channel.pulse_width(0)

    def cleanup(self):
        '''
        Removes resources
        '''

        self._channel.pulse_width(0)
        self._buzzing = False
        self._timer.deinit()
from pyb import Pin, ADC, Timer
from array import array
from math import log
from linear_regression import linear_reg
from time import sleep_ms

f = 750E3  # max = 750 kHz [84Mhz/4/(12+15) = 778 kHz]
nb = 100  # Nombre de points de mesure

pinE = Pin('A2', Pin.OUT)  # Source du circuit RC
adc = ADC(Pin('A3'))  # Activation du CAN
buf = array("h", nb * [0x7FFF])  # h = signed short (int 2 octets)
tim = Timer(6, freq=f)

while True:
    pinE.on()  # Décharge du condensateur E=0
    sleep_ms(100)  # Attendre 100 ms
    pinE.off()  # Début de la charge E=Vcc

    adc.read_timed(buf, tim)  # Lance les mesures

    f = tim.freq()  # Fréquence réelle utilisée par le timer
    x = [i / f * 1E6 for i in range(nb)]  # Tableau des fréquence en µs
    y = [log(val) for val in buf]  # Tableau des ln(u)

    a, b = linear_reg(x, y)  # Regression linéaire
    C = -1 / (a * 10)  # Calcul de la capacité
    print("C = ", C)  # Affichage

    sleep_ms(1000)
Example #9
0
class BuzzerPlayer(object):

    def __init__(self, pin="X8", timer_id=1, channel_id=1, callback=None, platform=None):

        if not platform:
            platform = sys.platform
            
        self.platform = platform
        
        if "esp" in platform:
            from machine import PWM, Pin
            self.buzzer_pin = PWM(Pin(pin, Pin.OUT), freq=1000)

        elif platform == "pyboard":
            import pyb
            from pyb import Pin, Timer
            self.pyb = pyb
            self.sound_pin = Pin(pin)
            self.timer = Timer(timer_id, freq=10000)
            self.channel = self.timer.channel(1, Timer.PWM, pin=self.sound_pin, pulse_width=0)
                  
        self.callback = callback

    def from_file(self, filename, chunksize=5):
        with open(filename, "rb") as f:
            while True:
                chunk = f.read(chunksize)
                if chunk:
                    for b in chunk:
                        yield chr(b)
                else:
                    break
    
    def play_nokia_tone(self, song, tempo=None, transpose=6, name="unkown"):
        
        pattern = "([0-9]*)(.*)([0-9]?)"
        def tune(): 
            for item in isplit(song):
                if item.startswith('t'):
                    _, tempo = item.split('=')
                    yield tempo
                    continue
                match = re.match(pattern, item)
                duration = match.group(1)
                pitch = match.group(2)
                octave = match.group(3)

                if pitch == "-":
                    pitch = "r"
                if pitch.startswith("#"):
                    pitch = pitch[1] + "#" + pitch[2:]
                dotted = pitch.startswith(".")
                duration = -int(duration) if dotted else int(duration)
                yield (pitch + octave, int(duration))

        t = tune()
        if not tempo:
            tempo = next(t)
        self.play_tune(tempo, t, transpose=transpose, name=name)

    def tone(self, freq, duration=0, duty=30):
        if self.platform == "esp8266":
            self.buzzer_pin.freq(int(freq))
            self.buzzer_pin.duty(duty)
            time.sleep_us( int(duration * 0.9 * 1000) )
            self.buzzer_pin.duty(0)
            time.sleep_us(int(duration * 0.1 * 1000))

        elif self.platform == "pyboard":
            self.timer.freq(freq)  # change frequency for change tone
            self.channel.pulse_width_percent(30)
            self.pyb.delay(duration)

        if callable(self.callback):
            self.callback(freq)
            
    def play_tune(self, tempo, tune, transpose=0, name="unknown"):

        print("\n== playing '%s' ==:" % name)
        full_notes_per_second = float(tempo) / 60 / 4
        full_note_in_samples = SAMPLING_RATE / full_notes_per_second

        for note_pitch, note_duration in tune:
            duration = int(full_note_in_samples / note_duration)

            if note_pitch == "r":
                self.tone(0, duration, 0)
            else:
                freq = note_freq(note_pitch)
                if transpose: freq *= 2 ** transpose
                print("%s " % note_pitch, end="")
                self.tone(freq, duration, 30)
                
        self.tone(0, 0, 0)

    if MidiFile:
        def play_midi(self, filename, track=1,  transpose=6):
            midi = MidiFile(filename)
            tune = midi.read_track(track)
            self.play_tune(midi.tempo, tune, transpose=transpose, name=filename)

    if RTTTL:
        def play_rtttl(self, input):
            tune = RTTTL(input)    
            for freq, msec in tune.notes():
                self.tone(freq, msec)
Example #10
0
class PWM:
    """A PWM output on the given pin.
    
    This uses the pins_af.py file created by the micropython build.

    The timer argument is the name of the timer to use, as a string in
    the form 'TIM#'.  If it is not set, the first timer available for
    the pin will be used. Either length or freq can be used to specify
    the pulse length of the pwm signal. Length is the total pulse
    length in microseconds, and frequency is Hz, so length=20000
    implies freq=50, which is the default. If both are specified, freq
    is ignored.

    self.timer & self.channel are made available if you want to read or
    adjust the settings after initialization."""
    def __init__(self, pin, timer=None, length=None, freq=None):
        timers = af_map['P' + pin.name()]
        if not timers:
            raise PwmError("Pin does not support PWM.")

        if not timer:
            timer = 'TIM'
        for af, name in timers:
            if name.startswith(timer):
                timer_af, timer_name = af, name
                timer_full, channel = timer_name.split('_')
                if channel.startswith('CH'):
                    break
        else:
            raise PwmError("Pin does not support timer %s" % timer)

        if length:
            freq = 1000000 / length
        elif not freq:
            freq = 50
        pin.init(Pin.OUT, alt=af)
        self.timer = Timer(int(timer_full[3:]), freq=freq)
        self.channel = self.timer.channel(
            int(channel[2:3]),
            Timer.PWM_INVERTED if channel.endswith('N') else Timer.PWM,
            pin=pin)

        self.length = 1000000 / self.timer.freq()
        self.duty(0)

    def duty(self, percentage=None):
        """Get/Set the duty cycle as a percentage.
        
        The duty cycle is the time the output signal is on.
        Returns the last set value if called with no arguments."""

        if percentage is None:
            return round(100 * self.channel.pulse_width() /
                         self.timer.period())
        self.channel.pulse_width_percent(max(0, min(percentage, 100)))

    def pulse_width(self, width=None, time=0):
        """Get/Set the pulse width in microseconds.
        
        The width is the length of time the signal is on.  Returns the
        current value rounded to the nearest int if called with no
        arguments.
        
        Time is the number of milliseconds to take to get to the new
        width.  At least that many milliseconds will pass; if it's 0,
        the change will happen now."""

        if width is None:
            return round(self.length * self.channel.pulse_width() /
                         self.timer.period())
        target = self.timer.period() * min(width, self.length) / self.length
        self.target = round(target)
        if time == 0:
            self.channel.pulse_width(self.target)
        else:
            self.delta = int((target - self.channel.pulse_width()) *
                             self.length / (time * 1000))
            self.channel.callback(self.timed_change)
            # No initial change so we get minimum length.

    def timed_change(self, timer):
        """Make a timed change in width."""

        old = self.channel.pulse_width()
        if abs(old - self.target) > abs(self.delta):
            self.channel.pulse_width(old + self.delta)
        else:
            self.channel.callback(None)
            self.channel.pulse_width(self.target)
Example #11
0
class Buzz():
    def __init__(self):
        """ constructeur, par défaut buzzerOn=False: non activé"""
        self.level = 25  # niveau sonnore 0 (off) à 100 (max)
        self.freq_lam7 = [440, 523, 659, 784
                          ]  #les bluesman vont reconnaître un accord de Lam7
        self.dic_freq = {
            'V': 440,  # fréquence ledG = La
            'B': 523,  # fréquence ledB = Do
            'J': 659,  # fréquence ledY = Mi
            'R': 784  # fréquence ledR = Sol
        }
        self.pin = 'S5'  # buzzer commandé par pin s5: Timer n°4, channel n°3
        self.timer = Timer(4, freq=self.dic_freq['V'])
        self.channel = self.timer.channel(3, Timer.PWM, pin=Pin(self.pin))
        self.mute()
        self.welcome_sound()

    def mute(self):
        """ arrête le buzzer"""
        self.channel.pulse_width_percent(0)

    def play(self):
        """ active le buzzer, volume de 0 à 100"""
        self.channel.pulse_width_percent(self.level % 101)

    def chg_freq(self, freq=500):
        """ modifie la fréquence du buzzer pour changer de note
        Table des fréquences par note/octave:
             0       1      2      3      4      5      6      7      8      9
        do   32.703  65.406 130.81 261.63 523.25 1046.5 2093.  4186.  8372.  16744.
        do#  34.648  69.296 138.59 277.18 554.37 1108.7 2217.5 4434.9 8869.8 17740.
        ré   36.708  73.416 146.83 293.66 587.33 1174.7 2349.3 4698.6 9397.3 18795.
        ré#  38.891  77.782 155.56 311.13 622.25 1244.5 2489.  4978.  9956.1 19912.
        mi   41.203  82.407 164.81 329.63 659.26 1318.5 2637.  5274.  10548. 21096.
        fa   43.654  87.307 174.61 349.23 698.46 1396.9 2793.8 5587.7 11175. 22351.
        fa#  46.249  92.499 185.   369.99 739.99 1480.  2960.  5919.9 11840. 23680.
        sol  48.999  97.999 196.   392.   783.99 1568.  3136.  6271.9 12544. 25088.
        sol# 51.913  103.83 207.65 415.3  830.61 1661.2 3322.4 6644.9 13290. 26580.
        la   55.     110.   220.   440.   880.   1760.  3520.  7040.  14080. 28160.
        la#  58.27   116.54 233.08 466.16 932.33 1864.7 3729.3 7458.6 14917. 29834.
        si   61.735  123.47 246.94 493.88 987.77 1975.5 3951.1 7902.1 15804. 31609.
        """
        self.timer.freq(freq)

    def buzzId(self, color):
        """fait sonner le buzzer avec une fréquence correspond à color
           color dans la liste ['green', 'blue','yellow', 'red']
        """
        self.chg_freq(self.dic_freq[color])  # modifie la fréquence du timer
        self.play()  # active le son du buzzer

    def welcome_sound(self):
        """ joue un accord de Lam7"""
        for freq in self.freq_lam7:
            self.chg_freq(freq)
            self.play()
            sleep(0.1)
        self.mute()

    def loose_sound(self):
        """ joue un accord de Lam7 à l'envers"""
        for freq in self.freq_lam7[::-1]:
            self.chg_freq(freq)
            self.play()
            sleep(0.08)
        self.mute()
Example #12
0
# This example shows how to do PWM with your OpenMV Cam.

import time, pyb
from pyb import Pin, Timer

#tim = pyb.Timer(4)              # create a timer object using timer 4
#tim.init(freq=2)                # trigger at 2Hz
#tim.callback(lambda t:pyb.LED(1).toggle())

#while(True):
#time.sleep(1000)

pin = Pin("P7")
tim = Timer(4, freq=50)  # Frequency in Hz
i = 1
## Generate a 1KHz square wave on TIM4 with 50% and 75% duty cycles on channels 1 and 2, respectively.
ch1 = tim.channel(1, Timer.PWM, pin=pin, pulse_width_percent=50)
##ch2 = tim.channel(2, Timer.PWM, pin=Pin("P8"), pulse_width_percent=75)

#pin.debug(True)

while (i < 20):
    #ch1.pulse_width_percent(i)
    tim.freq(i)
    print(i)
    #pin.value(0)
    time.sleep(2000)
    i += 1
    #pin.value(0)
    #time.sleep(1000)
from pyb import Pin, ADC, Timer
import time

led = Pin('LED1', Pin.OUT)
#adc_pin = Pin(Pin.cpu.C2, mode=Pin.ANALOG)
#adc_pin = Pin(Pin.cpu.C3, mode=Pin.ANALOG)
#adc_pin = Pin(Pin.cpu.A0, mode=Pin.ANALOG)
#adc_pin = Pin(Pin.cpu.A1, mode=Pin.ANALOG)
adc_pin = Pin(Pin.cpu.B0, mode=Pin.ANALOG) #on testpad
#adc_pin = Pin(Pin.cpu.B1, mode=Pin.ANALOG) #on testpad

adc = ADC(adc_pin)

tim = Timer(6)
tim.counter() # get counter value
tim.freq(20)

def tick(timer):                # we will receive the timer object when being called
    if led.value()==0:
        led.on()
    else:
        led.off()
    print(adc.read())

tim.callback(tick)

time.sleep(10)
tim.deinit()

    
Example #14
0
class PololuBuzzer(object):
    def __init__(self):
        self.buzzer = Pin("X1", Pin.OUT)
        self.tim_buzzer = Timer(2, freq=500)
        self.ch_buzzer = self.tim_buzzer.channel(1, Timer.PWM, pin=self.buzzer)
        self.buzzerInitialized = 0
        self.buzzerFinished = 1
        self.buzzerSequence = 0
        self.buzzerTimeout = 0
        self.play_mode_settings = PLAY_AUTOMATIC

        self.octave = 4
        self.whole_note_duration = 2000
        self.note_type = 4
        self.duration = 500
        self.volume = 15
        self.staccato = 0
        self.all_notes = False  #False au debut. N'agit que sur une note
        print("Init PololuBuzzer")

    def playFrequency(self, freq, dur, volume):
        self.freq = freq
        self.dur = dur
        self.volume = volume
        self.buzzerFinished = 0
        multiplier = 1
        if (self.freq & DIV_BY_10
            ):  #si le bit de résolution est activé on doit diviser par 10
            multiplier = 10
            self.freq = (self.freq and ~DIV_BY_10)
        min = 40 * multiplier  #(40*1 minimum)

        if (self.freq < min):
            self.freq = min
        if ((multiplier == 1) and (self.freq > 10000)):
            self.freq = 10000

        if (multiplier == 10):
            self.freq = int((self.freq + 5) / 10)
        if (self.freq == 1000):
            timeout = self.dur
        else:
            timeout = int((self.dur * self.freq / 1000))

        if (self.volume > 15):
            self.volume = 15

        if freq == 0:
            self.tim_buzzer.freq(self.freq)
            self.ch_buzzer.pulse_width_percent(0)
        else:

            self.tim_buzzer.freq(self.freq)
            self.ch_buzzer.pulse_width_percent(30)
            time.sleep_us(self.dur *
                          1000)  #sert a arreter le son apres le temps demandé
            self.ch_buzzer.pulse_width_percent(0)

    def playNote(self, note, dur, volume):
        self.freq = 0
        self.dur = dur
        self.note = note
        self.volume = volume
        offset_note = self.note - 16

        if ((note == SILENT_NOTE)):
            print("play note silence:  %s" % self.freq)
            #if((note == SILENT_NOTE) or (volume ==0)):
            freq = 1000
            self.playFrequency(0, self.dur, 0)
            time.sleep_us(self.dur * 1000)
            return

        if (self.note <= 16):
            offset_note = 0
        elif (offset_note > 95):
            offset_note = 95

        exponent = offset_note // 12  # // division entière
        tab_sound = {
            0: 412,
            1: 437,
            2: 463,
            3: 490,
            4: 519,
            5: 550,
            6: 583,
            7: 617,
            8: 654,
            9: 693,
            10: 734,
            11: 778
        }
        self.freq = tab_sound[offset_note - (exponent * 12)]

        #print("Offset: %s - Exponent: %s - Freq/tableau: %s" %(offset_note, exponent,self.freq))
        if (exponent < 7):
            self.freq = (self.freq << exponent)
            #print("freq apres exp: %s" %self.freq)
            if (exponent > 1):
                self.freq = int((self.freq + 5) // 10)
                #print("Freq - exponent>1 : %s " %self.freq)
            else:
                self.freq += DIV_BY_10
                #print("Freq - DIV_BY_10: %s" %self.freq)
        else:
            self.freq = int((self.freq * 64 + 2) // 5)
            #print("Freq - else: %s" %self.freq)
        if (volume > 15):
            volume = 15

        if (self.freq > 0):
            print("freq > 0")
            self.playFrequency(self.freq, self.dur, self.volume)
        else:
            print("freq pas plus grand que zero")
            self.playFrequency(0, 0, 0)

    def isPlaying(self):
        return (self.buzzerFinished == False or self.buzzerSequence != 0)

    def play(self, notes):
        self.buzzerSequence = 0  #on est au premier caractère de la sequence
        self._notes = notes  #on retiens la séquence
        self.staccato_rest_duration = 0
        self.octave = 4

        note = self.nextNote()  #note pour vérifier qu'il y a un charactère
        while (note):

            note = self.nextNote()

        self.reset()
        self.off()

    """def playFromProgramSpace(self,notes_p):
        self.buzzerSequence = notes_p
        self.use_program_space = 1
        self.staccato_rest_duration = 0
        print("playFromProgramSpace")
        self.nextNote()"""

    def reset(self):
        self.octave = 4
        self.whole_note_duration = 2000
        self.note_type = 4
        self.duration = 500
        self.volume = 15
        self.staccato = 0
        self.octave = 4
        tmp_duration = self.duration

    def stopPlaying(self):
        self.buzzerFinished = 1
        self.buzzerSequence = 0
        print("stopPlaying")

    def off(self):
        self.ch_buzzer.pulse_width_percent(0)

    def currentCharacter(self):

        c = None

        if (
                self.buzzerSequence >= len(self._notes)
        ):  #Si le compteur buzzerSequence et plus grand que la longeur de caractères
            return None  #c=None

        c = self._notes[
            self.
            buzzerSequence]  #On prend le premier caractère [buzzerSequence == 0] initialement,
        if (c and c.isdigit() and self.buzzerSequence == 0):
            pass
            # exeption(" First character has to be a letter")
            # Ecrire erreur quand 1er pas une lettre
            # doit etre incrémenté pour pouvoir utiliser le nieme caractère
        c = c.lower()  # C toujours en minuscule

        while (
                c == " "
        ):  #on recherche si il y a un espace "silence" et qu'il y ai un autre caractère apres
            self.buzzerSequence += 1
            if (self.buzzerSequence >= len(
                    self._notes)):  #verifie si il y a un autre  carac
                return None
            c = self._notes[self.buzzerSequence]
            c = c.lower()
        return (c)

    def getNumber(
            self):  #Fonction qui permet d'avoir un nombre a plusieurs chiffres
        arg = 0
        c = self.currentCharacter()  #Prends le caractère
        while (c and c.isdigit()
               ):  #si il y a un caractère et que le caractère est un chiffre
            arg *= 10  #première fois (0*10), deuxieme fois (c*10), troisième fois ((c*10)*10)
            arg += int(
                c)  #change une chaine de caractères en integer et ajoute ,
            print(
                arg
            )  #remets le chiffre en integer pour etre utilise dans des calculs
            # on soustrait les nombres et on les remets en chaine de caractères
            self.buzzerSequence += 1  #aug buzzerSequence pour le prochain caractère
            c = self.currentCharacter(
            )  #on recherche un caractère. Si ce n'est plus un chiffre ou qu'il n'y a plus rien on sort de la boucle while
        return (arg)  #retourne le nombre complet

    def nextNote(self):
        self.note = 0  #note vaut 0 au debut
        self.rest = 0
        tmp_octave = 0  #le rest vaut 0 au debut
        while (True):
            #octave vaut 4
            #Sert a jouer une note silencieuse si il faut
            if (
                    self.staccato == True and self.staccato_rest_duration > 0
            ):  #si on utilise le mode staccato on place un note de silence entre chaque note
                print("Staccato True: %s" % self.freq)
                self.playNote(SILENT_NOTE, self.staccato_rest_duration,
                              5)  #(note,dur,volume)
                self.staccato_rest_duration = 0  #On remets le variable a 0 pour produire du son prochaine fois

            c = self.currentCharacter(
            )  #on prend le premier caractère, en fonction de ce que c'est on peut faire plusieurs choses
            self.buzzerSequence += 1
            """> plays the next note one octave higher"""
            if (c == '>'):
                self.all_notes = False  #on agit que sur une note

                tmp_octave = tmp_octave + 1  #on aug

                continue  # on revient au début su while pour voir

            elif (c == '<'):
                self.all_notes = False
                tmp_octave = tmp_octave - 1

                continue
            elif (c == 'a'):
                self.note = NOTE_A(0)
                print("----------------------")
                print("Lettre: a - Note: La.")
                break
            elif (c == 'b'):
                self.note = NOTE_B(0)
                print("----------------------")
                print("Lettre b - Note: Si.")
                break
            elif (c == 'c'):
                self.note = NOTE_C(0)
                print("----------------------")
                print("Lettre c - Note: Do.")
                break
            elif (c == 'd'):
                self.note = NOTE_D(0)
                print("----------------------")
                print("Lettre d - Note: Re.")
                break
            elif (c == 'e'):
                self.note = NOTE_E(0)
                print("----------------------")
                print("Lettre e - Note: Mi.")
                break
            elif (c == 'f'):
                self.note = NOTE_F(0)
                print("----------------------")
                print("Lettre f - Note: Fa.")
                break
            elif (c == 'g'):
                self.note = NOTE_G(0)
                print("----------------------")
                print("Lettre g - Note: Sol.")
                break

            #L' followed by a number sets the default note duration to
            #the type specified by the number: 4 for quarter notes, 8
            #for eighth notes, 16 for sixteenth notes, etc.
            #(default: L4)"""
            elif (c == 'l'):  #
                self.note_type = self.getNumber()
                self.duration = self.whole_note_duration / self.note_type
                c = self.currentCharacter()  #on prend le premier caractère
                self.buzzerSequence += 1
                print("Note duration changed to: %s." % self.note_type)
            #"""ML' sets all subsequent notes to play legato - each note is played
            #for its full length.  This is the default setting.

            #MS' sets all subsequent notes to play staccato - each note is played
            #for 1/2 of its allotted time, followed by an equal period
            #of silence."""
            elif (c == 'm'):
                if (self.currentCharacter() == 'l'):
                    self.staccato = False
                    print("Staccato mode OFF")
                elif (self.currentCharacter() == 's'):
                    self.staccato = True
                    self.staccato_rest_duration = 0
                    print("Staccato mode ON.")
                else:
                    pass
                self.buzzerSequence += 1
                continue
            #"""O' followed by a number sets the octave (default: O4)."""
            elif (c == 'o'):
                self.all_notes = True
                self.octave = self.getNumber()
                print("Octave set to: %s." % self.octave)
                continue

            elif (c == 'r'):
                self.rest = 1
                print("----------------------")
                print("Pause Note")

            #"""T' followed by a number sets the tempo (default: T120)."""
            elif (c == 't'):
                self.whole_note_duration = 60 * 400 / self.getNumber() * 10
                self.duration = self.whole_note_duration / self.note_type
                print("Tempo changed to: %s." % self.duration)
                continue
            #"""V' followed by a number from 0-15 sets the music volume.
            #(default: V15)"""
            elif (c == 'v'):
                self.volume = self.getNumber()
                continue
            #"""'!' resets all persistent settings to their defaults."""
            elif (c == '!'):
                self.octave = 4
                self.whole_note_duration = 2000
                self.note_type = 4
                self.duration = 500
                self.volume = 15
                self.staccato = 0
                self.octave = 4
                tmp_duration = self.duration
                print("Reset everything.")
                continue

                #c = self.currentCharacter()         #on prend le premier caractère
                #self.buzzerSequence +=1
            else:  #Si plus rien on remets buzzerSequence a 0 pour etre pret pour une nouvelle chaine de caractères
                self.buzzerSequence = 0
                break
            break
        #FIN WHILE
        if (self.all_notes == False):

            self.note += (self.octave + tmp_octave) * 12
            self.all_note = True
        else:
            self.note += self.octave * 12  # note = key + octave *12     (0<=key<12)  octave 4 initiallement

        print("apres self.note: %s" % self.octave)
        c = self.currentCharacter()
        #"""+' or '#' after a note raises any note one half-step"""
        while (c == '+' or c == '#'):
            self.buzzerSequence += 1
            self.note += 1
            c = self.currentCharacter()
        #"""-' after a note lowers any note one half-step"""
        while (c == '-'):
            self.buzzerSequence += 1
            self.note -= 1

            c = self.currentCharacter()

        tmp_duration = self.duration  #si rien de spécial tmp_duration ==500
        if (c and c.isdigit()):
            tmp_duration = int(self.whole_note_duration / self.getNumber())

        dot_add = tmp_duration / 2
        while (self.currentCharacter() == '.'):
            self.buzzerSequence += 1
            tmp_duration += dot_add
            dot_add = int(dot_add / 2)
            break

        if (self.staccato == True):
            self.staccato_rest_duration = int(tmp_duration / 2)
            tmp_duration = int(tmp_duration - self.staccato_rest_duration)
        print(tmp_duration)
        self.playNote(SILENT_NOTE if (self.rest > 0) else (self.note),
                      int(tmp_duration), self.volume)

        return (self.buzzerSequence < len(self._notes))

    def playMode(self, mode):
        self.play_mode_settings = mode

        if (mode == PLAY_AUTOMATIC):
            self.playCheck()

    def playCheck(self):
        self.nextNote()
        return (self.buzzerSequence != 0)
Example #15
0
aff = Seg7x4(i2c, address=0x70)

f = 750E3  # max = 750 kHz [84Mhz/4/(12+15) = 778 kHz]
nb = 100  # Nombre de points de mesure

pinE = Pin('A2', Pin.OUT)  # Source du circuit RC
adc = ADC(Pin('A3'))  # Activation du CAN
buf = array("h", nb * [0x7FFF])  # h = signed short (int 2 octets)
tim = Timer(6, freq=f)  # Déclaration du timer

while True:
    pinE.on()  # E=Vcc (charge)
    sleep_ms(100)  # Attendre 100 ms
    pinE.off()  # E=0   (décharge)

    adc.read_timed(buf, tim)  # Mesures

    f = tim.freq()  # Fréquence réelle du timer
    x = [i / f * 1E6 for i in range(nb)]  # Tableau des fréquence (µs)
    y = [log(u) for u in buf]  # Tableau des ln(u)

    a, b = linear_reg(y, x)  # Regression linéaire
    C = -a / 10  # Calcul de la capacité
    h = round(1.713 * C - 17.90, 1)

    aff.fill(0)  # Efface l'affichage précédent
    aff.text(str(h))  # Affichage
    aff.show()  # ...

    sleep_ms(1000)  # Temporisation
Example #16
0
        utime.sleep_ms(200)

    if can.any(0):
        get()

    if not (START_BUTTON.value()):
        print("START_BUTTON button:", X_POT.read(), Y_POT.read())
        utime.sleep_ms(200)

    if not (SELECT_BUTTON.value()):
        print("SELECT_BUTTON button")
        BUZZER_FREQ = Timer(3, freq=52)
        buzzer = BUZZER_FREQ.channel(1, Timer.PWM, pin=BUZZER_PIN)
        buzzer.pulse_width_percent(30)
        utime.sleep_ms(100)
        BUZZER_FREQ.freq(200)
        utime.sleep_ms(100)
        BUZZER_FREQ.freq(400)
        utime.sleep_ms(100)
        BUZZER_FREQ.freq(800)
        utime.sleep_ms(100)
        BUZZER_FREQ.freq(1000)
        utime.sleep_ms(100)
        BUZZER_FREQ.freq(1200)
        utime.sleep_ms(100)
        BUZZER_FREQ.freq(1500)
        BUZZER_FREQ.deinit()

    if not (GREEN_BUTTON.value()):
        print("GREEN_BUTTON button")
        utime.sleep_ms(200)
Example #17
0
class PWM(object):
  """docstring for PWMM"""

  #Dict pin name: timer #, channel #.
  PinChannels = {
    'X1': [(2,1), (5,1)],
    'X2': [(2,2), (5,2)],
    'X3': [(2,3), (5,3), (9,1)],
    'X4': [(2,4), (5,4), (9,2)],
    'X6': [(2,1), (8,1)],
    'X7': [(13, 1)],
    'X8': [(1,1), (8,1), (14,1)],
    'X9': [(4,1)],
    'X10': [(4,2)],
    'Y1': [(8,1)],
    'Y2': [(8,2)],
    'Y3': [(4,3), (10,1)],
    'Y4': [(4,4), (11,1)],
    'Y6': [(1,1)],
    'Y7': [(1,2), (8,2), (12,1)],
    'Y8': [(1,3), (8,3), (12,2)],
    'Y9': [(2,3)],
    'Y10': [(2,4)],
    'Y11': [(1,2), (8,2)],
    'Y12': [(1,3), (8,3)]
  }

  class PWMException(Exception):
      def __init__( self, msg ) :
          self.msg = msg

  @staticmethod
  def timerandchannel( pinname, timernum ) :
    try:
      a = PWM.PinChannels[pinname]
      if timernum <= 0:
        return a[0]
      else:
        for v in a:
          if v[0] == timernum:
            return v
    except Exception as e :
      raise PWM.PWMException("Pin {} cannot be used for PWM".format(pinname))

    raise PWM.PWMException("Pin {} cannot use timer {}".format(pinname, timernum))

  def __init__( self, p, timernum, afreq = 100 ) :
    isname = type(p) == str
    pinname = p if isname else p.name()
    timernum, channel = PWM.timerandchannel(pinname, timernum)
    if isname:
      p = Pin(pinname)

    self._timer = Timer(timernum, freq = afreq)
    self._channel = self._timer.channel(channel, Timer.PWM, pin = p)

  @property
  def pulse_width( self ) : return self._channel.pulse_width()

  @pulse_width.setter
  def pulse_width( self, value ) : self._channel.pulse_width(value)

  @property
  def pulse_width_percent( self ) : return self._channel.pulse_width_percent()

  @pulse_width_percent.setter
  def pulse_width_percent( self, value ) : self._channel.pulse_width_percent(value)

  @property
  def freq( self ) : return self._timer.freq()

  @freq.setter
  def freq( self, value ) : self._timer.freq(value)

  def callback( self, value ) :
    self._channel.callback(value)
Example #18
0
from pyb import Pin, Timer
from time import sleep_ms

tim = Timer(3, freq=440)    
pwm = tim.channel(2, Timer.PWM, pin=Pin('D5')) # Y2 pour Pyboard
pwm.pulse_width_percent(50)

for f in [440, 560, 780]:
    tim.freq(f)
    sleep_ms(1000)
    
tim.deinit()
Example #19
0
class pwm(object):
    """Class to help with PWM pin and clock initialization."""

    #Dict pin name: timer #, channel #.
    PinChannels = {
        'X1': [(2, 1), (5, 1)],
        'X2': [(2, 2), (5, 2)],
        'X3': [(2, 3), (5, 3), (9, 1)],
        'X4': [(2, 4), (5, 4), (9, 2)],
        'X6': [(2, 1), (8, 1)],
        'X7': [(13, 1)],
        'X8': [(1, 1), (8, 1), (14, 1)],
        'X9': [(4, 1)],
        'X10': [(4, 2)],
        'Y1': [(8, 1)],
        'Y2': [(8, 2)],
        'Y3': [(4, 3), (10, 1)],
        'Y4': [(4, 4), (11, 1)],
        'Y6': [(1, 1)],
        'Y7': [(1, 2), (8, 2), (12, 1)],
        'Y8': [(1, 3), (8, 3), (12, 2)],
        'Y9': [(2, 3)],
        'Y10': [(2, 4)],
        'Y11': [(1, 2), (8, 2)],
        'Y12': [(1, 3), (8, 3)]
    }

    class PWMException(Exception):
        def __init__(self, msg):
            self.msg = msg

    @staticmethod
    def timerandchannel(pinname, timernum):
        try:
            a = pwm.PinChannels[pinname]
            if timernum <= 0:
                return a[0]
            else:
                for v in a:
                    if v[0] == timernum:
                        return v
        except Exception as e:
            raise pwm.PWMException(
                "Pin {} cannot be used for PWM".format(pinname))

        raise pwm.PWMException("Pin {} cannot use timer {}".format(
            pinname, timernum))

    def __init__(self, aPin, timernum, afreq=100):
        '''aPin may be a pyb.Pin or a pin name.
       timernum must be a number corresponding to the given pin.
       afreq is the frequency for the PWM signal.
    '''
        isname = type(aPin) == str
        pinname = aPin if isname else aPin.name()
        timernum, channel = pwm.timerandchannel(pinname, timernum)
        if isname:
            aPin = Pin(pinname)

        self._timer = Timer(timernum, freq=afreq)
        self._channel = self._timer.channel(channel, Timer.PWM, pin=aPin)

    @property
    def pulse_width(self):
        return self._channel.pulse_width()

    @pulse_width.setter
    def pulse_width(self, value):
        self._channel.pulse_width(value)

    @property
    def pulse_width_percent(self):
        return self._channel.pulse_width_percent()

    @pulse_width_percent.setter
    def pulse_width_percent(self, value):
        self._channel.pulse_width_percent(value)

    @property
    def freq(self):
        return self._timer.freq()

    @freq.setter
    def freq(self, value):
        self._timer.freq(value)

    def callback(self, value):
        self._channel.callback(value)
Example #20
0
# check basic functionality of the timer class

import pyb
from pyb import Timer

tim = Timer(4)
tim = Timer(4, prescaler=100, period=200)
print(tim.prescaler())
print(tim.period())
tim.prescaler(300)
print(tim.prescaler())
tim.period(400)
print(tim.period())

# Setting and printing frequency
tim = Timer(2, freq=100)
print(tim.freq())
tim.freq(0.001)
print(tim.freq())
Example #21
0
from pyb import Pin, Timer

led = Pin('D5', Pin.OUT_PP)  # TIM3, CH2 pour D5 ou Y2
tim = Timer(3, freq=500)  # Timer 3 fixé à 500 Hz
pwm = tim.channel(2, Timer.PWM, pin=led)  # PWM sur la voie 2 du timer 3

pwm.pulse_width_percent(33)  # Lancement du signal - Rapport cyclique = 33%

tim.freq(400)  # Modification de la fréquence
Example #22
0
# check basic functionality of the timer class

import pyb
from pyb import Timer

tim = Timer(4)
tim = Timer(4, prescaler=100, period=200)
print(tim.prescaler())
print(tim.period())
tim.prescaler(300)
print(tim.prescaler())
tim.period(400)
print(tim.period())

# Setting and printing frequency
tim = Timer(2, freq=100)
print(tim.freq())
tim.freq(0.001)
print('{:.3f}'.format(tim.freq()))
Example #23
0
# check basic functionality of the timer class

import pyb
from pyb import Timer

tim = Timer(4)
tim = Timer(4, prescaler=100, period=200)
print(tim.prescaler())
print(tim.period())
tim.prescaler(300)
print(tim.prescaler())
tim.period(400)
print(tim.period())

# Setting and printing frequency
tim = Timer(2, freq=100)
print(tim.freq())
tim.freq(0.001)
print("{:.3f}".format(tim.freq()))
Example #24
0
	display._data(b"\x40")#设为开始输入数据
	s=(b"\xC0")
	for  i in  range(8):
		s+=pack('<H', result[i])
	print(s)
	display._data(s)
	display.disp_on()
	temp=(hours-clk_hours)*3600+(minutes-clk_minutes)*60+(seconds-clk_seconds)*1
	if temp==clk:
		for i in range(16):
			b=rtc.datetime()
			b_hours=b[4]
			b_minutes=b[5]
			b_seconds=b[6]
			print(b_hours,b_minutes,b_seconds)
			tm3.freq(MyScore[i][0])
			show(b_hours,b_minutes,b_seconds)
			display.disp_on()
			display._data(b"\x40")#设为开始输入数据
			clock_s=(b"\xC0")
			for  i in  range(8):
				clock_s+=pack('<H', result[i])
			display._data(clock_s)
			display.disp_on()
			pyb.delay(int(MyScore[i][1]))
			
	pyb.delay(1000)