importimage,audio,timefromulabimportnumpyasnpfromulabimportscipyasspCHANNELS=1FREQUENCY=32000N_SAMPLES=32ifFREQUENCY==16000else64SCALE=2SIZE=(N_SAMPLES*SCALE)//CHANNELSraw_buf=Nonefb=image.Image(SIZE+(50*SCALE),SIZE,image.RGB565,copy_to_fb=True)audio.init(channels=CHANNELS,frequency=FREQUENCY,gain_db=16)defaudio_callback(buf):# NOTE: do Not call any function that allocates memory.globalraw_bufif(raw_buf==None):raw_buf=buf# Start audio streamingaudio.start_streaming(audio_callback)defdraw_fft(img,fft_buf):fft_buf=(fft_buf/max(fft_buf))*SIZEfft_buf=np.log10(fft_buf+1)*20color=(0xFF,0x0F,0x00)foriinrange(0,len(fft_buf)):img.draw_line(i*SCALE,SIZE,i*SCALE,SIZE-int(fft_buf[i])*SCALE,color,SCALE)defdraw_audio_bar(img,level,offset):blk_size=(SIZE//10)color=(0xFF,0x00,0xF0)blk_space=(blk_size//4)foriinrange(0,int(round(level/10))):fb.draw_rectangle(SIZE+offset,SIZE-((i+1)*blk_size)+blk_space,20*SCALE,blk_size-blk_space,color,1,True)while(True):if(raw_buf!=None):pcm_buf=np.frombuffer(raw_buf,dtype=np.int16)raw_buf=NoneifCHANNELS==1:fft_buf=sp.signal.spectrogram(pcm_buf)l_lvl=int((np.mean(abs(pcm_buf[1::2]))/32768)*100)else:fft_buf=sp.signal.spectrogram(pcm_buf[0::2])l_lvl=int((np.mean(abs(pcm_buf[1::2]))/32768)*100)r_lvl=int((np.mean(abs(pcm_buf[0::2]))/32768)*100)fb.clear()draw_fft(fb,fft_buf)draw_audio_bar(fb,l_lvl,0)draw_audio_bar(fb,l_lvl,25*SCALE)ifCHANNELS==2:draw_audio_bar(fb,r_lvl,25*SCALE)fb.flush()# Stop streamingaudio.stop_streaming()
通信
I2C
I2Cバスに接続されているデバイスをスキャンします。
1
2
3
4
5
6
7
8
9
10
11
importtimefrommachineimportPin,I2Ci2c_list=[None,None]i2c_list[0]=I2C(0,scl=Pin(13),sda=Pin(12),freq=100_000)i2c_list[1]=I2C(1,scl=Pin(7),sda=Pin(6),freq=100_000)forbusinrange(0,2):print("\nScanning bus %d..."%(bus))foraddrini2c_list[bus].scan():print("Found device at address %d:0x%x"%(bus,addr))
frommachineimportUART,Pinimporttimeuart=UART(0,baudrate=9600,tx=Pin(0),rx=Pin(1))whileTrue:uart.write('hello')# writes 5 bytesval=uart.read(5)# reads up to 5 bytesprint(val)# prints datatime.sleep(1)
# Wi-Fi AP Mode Example## This example shows how to use Wi-Fi in Access Point mode.importnetwork,socket,sys,time,gcSSID='My_Nano_RP2040_Connect'# Network SSIDKEY='1234567890'# Network key (must be 10 chars)HOST=''# Use first available interfacePORT=8080# Arbitrary non-privileged port# Init wlan module and connect to networkwlan=network.WLAN(network.AP_IF)wlan.active(True)wlan.config(essid=SSID,key=KEY,security=wlan.WEP,channel=2)print("AP mode started. SSID: {} IP: {}".format(SSID,wlan.ifconfig()[0]))defrecvall(sock,n):# Helper function to recv n bytes or return None if EOF is hitdata=bytearray()whilelen(data)<n:packet=sock.recv(n-len(data))ifnotpacket:raiseOSError("Timeout")data.extend(packet)returndatadefstart_streaming(server):print('Waiting for connections..')client,addr=server.accept()# set client socket timeout to 5sclient.settimeout(5.0)print('Connected to '+addr[0]+':'+str(addr[1]))# FPS clockclock=time.clock()while(True):try:# Read data from clientdata=recvall(client,1024)# Send it backclient.send(data)exceptOSErrorase:print("start_streaming(): socket error: ",e)client.close()breakwhile(True):try:server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)# Bind and listenserver.bind([HOST,PORT])server.listen(1)# Set server socket to blockingserver.setblocking(True)while(True):start_streaming(server)exceptOSErrorase:server.close()print("Server socket error: ",e)
Wi-Fi®スキャン
利用可能なネットワークをスキャンします。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Scan Example# This example shows how to scan for Wi-Fi networks.importtime,networkwlan=network.WLAN(network.STA_IF)wlan.active(True)print("Scanning...")while(True):scan_result=wlan.scan()forapinscan_result:print("Channel:%d RSSI:%d Auth:%d BSSID:%s SSID:%s"%(ap))print()time.sleep_ms(1000)
importnetwork,socket# AP infoSSID=''# Network SSIDKEY=''# Network keyPORT=80HOST="www.google.com"# Init wlan module and connect to networkprint("Trying to connect. Note this may take a while...")wlan=network.WLAN(network.STA_IF)wlan.active(True)wlan.connect(SSID,KEY)# We should have a valid IP now via DHCPprint("Wi-Fi Connected ",wlan.ifconfig())# Get addr info via DNSaddr=socket.getaddrinfo(HOST,PORT)[0][4]print(addr)# Create a new socket and connect to addrclient=socket.socket(socket.AF_INET,socket.SOCK_STREAM)client.connect(addr)# Set timeoutclient.settimeout(3.0)# Send HTTP request and recv responseclient.send("GET / HTTP/1.1\r\nHost: %s\r\n\r\n"%(HOST))print(client.recv(1024))# Close socketclient.close()
# NTP Example## This example shows how to get the current time using NTPimportnetwork,usocket,ustruct,utime# AP infoSSID=''# Network SSIDKEY=''# Network keyTIMESTAMP=2208988800# Init wlan module and connect to networkprint("Trying to connect... (may take a while)...")wlan=network.WLAN()wlan.active(True)wlan.connect(SSID,key=KEY,security=wlan.WPA_PSK)# We should have a valid IP now via DHCPprint(wlan.ifconfig())# Create new socketclient=usocket.socket(usocket.AF_INET,usocket.SOCK_DGRAM)client.bind(("",8080))#client.settimeout(3.0)# Get addr info via DNSaddr=usocket.getaddrinfo("pool.ntp.org",123)[0][4]# Send queryclient.sendto('\x1b'+47*'\0',addr)data,address=client.recvfrom(1024)# Print timet=ustruct.unpack(">IIIIIIIIIIII",data)[10]-TIMESTAMPprint("Year:%d Month:%d Day:%d Time: %d:%d:%d"%(utime.localtime(t)[0:6]))
importbluetoothimportrandomimportstructimporttimefromble_advertisingimportadvertising_payloadfrommachineimportPinfrommicropythonimportconstLED_PIN=6_IRQ_CENTRAL_CONNECT=const(1)_IRQ_CENTRAL_DISCONNECT=const(2)_IRQ_GATTS_WRITE=const(3)_FLAG_READ=const(0x0002)_FLAG_WRITE=const(0x0008)_FLAG_NOTIFY=const(0x0010)_FLAG_INDICATE=const(0x0020)_SERVICE_UUID=bluetooth.UUID(0x1523)_LED_CHAR_UUID=(bluetooth.UUID(0x1525),_FLAG_WRITE)_LED_SERVICE=(_SERVICE_UUID,(_LED_CHAR_UUID,),)classBLETemperature:def__init__(self,ble,name="NANO RP2040"):self._ble=bleself._ble.active(True)self._ble.irq(self._irq)((self._handle,),)=self._ble.gatts_register_services((_LED_SERVICE,))self._connections=set()self._payload=advertising_payload(name=name,services=[_SERVICE_UUID])self._advertise()def_irq(self,event,data):# Track connections so we can send notifications.ifevent==_IRQ_CENTRAL_CONNECT:conn_handle,_,_=dataself._connections.add(conn_handle)elifevent==_IRQ_CENTRAL_DISCONNECT:conn_handle,_,_=dataself._connections.remove(conn_handle)# Start advertising again to allow a new connection.self._advertise()elifevent==_IRQ_GATTS_WRITE:Pin(LED_PIN,Pin.OUT).value(int(self._ble.gatts_read(data[-1])[0]))def_advertise(self,interval_us=500000):self._ble.gap_advertise(interval_us,adv_data=self._payload)if__name__=="__main__":ble=bluetooth.BLE()temp=BLETemperature(ble)whileTrue:time.sleep_ms(1000)
fromboardimportLEDled_red=LED(1)# red LEDled_green=LED(2)# green LEDled_blue=LED(3)# blue LEDled_builtin=LED(4)# classic built-in LED (also accessible through pin 13)
importimage,audio,timefromulabimportnumpyasnpfromulabimportscipyasspCHANNELS=1SIZE=256//(2*CHANNELS)raw_buf=Nonefb=image.Image(SIZE+50,SIZE,image.RGB565,copy_to_fb=True)audio.init(channels=CHANNELS,frequency=16000,gain_db=80,highpass=0.9883)defaudio_callback(buf):# NOTE: do Not call any function that allocates memory.globalraw_bufif(raw_buf==None):raw_buf=buf# Start audio streamingaudio.start_streaming(audio_callback)defdraw_fft(img,fft_buf):fft_buf=(fft_buf/max(fft_buf))*SIZEfft_buf=np.log10(fft_buf+1)*20color=(0xFF,0x0F,0x00)foriinrange(0,SIZE):img.draw_line(i,SIZE,i,SIZE-int(fft_buf[i]),color,1)defdraw_audio_bar(img,level,offset):blk_size=SIZE//10color=(0xFF,0x00,0xF0)blk_space=(blk_size//4)foriinrange(0,int(round(level/10))):fb.draw_rectangle(SIZE+offset,SIZE-((i+1)*blk_size)+blk_space,20,blk_size-blk_space,color,1,True)while(True):if(raw_buf!=None):pcm_buf=np.frombuffer(raw_buf,dtype=np.int16)raw_buf=NoneifCHANNELS==1:fft_buf=sp.signal.spectrogram(pcm_buf)l_lvl=int((np.mean(abs(pcm_buf[1::2]))/32768)*100)else:fft_buf=sp.signal.spectrogram(pcm_buf[0::2])l_lvl=int((np.mean(abs(pcm_buf[1::2]))/32768)*100)r_lvl=int((np.mean(abs(pcm_buf[0::2]))/32768)*100)fb.clear()draw_fft(fb,fft_buf)draw_audio_bar(fb,l_lvl,0)ifCHANNELS==2:draw_audio_bar(fb,r_lvl,25)fb.flush()# Stop streamingaudio.stop_streaming()
# Use nRF Connect from App store, connect to the Nano and write 1/0 to control the LED.importtimefromboardimportLEDfromubluepyimportService,Characteristic,UUID,Peripheral,constantsdefevent_handler(id,handle,data):globalperiphglobalserviceifid==constants.EVT_GAP_CONNECTED:passelifid==constants.EVT_GAP_DISCONNECTED:# restart advertisementperiph.advertise(device_name="Nano 33 BLE Sense",services=[service])elifid==constants.EVT_GATTS_WRITE:LED(1).on()ifint(data[0])elseLED(1).off()# start off with LED(1) offLED(1).off()notif_enabled=Falseuuid_service=UUID("0x1523")uuid_led=UUID("0x1525")service=Service(uuid_service)char_led=Characteristic(uuid_led,props=Characteristic.PROP_WRITE)service.addCharacteristic(char_led)periph=Peripheral()periph.addService(service)periph.setConnectionHandler(event_handler)periph.advertise(device_name="Nano 33 BLE Sense",services=[service])while(True):time.sleep_ms(500)
# Reconfiguring P105 as an input with a pull-down resistorp105.init(Pin.IN,Pin.PULL_DOWN)# Setting up an interrupt on P105p105.irq(lambdap:print("- IRQ triggered!",p))
frommachineimportPinimporttime# Configure pin P107 as an output (for the LED)led=Pin('P107',Pin.OUT_PP)# Configure pin P105 as input with pull-up resistor enabled (for the button)button=Pin('P105',Pin.IN,Pin.PULL_UP)whileTrue:# Read the state of the buttonbutton_state=button.value()ifbutton_state==0:# Turn on LED if button is pressed (button_state is LOW)led.value(1)else:# Turn off LED if button is not pressed (button_state is HIGH)led.value(0)# Short delay to debounce the button time.sleep(0.1)
frommachineimportADC,Pinimporttime# Initialize the ADC on the potentiometer-connected pinpot_pin=Pin('P006')pot_adc=ADC(pot_pin)whileTrue:# Read the raw analog valueraw_value=pot_adc.read_u16()print("- Potentiometer raw value:",raw_value)# Delay for readabilitytime.sleep(0.1)
importmachineimporttime# Configure the LED pin and PWMled_pin=machine.Pin('P105')led_pwm=machine.PWM(led_pin)led_pwm.freq(500)# Loop to vary brightnesswhileTrue:# Increase brightnessfordutyinrange(100):led_pwm.duty(duty)time.sleep(0.001)# Decrease brightnessfordutyinrange(100,-1,-1):led_pwm.duty(duty)time.sleep(0.001)
importmachine# Create an RTC objectrtc=machine.RTC()
日時を設定し、取得する
RTCを使えば、現在日時の設定と取得ができます。日時は8個の組を使ったフォーマットで表現します。
1
2
3
4
5
6
# Setting the RTC date and timertc.datetime((2024,1,4,4,20,0,0,0))# Getting the current date and timecurrent_datetime=rtc.datetime()print("- Current date and time:",current_datetime)
importmachine# Initialize the RTC and set the current datetimertc.datetime((2024,1,4,4,20,0,0,0))# Function to read a sensor value (placeholder)defread_sensor():# Replace with actual sensor reading logicreturn42# Read sensor value and get the current timesensor_value=read_sensor()timestamp=rtc.datetime()# Output the sensor value with its timestampprint("- Sensor value at ",timestamp,":",sensor_value)