Hyungsun Yoon

[HW] Platform change to RPI Pico

......@@ -8,3 +8,4 @@
## 일정
+ 2021.05.03: Init(개인 아두이노 코드 git에서 이전)
+ 2021.05.11: Arduino 개발 중단, RaspberryPi Pico로 플랫폼 이전, C++ -> MicroPython
\ No newline at end of file
......
from bluetooth import *
socket = BluetoothSocket( RFCOMM )
socket.connect(("04:A3:16:99:C7:42", 1))
print("bluetooth connected!")
msg = input("send message : ")
socket.send(msg)
print("finished")
socket.close()
\ No newline at end of file
from bluetooth import *
import time
client_socket = BluetoothSocket( RFCOMM )
client_socket.connect(("00:18:91:D8:24:39", 1))
print("bluetooth connected!")
def _send_data(msg:str):
client_socket.send(msg)
def _recv_data():
# 소켓에 2초간 받을 수 있는 시간을 준다
client_socket.settimeout(2)
# 데이터 받을 변수
data = ''
try:
timeout_start = time.time()
timeout = 2
while time.time() < timeout_start + timeout:
data += client_socket.recv(1024).decode('utf-8')
except:
print("INFO: DATA RECV TIMEOUT")
finally:
return data
while True:
sel_mode = input("SELECT MODE: ")
if sel_mode == 'W':
msg = input("send message : ")
_send_data(msg)
elif sel_mode == 'WR':
msg = input("send message : ")
_send_data(msg)
data = _recv_data()
print(f"Received: {data}")
client_socket.close()
\ No newline at end of file
import uos
import machine
import utime
uart0 = machine.UART(0,baudrate=9600)
# --------------------------------------------------- #
# INTERNAL FUNCTIONS
# --------------------------------------------------- #
def _clartBuf(uart=uart0):
''' Clear Buffer
'''
while uart.any():
print(uart.read(1))
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def send_data_bt(sdata:str):
''' Send string data using Bluetooth
'''
_clartBuf()
uart0.write(sdata)
def recv_data_bt():
''' Receive string data using Bluetooth
'''
_clartBuf()
prvMills = utime.ticks_ms()
received_data = ''
while (utime.ticks_ms()-prvMills)<2000:
if uart0.any():
single_data = uart0.read(1)
received_data += single_data.decode('utf-8')
return received_data
\ No newline at end of file
''' Original code from https://www.raspberrypi.org/forums/viewtopic.php?t=303606
'''
import utime
import rp2
from rp2 import PIO, asm_pio
from machine import Pin
# --------------------------------------------------- #
# INIT
# --------------------------------------------------- #
# For VCC
dht_pwr = Pin(14, Pin.OUT)
# For data
dht_data = Pin(15, Pin.IN, Pin.PULL_UP)
# Power on
dht_pwr.value(1)
# Create empty state
sm=rp2.StateMachine(1)
# Wait for DHT22 to start up
utime.sleep(2)
# --------------------------------------------------- #
# INIT2
# --------------------------------------------------- #
@asm_pio(set_init=(PIO.OUT_HIGH),autopush=True, push_thresh=8) #output one byte at a time
def DHT22():
#drive output low for at least 20ms
set(pindirs,1) #set pin to output
set(pins,0) #set pin low
set(y,31) #prepare countdown, y*x*100cycles
label ('waity')
set(x,31)
label ('waitx')
nop() [30]
jmp(x_dec,'waitx') #decrement x reg every 100 cycles
jmp(y_dec,'waity') #decrement y reg every time x reaches zero
#begin reading from device
set(pindirs,0) #set pin to input
wait(1,pin,0) #check pin is high before starting
wait(0,pin,0)
wait(1,pin,0)
wait(0,pin,0) #wait for start of data
#read databit
label('readdata')
set(x,21) #reset x register to count down from 20
wait(1,pin,0) #wait for high signal
label('countdown')
jmp(pin,'continue') #if pin still high continue counting
#pin is low before countdown is complete - bit '0' detected
set(y,0)
in_(y, 1) #shift '0' into the isr
jmp('readdata') #read the next bit
label('continue')
jmp(x_dec,'countdown') #decrement x reg and continue counting if x!=0
#pin is still high after countdown complete - bit '1' detected
set(y,1)
in_(y, 1) #shift one bit into the isr
wait(0,pin,0) #wait for low signal (next bit)
jmp('readdata') #read the next bit
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def work_dht():
data=[]
total=0
sm.init(DHT22,freq=1600000,set_base=dht_data,in_base=dht_data,jmp_pin=dht_data)
sm.active(1)
for i in range(5): #data should be 40 bits (5 bytes) long
data.append(sm.get()) #read byte
#check checksum (lowest 8 bits of the sum of the first 4 bytes)
for i in range(4):
total=total+data[i]
if((total & 255) == data[4]):
humidity=((data[0]<<8) + data[1])/10.0
temperature=(((data[2] &0x7f) << 8) + data[3]) /10.0
if (data[2] & 0x80) == 0x80:
temperature = -temperature
return [humidity, temperature]
else:
return False
\ No newline at end of file
import array, utime
from machine import Pin
import rp2
import neopixel
import dht
import bluetoooth as bto
# --------------------------------------------------- #
# INIT
# --------------------------------------------------- #
# --------------------------------------------------- #
# ENTRYPOINT
# --------------------------------------------------- #
def _run():
while True:
input_data = bto.recv_data_bt()
if input_data != '':
input_data = input_data.strip()
print('INPUT FOUND ', input_data)
print(len(input_data))
if input_data == 'A':
neopixel.work_led(0.2)
elif input_data == 'B':
dht_data = dht.work_dht()
if dht_data == False:
print("ERROR: DHT22 NOT WORKING")
else:
print("INFO: HUMI ", dht_data[0])
print("INFO: TEMP ", dht_data[1])
send_string = str(dht_data[0]) + ',' + str(dht_data[1])
print(send_string)
bto.send_data_bt(send_string)
else:
print('WRONG INPUT')
if __name__ == '__main__':
_run()
\ No newline at end of file
''' Original code from https://core-electronics.com.au/tutorials/how-to-use-ws2812b-rgb-leds-with-raspberry-pi-pico.html
'''
import array, utime
from machine import Pin
import rp2
# --------------------------------------------------- #
# INIT
# --------------------------------------------------- #
NUM_LEDS = 8
PIN_NUM = 22
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 150, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
BLUE = (0, 0, 255)
PURPLE = (180, 0, 255)
WHITE = (255, 255, 255)
COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE, BLACK)
# --------------------------------------------------- #
# INIT2
# --------------------------------------------------- #
@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24)
def ws2812():
T1 = 2
T2 = 5
T3 = 3
wrap_target()
label("bitloop")
out(x, 1) .side(0) [T3 - 1]
jmp(not_x, "do_zero") .side(1) [T1 - 1]
jmp("bitloop") .side(1) [T2 - 1]
label("do_zero")
nop() .side(0) [T2 - 1]
wrap()
# Create the StateMachine with the ws2812 program, outputting on pin
sm = rp2.StateMachine(0, ws2812, freq=8_000_000, sideset_base=Pin(PIN_NUM))
# Start the StateMachine, it will wait for data on its FIFO.
sm.active(1)
# Display a pattern on the LEDs via an array of LED RGB values.
ar = array.array("I", [0 for _ in range(NUM_LEDS)])
# --------------------------------------------------- #
# INTERNAL FUNCTIONS
# --------------------------------------------------- #
def _pixels_show(brightness:int = 0.2):
dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)])
for i,c in enumerate(ar):
r = int(((c >> 8) & 0xFF) * brightness)
g = int(((c >> 16) & 0xFF) * brightness)
b = int((c & 0xFF) * brightness)
dimmer_ar[i] = (g<<16) + (r<<8) + b
sm.put(dimmer_ar, 8)
utime.sleep_ms(10)
def _pixels_set(i, color):
ar[i] = (color[1]<<16) + (color[0]<<8) + color[2]
def _pixels_fill(color):
for i in range(len(ar)):
_pixels_set(i, color)
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def work_led(brightness:int = 0.2):
for color in COLORS:
_pixels_fill(color)
_pixels_show(brightness)
utime.sleep(0.4)