ESP 32 MicroPython网络服务器

ESP32、ESP8266
ESP32-S2、ESP32-S3、ESP32-C3
回复
头像
shaoziyang
帖子: 3917
注册时间: 2019年 10月 21日 13:48

ESP 32 MicroPython网络服务器

#1

帖子 shaoziyang »

图片

基于ESP32 MicroPython的Web服务器。ESP32 读取 DS18B20 温度传感器的温度值,然后发送到Web服务器。使用 IP地址可以查看传感器数据网页。


隐藏内容
你必须登入/注册才可观看隐藏内容
 
 
 
 

头像
shaoziyang
帖子: 3917
注册时间: 2019年 10月 21日 13:48

Re: ESP 32 MicroPython网络服务器

#2

帖子 shaoziyang »

参考程序

代码: 全选

def  read_ds_sensor ( ) : 
  roms  = ds_sensor . scan ( ) 
  print ( 'Found DS devices: ' ,  roms ) 
  print ( 'Temperatures: ' ) 
  ds_sensor . convert_temp ( ) 
  for  rom  in  roms : 
    temp  = ds_sensor . read_temp ( rom ) 
    if  isinstance ( temp ,  float ) : 
      msg  = round ( temp ,  2) 
      print ( temp ,  end =' ' ) 
      print ( 'Valid temperature' ) 
      return  msg 
  return  b '0.0'
  
def web_page():
  temp = read_ds_sensor()
  html = """<!DOCTYPE HTML><html><head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  <style> html { font-family: Arial; display: inline-block; margin: 0px auto; text-align: center; }
    h2 { font-size: 3.0rem; } p { font-size: 3.0rem; } .units { font-size: 1.2rem; } 
    .ds-labels{ font-size: 1.5rem; vertical-align:middle; padding-bottom: 15px; }
  </style></head><body><h2>ESP32 DS18B20 WebServer</h2>
  <p><i class="fas fa-thermometer-half" style="color:#059e8a;"></i> 
    <span class="ds-labels">Temperature</span>
    <span id="temperature">""" + str(temp) + """</span>
    <sup class="units">&deg;C</sup>
  </p>
    <p><i class="fas fa-thermometer-half" style="color:#059e8a;"></i> 
    <span class="ds-labels">Temperature</span>
    <span id="temperature">""" + str(round(temp * (9/5) + 32.0, 2)) + """</span>
    <sup class="units">&deg;F</sup>
  </p></body></html>"""
  return html
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
 
while True:
  try:
    if gc.mem_free() < 102000:
      gc.collect()
    conn, addr = s.accept()
    conn.settimeout(3.0)
    print('Got a connection from %s' % str(addr))
    request = conn.recv(1024)
    conn.settimeout(None)
    request = str(request)
    print('Content = %s' % request)
    response = web_page()
    conn.send('HTTP/1.1 200 OK\n')
    conn.send('Content-Type: text/html\n')
    conn.send('Connection: close\n\n')
    conn.sendall(response)
    conn.close()
  except OSError as e:
    conn.close()
    print('Connection closed')
 
 

回复

  • 随机主题
    回复总数
    阅读次数
    最新文章