欢迎来到淘文阁 - 分享文档赚钱的网站! | 帮助中心 好文档才是您的得力助手!
淘文阁 - 分享文档赚钱的网站
全部分类
  • 研究报告>
  • 管理文献>
  • 标准材料>
  • 技术资料>
  • 教育专区>
  • 应用文书>
  • 生活休闲>
  • 考试试题>
  • pptx模板>
  • 工商注册>
  • 期刊短文>
  • 图片设计>
  • ImageVerifierCode 换一换

    ESP32物联网智能硬件开发实战(李永华)-课后习题及答案 第6--8章.docx

    • 资源ID:74287089       资源大小:62.79KB        全文页数:15页
    • 资源格式: DOCX        下载积分:15金币
    快捷下载 游客一键下载
    会员登录下载
    微信登录下载
    三方登录下载: 微信开放平台登录   QQ登录  
    二维码
    微信扫一扫登录
    下载资源需要15金币
    邮箱/手机:
    温馨提示:
    快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。
    如填写123,账号就是123,密码也是123。
    支付方式: 支付宝    微信支付   
    验证码:   换一换

     
    账号:
    密码:
    验证码:   换一换
      忘记密码?
        
    友情提示
    2、PDF文件下载后,可能会被浏览器默认打开,此种情况可以点击浏览器菜单,保存网页到桌面,就可以正常下载了。
    3、本站不支持迅雷下载,请使用电脑自带的IE浏览器,或者360浏览器、谷歌浏览器下载即可。
    4、本站资源下载后的文档和图纸-无水印,预览文档经过压缩,下载后原文更清晰。
    5、试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。

    ESP32物联网智能硬件开发实战(李永华)-课后习题及答案 第6--8章.docx

    ESP32物联网智能硬件开发实战习题及答案第6章1 . ESP32 WiFi连网功能支持配置哪三种模式?答案:站点模式(即STA模式或WiFi客户端模式),此时ESP32连接到接入点(AP)或者 路由器。AP模式(即Soft-AP模式或接入点模式),也就是ESP32作为路由器,此时站点连 接到ESP320AP-STA共存模式(ESP32既是接入点,同时又作为站点连接到另外一个接入点)。2 .在ESP-IDF开发框架中,将ESP32开发板设置为AP模式,SSID为“MyESP32",密 码为“123456789",如何修改AP示例程序?将sdkconfig文件中修改如下字段CONFIG EXAMPLE WIFI SSID="MyESP32 ”C0NFIG_EXAMPLE_WIFI_PASSW0RD=,123456789z,3 .在 Arduino IDE 中,实现 AP 模式,SSID 为 “MyESP32”,密码为 “ 123456789”, 并在串口打印相关信息。include <Arduino. h>* include "WiFi, h”void setup()Serial. bcgin(l 15200);WiFi.softAP(*MyESP32*, ”123456789"); 设置 AP 参数,名称和密码)void loopO(Serial, print("主机名:");Serial, print In (WiFi, softAPgetHostname ();Serial. print("主机 IP:");Serial. println(WiFi. softAPIPO);Serial, print ("主机 IPV6:");Serial, print In (WiFi. softAPIPv6():Serial, print("主机SSID:*);Serial. println(WiFi. SSIDO):Serial, print(“主机 mac 地址:”);Serial. println(WiFi. softAPmacAddress();Serial, print("主机连接个数:");Serial, print In (WiFi. softAPgetSlalionNumO);Serial. print ("主机状态;Serial. println(WiFi. status。); delay(1000);)4.使用microPython开发环境,实现ESP32作为站点连接WiFi时密码的动态输入功 能。import networknewdata =for i, item in enumerate (data): #解码数据j = i % 4newdata. append (chr(datai mskLj) res = ''.join(newdata) return resprint C my server start. ,) try:sta_if = network. WLAN(network. STA_IF)staif. active (True)sta.if. connectC Redmi_77DE'12345678')while True:if sta_if. ifconfigO 0 != ' 0. 0. 0. 01 :breakprint C succ connect wi fi ap, get ipaddr:*)print(sta_if. ifconfigO)except:passsock = socket, socket ()sock, setsockopt (socket. SOL_SOCKET, socket. SO_REUSEAI)DR, 1)sock, bind(C 0. 0. 0. 0, 8000)sock. 1isten (5)print(*websocket listen at 8000.')while True:conn, address = sock, accept () # 接收到 socketprint (* client connect. / )print(address)websocket_he1per. server_handshake(conn)ws = websocket(conn)print (J websocket connect succ')while True:text = ws. read ()print(text)if text =' H':led = Pin(2, Pin. OUT, value = 1)el if text =' L':led = Pin(2, Pin. OUT, value = 0)9.根据MQTT示例中使用的服务器,在Arduino IDE下,客户端发布“Hello World” 消息、,订阅服务端消息、,控制2引脚上LED亮灭。includeWiFi. h>include <PubSubClicnt. h>需要管理库添加/ Update these with values suitable for your network.int BUILTIN_LED=2; LED 引脚const char* ssid = *; 修改 WiFi 名称const char* password =修改 WiFi 密码const char* mqtt_server = *; /修改 MQTT 服务器地址WiFiClient espClient;BubSubClicnt client(espClient);unsigned long lastMsg = 0;define MSG_BIFFER_SIZE (50)char msgMSG BUFFER SIZE;int value = 0;void setup_wifi() delay(10);/连接WiFiSerial. printlnO :Serial, print("Connecting to ");Serial, println(ssid):WiFi, mode(WIFI_STA):WiFi. begin(ssid, password);while (WiFi.statusO != WL_CONNECTED) delay (500):Serial, print (".");randomSeed(micros ():Serial. prinlln);Sei'ial. print In (WiFi connected*);Serial. println(*TP address:");Serial. println(WiFi. localiPO):void callback(char* topic, byte* payload, unsigned int length) Serial, print(Message arrived ”);Serial, print(topic):Serial, print (*");or (int i = 0; i < length; i+) Serial, print(char)payloadi);)Serial. printlnO ;如果第一个字符为1,打开LEDif (char)payload0 = '1') digitalWrite (BUILTIN_LED, HIGH); else digitalWrite(BUILTIN_LED, LOW);)void reconnect 0 while (!client. connected() Serial, print CAI tempting MQTT connection. M);String clientld = "ESP8266Client-”;clientld += String(random(Oxffff), HEX);if (client, connect (clientld. c_str() Serial.println("connected");发布消息client. publishC,outTopic/,, “hello world*);订阅消息client.subscribe(winTopic*); else (Serial, print(*failed, rc=*);Serial, print (cl ient. stateO);Serial, printing try again in 5 seconds*): delay(5000);)void setup() pinMode(BUTLTTN_LED, OUTPUT); /BUII.TINJ.ED 引脚为输出Serial. begin(l 15200);setup wifi ();client.setServer(mqtt_server, 1883);client.setCa11 back(ca11back);)void loopO i f (!cl ient. connected() reconnect ();)client. loopO ;unsigned long now = millisO ;if (now - lastMsg > 2000) lastMsg = now;+value;snprintf (msg, MSG_BUFEER_SIZE, hello world value):Serial.print(*Publish message:");Serial, print In(msg);client.publish(*outTopic*, msg); )第8章1 .简述蓝牙的协议栈。答案:蓝牙协议规定了两个层次,分别为蓝牙核心协议和蓝牙应用层协议。蓝牙核心协 议是对蓝牙技术本身的规范,主要包括控制器(Controller)和主机(Host),不涉及其应 用方式;蓝牙应用层协议(Application)是在蓝牙核心协议的基础匕根据具体的应用需 求定义出的特定策略。2 .简述GATT的作用。答案:通用属性配置文件层(Generic Attribute profile,简写GATT),定义了使用 ATT的服务框架,GATT规定配置文件(profile)的结构。在BLE中,所有被profile或者 服务用到的数据块称为“特性”,两个建立连接设备之间的所有数据通信都是通过GATT子 程序处理。GATT层用于已连接蓝牙设备之间的数据通信,应用程序和proi Ie直接使用GATT 层。当两个设备建立连接之后,它们就处于两种角色之一:GATT服务器端:为GATT客户端 提供数据服务的设备。GATT客户端:从GATT服务器端读写应用数据的设备。3 .简述传统蓝牙和低功耗蓝牙的区别。答案:BT与BLE的区别:当前的蓝牙协议分为基础率/增强数据率和低耗能两种技术类 型。经典蓝牙统称BT,低功耗蓝牙称为BLE。经典蓝牙模块(BT),泛指支持蓝牙协议在4. 0 以卜的模块,一般用于数据量比较大的传输。经典蓝牙模块可再细分为:传统蓝牙模块和高 速蓝牙模块。传统蓝牙模块在2004年推出,.主要代表是支持蓝牙2.1协议的模块,在智能 手机爆发的时期得到广泛支持。高速蓝牙模块在2009年推出,速率提高到约24Mbit/s,是 传统蓝牙模块的八倍。低功耗蓝牙模块(BLE),指支持蓝牙协议4.0或更高的模块,最大的 特点是功耗的降低。4 .使用Arduino IDE通过蓝牙循环向手机端发送"Hello World!",手机端使用BLE调 试助手进行读取数据。include <BLEDevice.h>include <BLEServer. h>include <BLEftils. h>include <B1.E29O2. h>BLECharacteristic *pCharacteristic;bool deviceConnected = false;char BLEbuf32 = 0;uint32_t ent = 0;#dcfinc SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E* / UART service UUIDdefine CHARACTERISTIC_UUID_RX *6E400002-B5A3-F393-E0A9-E50E24DCCA9E*Olefine C1IARACTERISTIC_UUIDTX ”6E400003-B5A3-F393-E0A9-E50E24DCCA9E”class MyServerCa11backs: public BLEServerCa11 backs void onConnect(BLEServer* pServer) deviceConnected = true;;void onDisconncct(BLEScrvcr* pServer) deviceConnected = false;;class MyCal1 backs: pub 1ic BLECharacteristicCalIbacks void onWrite(BLECharacteristic *pCharacteristic) std:string rxValue = pCharacteristic->getValue();if (rxValue. length() > 0) Serial, print(*>Received Value:");for (int i = 0; i < rxValue. length(); i+) Serial, print(rxValuei);Serial, print In ();if (rxValue.find(*A*) != -1)(Serial, print (wRx A!”);)else if (rxValue. find("B") != -1) Serial, print(wRx B!");)Serial. printlnO ;);void setup() Serial. begin(l15200):BLEDcvicc:inil("ESP32 BLE Tcsl");/ Create the BLE DeviceBLEServer *pServer = BLEDevice:createServer();/ Create the BLE ServerpServer->setCal1 backs(new MyServerCal1 backs();BLEService *pService = pServer->createService(SERVICE_LUID); / Create the BLE Service pCharacteristic = pSer v i ce->c rea t eCharac t er i s t i c (CHAR/CTER I ST IC UUID TX, BLECharacteristic:PROPERTY_NOTIFY);/ Create a BLE CharacteristicpCharacteri stic->addDescri ptor(new BLE2902():BLECharacteristic *pCharacteristic = pServ i ce->createCharac ter i st i c (CHARACTER I ST I C_UUI D_RX, BLECharac ter i st i c:PKOPERTYJVRITE);pCharacteri stic->setCalIbacks(new MyCa11 backs();pService->start();/ Start the servicepServer->getAdvertising()->start(); / Start advertisingSerial. printlnC'Waiting a client connection to notify. w);)void loopO if (deviceConnected) memset (BLEbuf, 0, 32);memepy(BLEbuf, (char*)*Hello World!*, 32);pCharacteri st ic->setValue(BLEbuf):pCharactcristic->nolify(); / Send the value to the app!Serial, print(w* Sent Value:");Serial. print(BLEbuf);Serial, printing *");)delay(1000);)5 .在ESP32开发板上GPIOO引脚接按键开关,按键开关另一端接地。使用Arduino IDE 实现,每按次按键,更改BLE蓝牙设备名字,通过申口监视器和BLE调试助手观察结果。 参考Arduin。IDE的示例程序,代码如下include "SimpleBLE. h"#ir!defined(CONFIG_BT_ENABLED) | | !defined(CONFTG_BLUEDROID_ENABI.ED)terror Bluetooth is not enabled! Blease run make menuconfig to and enable itSendifSimpleBLE ble;void onButtonO String out = "BLE32 name:out += String(millisO / 1000):Serial, print In (out);ble. begin (out);)void setup() Serial, begin(115200);Serial. setDcbugOutput(true);pinMode(0, INPUT PULLUP);Serial, print(*ESP32 SDK: *);Serial, print In (ESP. getSdkVersionO);ble.begin(*ESP32 SimpleBLE*);Serial. println(*Press the button to change the device's name*);)void loopO static uint8 t lastPinState = 1;uint8_t pinStatc = digitalRcad(O);if(IpinState && lastPinState)onButtonO ;lastPinState = pinState;whi le (Serial. availableO) Serial, write (Serial. readO);6 .在ESP32开发板上15引脚读取DHTU温湿度传感器的值,通过蓝牙notify发送, 手机蓝牙调试助手连接后,可以读取温湿度的值。Sble. py文件,将此py文件拷贝到开发板根目录import bluetoothimport structimport timefrom micropython import const#ble常量设置,不用动_IRQ_CENTRAL_CONNECT = const (1)RQ_CENTRAL_DISCO、NECT = const (2)_IKQ_GATTS_WRITE = const(3)FLAG READ = const(0x0002)_FLAG_WRITE_NO_RESPONSE = const(0x0004)_FLAG_WRITE = const(0x0008)_FLAG_NOTIFY = const(0x0010)ADV TYPE FLAGS = const(0x01)_ADV_TYPE_NAME = const(0x09)_ADV_TYPE_UU1D16_COMPLETE = const(0x3)_ADV_TYPE_UUID32_COMPLETE = const(0x5) _ADV_TYPE_UUID128_C0MPLETE = const (0x7) _ADV_TYPE_UUID16 MORE = const(0x2) _ADV_TYPE_UUID32_MORE = const(0x4) _ADV TYPE UUID128 MORE = const(0x6) _ADV_TYPE_APPEARANCE = const(0x19) #服务注册部分 _UART_UUID = bluetooth. UUID(/,6E400001-B5A3-F393-E0A9-E50E24DCCA9E*) _UART_TX =(bluetooth. UUID("6E400003-B5A3-F393-E0A9-E50E24DCCA9E*),_FLAG_RE;D | _FLAG_NOTIFY, ) _UART_RX =(bluetooth. UUID(*6E400002-B5A3-F393-E0A9-E50E24DCCA9E*),_FLAG_WRITE | _F1.AG_WRITE_N0_RESP0NSE, ) _UART_SERVICE =(JJARTJUID,(UART TX, LART RX), ) *广播函数 def advertising_payload(limited_disc=False, br_edr=False, name=None, services=None, appearance=0):pay load = bytearray()def _appcnd(adv_type, value): nonlocal payloadpay load += struct, pack ("BB”, len (value) + 1, adv_typc) + value _append(_ADV_TYPE_FLAGS,struct. pack(*B*, (0x01 if limited_disc else 0x02) + (0x18 if br_edr else 0x04), ) if name:_append (_?DV_TYPE_NAME, name) i f services:for uuid in services: b = bytes(uuid) if len(b) = 2:_append (_ADV TYPE_UUID16 COMPLETE, b)clif lcn(b) = 4:.append (_ADV_TYPE_UUID32_COMPLETE, b)elif len(b) = 16:.append (_ADV_TYIE_1'U1D128_COMPLETE, b)i f appearance:_append(_ADV_TYPE_APPEARACE, struct, packappearance) return payload#BLE 类class BLESimplePeripheral:def _init_(self, ble, name="myesp32"): #ble 名称self. _ble = bleself. _ble. active (True)self. _ble. irq(self. _irq)(seif. handle_tx, self. _handle_rx),)=self. _ble. gatts_register_services(_UART_SERV1CE,) self, connections = set()se1f._wr i te_ca11back = Noneself, payload = advertising pay1oad(name=name) self, .advertise。def _irq(self, event, data):if event = _IRQ_CENTRAL_CONNECT: conn_handle, = dataprint("New connection”, conn handle) self, -connections, add(conn_handle) self, advertise()clif event = _IRQ_CENTRAL_DISCONNECT: conn_handle, = data print("Disconnected”, conn_handle) self, -connections, remove(conn_handle) self, advertise()elif event = _IRQ_GATTS_WRITE:conn handle, value handle = datavalue = self. _blc. gatts_rcad(valuc_handlc)if value_handle = self._handle_rx and self. _write_callback: sei f. _wr i te_cal 1 back (val ue)def send (self, data):for conn handle in self, connections: self. _blc. gatts_writc(21, data) def notify (self, data):for conn handle in sei f. _connections:self. _ble. gatts_notify (conn_hand 1 e, 21, data)def is_connected(self):return len(self. .connections) > 0def advertise(self, interval us=500000):print (""Starting advertising*)self._ble. gap_advertise(interval_us, adv_data=self. _payload) def on_write(self, callback):self, write callback = callback#ma i n. py,执行的主函数import dhtimport machineimport timeimport bleimport bluetoothimport utimed = dht. DHT11 (machine. Pin(15)d. measure ()print (, 温度和湿度分别为:',d. temperature(),' 度',d. humidity(),'%') time, sleep(3)*新建ble对象b = bluetooth. BLE()#导入类p = ble. BLESimplePeripheral(b)while 1:1 f p. is_connected():dataT=d. temperature ()print (' T= n*. format (dataT)dataH=d. humidity()print C H=n .format(dataH)p. notifyC T=n,. format (dataT)#发送数据(以通知形式)p. notifyC H=n(. format(dataH)#发送数据(以通知形式)utime. sieep_ms(1000)import limedef do_connect(essid, password): ,根据给定的eddid和password连接wifi:param essid: wifi sid:param password: password:return: None ,if essid = None or essid = '':raise BaseException(* essid can not be null')if password = None or password :raise BaseException(' password can not be null') sta_if = network. WLAN(network. STA_IF) if not sta if. activeO :print("set sta active*)sta_if. active (True)i f not sta_if. isconnectedO :print C connecting to network. ,)sta if. connect (essid, password)retry_timcs = 30while not sta if. isconnectedO and retry times > 0:printC wait a moment i will try %s items, please" % rctry_timcs) time, sleep(2) retry_times -= 1print (* network config:', sta_if. ifconfigO) def disconnect(): ,断开网络连接:return: None ,>,sta_i f = network. WI.AN(network. STA IF)if sta_if. isconnectedO :sta if. disconnect()printC the network had been disconnect') if name = " main ”:essid = input (* please input your essid:') password = input please input your password / ) do_connect(essid, password)while True:exit = input("press Q to exit:*) if exit = 'Q':disconnect () break5 .在ESP-IDF开发中,TCP服务器和客户端通信,需要哪些步骤?TCP是面向连接的可靠服务,服务器端的步骤:(1)创建套接字socket。; (2)绑定套 接字到一个IP地址和一个端口上,bindO; (3)将套接字设置为监听模步等待连接请求, listen。;(4)请求到来后,接收连接请求,返回一个新的对应于此次连接的套接字,accept。; (5)用返回的套接字和客户端进行通信,sendO/reevO; (6)关闭套接字,close。客户端的步骤:(1)创建套接字,socket () ; (2)向服务器端发出连接请求,connect (); (3)与服务器端进行通信,send()/recv(); (4)关闭套接字,close。6 .使用MicroPython开发一个TCP服务器,使用网络调试助手作为TCP客户端,控制 ESP32开发板上GPIO22引脚上LED的亮灭。#ESP32上运行相关代码import networkimport socketimport timefrom machine import Pin # 导入 Pin 模块 from utime import sleep_ms #导入延时函数 SSID=* "PASSWORD-"port=10000wlan=None1istenSocket=Nonedef led(control_cmd):LED = Pin(22, Pin. OLT) # 构建 LED 对象,GPIO22 输出if control_cmd = "1”:LED. value(l) # 点亮 LEDelif control emd = "0":LED. value(0) # 熄灭 LEDdef connectWifi(ssid, passwd):global wlanwlan=network. WLAN (network. ST?_IF)wlan. active (True)wlan. disconnect ()wlan.connect(ssid, passwd)while(wlan. ifconfigO 0=,0. 0. 0. O'):time, sleep(l)return Truetry:connectWifi(SSID, PASSWORD)ip=wlan. ifconfigO 0listenSocket = socket, socket ()listenSocket. bind(ip, port)listenSocket. listen(l)listenSocket. sctsockopt (socket. SOL_SOCKET, socket. SO_REUSEADl)R, 1)print("*"*90)print(*TCP 服务器开启,IP: %s PORT: %s"%(ip, port)print("*"*90)while True:print ("等待消息接收 ”)conn, addr = 1 i stenSocket. accept ()print ("连接自 ",addr)while True:data = conn. recv(1024)if (len(data) = 0):print (”接收完成”)conn. closeObreakmcssagc_t = data, decode ()led(me s sage_con tent)print (0330;36;32m 接收消息内容:%s033Om,z%niessagc_content)ret = conn, send(data)except:if(listenSocket):1 istenSocket. closeOwlan. disconnect ()wlan. active(False)7 .简述UDP通信的过程。答案:服务器端步骤:(1)使用函数socket。,生成套接字文件描述符:(2)通过Socket 结构设置服务器端地址和监听端口;(

    注意事项

    本文(ESP32物联网智能硬件开发实战(李永华)-课后习题及答案 第6--8章.docx)为本站会员(太**)主动上传,淘文阁 - 分享文档赚钱的网站仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知淘文阁 - 分享文档赚钱的网站(点击联系客服),我们立即给予删除!

    温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载不扣分。




    关于淘文阁 - 版权申诉 - 用户使用规则 - 积分规则 - 联系我们

    本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

    工信部备案号:黑ICP备15003705号 © 2020-2023 www.taowenge.com 淘文阁 

    收起
    展开