示例#1
0
	def luminance(self, mode):
		"""Sample luminance (in lux), using specified sensor mode."""
		# continuous modes
		if mode & 0x10 and mode != self.mode:
			self.set_mode(mode)
		# one shot modes
		if mode & 0x20:
			self.set_mode(mode)
		# earlier measurements return previous reading
		if mode in (0x13, 0x23):
			time.sleep_ms(24)
		else:
			time.sleep_ms(180)
		data = self.bus.recv(16,addr=self.addr)
		if mode in (0x11, 0x21):
			factor = 2.0
		else:
			factor = 1.0
		
		print ((data[0]<<8 | data[1]) / (1.2 * factor))
		buf = bytearray(16)
		for i in range(len(data)):
			buf[i]=data[i]
		
		print(buf)
		# output the sine-wave at 400Hz
		dac = DAC(1)
		dac.write_timed(buf, 400 * len(buf), mode=DAC.CIRCULAR)
示例#2
0
 def redac(self):
     self.dac = DAC(Pin('X5'),buffering=self.buffer_dac)
     self.bmv = memoryview(self.buf)[:len(self)]
     self.dac_tim = Timer(6, freq=int(self.hres*1000000/self.line_time))
     self.dac.write_timed(self.bmv,self.dac_tim,mode=DAC.CIRCULAR)
     self.frame_tim = Timer(5, prescaler=self.dac_tim.prescaler(),period=self.dac_tim.period()*len(self))
     self.frame_tim.counter(self.phase)
示例#3
0
class caliMagCtrl1():
    def __init__(self, amps=[], freqs=[], bufs=[], ch=1):
        # amps: 幅值序列
        # bufs: 对应幅值的正弦序列

        self.timer = Timer(6)
        self.dac = DAC(ch, bits=12)
        self.amps = amps
        self.bufs = bufs

        self.freqs = freqs
        self.indx = range(len(amps))
        self.newtask = False

    def next(self):
        ind = self.indx.pop(0)
        self.indx.append(ind)

        self.amp = self.amps[ind]
        buf = self.bufs[ind]
        self.freq = self.freqs[ind]

        if self.amp == 0:
            self.timer.deinit()
            self.dac.write(0)
        else:
            self.dac.write_timed(buf, self.timer, mode=DAC.CIRCULAR)
            self.timer.init(freq=self.freq * len(buf))

        self.newtask = True
示例#4
0
class caliMagCtrl():
    def __init__(self, buf=array('H', [100]), ch=1):
        self.timer = Timer(6)
        self.dac = DAC(ch, bits=12)
        self.buf = buf
        self.dac_on = 0

    def reset_buf(self, buf):
        self.buf = buf

    def start(self, freq=10):
        self.dac.write_timed(self.buf, self.timer, mode=DAC.CIRCULAR)
        self.timer.init(freq=freq * len(self.buf))
        self.dac_on = 1

    def stop(self):
        self.timer.deinit()
        self.dac.write(0)
        self.dac_on = 0

    def toggle(self, freq=5):
        if self.dac_on:
            self.stop()
        else:
            self.start(freq)
示例#5
0
def beep(delay=500):
    dac = DAC(1)
    buf = bytearray(100)
    for i in range(len(buf)):
        buf[i] = 128 + int(127 * math.sin(2 * math.pi * i / len(buf)))

    dac.write_timed(buf, 5000, mode=DAC.CIRCULAR)
    pyb.delay(1000)
示例#6
0
def tone1(freq):
    t0 = micros()
    dac = DAC(1)
    while True:
        theta = 2*math.pi*float(elapsed_micros(t0))*freq/1e6
        fv = math.sin(theta)
        v = int(126.0 * fv) + 127
        #print("Theta %f, sin %f, scaled %d" % (theta, fv, v))
        #delay(100)
        dac.write(v)
示例#7
0
    def __init__(self, amps=[], freqs=[], bufs=[], ch=1):
        # amps: 幅值序列
        # bufs: 对应幅值的正弦序列

        self.timer = Timer(6)
        self.dac = DAC(ch, bits=12)
        self.amps = amps
        self.bufs = bufs

        self.freqs = freqs
        self.indx = range(len(amps))
        self.newtask = False
示例#8
0
class OutputToDue(object):
    def __init__(self, op_pin):
        self.pin = op_pin
        self.dac_output = DAC(op_pin)

    # setting transportting:
    # range of number: 0 - 255 !!!
    def write_message(self, number):
        if number > 150:
            number = 150
        elif number < 3:
            number = 0
        self.dac_output.write(int(number))
示例#9
0
def play_wav(filename, chunksize=3096, freq=44100):
    dac = DAC(1)
    delay_ms = int(chunksize / (freq / 1000000))
    micros = pyb.Timer(2, prescaler=83, period=0x3fffffff)
    start = time.time()
    with open(filename, "rb") as wav:
        chunk = wav.read(chunksize)
        buf = bytearray(chunk)
        while chunk:
            micros.counter(0)
            dac.write_timed(buf, freq, mode=DAC.NORMAL)
            chunk = wav.read(chunksize)
            buf = bytearray(chunk)
            while micros.counter() < delay_ms:
                pyb.wfi()

    dac = DAC(1)
    print (time.time() - start)
    def __init__(self):
        self.p_SICL = Pin(config.SICL, Pin.OUT_PP)
        self.p_SIBL = Pin(config.SIBL, Pin.OUT_PP)
        self.p_CK = Pin(config.CK, Pin.OUT_PP)
        self.p_LAT = Pin(config.LAT, Pin.OUT_PP)
        self.p_CH = Pin(config.CH, Pin.OUT_PP)
        self.p_NCHG = Pin(config.NCHG, Pin.OUT_PP)

        self.p_LAT.value(0)
        self.p_NCHG.value(0)

        self.dac = DAC(1)
        self.dac.write(127)

        waveform = config.WAVEFORM
        factor = max(waveform)
        for i in range(len(waveform)):
            waveform[i] = int(255*(waveform[i]/factor))
        self.waveform = array('i', waveform)
示例#11
0
    def __init__(self, freqs=[], bufs=[], ch=1, **kwargs):
        # freqs:待测试的频率
        # bufs: 对应幅值的正弦序列等消息,每个元素包含(amp,buf,port)
        # 其中port是指,使用可变电阻时对应控制的端口
        # ch:测试信号输出端口选择
        # kwargs: r_port,电阻选择的端口列表

        self.timer = Timer(6)
        self.dac = DAC(ch, bits=12)
        self.freqs = freqs
        self.bufs = bufs
        self.r_adapt = False
        if len(kwargs) > 0:
            if 'r_port' in kwargs:  #使用电阻自适应调整
                self.r_adapt = True
                (pyb.Pin(pin, pyb.Pin.OUT_PP) for pin in kwargs['r_port'])

        self.freqs = freqs
        self.indx = range(len(amps))
        self.newtask = False
示例#12
0
    def __init__(self,
                 bufs,
                 freqs,
                 DAC_ch,
                 sync,
                 BoardCtrl,
                 repeat=50,
                 timer_num=6):
        '''
        bufs: list, DAC output array
        typ: list, the same length with bufs, 'tiny','big','cut' to describe which type of the buf
        freqs: list, tested frequences
        ch: DAC output channel, 1: 'X5'  2: 'X6'
        sync: object for output synchronus signal to record client
        resistset: object for adjusting resist according to the magnet strength
        timer: internal timer, default 6
        '''

        self.bufs = bufs
        self.freqs = freqs

        if DAC_ch == 'X5':
            self.dac = DAC(1, bits=12)
        elif DAC_ch == 'X6':
            self.dac = DAC(2, bits=12)
        else:
            raise ValueError('DAC pin should be X5 or X6')

        self.sync = sync
        self.boardctrl = BoardCtrl
        self.timer = Timer(timer_num)
        self.buf_indx = 0
        self.fre_indx = 0
        self.fre_len = len(self.freqs)
        self.buf_len = len(self.bufs)
        self.repeat = repeat
        self.rcount = 0
        self.end_flg = False
        self.new_block = False
        self.stimulus_level = 0
示例#13
0
class caliMagCtrl2():
    def __init__(self, freqs=[], bufs=[], ch=1, **kwargs):
        # freqs:待测试的频率
        # bufs: 对应幅值的正弦序列等消息,每个元素包含(amp,buf,port)
        # 其中port是指,使用可变电阻时对应控制的端口
        # ch:测试信号输出端口选择
        # kwargs: r_port,电阻选择的端口列表

        self.timer = Timer(6)
        self.dac = DAC(ch, bits=12)
        self.freqs = freqs
        self.bufs = bufs
        self.r_adapt = False
        if len(kwargs) > 0:
            if 'r_port' in kwargs:  #使用电阻自适应调整
                self.r_adapt = True
                (pyb.Pin(pin, pyb.Pin.OUT_PP) for pin in kwargs['r_port'])

        self.freqs = freqs
        self.indx = range(len(amps))
        self.newtask = False

    def next(self):
        ind = self.indx.pop(0)
        self.indx.append(ind)

        self.amp = self.amps[ind]
        buf = self.bufs[ind]
        self.freq = self.freqs[ind]

        if self.amp == 0:
            self.timer.deinit()
            self.dac.write(0)
        else:
            self.dac.write_timed(buf, self.timer, mode=DAC.CIRCULAR)
            self.timer.init(freq=self.freq * len(buf))

        self.newtask = True
示例#14
0
 def __init__(self, dac=DAC(1), timerno=4):
     global lwr
     lwr = self
     self._f = None
     self._rate = 0
     self._amount = 0
     self._freq = 4  # in Hertz
     self._dac = dac
     self._have = [False, False]
     self._buf = [None, None]
     self._doneindex = 0
     self._speed = 100
     self._timer = pyb.Timer(timerno, freq=self._freq)
     self._running = False
     self._fill()
示例#15
0
def pins_test():
    i2c = I2C(1, I2C.MASTER)
    spi = SPI(2, SPI.MASTER)
    uart = UART(3, 9600)
    servo = Servo(1)
    adc = ADC(Pin.board.X3)
    dac = DAC(1)
    pin = Pin('X4', mode=Pin.AF_PP, af=Pin.AF3_TIM9)
    pin = Pin('Y1', mode=Pin.AF_OD, af=3)
    pin = Pin('Y2', mode=Pin.OUT_PP)
    pin = Pin('Y3', mode=Pin.OUT_OD, pull=Pin.PULL_UP)
    pin.high()
    pin = Pin('Y4', mode=Pin.OUT_OD, pull=Pin.PULL_DOWN)
    pin.high()
    pin = Pin('X18', mode=Pin.IN, pull=Pin.PULL_NONE)
    pin = Pin('X19', mode=Pin.IN, pull=Pin.PULL_UP)
    pin = Pin('X20', mode=Pin.IN, pull=Pin.PULL_DOWN)
    print('===== output of pins() =====')
    pins()
    print('===== output of af() =====')
    af()
示例#16
0
from pyb import DAC
from array import array
import math

dac = DAC(1, bits=12, buffering=True)   # use 12 bit resolution
dac.write(4095)         # output maximum value, 3.3V


# To output a continuous sine-wave at 12-bit resolution:
# create a buffer containing a sine-wave, using half-word samples
buf = array("H", 2048 + int(2047 * math.sin(2 * math.pi * i / 128)) for i in range(128))

# output the sine-wave at 200Hz
dac.write_timed(buf, 200 * len(buf), mode=DAC.CIRCULAR)
示例#17
0
 def __init__(self, buf=array('H', [100]), ch=1):
     self.timer = Timer(6)
     self.dac = DAC(ch, bits=12)
     self.buf = buf
     self.dac_on = 0
try:
	from pyb import DAC
	from pyb import LED
	from pyb import Pin
	from pyb import USB_VCP
	
	sensitivity, maxn, minn = .5, 255, 0
	
	com = USB_VCP()
	light = DAC(2)
	y1, y2, y3 = Pin('Y1', Pin.IN), Pin('Y2', Pin.IN), Pin('Y3', Pin.IN)
	intensity, oldStr = maxn, str(y1.value()) + str(y2.value())
	
	directTab = {
	'1000' : 1,
	'0001' : 1,
	'0111' : 1,
	'1110' : 1,
	'1011' : -1,
	'1101' : -1,
	'0100' : -1,
	'0010' : -1
	}
	
	
	def setByte(i):
		return i.to_bytes(1)

	
	def limitNums(num, maxn, minn):
		return max(minn, min(maxn, num))
示例#19
0
sensor.set_auto_gain(False) # must be turned off for color tracking
sensor.set_auto_whitebal(False) # must be turned off for color tracking
clock = time.clock()

# Only blobs that with more pixels than "pixel_threshold" and more area than "area_threshold" are
# returned by "find_blobs" below. Change "pixels_threshold" and "area_threshold" if you change the
# camera resolution. "merge=True" must be set to merge overlapping color blobs for color codes.

while(True):
    clock.tick()
    img = sensor.snapshot()
    for blob in img.find_blobs([thresholds[1]], pixels_threshold=100, area_threshold=100, merge=True):
            img.draw_rectangle(blob.rect())
            img.draw_cross(blob.cx(), blob.cy())
            img.draw_string(blob.x() + 2, blob.y() + 2, "verde")
            dac = DAC('P6')#Select pin whit DAC or ADC
            dac.write(255)  # output between 0 and 255
    for blob in img.find_blobs([thresholds[0]], pixels_threshold=100, area_threshold=100, merge=True):
            img.draw_rectangle(blob.rect())
            img.draw_cross(blob.cx(), blob.cy())
            img.draw_string(blob.x() + 2, blob.y() + 2, "rojo")
            dac = DAC('P6')#Select pin whit DAC or ADC
            dac.write(100)  # output between 0 and 255
    for blob in img.find_blobs([thresholds[2]], pixels_threshold=100, area_threshold=100, merge=True):
            img.draw_rectangle(blob.rect())
            img.draw_cross(blob.cx(), blob.cy())
            img.draw_string(blob.x() + 2, blob.y() + 2, "amarillo")
            dac = DAC('P6')#Select pin whit DAC or ADC
            dac.write(50)  # output between 0 and 255
    print(clock.fps())
示例#20
0
tim = Timer(2, freq=1000)
ch = Timer.channel(1, Timer.PWM, pin=p)
ch.pulse_width_percent(50)
'''
1.9 ADC
'''
from pyb import Pin, ADC

adc = ADC(Pin('X19'))
adc.read()  # read value, 0 - 4095
'''
1.10 DAC
'''
from pyb import Pin, DAC

dac = DAC(Pin('X5'))
dac.write(120)  # output between 0 and 255
'''
1.11 UART
'''
from pyb import UART

uart1 = UART(1, 9600)
uart1.write('hello')
uart1.read(5)  # read up to 5 bytes
'''
1.12 SPI Bus
'''
from pyb import SPI

spi1 = SPI(1, SPI.MASTER, baudrate=200000, polarity=1, phase=0)
from pyb import DAC
sa1 = DAC(1)
sa1.triangle(400*2048)
import pyb
import random
from pyb import DAC


def volume(val):
    pyb.I2C(1, pyb.I2C.MASTER).mem_write(val, 46, 0)


volume(127)
dac = DAC(1)
while True:
    dac.write(random.randint(0, 256))
示例#23
0
文件: main.py 项目: blmorris/Myriad2
        return ((sensor.read()/2552.3)**(1/-1.045))*12
    elif unit == 'cm':
        return ((sensor.read()/2552.3)**(1/-1.045))*30.48
    else:
        return (sensor.read()/2552.3)**(1/-1.045)


# decrease volume as object gets closer
def v_change_dis():
    return 255-int((sensor.read()) >> 4)
    # you can get rid of "255-" to make it do the opposite
# volume control

tim = Timer(1)
tim.init(freq=20)
dac = DAC(1)
pot = ADC('B0')
# tim.callback(lambda t: dac.write(int(pot.read()>>4)))
tim.callback(lambda t: dac.write(v_change_dis()))
# GPIO test

gpio = pyb.Pin('A13', pyb.Pin.OUT_PP)
gpio.high()
pyb.delay(10)
gpio.low()
pyb.delay(10)
gpio.high()
pyb.delay(10)
'''
class stat:
    def __init__(self):
示例#24
0
import math
import pyb
from array import array
from pyb import DAC

#NOTE: For frequencies less than 100Hz change delay to 1000ms

#Buffer containing sine wave 
buf = array('H', 2048 + int(2047 * math.sin(2 * math.pi * i /256)) for i in range(256))

#X5 on Pyboard
dac = DAC(1, bits=12)

#Simulates a stream of Data
stream = (0,1,0,1,1,1)

def fsk():
    #Mark Frequency (Fm), Logic 1
    dac.write_timed(buf, 500 * len(buf), mode=DAC.CIRCULAR)
    pyb.delay(60)
    return


while(1):
    for i in stream:
        if i == 0:
            #Space Frequency (Fs), Logic 0
            dac.write_timed(buf, 100 * len(buf), mode=DAC.CIRCULAR)    
            pyb.delay(60)
        else:  
            fsk()
示例#25
0
# DAC Control Example
#
# This example shows how to use the DAC pin output onboard your OpenMV Cam.

import time
from pyb import DAC

dac = DAC("P6") # Must always be "P6".

while(True):
    # The DAC has 8-12 bits of resolution (default 8-bits).
    for i in range(256):
        dac.write(i)
        time.sleep_ms(20)
    for i in range(256):
        dac.write(255-i)
        time.sleep_ms(20)
示例#26
0
#import numpy as np
#import commpy.channelcoding.convcode as cc
#from commpy.utilities import dec2bitarray
import binascii
from pyb import DAC
import utime

#***********************************************
# DAC parameters configuration
#***********************************************
dac = DAC(1, bits=8)

#***********************************************
#Conversion from text message into single decimal byte#
#***********************************************
msg = 'Hello World'
#Ascci converted to hex and then to dec
for s in range(len(msg)):
    msg_dec = int(binascii.hexlify(msg[s]), 16)
    dac.write(msg_dec)
    #pyb.delay(50)

print(msg)
print(msg_dec)
示例#27
0
def tone6(freq, wavefun=lambda x: math.sin(2.0*math.pi*x), l_buf=256, dacnum=1):
    dac = DAC(dacnum)
    dt = 1.0 / l_buf
    scale = lambda fv: int(123 * fv) + 127
    buf = bytearray(scale(wavefun(t*dt)) for t in range(l_buf))
    dac.write_timed(buf, freq * l_buf, mode=DAC.CIRCULAR)
示例#28
0
def tone4(freq, l_buf=256):
    dac = DAC(1)
    dtheta = 2 * math.pi / l_buf
    scale = lambda fv: int(123 * fv) + 127
    buf = bytearray(scale(math.sin(dtheta*t)) for t in range(l_buf))
    dac.write_timed(buf, freq * l_buf, mode=DAC.CIRCULAR)
示例#29
0
import math
from pyb import DAC

# create a buffer containing a sine-wave
buf = bytearray(100)
for i in range(len(buf)):
    buf[i] = 128 + int(127 * math.sin(2 * math.pi * i / len(buf)))

# output the sine-wave at 400Hz
dac = DAC(1)
dac.write_timed(buf, pyb.Timer(8, freq=200000 * len(buf)), mode=DAC.CIRCULAR)
示例#30
0
# DAC Control Example
#
# This example shows how to use the DAC pin output onboard your OpenMV Cam.

import time
from pyb import DAC

dac = DAC("P6") # Must always be "P6".

while(True):
    # The DAC has 8-12 bits of resolution (default 8-bits).
    for i in range(256):
        dac.write(i)
        time.sleep(20)
    for i in range(256):
        dac.write(255-i)
        time.sleep(20)
示例#31
0
import pyb, math
from array import array
import uio
from pyb import Pin, ADC, DAC
import time

tim = pyb.Timer(6, freq=10)

#buf = array('u',range(128))
# create a buffer containing a sine-wave, using half-word samples
buf_dac = array(
    'H', 2048 + int(2047 * math.sin(2 * math.pi * i / 128))
    for i in range(128))
buf_adc = array('H', range(128))

# output the sine-wave at 400Hz
dac = DAC(1, bits=12)
dac.write_timed(buf_dac, 128, mode=DAC.CIRCULAR)
adc = pyb.ADC(Pin('Y12'))  # create an analog object from a pin
adc.ADCALL(bits=12)
adc.read_timed(buf_adc, tim)

file = uio.open('3.txt', mode='w')
file.write('DAC')
file.write(str(buf_dac))
file.write('ADC')
file.write(str(buf_adc))
file.close()
示例#32
0
try:
    from pyb import DAC
    from pyb import LED
    from pyb import Pin
    from pyb import USB_VCP

    sensitivity, maxn, minn = .5, 255, 0

    com = USB_VCP()
    light = DAC(2)
    y1, y2, y3 = Pin('Y1', Pin.IN), Pin('Y2', Pin.IN), Pin('Y3', Pin.IN)
    intensity, oldStr = maxn, str(y1.value()) + str(y2.value())

    directTab = {
        '1000': 1,
        '0001': 1,
        '0111': 1,
        '1110': 1,
        '1011': -1,
        '1101': -1,
        '0100': -1,
        '0010': -1
    }

    def setByte(i):
        return i.to_bytes(1)

    def limitNums(num, maxn, minn):
        return max(minn, min(maxn, num))

    def handleLEDs(intensity, value):
示例#33
0
#import numpy as np
#import commpy.channelcoding.convcode as cc
#from commpy.utilities import dec2bitarray
import binascii
from pyb import DAC
import utime

#En esta prueba se crea un arreglo predefinido
#con decimales del 0 al 255 y se envia cada
#elemento del arreglo al DAC(1)
#***********************************************
# DAC parameters configuration
#***********************************************
dac = DAC(1, bits=8)
#***********************************************
#Conversion from text message into single decimal byte#
#***********************************************
msg = bytearray([
    255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255,
    0, 0, 255, 255, 0, 0
])
#msg = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255])

#Ascci converted to hex and then to dec
for s in range(len(msg)):
    #msg_dec = int(binascii.hexlify(msg[s]), 16)
    dac.write(msg[s])

print(msg)
print(len(msg))
示例#34
0
#>>> volume(0)   # minimum volume
#>>> volume(127) # maximum volume

#To play a sound, use the write_timed method of the DAC object. For example:

import math
from pyb import DAC

# create a buffer containing a sine-wave
buf = bytearray(100)
for i in range(len(buf)):
    buf[i] = 128 + int(127 * math.sin(2 * math.pi * i / len(buf)))

# output the sine-wave at 400Hz
dac = DAC(1)
dac.write_timed(buf, 400 * len(buf), mode=DAC.CIRCULAR)

# or playing a wave file from the SD Card

import wave
from pyb import DAC
from pyb import delay
dac = DAC(1)


def play(filename):
    f = wave.open(filename, 'r')
    total_frames = f.getnframes()
    framerate = f.getframerate()
示例#35
0
from pyb import DAC
from pyb import LED
import math

# Turn on the light so you know something is happening
led = LED(4)
led.on()

# Write out a sinusoidal curve to channel X5, which is wired via a
# female-female jumper to X2
# --
# create a buffer containing a sine-wave, using half-word samples
buf = array(
    'H', 2048 + int(2047 * math.sin(2 * math.pi * i / 128))
    for i in range(128))
dac = DAC(1, bits=12)  # Wired to X5
dac.write_timed(buf, 400 * len(buf), mode=DAC.CIRCULAR)

# Instatiate the USB serial object
u = USB_VCP()

u.write('Hello world!!')

# Enter into an infinite loop
while True:

    # Get a line from the serial connection
    line = u.readline()

    # If there is nothing, line will be None
    if not line is None and line:
示例#36
0
'''
import pyb, time
from pyb import LED, DAC, ADC, Pin, Timer
from oled_938 import OLED_938
from mpu6050 import MPU6050
from motor import MOTOR
from g24_pid_controller import PIDC
from array import array
from mic import MICROPHONE
from g24_choreo_functions import *
import micropython
micropython.alloc_emergency_exception_buf(100)


# Define ports, pins and peripherals
a_out = DAC(1, bits=12)
pot = ADC(Pin('X11'))
b_LED = LED(4)

# IMU connected to X9 and X10
imu = MPU6050(1, False)

# Use OLED to say what it is doing
oled = OLED_938(pinout={'sda': 'Y10', 'scl': 'Y9', 'res': 'Y8'}, height=64, external_vcc=False, i2c_devid=61)
oled.poweron()
oled.init_display()
oled.draw_text(0, 0, 'Group 24')
oled.draw_text(0,10, 'Balance & Dance')
oled.draw_text(0,20, 'Press USR button')
oled.display()
示例#37
0
版本:v1.0
日期:2019.9
作者:01Studio
说明:通过KEY按键让DAC输出不同频率的方波来驱动蜂鸣器。
'''

#导入相关模块
from pyb import DAC,ExtInt
from machine import Pin,I2C
from ssd1306x import SSD1306_I2C

#初始化相关模块
i2c = I2C(sda=Pin("P0"), scl=Pin("P2"),freq=80000)
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)

dac = DAC(Pin("P6"))     #定义DAC对象名字为dac,输出引脚为P6

#定义4组频率值:1Hz、200Hz、1000Hz、5000Hz
freq=[1,200,1000,5000]

# 定义8位精度下方波的值。0、255分别对应输出0V、3.3V。需要定义成字节数组。
buf = bytearray(2)
buf[0]=0
buf[1]=255

key_node = 0  #按键标志位
i = 0         #用于选择频率数组

##############################################
#  按键和其回调函数
##############################################
示例#38
0
state = 'front'
control_dict = {
    "__START__": 1000,
    "__SPEED15__": 1001,
    "__SPEED20__": 1002,
    "__SPEED25__": 1003,
    "__STATUSUPDATE__": 1004,
    "__TURNRIGHT__": 2500,
    "__TURNLEFT__": 1500,
    "__BREAK__": 4000,
    "__SET__": 6000,
    "__RESETPIBOARD__": 5000
}  #Here __RESETPIBOARD__ is to stop the vehicle (ie., to set DAC=0)
# ------- Complex--------#
tim = pyb.Timer(10, freq=10)  #timer
dacA, dacB = DAC(1, bits=12), DAC(2, bits=12)  #DAC Initialization
pidL = PID.PID(45, 0, 90)  #PID
pidR = PID.PID(40, 0, 80)
# -------- PINS---------#
#Y1,Y2,Y3 are for ExtInt
motor_relay_L = Pin(
    'Y4',
    Pin.OUT_PP)  #relay for brakes; connected in a normally open connection
motor_relay_R = Pin('Y5', Pin.OUT_PP)
motor1_switch = Pin(
    'Y6', Pin.OUT_PP)  #Relay for DAC; connected in a normally open connection
motor2_switch = Pin('Y7', Pin.OUT_PP)
motor_L_brake = Pin('X9', Pin.OUT_PP)  #regenerative braking
motor_R_brake = Pin('X10', Pin.OUT_PP)

#############################################################################################################
示例#39
0
def play_wave(file):
    dac = DAC(1)
    f = wave.open(file)
    dac.write_timed(f.readframes(f.getnframes()), f.getframerate())