Beispiel #1
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)
Beispiel #2
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
Beispiel #3
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)
Beispiel #4
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)
Beispiel #5
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)
Beispiel #6
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
#下降沿触发,打开上拉电阻
ext = ExtInt(Pin('P9'), ExtInt.IRQ_FALLING, Pin.PULL_UP, key)

##############################################
#  OLED初始显示
##############################################
oled.fill(0)  # 清屏显示黑色背景
oled.text('01Studio', 0, 0)  # 首行显示01Studio
oled.text('DAC-Beep', 0, 15)  # 次行显示实验名称
oled.text('Pls Press USER', 0, 40)  # 显示当前频率
oled.show()

while True:

    if key_node==1: #按键被按下
        i = i+1
        if i == 4:
            i = 0
        key_node = 0 #清空按键标志位

        #DAC输出指定频率
        dac.write_timed(buf, freq[i]*len(buf), mode=DAC.CIRCULAR)

        #显示当前频率
        oled.fill(0)  # 清屏显示黑色背景
        oled.text('01Studio', 0, 0)  # 首行显示01Studio
        oled.text('DAC-Beep', 0, 15)  # 次行显示实验名称
        oled.text(str(freq[i]) + 'Hz', 0, 40)  # 显示当前频率
        oled.show()
Beispiel #8
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()
import wave
from pyb import DAC
dac = DAC(1)
f = wave.open('/sd/test2.wav')
dac.write_timed(f.readframes(f.getnframes()), f.getframerate())
Beispiel #10
0
        if value > 0 and intensity != maxn:
            LED(2).on()
            LED(3).off()
        elif value < 0 and intensity != minn:
            LED(3).on()
            LED(2).off()
        else:
            LED(2).off()
            LED(3).off()

    while True:
        v1, v2 = y1.value(), y2.value()
        currentStr = str(v1) + str(v2)
        usedStr = oldStr + currentStr
        oldStr = currentStr if directTab.get(usedStr) else oldStr

        additive = 0 if not directTab.get(
            usedStr) else directTab[usedStr] * sensitivity * (maxn -
                                                              minn) / 255
        intensity = limitNums(intensity + additive, maxn, minn)
        light.write_timed(setByte(round(intensity)), 1)

        print('Additive:', additive, 'Value:', intensity, eol='\n')
        handleLEDs(intensity, additive)

except BaseException as errStr:
    f = open('error.txt', 'w')
    f.write(str(errStr))
    f.close()
Beispiel #11
0
def play_wave(file):
    dac = DAC(1)
    f = wave.open(file)
    dac.write_timed(f.readframes(f.getnframes()), f.getframerate())
Beispiel #12
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)
Beispiel #13
0
#Amplitude shift, Change '0.25'
#Range from 0 to 1
buf2 = array('H', 2048 + int(2047 * (0.25*(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 ask():
    #Logic 1 signal
    dac.write_timed(buf, 100 * len(buf), mode=DAC.CIRCULAR)
    pyb.delay(60)
    return

while(1):
    for i in stream:
        if i == 0:
            #Logic 0 signal
            dac.write_timed(buf2, 100 * len(buf2), mode=DAC.CIRCULAR)
            pyb.delay(60)
        else:  
            ask()





			LED(1).off()
			LED(4).off()
		
		if value > 0 and intensity != maxn:
			LED(2).on()
			LED(3).off()
		elif value < 0 and intensity != minn:
			LED(3).on()
			LED(2).off()
		else:
			LED(2).off()
			LED(3).off()

	while True:
		v1, v2 = y1.value(), y2.value()
		currentStr = str(v1) + str(v2)
		usedStr = oldStr + currentStr
		oldStr = currentStr if directTab.get(usedStr) else oldStr

		additive = 0 if not directTab.get(usedStr) else directTab[usedStr] * sensitivity * (maxn - minn)/255
		intensity = limitNums(intensity + additive, maxn, minn)
		light.write_timed(setByte(round(intensity)), 1)

		print('Additive:', additive, 'Value:', intensity, eol = '\n')
		handleLEDs(intensity, additive)

except BaseException as errStr:
	f = open('error.txt', 'w')
	f.write(str(errStr))
	f.close()
#In this script, every ASCII character from text message is
#sent to DAC(1), so that can be created a digital waveform
#author: German Chavarro 23/02/2017

from ubinascii import hexlify
from pyb import DAC
#***********************************************
# DAC parameters configuration
#***********************************************


#***********************************************
#Conversion from text message into single decimal byte#
#***********************************************
msg = 'Hello World'
buf = bytearray(256)
msgHex = hexlify(msg)
	
for c in range(len(msgHex)):
	buf[c] = msgHex[c]

dac = DAC(1, bits=8)
dac.write_timed(buf, 100000 * len(buf), mode=DAC.NORMAL)

print(msg)
print(msgHex)
print(buf)
Beispiel #16
0
class tv:
    def __init__(self,hres=64,progressive=False,lines=None,linetime=64,buf=None):
        if lines == None:
            lines = 262 if progressive else 525
        self.lines = lines
        if buf == None:
            if progressive:
                self.buf = bytearray(262*hres)
            else:
                self.buf = bytearray(525*hres)
        else:
            self.buf = buf
        self.hres = hres
        self.line_time = linetime
        self.progressive = progressive
        
        self.sync_level = 0
        self.blanking_level = 56
        self.black_level = 58
        self.white_level = 73

        self.phase = 0
        self.buffer_dac = True
        self.reinit()
    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)
    def reinit(self):
        self.calc_porch_magic_numbers()
        self.init()
    def set_progressive(self,prog=True):
        self.progressive = prog
        self.calc_porch_magic_numbers()
        self.init()
    
    def __len__(self):
        return self.hres*self.lines
    def calc_porch_magic_numbers(self):
        br = self.hres/self.line_time

        w = round(4.7*br)
        t = int(10.9*br+0.9)#round mostly up
        s = round(1.5*br)
        self.h_blank = [s,s+w,t]
        self.v_blank_e = [6,12,18]
        self.v_blank_o = [6,12,19]

        hsl = round(18*br)
        hsh = round(58*br)
        
        self.h_safe = [hsl-t,hsh-t]
        self.v_safe = [32*(2-self.progressive),208*(2-self.progressive)]
        
    def init(self):
        self.carrier = Pin('X1') 
        self.tim = Timer(2, prescaler=1,period=1)
        self.ch = self.tim.channel(1, Timer.PWM, pin=self.carrier)
        self.ch.pulse_width(1)

        self.redac()
        
        self.be = self.bmv
        if not self.progressive:
            self.bo = self.be[len(self)//2:]
        self.fb = framebuf.FrameBuffer(self.buf,self.hres,self.lines,framebuf.GS8)
        self.fbe_mv = self.be[self.hres*21+self.h_blank[2]:]
        if not self.progressive:
            self.fbo_mv = self.bo[self.hres*43//2+self.h_blank[2]:]
        h = self.y_dim()//(2-self.progressive)
        self.fbe = framebuf.FrameBuffer(self.fbe_mv,self.hres-self.h_blank[2],h,framebuf.GS8,self.hres)
        if not self.progressive:
            self.fbo = framebuf.FrameBuffer(self.fbo_mv,self.hres-self.h_blank[2],h,framebuf.GS8,self.hres)
        self.clear()

    def set_pixel(self,x,y,v):
        if self.progressive:
            self.fbe.pixel(x,y,int(v*(self.white_level-self.black_level)+self.black_level))
        else:
            [self.fbe,self.fbo][y&1].pixel(x,y//2,int(v*(self.white_level-self.black_level)+self.black_level))
    def get_pixel(self,x,y):
        if self.progressive:
            return (self.fbe_mv[x+y*self.hres]-self.black_level)/(self.white_level-self.black_level)
        else:
            return ([self.fbe_mv,self.fbo_mv][y&1][x+(y//2)*self.hres]-self.black_level)/(self.white_level-self.black_level)
    def set_carrier(self,pre=1,per=1,w=1):
        self.tim.init(prescaler=pre,period=per)
        self.ch.pulse_width(w)
    def clear(self):
        self.fb.fill(self.black_level)
        self.syncs()
    def syncs(self):
        self.fb.fill_rect(0,0,self.h_blank[2],self.lines,self.blanking_level)
        self.fb.fill_rect(self.h_blank[0],0,self.h_blank[1]-self.h_blank[0],self.lines,self.sync_level)
        for y in range(self.v_blank_e[2]):
            inv = self.v_blank_e[0] <= y < self.v_blank_e[1]
            for x in range(self.hres//2):
                val = self.blanking_level
                if (self.h_blank[0] <= x < self.h_blank[1]) ^ inv:
                    val = self.sync_level
                self.buf[y*self.hres//2+x] = val
        if not self.progressive:
            for y in range(self.v_blank_o[2]):
                inv = self.v_blank_o[0] <= y < self.v_blank_o[1]
                for x in range(self.hres//2):
                    val = self.blanking_level
                    if (self.h_blank[0] <= x < self.h_blank[1]) ^ inv:
                        val = self.sync_level
                    self.bo[y*self.hres//2+x] = val
    def x_dim(self):
        return self.hres-self.h_blank[2]
    def y_dim(self):
        return self.lines-(21 if self.progressive else 43)
    
    def mandelbrot(self,imax=8,p=0,s=2,julia=False,il=0,x0=None,y0=None,x1=None,y1=None,asm=True,julia_seed=0):
        
        x0 = self.h_safe[0] if x0 == None else x0
        x1 = self.h_safe[1] if x1 == None else x1
        y0 = self.v_safe[0] if y0 == None else y0
        y1 = self.v_safe[1] if y1 == None else y1
        
        for x in range(x0,x1):
            for y in range(y0,y1):
                c = (((x-x0)/(x1-x0-1)-.5)*2 + ((y-y0)/(y1-y0-1)-.5)*2j)*s+p
                z = c
                if julia:
                    c = julia_seed
                if asm:
                    i = a_mandelbrot(z,c,imax)
                else:
                    for i in range(imax):
                        if z.real*z.real+z.imag*z.imag > 4:
                            break
                        z = z*z+c
                    else:
                        self.set_pixel(x,y,il)
                        continue
                if i == -1:
                    self.set_pixel(x,y,il)
                else:
                    self.set_pixel(x,y,i/imax)
    def demo(self,x0=None,y0=None,x1=None,y1=None):

        x0 = self.h_safe[0] if x0 == None else x0
        x1 = self.h_safe[1] if x1 == None else x1
        w = x1-x0
        y0 = self.v_safe[0] if y0 == None else y0
        y1 = self.v_safe[1] if y1 == None else y1
        h = y1-y0
        
        mx = x0
        my = y0
        import pyb
        import time
        acc = pyb.Accel()
        btn = pyb.Switch()
        p = self.get_pixel(int(mx),int(my))
        pos = 0
        zoom = 2
        it = 16
        julia = False
        jp = 0
        self.mandelbrot(it,pos,zoom,julia,0,x0,y0,x1,y1,julia_seed=jp)

        def paddles(c):
            x = int(mx-.125*w)
            xw = w//4
            y = int(my-.125*h)
            yw = h//4
            y_0 = y0
            y_1 = y1
            if not self.progressive:
                y //= 2
                yw //= 2
                y_0 //= 2
                y_1 //= 2
            self.fbe.hline(x,y_0,xw,c)
            self.fbe.vline(x0,y,yw,c)
            self.fbe.hline(x,y_1,xw,c)
            self.fbe.vline(x1,y,yw,c)
            if not self.progressive:
                self.fbo.hline(x,y_0,xw,c)
                self.fbo.vline(x0,y,yw,c)
                self.fbo.hline(x,y_1,xw,c)
                self.fbo.vline(x1,y,yw,c)
        
        while 1:
            paddles(self.black_level)
            mx = min(x1-2,max(x0,mx*.98+(-acc.x()/24+.5)*w*.02))
            my = min(y1-2,max(y0,my*.98+(acc.y()/24+.5)*h*.02))
            paddles(self.white_level)
            p = self.get_pixel(int(mx),int(my))
            self.set_pixel(int(mx),int(my),(p+.5)%1)
            pyb.delay(10)
            self.set_pixel(int(mx),int(my),p)
            if btn():
                st = time.ticks_ms()
                nit = it*2
                while btn():
                    if time.ticks_diff(time.ticks_ms(),st) > 1000:
                        if acc.z()>0:
                            nit = it*2
                        else:
                            nit = "Julia"
                        self.fbe.fill_rect(x0,y0,w,10,self.black_level)
                        if not self.progressive:
                            self.fbo.fill_rect(x0,y0,w,10,self.black_level)
                        self.fbe.text(str(nit),x0+1,y0+1,self.white_level)
                        if not self.progressive:
                            self.fbo.text(str(nit),x0+1,y0+1,self.white_level)
                cp = (((mx-x0)/w-.5)*2+2j*((my-y0)/h-.5))*zoom
                if time.ticks_diff(time.ticks_ms(),st) > 1000:
                    if nit == "Julia":
                        julia ^= 1
                        jp = pos + cp
                        pos = 0
                        zoom = 2
                        it = 16
                    else:
                        it = nit
                else:
                    pos += cp
                    zoom *= .25
                self.mandelbrot(it,pos,zoom,julia,0,x0,y0,x1,y1,julia_seed=jp)
Beispiel #17
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)
Beispiel #18
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)
Beispiel #19
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()

    for position in range(0, total_frames, framerate):
Beispiel #20
0
class magCtrl():
    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

    def next(self, t):
        self.new_block = True
        if not self.end_flg:
            freq = self.freqs[self.fre_indx]
            s, self.stimulus_level, buf = self.bufs[self.buf_indx]
            self.boardctrl.update(self.stimulus_level)
            print('new trial:', s, 'pT ', freq, 'Hz')

            self.buf_indx += 1
            if self.buf_indx == self.buf_len:
                self.buf_indx = 0
                self.fre_indx += 1
                if self.fre_indx == self.fre_len:
                    self.fre_indx = 0
                    self.rcount += 1
                    if self.rcount == self.repeat:
                        self.end_flg = True

            self.timer.deinit()
            self.dac.write_timed(buf, self.timer,
                                 mode=DAC.CIRCULAR)  #启动定时器,写DAC
            self.timer.init(freq=freq * len(buf))
            self.sync.falling_edge()  # 发送同步信号