ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 라즈베리파이 피코
    카테고리 없음 2023. 7. 29. 11:29

    rp2-pico-w-20230426-v1.20.0.uf2 이 파일을 잘못 받아서, 하루 시간 날려버렸네요..

     

    라즈베리파이 피코 wifi 버전을 잘 확인하고 설치하세요.

     

    import machine
    import time
    
    led = machine.Pin('LED', machine.Pin.OUT)
    
    while (True):
        led.on()
        time.sleep(1)
        led.off()
        time.sleep(1)
        
    led.off()
    from network import WLAN, STA_IF
    from time import sleep
    
    from machine import Pin
    from dht import DHT22
    
    import socket
    
    led = machine.Pin('LED', machine.Pin.OUT)
    
    pin3 = machine.Pin(3, machine.Pin.OUT)
    pin3.on()
    
    dht = DHT22(Pin(2))
    
    SSID = ''
    PASSWORD = ''
    
    wlan = WLAN(STA_IF)
    wlan.active(True)
    wlan.connect(SSID, PASSWORD)
    
    max_wait = 10
    while max_wait > 0:
        if wlan.status() < 0 or wlan.status() >= 3:
            break
        max_wait -= 1
        print('waiting for connection...')
        sleep(1)
        
    if wlan.status() != 3:
        raise RuntimeError('network connection failed')
    else: # wlan.status() == 3
        print('connected')
        status = wlan.ifconfig()
        print('ip = ' + status[0])
        led.on()
        
    ##########################################################
    # 서버의 IP 주소와 포트 번호를 설정합니다.
    HOST = '192.168.168.226'  # 모든 인터페이스에서 접속을 허용하려면 '0.0.0.0'을 사용합니다.
    PORT = 12345     # 사용할 포트 번호를 지정합니다.
    
    # 소켓을 생성하고 바인딩합니다.
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((HOST, PORT))
    server_socket.listen()
    
    print('서버가 시작되었습니다. 클라이언트의 연결을 기다립니다...')
    
    # 클라이언트로부터 연결 요청을 받습니다.
    client_socket, client_address = server_socket.accept()
    print(f'클라이언트가 접속했습니다: {client_address}')
    
    while True:
        dht.measure()
        temp = dht.temperature()
        hum = dht.humidity()
    
        # displaying values to the console
        message = f"Temperature: {temp}°C   Humidity: {hum}% "
        print( message )
        
        # 클라이언트로부터 데이터를 받습니다.
        data = client_socket.recv(1024).decode('utf-8')
    
        print(f'수신한 데이터: {data}')
        
        # 클라이언트로 데이터를 전송합니다.
        client_socket.sendall(message.encode('utf-8'))
    
    # 소켓을 닫습니다.
    client_socket.close()
    server_socket.close()
    #import modules
    import network
    import socket
    from time import sleep
    from machine import Pin, I2C
    
    from dht import DHT22
    
    SSID = ''
    PASSWORD = ''
    
    #initialize I2C 
    i2c=I2C(0,sda=Pin(0), scl=Pin(1), freq=400000)
    
    led = machine.Pin('LED', machine.Pin.OUT)
    
    pin3 = machine.Pin(3, machine.Pin.OUT)
    pin3.on()
    
    dht = DHT22(Pin(2))
    
    # Static IP configuration
    STATIC_IP = '192.168.168.101'  # Replace with the desired static IP address
    SUBNET_MASK = '255.255.255.0'
    GATEWAY_IP = '192.168.168.1'
    DNS_SERVER = '8.8.8.8'
    
    def set_static_ip():
        # Connect to WLAN
        wlan = network.WLAN(network.STA_IF)
        wlan.active(True)
        wlan.connect(SSID, PASSWORD)
        while not wlan.isconnected():
            print('Waiting for connection...')
            sleep(1)
        print('Connected to Wi-Fi')
    
        # Set static IP configuration
        wlan.ifconfig((STATIC_IP, SUBNET_MASK, GATEWAY_IP, DNS_SERVER))
        ip = wlan.ifconfig()[0]
        print(f'Connected on {ip}')
        led.on()
        return ip
    
    def open_socket(ip):
        # Open a socket
        address = (ip, 80)
        connection = socket.socket()
        connection.bind(address)
        connection.listen(1)
        return connection
    
    def webpage(reading):
        #Template HTML
        html = f"""
                <!DOCTYPE html>
                <html lang="ko">
                <head>
                <title>Pico W Weather Station</title>
                <meta http-equiv="refresh" content="10">
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                </head>
                <body>
                <p>{reading}</p>
                </body>
                </html>
                """
        return str(html)
        
    def serve(connection):
        #Start a web server
        
        while True:
            #bme = bme280.BME280(i2c=i2c)
            #temp = bme.values[0]
            #pressure = bme.values[1]
            #humidity = bme.values[2]
            dht.measure()
            temp = int(dht.temperature())
            humidity = int(dht.humidity())
    
            reading = '온도 : ' + str(temp) + ',&nbsp;&nbsp;&nbsp; 습도 : ' + str(humidity)
            client = connection.accept()[0]
            request = client.recv(1024)
            request = str(request)       
            html = webpage(reading)
            client.send(html)
            client.close()
    
    try:
        ip = set_static_ip()
        connection = open_socket(ip)
        serve(connection)
    except KeyboardInterrupt:
        machine.reset()
        
    # 소켓을 닫습니다.
    client_socket.close()
    server_socket.close()
Designed by Tistory.