赞
踩
说点什么吧
ESP32C3使用的是合宙公司的产品,主要原因就是9.9一片,尼玛就相当于白嫖,还能跑Luatos,之后趋势吧。
合宙CORE ESP32-C3核心板,是一款基于乐鑫ESP32-C3所设计的开发板,其体型小巧仅为21mm×51mm,它采用邮票孔设计,可直接嵌入开发板上来使用。该核心板支持UART、GPIO、SPI、I2C、ADC、PWM等接口,并板载 Wi-Fi/BLE天线以便于开发者在不同场景下使用。
该核心板的外观如图1所示,其引脚及分布见图2所示。
图1 开发板外观
这里很重要
GPIO 6-11 连接到SPI Flash。
GPIO 34-39 只能作为输入且没有内部上拉,其他的可以作为输入或者输出。
GPIO 20, 24, 28, 29, 30, 31 不对外开放。
GPIO 32,33默认连接到RTC域。可能需要如下设置:
https://www.seeedstudio.com/Seeed-XIAO-ESP32C3-p-5431.html
使用arduino开发是最方便的,而且开发周期较短,最主要是的是有大量的支持库
https://blog.csdn.net/a1415539404a/article/details/124534428
可以看看这个老哥写的,很详细了。最重要的是要选择
使用注意事项(第3条):
IO12(GPIO12)、IO13(GPIO13)在QIO模式下为SPI信号SPIHD和SPIWP复用,为了增加可用GPIO数量,开发板选择采用2线SPI的DIO模式,IO12、IO13并未连接flash,使用自己编译的软件时需要注意配置flash为DIO模式。
![在这里插入图片描述](https://img-blog.csdnimg.cn/513d3a9220c84018b9ae65e7766d6a2f.png
固件从这个里面下载,配置如图
https://www.micropython.org/download/esp32c3/
下载最新的就行
在这一步这里,先点击擦除后会显示“等待上电同步”,之后我们按下板子上的BOOT键1S,进入下载程序模式,就可以了,下面下载固件操作也需要
升级完成后需要重新拔插一下 TPYE-C 线复位一下开发板,即可使用。
#include <WiFi.h>
#include <WiFiUdp.h> //引用以使用UDP
const char *ssid = "ESP82666";
const char *password = "12345678";
WiFiUDP Udp; //创建UDP对象
unsigned int localUdpPort = 2333; //本地端口号
void setup()
{
Serial.begin(115200);
Serial.println();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (!WiFi.isConnected())
{
delay(500);
Serial.print(".");
}
Serial.println("Connected");
Serial.print("IP Address:");
Serial.println(WiFi.localIP());
Udp.begin(localUdpPort); //启用UDP监听以接收数据
}
void loop()
{
int packetSize = Udp.parsePacket(); //获取当前队首数据包长度
if (packetSize) //如果有数据可用
{
char buf[packetSize];
Udp.read(buf, packetSize); //读取当前包数据
Serial.println();
Serial.print("Received: ");
Serial.println(buf);
Serial.print("From IP: ");
Serial.println(Udp.remoteIP());
Serial.print("From Port: ");
Serial.println(Udp.remotePort());
Udp.beginPacket("192.168.137.122", 5678); //准备发送数据
Udp.print("Received: "); //复制数据到发送缓存
Udp.write((const uint8_t*)buf, packetSize); //复制数据到发送缓存
Udp.endPacket(); //发送数据
}
}
#include <WiFi.h> //wifi功能需要的库
WiFiUDP Udp;//声明UDP对象
const char* wifi_SSID="ESP32_Udp"; //存储AP的名称信息
const char* wifi_Password="ESP32_1234"; //存储AP的密码信息
uint16_t udp_port=1122; //存储需要监听的端口号
char incomingPacket[255]; //存储Udp客户端发过来的数据
void setup() {
// put your setup code here, to run once:
Serial.begin(115200); //开启串口,波特率为115200
WiFi.mode(WIFI_AP); //设置为AP模式
WiFi.softAP(ssid, password); //配置AP信息,并开启AP
IPAddress softLocal(192,168,1,1); //IP地址,用以设置IP第4字段
IPAddress softGateway(192,168,1,1); //IP网关,用以设置IP第3字段
IPAddress softSubnet(255,255,255,0);
//配置自定义的IP信息
WiFi.softAPConfig(softLocal, softGateway, softSubnet);
IPAddress IP = WiFi.softAPIP(); //用变量IP接收AP当前的IP地址
Serial.println(IP); //打印输出IP的IP地址
Udp.begin(udp_port);//启动UDP监听这个端口
}
void loop() {
// put your main code here, to run repeatedly:
/*接收发送过来的Udp数据*/
int Data_length=Udp.parsePacket(); //获取接收的数据的长度
if(Data_length) //如果有数据那么Data_length不为0,无数据Data_length为0
{
int len = Udp.read(incomingPacket, 255); //读取数据,将数据保存在数组incomingPacket中
if (len > 0) //为了避免获取的数据后面乱码做的判断
{
incomingPacket[len] = 0;
}
Serial.print(incomingPacket);
if(incomingPacket[0]=='E'){Serial.println("E");}
if(incomingPacket[0]=='A'){Serial.println("A");}
if(incomingPacket[0]=='B'){Serial.println("B");}
if(incomingPacket[0]=='C'){Serial.println("C");}
}
}
#include <ESP8266WiFi.h>
#include <WiFiUdp.h> //引用以使用UDP
const char* wifi_SSID="ESP"; //存储AP的名称信息
const char* wifi_Password="12345678"; //存储AP的密码信息
uint16_t udp_port=2333; //存储需要监听的端口号
char incomingPacket[255]; //存储Udp客户端发过来的数据
void setup()
{
Serial.begin(115200);
Serial.println();
WiFi.mode(WIFI_AP); //设置为AP模式
WiFi.softAP(wifi_SSID, wifi_Password); //配置AP信息,并开启AP
IPAddress softLocal(192,168,4,1); //IP地址,用以设置IP第4字段
IPAddress softGateway(192,168,4,1); //IP网关,用以设置IP第3字段
IPAddress softSubnet(255,255,255,0);
//配置自定义的IP信息
WiFi.softAPConfig(softLocal, softGateway, softSubnet);
IPAddress IP = WiFi.softAPIP(); //用变量IP接收AP当前的IP地址
Serial.println(IP); //打印输出IP的IP地址
Udp.begin(udp_port);//启动UDP监听这个端口
}
void loop()
{
/*接收发送过来的Udp数据*/
int Data_length=Udp.parsePacket(); //获取接收的数据的长度
if(Data_length) //如果有数据那么Data_length不为0,无数据Data_length为0
{
int len = Udp.read(incomingPacket, 255); //读取数据,将数据保存在数组incomingPacket中
if (len > 0) //为了避免获取的数据后面乱码做的判断
{
incomingPacket[len] = 0;
}
Serial.print(incomingPacket);
}
}
#include <WiFi.h> //wifi功能需要的库
WiFiUDP Udp;//声明UDP对象
const char* wifi_SSID="ESP32"; //存储AP的名称信息
const char* wifi_Password="12345678"; //存储AP的密码信息
uint16_t udp_port=1122; //存储需要监听的端口号
char incomingPacket[255]; //存储Udp客户端发过来的数据
void setup() {
// put your setup code here, to run once:
Serial.begin(115200); //开启串口,波特率为115200
WiFi.softAP(wifi_SSID,wifi_Password); //打开ESP32热点
Serial.print("\n开发板IP地址为:");
Serial.print(WiFi.softAPIP()); //串口输出模块IP地址
Udp.begin(udp_port);//启动UDP监听这个端口
}
void loop() {
// put your main code here, to run repeatedly:
udp();
}
void udp(){
/*接收发送过来的Udp数据*/
int Data_length=Udp.parsePacket(); //获取接收的数据的长度
if(Data_length) //如果有数据那么Data_length不为0,无数据Data_length为0
{
int len = Udp.read(incomingPacket, 255); //读取数据,将数据保存在数组incomingPacket中
if (len > 0) //为了避免获取的数据后面乱码做的判断
{
incomingPacket[len] = 0;
}
/*将接受到的数据发送回去*/
Serial.print(String(incomingPacket));
if(String(incomingPacket)=="B1C2" or String(incomingPacket)=="C2B1"){Serial.println("启动+驻车取消");}
if(String(incomingPacket)=="H"){Serial.println("A");}
if(String(incomingPacket)=="F"){Serial.println("B");}
if(String(incomingPacket)=="E"){Serial.println("C");}
}
}
先说一下ESP-NOW,它是Espressif开发的一种协议,它使多个设备无需使用Wi-Fi即可相互通信。该协议类似于低功率的2.4GHz无线连接。设备之间需要进行配对,然后才能进行通信。配对完成后,连接安全且点对点,无需握手。”这意味着在将设备彼此配对后,连接将保持不变。换句话说,如果您的一块板突然断电或重置,则在重新启动时,它将自动连接到其对等端以继续通信。
简而言之,ESP-NOW是一种快速通信协议,可用于在ESP8266板之间交换小消息(最大250字节)。
ESP-NOW有多种用途
可以在不同的设置中进行单向或双向通信
一个 主 ESP8266向多个ESP8266 从 发送数据
一块ESP8266板向不同的ESP8266板发送相同或不同的命令。此配置是构建遥控器之类的理想选择
一个ESP8266从站从多个主站接收数据
如果要将多个传感器节点的数据收集到一个ESP8266板中,则此配置非常理想
ESP-NOW双向通讯
使用ESP-NOW,每个板可以同时是发送者和接收者。因此,您可以在板之间建立双向通信。
总而言之,ESP-NOW是构建网络的理想选择,在该网络中,您可以有多个ESP8266板相互交换数据,这篇只是测试单方向的发送数据和接受数据
#include <ESP8266WiFi.h>
void setup()
{
Serial.begin(115200);//设置串口波特率为115200
WiFi.mode(WIFI_STA);//设置WiFi模式为STA,这里要与之后使用的模式相对应
}
void loop()
{
//每隔一秒钟打印一次MAC地址
Serial.println(WiFi.macAddress());
delay(1000);
}
#include <esp_now.h>
#include <WiFi.h>
// 接收端的MAC地址
uint8_t broadcastAddress[] = {0xC4, 0x5B, 0xBE, 0x42, 0x25, 0x6C};//C4:5B:BE:42:25:6C
// 发送结构体类型
typedef struct struct_message {
char a[32];
int b;
float c;
bool d;
} struct_message;
// 创建一个结构体变量
struct_message myData;
// 回调函数,函数将在发送消息时执行。此函数告诉我们信息是否成功发送;
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("\r\nLast Packet Send Status:\t");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}
void setup() {
// 初始化串口波特率
Serial.begin(115200);
// 设置WIFI模式为STA模式,即无线终端
WiFi.mode(WIFI_STA);
// 初始化ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
//注册回调函数
esp_now_register_send_cb(OnDataSent);
// 注册通信频道
esp_now_peer_info_t peerInfo;
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0; //通道
peerInfo.encrypt = false;//是否加密为False
if (esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("Failed to add peer");
return;
}
}
void loop() {
//设置要发送的值
strcpy(myData.a, "THIS IS A CHAR");
myData.b = random(1,20);
myData.c = 1.2;
myData.d = false;
//发送信息到指定ESP32上
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));
//判断是否发送成功
if (result == ESP_OK) {
Serial.println("Sent with success");
}
else {
Serial.println("Error sending the data");
}
delay(2000);
}
//接收
#include <ESP8266WiFi.h>
#include <espnow.h>
//接收数据保存的结构体和发送方一致
typedef struct struct_message {
char a[32];
int b;
float c;
bool d;
} struct_message;
//创建结构体变量
struct_message myData;
//创建一个回调函数作为接收数据后的串口显示
void OnDataRecv(uint8_t * mac, uint8_t *incomingData, uint8_t len) {
memcpy(&myData, incomingData, sizeof(myData));
Serial.print("Bytes received: ");
Serial.println(len);
Serial.print("Char: ");
Serial.println(myData.a);
Serial.print("Int: ");
Serial.println(myData.b);
Serial.print("Float: ");
Serial.println(myData.c);
Serial.print("Bool: ");
Serial.println(myData.d);
Serial.println();
}
void setup() {
//初始化窗口
Serial.begin(115200);
//设置ESP8266模式
WiFi.mode(WIFI_STA);
//初始化 ESP-NOW
if (esp_now_init() != 0) {
Serial.println("Error initializing ESP-NOW");
return;
}
//设置ESP8266角色:
esp_now_set_self_role(ESP_NOW_ROLE_SLAVE);
//先前创建的功能 测试ESP-NOW通信
esp_now_register_recv_cb(OnDataRecv);
}
void loop(){
}
#include <OneWire.h>
#include <DallasTemperature.h>
// 定义DS18B20数据口连接ESP32的4号IO上
#define ONE_WIRE_BUS D7
// 初始连接在单总线上的单总线设备
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
void setup(void)
{
// 设置串口通信波特率
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// 初始库
pinMode(D7, INPUT_PULLUP);
sensors.begin();
}
void loop(void)
{
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // 发送命令获取温度
Serial.println("DONE");
Serial.print("Temperature for the device 1 (index 0) is: ");
Serial.println(sensors.getTempCByIndex(0));
delay(500);
}
#include <HardwareSerial.h> //导入ESP32串口操作库,使用这个库我们可以把串口映射到其他的引脚上使用
//我们测试需要用到的串口,ESP32一共有3个串口,串口0应该是用于程序烧写和打印输出调试用的,所以我们只用1和2
HardwareSerial MySerial_stm32(1);
void setup() {
Serial.begin(115200);
//串口的开启,这里还可以传一些别的参数,但是我们只传入下面四个最重要的:波特率,默认SERIAL_8N1为8位数据位、无校验、1位停止位,后面两个分别为 RXD,TXD 引脚
MySerial_stm32.begin(115200, SERIAL_8N1, 14, 2);
//MySerial_stm32.updateBaudRate(9600); //重新设置波特率;
//MySerial_stm32.end(); //失能串口,释放占用的资源
}
void loop() {
MySerial_stm32.println("usart test!!!");
delay(1000);
}
#include <ArduinoJson.h>
void setup()
{
// 初始化串口
Serial.begin(9600);
}
void loop() {
/* 构建JSON */
StaticJsonDocument<200> jsonBuffer; //声明一个JsonDocument对象,长度200
/* 构建JSON的另外一种方法 */
DynamicJsonDocument doc(200); // 声明对象的另外一种方法,和上面的 StaticJsonDocument<200> jsonBuffer 一样
char string[100] = {"{\"time1\":45,\"time2\":420,\"time3\":863}"}; // 声明一个JSON数据
obj["time1"] = 123; // 修改原来的值
obj["add"] = 123; // 添加新对象
deserializeJson(doc, string);
JsonObject obj = doc.as<JsonObject>();
// 输出结果:打印构建好的JSON数据
String output2;
serializeJson(doc, output2); // 序列化JSON数据并导出字符串
Serial.println(output2); // 串口打印最后输出的字符串
delay(1000);
}
StaticJsonDocument<200> jsonBuffer2; //声明一个JsonDocument对象,长度200
// 声明一个JSON数据,用作测试
// 反序列化JSON
DeserializationError error = deserializeJson(jsonBuffer2, comdata_ble);
if (error)
{
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
// 解析JSON
long data1 = jsonBuffer2["time1"]; // 读取整形数据
long data2 = jsonBuffer2["time2"]; // 读取整形数据
long data3 = jsonBuffer2["time3"]; // 读取整形数据
// 输出结果:打印解析后的值
Serial.println(data1);
Serial.println(data2);
Serial.println(data3);
#include "esp_camera.h"
#include <WiFi.h>
#define CAMERA_MODEL_AI_THINKER // Has PSRAM
#include "camera_pins.h"
// ===========================
// Enter your WiFi credentials
// ===========================
const char *ssid = "ESP82666";
const char *password = "12345678";
//*********设置固定IP*************//
IPAddress local_IP(192, 168, 137, 184);
// Set your Gateway IP address
IPAddress gateway(192, 168, 137, 1);
IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8); //optional
IPAddress secondaryDNS(8, 8, 4, 4); //optional
void startCameraServer();
void setup() {
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println();
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.frame_size = FRAMESIZE_UXGA;
config.pixel_format = PIXFORMAT_JPEG; // for streaming
//config.pixel_format = PIXFORMAT_RGB565; // for face detection/recognition
config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
config.fb_location = CAMERA_FB_IN_PSRAM;
config.jpeg_quality = 12;
config.fb_count = 1;
// if PSRAM IC present, init with UXGA resolution and higher JPEG quality
// for larger pre-allocated frame buffer.
if(config.pixel_format == PIXFORMAT_JPEG){
if(psramFound()){
config.jpeg_quality = 10;
config.fb_count = 2;
config.grab_mode = CAMERA_GRAB_LATEST;
} else {
// Limit the frame size when PSRAM is not available
config.frame_size = FRAMESIZE_SVGA;
config.fb_location = CAMERA_FB_IN_DRAM;
}
} else {
// Best option for face detection/recognition
config.frame_size = FRAMESIZE_240X240;
#if CONFIG_IDF_TARGET_ESP32S3
config.fb_count = 2;
#endif
}
#if defined(CAMERA_MODEL_ESP_EYE)
pinMode(13, INPUT_PULLUP);
pinMode(14, INPUT_PULLUP);
#endif
// camera init
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init failed with error 0x%x", err);
return;
}
sensor_t * s = esp_camera_sensor_get();
// initial sensors are flipped vertically and colors are a bit saturated
if (s->id.PID == OV3660_PID) {
s->set_vflip(s, 1); // flip it back
s->set_brightness(s, 1); // up the brightness just a bit
s->set_saturation(s, -2); // lower the saturation
}
// drop down frame size for higher initial frame rate
if(config.pixel_format == PIXFORMAT_JPEG){
s->set_framesize(s, FRAMESIZE_QVGA);
}
#if defined(CAMERA_MODEL_M5STACK_WIDE) || defined(CAMERA_MODEL_M5STACK_ESP32CAM)
s->set_vflip(s, 1);
s->set_hmirror(s, 1);
#endif
#if defined(CAMERA_MODEL_ESP32S3_EYE)
s->set_vflip(s, 1);
#endif
if(!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
Serial.println("STA Failed to configure");
}
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (!WiFi.isConnected())
{
delay(500);
Serial.print(".");
}
startCameraServer();
Serial.print("Camera Ready! Use 'http://");
Serial.print(WiFi.localIP());
Serial.println("' to connect");
}
void loop() {
// Do nothing. Everything is done in another task by the web server
delay(10000);
}
#include "esp_camera.h"
#include <WiFi.h>
#include "esp_timer.h"
#include "img_converters.h"
#include "Arduino.h"
#include "fb_gfx.h"
#include "soc/soc.h" //disable brownout problems
#include "soc/rtc_cntl_reg.h" //disable brownout problems
#include "esp_http_server.h"
// 视频传输 http://192.168.xx.xx/
//Replace with your network credentials
const char *ssid = "OPENMV_AP";
const char *password = "12345678";
char incomingPacket[255]; //存储Udp客户端发过来的数据
#define PART_BOUNDARY "123456789000000000000987654321"
// This project was tested with the AI Thinker Model, M5STACK PSRAM Model and M5STACK WITHOUT PSRAM
#define CAMERA_MODEL_AI_THINKER
//#define CAMERA_MODEL_M5STACK_PSRAM
//#define CAMERA_MODEL_M5STACK_WITHOUT_PSRAM
// Not tested with this model
//#define CAMERA_MODEL_WROVER_KIT
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 21
#define Y4_GPIO_NUM 19
#define Y3_GPIO_NUM 18
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
static const char* _STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY;
static const char* _STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n";
static const char* _STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n";
httpd_handle_t stream_httpd = NULL;
static esp_err_t stream_handler(httpd_req_t *req){
camera_fb_t * fb = NULL;
esp_err_t res = ESP_OK;
size_t _jpg_buf_len = 0;
uint8_t * _jpg_buf = NULL;
char * part_buf[64];
res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
if(res != ESP_OK){
return res;
}
while(true){
fb = esp_camera_fb_get();
if (!fb) {
Serial.println("Camera capture failed");
res = ESP_FAIL;
} else {
if(fb->width > 400){
if(fb->format != PIXFORMAT_JPEG){
bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len);
esp_camera_fb_return(fb);
fb = NULL;
if(!jpeg_converted){
Serial.println("JPEG compression failed");
res = ESP_FAIL;
}
} else {
_jpg_buf_len = fb->len;
_jpg_buf = fb->buf;
}
}
}
if(res == ESP_OK){
size_t hlen = snprintf((char *)part_buf, 64, _STREAM_PART, _jpg_buf_len);
res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen);
}
if(res == ESP_OK){
res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len);
}
if(res == ESP_OK){
res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
}
if(fb){
esp_camera_fb_return(fb);
fb = NULL;
_jpg_buf = NULL;
} else if(_jpg_buf){
free(_jpg_buf);
_jpg_buf = NULL;
}
if(res != ESP_OK){
break;
}
//Serial.printf("MJPG: %uB\n",(uint32_t)(_jpg_buf_len));
}
return res;
}
void startCameraServer(){
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.server_port = 80;
httpd_uri_t index_uri = {
.uri = "/",
.method = HTTP_GET,
.handler = stream_handler,
.user_ctx = NULL
};
//Serial.printf("Starting web server on port: '%d'\n", config.server_port);
if (httpd_start(&stream_httpd, &config) == ESP_OK) {
httpd_register_uri_handler(stream_httpd, &index_uri);
}
}
void setup() {
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
Serial.begin(115200);
Serial.setDebugOutput(false);
pinMode(4,OUTPUT); //将8号引脚设置为输出模式
digitalWrite(4,1);//8号引脚输出高电平
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.pixel_format = PIXFORMAT_JPEG;
if(psramFound()){
config.frame_size = FRAMESIZE_UXGA;
config.jpeg_quality = 10;
config.fb_count = 2;
} else {
config.frame_size = FRAMESIZE_SVGA;
config.jpeg_quality = 12;
config.fb_count = 1;
}
// Camera init
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init failed with error 0x%x", err);
return;
}
// Wi-Fi connection
WiFi.mode(WIFI_AP); //设置为AP模式
WiFi.softAP(ssid, password); //配置AP信息,并开启AP
IPAddress softLocal(192,168,4,1); //IP地址,用以设置IP第4字段
IPAddress softGateway(192,168,4,1); //IP网关,用以设置IP第3字段
IPAddress softSubnet(255,255,255,0);
//配置自定义的IP信息
WiFi.softAPConfig(softLocal, softGateway, softSubnet);
IPAddress IP = WiFi.softAPIP(); //用变量IP接收AP当前的IP地址
Serial.println(IP); //打印输出IP的IP地址
digitalWrite(4,0);//8号引脚输出高电平
startCameraServer();
}
void loop() {
delay(1);
}
#include <SPI.h> // 加载SPI库
#include <Wire.h> // 加载Wire库
#include <Adafruit_GFX.h> // 加载Adafruit_GFX库
#include <Adafruit_SSD1306.h> // 加载Adafruit_SSD1306库
// 定义 OLED屏幕的分辨率
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire);
void setup() {
Serial.begin(9600); // 设置串口波特率
Serial.println("OLED FeatherWing test"); // 串口输出
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // 设置OLED的I2C地址
display.clearDisplay(); // 清空屏幕
display.setTextSize(1); // 设置字体大小
display.setTextColor(SSD1306_WHITE); // 设置字体颜色
display.setCursor(0,0); // 设置开始显示文字的坐标
display.println("Hello World!"); // 输出的字符
display.println(" by Lingshunlab.com");
display.display(); // 使更改的显示生效
}
void loop() {
}
void Oled(){
display.clearDisplay(); // 清空屏幕
display.setCursor(0,0); display.print("SSID:"); display.print("ESP82666");
display.display(); // 使更改的显示生效
}
#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>
const char *ssid = "ESP826";
const char *password = "12345678";
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "ntp1.aliyun.com",60*60*8, 30*60*1000);
void setup(){
Serial.begin(115200);
WiFi.begin(ssid, password);
while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 );
Serial.print ( "." );
}
timeClient.begin();
}
//***********进行日期获取*********//
void Time(){
unsigned long epochTime = timeClient.getEpochTime();
//***时间戳******//
// Serial.print("Epoch Time:");
// Serial.println(epochTime);
//将epochTime换算成年月日
struct tm *ptm = gmtime((time_t *)&epochTime);
int monthDay = ptm->tm_mday;
int currentMonth = ptm->tm_mon + 1;
int year = 1900 + ptm->tm_year;
Serial.print(year);
Serial.print("年");
Serial.print(currentMonth);
Serial.print("月");
Serial.print(monthDay);
Serial.println("日");
}
//***********进行时间获取*********//
void Hours(){
int hours = timeClient.getHours();
int minu = timeClient.getMinutes();
int sece = timeClient.getSeconds();
Serial.printf("%d:%d:%d\n", hours,minu,sece);
}
void loop() {
timeClient.update();
Time();
Hours();
delay(1000);
}
运行效果
因为CS和RX引脚复用了。所以在PIN改了引脚,改成了D0;
主要参考这个https://blog.csdn.net/finedayforu/article/details/108727110
#include <Arduino.h>
#include "SD.h"
void setup()
{
Serial.begin(115200);
if (!SD.begin())
{
Serial.print(".");
}
Serial.println("SD card Ready!");
Serial.printf("SD.cardSize = %lld \r\n", SD.cardSize());//SD卡大小
Serial.printf("SD.totalBytes = %lld \r\n", SD.totalBytes());
Serial.printf("SD.usedBytes = %lld \r\n", SD.usedBytes());
Serial.printf("SD.cardType = %d \r\n", SD.cardType());//SD卡类型
Serial.printf("is there /test.txt? :%d \r\n", SD.exists("/sd/doc1/test.txt"));//是否存在文件test.txt
Serial.println(SD.mkdir("/doc1"));//创建文件夹
Serial.printf("is there /doc1? :%d \r\n", SD.exists("/doc1"));//是否存在文件test.txt
Serial.printf("is there /test.txt? :%d \r\n", SD.exists("/test.txt"));//是否存在文件test.txt
File file = SD.open("/test.txt", FILE_WRITE);//创建/打开test.txt,写入
Serial.printf("is there /test.txt? :%d \r\n", SD.exists("/test.txt"));//是否存在文件test.txt
file.printf("hello!!!");//写入hello!!!
file.close();//关闭
file = SD.open("/test.txt", FILE_READ);//读取test.txt文件
Serial.println(file.readString());
file.close();
Serial.printf("is there /doc1/test1.txt? :%d \r\n", SD.exists("/doc1/test1.txt"));
File file2 = SD.open("/doc1/test1.txt", FILE_WRITE);
Serial.printf("is there /doc1/test1.txt? :%d \r\n", SD.exists("/doc1/test1.txt"));
file2.printf("hello!!!");
file2.close();
file2 = SD.open("/test.txt", FILE_READ);
Serial.println(file2.readString());
file2.close();
SD.end();
}
void loop()
{
}
实测可用
#include "FS.h"
#include "SD.h"
#include "SPI.h"
void readFile(fs::FS &fs, const char * path){
Serial.printf("Reading file: %s\n", path);
File file = fs.open(path);
if(!file){
Serial.println("Failed to open file for reading");
return;
}
Serial.print("Read from file: ");
while(file.available()){
Serial.write(file.read());
}
file.close();
}
void appendFile(fs::FS &fs, const char * path, const char * message){
Serial.printf("Appending to file: %s\n", path);
File file = fs.open(path, FILE_APPEND);
if(!file){
Serial.println("Failed to open file for appending");
return;
}
if(file.print(message)){
Serial.println("Message appended");
} else {
Serial.println("Append failed");
}
file.close();
}
void setup(){
Serial.begin(115200);
if(!SD.begin()){
Serial.println("Card Mount Failed");
return;
}
appendFile(SD, "/hello.txt", "World!\n"); // 在hello.txt文件末尾继续写入"World!",然后换行
appendFile(SD, "/hello.txt", "asfdfg!\n"); // 在hello.txt文件末尾继续写入"World!",然后换行
appendFile(SD, "/hello.txt", "asdgfgh!\n"); // 在hello.txt文件末尾继续写入"World!",然后换行
readFile(SD, "/hello.txt"); // 读取hello.txt文件的内容并打印出来
}
void loop(){
}
String comdata = "";
void setup()
{
Serial.begin(9600);
}
void loop()
{
while (Serial.available() > 0)
{
comdata += char(Serial.read());
delay(2);
}
if (comdata.length() > 0)
{
Serial.println(comdata);
comdata = "";
}
}
```cpp
#include <HardwareSerial.h> //导入ESP32串口操作库,使用这个库我们可以把串口映射到其他的引脚上使用
//我们测试需要用到的串口,ESP32一共有3个串口,串口0应该是用于程序烧写和打印输出调试用的,所以我们只用1和2
HardwareSerial MySerial_stm32(1);
void setup() {
Serial.begin(115200);
//串口的开启,这里还可以传一些别的参数,但是我们只传入下面四个最重要的:波特率,默认SERIAL_8N1为8位数据位、无校验、1位停止位,后面两个分别为 RXD,TXD 引脚
MySerial_stm32.begin(115200, SERIAL_8N1, 3, 1);
//MySerial_stm32.updateBaudRate(9600); //重新设置波特率;
//MySerial_stm32.end(); //失能串口,释放占用的资源
}
void loop() {
MySerial_stm32.println("usart test!!!");
delay(1000);
}
## 11.MPU6050
### ESP32
```cpp
```cpp
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Adafruit_MPU6050 mpu;
void setup(void) {
Serial.begin(115200);
// Try to initialize!
if (!mpu.begin()) {
Serial.println("Failed to find MPU6050 chip");
while (1) {
delay(10);
}
}
Serial.println("MPU6050 Found!");
// set accelerometer range to +-8G
mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
// set gyro range to +- 500 deg/s
mpu.setGyroRange(MPU6050_RANGE_500_DEG);
// set filter bandwidth to 21 Hz
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
delay(100);
}
void loop() {
/* Get new sensor events with the readings */
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
/* Print out the readings */
Serial.print("Acceleration X: ");
Serial.print(a.acceleration.x);
Serial.print(", Y: ");
Serial.print(a.acceleration.y);
Serial.print(", Z: ");
Serial.print(a.acceleration.z);
Serial.println(" m/s^2");
Serial.print("Rotation X: ");
Serial.print(g.gyro.x);
Serial.print(", Y: ");
Serial.print(g.gyro.y);
Serial.print(", Z: ");
Serial.print(g.gyro.z);
Serial.println(" rad/s");
Serial.print("Temperature: ");
Serial.print(temp.temperature);
Serial.println(" degC");
Serial.println("");
delay(10);
}
#include <Wire.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
Adafruit_MPU6050 mpu;
void setup(void) {
Serial.begin(115200);
Wire.begin(4,5);
while (!Serial)
delay(10); //初始化MPU-6050传感器。
Serial.println("Adafruit MPU6050 test!");
// 尝试初始化
if (!mpu.begin()) {
Serial.println("not find MPU6050");
while (1) {
delay(10);
}
}
Serial.println("MPU6050 Found!");
mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
Serial.print("加速计范围设置为: ");
switch (mpu.getAccelerometerRange()) {
case MPU6050_RANGE_2_G:
Serial.println("+-2G");
break;
case MPU6050_RANGE_4_G:
Serial.println("+-4G");
break;
case MPU6050_RANGE_8_G:
Serial.println("+-8G");
break;
case MPU6050_RANGE_16_G:
Serial.println("+-16G");
break;
}
mpu.setGyroRange(MPU6050_RANGE_500_DEG);
Serial.print("陀螺仪量程设置为: ");
switch (mpu.getGyroRange()) {
case MPU6050_RANGE_250_DEG:
Serial.println("+- 250 deg/s");
break;
case MPU6050_RANGE_500_DEG:
Serial.println("+- 500 deg/s");
break;
case MPU6050_RANGE_1000_DEG:
Serial.println("+- 1000 deg/s");
break;
case MPU6050_RANGE_2000_DEG:
Serial.println("+- 2000 deg/s");
break;
}
mpu.setFilterBandwidth(MPU6050_BAND_5_HZ);
Serial.print("过滤器带宽设置为: ");
switch (mpu.getFilterBandwidth()) {
case MPU6050_BAND_260_HZ:
Serial.println("260 Hz");
break;
case MPU6050_BAND_184_HZ:
Serial.println("184 Hz");
break;
case MPU6050_BAND_94_HZ:
Serial.println("94 Hz");
break;
case MPU6050_BAND_44_HZ:
Serial.println("44 Hz");
break;
case MPU6050_BAND_21_HZ:
Serial.println("21 Hz");
break;
case MPU6050_BAND_10_HZ:
Serial.println("10 Hz");
break;
case MPU6050_BAND_5_HZ:
Serial.println("5 Hz");
break;
}
Serial.println("");
delay(100);
}
void loop() {
/* 通过读数获取新的传感器事件 */
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
/* 打印出值 */
Serial.print("加速度 X: ");
Serial.print(a.acceleration.x);
Serial.print(", Y: ");
Serial.print(a.acceleration.y);
Serial.print(", Z: ");
Serial.print(a.acceleration.z);
Serial.println(" m/s^2");
Serial.print("角度 X: ");
Serial.print(g.gyro.x);
Serial.print(", Y: ");
Serial.print(g.gyro.y);
Serial.print(", Z: ");
Serial.print(g.gyro.z);
Serial.println(" rad/s");
Serial.print("温度: ");
Serial.print(temp.temperature);
Serial.println(" degC");
Serial.println("");
delay(500);
}
#include "esp_camera.h"
#include <WiFi.h>
#include "esp_timer.h"
#include "img_converters.h"
#include "Arduino.h"
#include "fb_gfx.h"
#include "soc/soc.h" //disable brownout problems
#include "soc/rtc_cntl_reg.h" //disable brownout problems
#include "esp_http_server.h"
// 视频传输 http://192.168.xx.xx/
//Replace with your network credentials
const char* wifi_SSID="ESP82666"; //存储AP的名称信息
const char* wifi_Password="12345678"; //存储AP的密码信息
//*********设置固定IP*************//
IPAddress local_IP(192, 168, 137, 45);
// Set your Gateway IP address
IPAddress gateway(192, 168, 137, 1);
IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8); //optional
IPAddress secondaryDNS(8, 8, 4, 4); //optional
char incomingPacket[255]; //存储Udp客户端发过来的数据
#define PART_BOUNDARY "123456789000000000000987654321"
// This project was tested with the AI Thinker Model, M5STACK PSRAM Model and M5STACK WITHOUT PSRAM
#define CAMERA_MODEL_AI_THINKER
//#define CAMERA_MODEL_M5STACK_PSRAM
//#define CAMERA_MODEL_M5STACK_WITHOUT_PSRAM
// Not tested with this model
//#define CAMERA_MODEL_WROVER_KIT
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 21
#define Y4_GPIO_NUM 19
#define Y3_GPIO_NUM 18
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
static const char* _STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY;
static const char* _STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n";
static const char* _STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n";
httpd_handle_t stream_httpd = NULL;
static esp_err_t stream_handler(httpd_req_t *req){
camera_fb_t * fb = NULL;
esp_err_t res = ESP_OK;
size_t _jpg_buf_len = 0;
uint8_t * _jpg_buf = NULL;
char * part_buf[64];
res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
if(res != ESP_OK){
return res;
}
while(true){
fb = esp_camera_fb_get();
if (!fb) {
Serial.println("Camera capture failed");
res = ESP_FAIL;
} else {
if(fb->width > 400){
if(fb->format != PIXFORMAT_JPEG){
bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len);
esp_camera_fb_return(fb);
fb = NULL;
if(!jpeg_converted){
Serial.println("JPEG compression failed");
res = ESP_FAIL;
}
} else {
_jpg_buf_len = fb->len;
_jpg_buf = fb->buf;
}
}
}
if(res == ESP_OK){
size_t hlen = snprintf((char *)part_buf, 64, _STREAM_PART, _jpg_buf_len);
res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen);
}
if(res == ESP_OK){
res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len);
}
if(res == ESP_OK){
res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
}
if(fb){
esp_camera_fb_return(fb);
fb = NULL;
_jpg_buf = NULL;
} else if(_jpg_buf){
free(_jpg_buf);
_jpg_buf = NULL;
}
if(res != ESP_OK){
break;
}
//Serial.printf("MJPG: %uB\n",(uint32_t)(_jpg_buf_len));
}
return res;
}
void startCameraServer(){
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.server_port = 80;
httpd_uri_t index_uri = {
.uri = "/",
.method = HTTP_GET,
.handler = stream_handler,
.user_ctx = NULL
};
//Serial.printf("Starting web server on port: '%d'\n", config.server_port);
if (httpd_start(&stream_httpd, &config) == ESP_OK) {
httpd_register_uri_handler(stream_httpd, &index_uri);
}
}
void setup() {
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
Serial.begin(115200);
Serial.setDebugOutput(false);
pinMode(4,OUTPUT); //将8号引脚设置为输出模式
digitalWrite(4,1);//8号引脚输出高电平
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.pixel_format = PIXFORMAT_JPEG;
if(psramFound()){
config.frame_size = FRAMESIZE_UXGA;
config.jpeg_quality = 10;
config.fb_count = 2;
} else {
config.frame_size = FRAMESIZE_SVGA;
config.jpeg_quality = 12;
config.fb_count = 1;
}
// Camera init
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init failed with error 0x%x", err);
return;
}
// Wi-Fi connection
WiFi.mode(WIFI_STA);
if(!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
Serial.println("STA Failed to configure");
}
WiFi.begin(wifi_SSID, wifi_Password);
while (!WiFi.isConnected())
{
delay(500);
Serial.print(".");
digitalWrite(4,!digitalRead(4));//8号引脚输出高电平
}
//打印本机IP
Serial.println("Connected");
Serial.print("IP Address:");
Serial.println(WiFi.localIP());
digitalWrite(4,0);//8号引脚输出高电平
startCameraServer();
}
void loop() {
delay(1);
}
#include <DHT.h>
//定义针脚
#define DHTPIN 8
//定义类型,DHT11或者其它
#define DHTTYPE DHT11
//进行初始设置
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin(); //DHT开始工作
}
void loop() {
// 两次检测之间,要等几秒钟,这个传感器有点慢。
delay(2000);
// 读温度或湿度要用250毫秒
float h = dht.readHumidity();//读湿度
float t = dht.readTemperature();//读温度,默认为摄氏度
Serial.print("Humidity: ");//湿度
Serial.println(h);
Serial.print("Temperature: ");//温度
Serial.print(t);
Serial.println(" ℃ ");
}
unsigned char USART_TX_BUF[8]={0x01,0x03,0x00,0x48,0x00,0x08,0xC4,0x1A}; //指令,模块收到该指令后会反馈电流电压值信息HEX
#define TJC Serial2
String str1="";
String str2="";
String a="";
String b="";
String c="";
String d1="";//电压的第1个参数
String d2="";//电压的第2个参数
String d3="";//电压的第3个参数
String d4="";//电压的第4个参数
String e1="";//电流的第1个参数
String e2="";//电流的第2个参数
String e3="";//电流的第3个参数
String e4="";//电流的第4个参数
String f1="";//功率的第1个参数
String f2="";//功率的第2个参数
String f3="";//功率的第3个参数
String f4="";//功率的第4个参数
//String g1="";//电能的第1个参数
//String g2="";//电能的第2个参数
//String g3="";//电能的第3个参数
//String g4="";//电能的第4个参数
//String h1="";//功率因素的第1个参数
//String h2="";//功率因素的第2个参数
//String h3="";//功率因素的第3个参数
//String h4="";//功率因素的第4个参数
//String i1="";//二氧化碳的第1个参数
//String i2="";//二氧化碳的第2个参数
//String i3="";//二氧化碳的第3个参数
//String i4="";//二氧化碳的第4个参数
//String j1="";//频率的第1个参数
//String j2="";//频率的第2个参数
//String j3="";//频率的第3个参数
//String j4="";//频率的第4个参数
long int cmd=0;//字符串转换为整形数据的过程变量
float datas;//测量值
void setup() {
Serial.begin(9600);
TJC.begin(4800);
}
void loop() {
int num = 0;
TJC.write(USART_TX_BUF,8);
delay(200);
for(int i=0; i<=40; i++)
{
str2 = String(TJC.read(),HEX);//将数据以16进制的形式存储进字符串str2
str1 += str2;
str1 += " ";
if(i==0)
{
a = str2;
}
if(i==1)
{
b = str2;
}
if(i==2)
{
c = str2;
}
if(i==3)
{
d1 = str2;
}
if(i==4)
{
d2 = str2;
}
if(i==5)
{
d3 = str2;
}
if(i==6)
{
d4 = str2;
}
if(i==7)
{
e1 = str2;
}
if(i==8)
{
e2 = str2;
}
if(i==9)
{
e3 = str2;
}
if(i==10)
{
e4 = str2;
}
// if(i==11)
// {
// f1 = str2;
// }
// if(i==12)
// {
// f2 = str2;
// }
// if(i==13)
// {
// f3 = str2;
// }
// if(i==14)
// {
// f4 = str2;
// }
// if(i==15)
// {
// g1 = str2;
// }
// if(i==16)
// {
// g2 = str2;
// }
// if(i==17)
// {
// g3 = str2;
// }
// if(i==18)
// {
// g4 = str2;
// }
// if(i==19)
// {
// h1 = str2;
// }
// if(i==20)
// {
// h2 = str2;
// }
// if(i==21)
// {
// h3 = str2;
// }
// if(i==22)
// {
// h4 = str2;
// }
// if(i==23)
// {
// i1 = str2;
// }
// if(i==24)
// {
// i2 = str2;
// }
// if(i==25)
// {
// i3 = str2;
// }
// if(i==26)
// {
// i4 = str2;
// }
// if(i==31)
// {
// j1 = str2;
// }
// if(i==32)
// {
// j2 = str2;
// }
// if(i==33)
// {
// j3 = str2;
// }
// if(i==34)
// {
// j4 = str2;
// }
}
if(str1.charAt(2)=='3')//由于开始几次会得到乱码,第二字符为'3'的时候才进行数据处理
{
//Serial.println(str1);
//<地址>值
if (a.length()<2){a="0"+a;} //当为个位数补0
str2=a;
char charBuf[str2.length() + 1];//String转char*,char*转long,long转10进制数
str2.toCharArray(charBuf, str2.length() + 1) ;
cmd = strtoul(charBuf, NULL, 16);
datas = cmd;
Serial.print("Address:");Serial.println(int(datas));
str2="";
datas=0;
//<地址>值结束
//<命令>值
if (b.length()<2){b="0"+b;} //当为个位数补0
str2=b;
charBuf[str2.length() + 1];//String转char*,char*转long,long转10进制数
str2.toCharArray(charBuf, str2.length() + 1) ;
cmd = strtoul(charBuf, NULL, 16);
datas = cmd;
Serial.print("Command:");Serial.println(int(datas));
str2="";
datas=0;
//<数据长度>值
if (c.length()<2){c="0"+c;} //当为个位数补0
str2=c;
charBuf[str2.length() + 1];//String转char*,char*转long,long转10进制数
str2.toCharArray(charBuf, str2.length() + 1) ;
cmd = strtoul(charBuf, NULL, 16);
datas = cmd;
Serial.print("Data length:");Serial.println(int(datas));
str2="";
datas=0;
//<电压>值
if (d1.length()<2){d1="0"+d1;} //当为个位数补0
if (d2.length()<2){d2="0"+d2;}
if (d3.length()<2){d3="0"+d3;}
if (d4.length()<2){d4="0"+d4;}
str2=d1+d2+d3+d4;
charBuf[str2.length() + 1];//String转char*,char*转long,long转10进制数
str2.toCharArray(charBuf, str2.length() + 1) ;
cmd = strtoul(charBuf, NULL, 16);
datas = cmd *0.0001;
Serial.print("Voltage:");Serial.print(datas,4);Serial.println("V");
str2="";
datas=0;
//<电流>值
if (e1.length()<2){e1="0"+e1;} //当为个位数补0
if (e2.length()<2){e2="0"+e2;}
if (e3.length()<2){e3="0"+e3;}
if (e4.length()<2){e4="0"+e4;}
str2=e1+e2+e3+e4;
charBuf[str2.length() + 1];//String转char*,char*转long,long转10进制数
str2.toCharArray(charBuf, str2.length() + 1) ;
cmd = strtoul(charBuf, NULL, 16);
datas = cmd *0.0001;
Serial.print("Ampere:");Serial.print(datas,4);Serial.println("A");
str2="";
datas=0;
// //<功率>值
// if (f1.length()<2){f1="0"+f1;} //当为个位数补0
// if (f2.length()<2){f2="0"+f2;}
// if (f3.length()<2){f3="0"+f3;}
// if (f4.length()<2){f4="0"+f4;}
// str2=f1+f2+f3+f4;
// charBuf[str2.length() + 1];//String转char*,char*转long,long转10进制数
// str2.toCharArray(charBuf, str2.length() + 1) ;
// cmd = strtoul(charBuf, NULL, 16);
// datas = cmd *0.0001;
// Serial.print("Power:");Serial.print(datas,4);Serial.println("W");
// str2="";
// datas=0;
//
// //<电能>值
// if (g1.length()<2){g1="0"+g1;} //当为个位数补0
// if (g2.length()<2){g2="0"+g2;}
// if (g3.length()<2){g3="0"+g3;}
// if (g4.length()<2){g4="0"+g4;}
// str2=g1+g2+g3+g4;
// charBuf[str2.length() + 1];//String转char*,char*转long,long转10进制数
// str2.toCharArray(charBuf, str2.length() + 1) ;
// cmd = strtoul(charBuf, NULL, 16);
// datas = cmd *0.0001;
// Serial.print("Electric energy:");Serial.print(datas,4);Serial.println("kWh");
// str2="";
// datas=0;
//
// //<功率因素>值
// if (h1.length()<2){h1="0"+h1;} //当为个位数补0
// if (h2.length()<2){h2="0"+h2;}
// if (h3.length()<2){h3="0"+h3;}
// if (h4.length()<2){h4="0"+h4;}
// str2=h1+h2+h3+h4;
// charBuf[str2.length() + 1];//String转char*,char*转long,long转10进制数
// str2.toCharArray(charBuf, str2.length() + 1) ;
// cmd = strtoul(charBuf, NULL, 16);
// datas = cmd *0.001;
// Serial.print("Power factor:");Serial.println(datas,3);
// str2="";
// datas=0;
//
// //<二氧化碳>值
// if (i1.length()<2){i1="0"+i1;} //当为个位数补0
// if (i2.length()<2){i2="0"+i2;}
// if (i3.length()<2){i3="0"+i3;}
// if (i4.length()<2){i4="0"+i4;}
// str2=i1+i2+i3+i4;
// charBuf[str2.length() + 1];//String转char*,char*转long,long转10进制数
// str2.toCharArray(charBuf, str2.length() + 1) ;
// cmd = strtoul(charBuf, NULL, 16);
// datas = cmd *0.0001;
// Serial.print("Carbon dioxide:");Serial.print(datas,4);Serial.println("kg");
// str2="";
// datas=0;
//<频率>值
if (f1.length()<2){f1="0"+f1;} //当为个位数补0
if (f2.length()<2){f2="0"+f2;}
if (f3.length()<2){f3="0"+f3;}
if (f4.length()<2){f4="0"+f4;}
str2=f1+f2+f3+f4;
charBuf[str2.length() + 1];//String转char*,char*转long,long转10进制数
str2.toCharArray(charBuf, str2.length() + 1) ;
cmd = strtoul(charBuf, NULL, 16);
datas = cmd *0.01;
Serial.print("Frequency:");Serial.print(datas);Serial.println("Hz");
str2="";
datas=0;
}
str1 = "";//字符串清空
}
#include <WiFi.h>//默认,加载WIFI头文件
#include "PubSubClient.h"//默认,加载MQTT库文件
const char* ssid = "ESP82666";//修改,你的路由去WIFI名字
const char* password = "12345678";//你的WIFI密码
const char* mqtt_server = "bemfa.com";//默认,MQTT服务器
const int mqtt_server_port = 9501;//默认,MQTT服务器
#define ID_MQTT "c10d9affdff5545b3a6bb80b4fe55d59" //Client ID 修改成自己的,巴法云用户私钥
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(ID_MQTT)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server,mqtt_server_port);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
snprintf(msg,6,"%.2f",10.2); //读取字符并保存在msg
//dtostrf(temp,2,2,msg); // 要转换的float或者double值,转换后整数部分长度,转换后小数部分长度。保存到该char数组中。
Serial.println(msg);
client.publish("ESP32",msg);//修改DS18b20为你的主题名
}
}
int freq = 50; // 1/50秒,50Hz的频率,20ms的周期,这个变量用来存储时钟基准。
int resolution = 8; // 分辨率设置为8,就是2的8次方,用256的数值来映射角度,看下方的占空比函数。
int channel1 = 8; // 通道(高速通道(0 ~ 7)由80MHz时钟驱动,低速通道(8 ~ 15)由 1MHz 时钟驱动。)
const int sg901 = 13;
int channel2 = 9; // 通道(高速通道(0 ~ 7)由80MHz时钟驱动,低速通道(8 ~ 15)由 1MHz 时钟驱动。)
const int sg902 = 12;
int channel3 = 10; // 通道(高速通道(0 ~ 7)由80MHz时钟驱动,低速通道(8 ~ 15)由 1MHz 时钟驱动。)
const int sg903 = 14;
int channel4 = 11; // 通道(高速通道(0 ~ 7)由80MHz时钟驱动,低速通道(8 ~ 15)由 1MHz 时钟驱动。)
const int sg904 = 27;
int jiaodu1=0;
int jiaodu2=0;
int jiaodu3=0;
int jiaodu4=0;
int calculatePWM(int degree) //定义函数用于输出PWM的占空比
{ //0-180度
//20ms周期内,高电平持续时长0.5-2.5ms,对应0-180度舵机角度,参考上面的180度对应图。
const float deadZone = 6.4;//对应0.5ms(0.5ms/(20ms/256))
const float max = 32;//对应2.5ms(2.5ms/(20ms/256))
if (degree < 0)
degree = 0;
if (degree > 180)
degree = 180;
return (int)(((max - deadZone) / 180) * degree + deadZone); //返回度数对应的高电平的数值
}
void setup()
{
Serial.begin(9600);
ledcSetup(channel1, freq, resolution); // 用于设置 LEDC 通道的频率和分辨率。
ledcAttachPin(sg901, channel1); // 将通道与对应的引脚连接
ledcSetup(channel2, freq, resolution); // 用于设置 LEDC 通道的频率和分辨率。
ledcAttachPin(sg902, channel2); // 将通道与对应的引脚连接
ledcSetup(channel3, freq, resolution); // 用于设置 LEDC 通道的频率和分辨率。
ledcAttachPin(sg903, channel3); // 将通道与对应的引脚连接
ledcSetup(channel4, freq, resolution); // 用于设置 LEDC 通道的频率和分辨率。
ledcAttachPin(sg904, channel4); // 将通道与对应的引脚连接
}
void loop()
{
for (int d = 0; d <= 180; d += 10)
{
ledcWrite(channel4, calculatePWM(jiaodu1)); // 输出PWM,设置 LEDC 通道的占空比。
Serial.printf("value=%d,calcu=%d\n", d, calculatePWM(d));
delay(1000);
}
}
云台调试
int freq = 50; // 1/50秒,50Hz的频率,20ms的周期,这个变量用来存储时钟基准。
int resolution = 8; // 分辨率设置为8,就是2的8次方,用256的数值来映射角度,看下方的占空比函数。
int channel1 = 0; // 通道(高速通道(0 ~ 7)由80MHz时钟驱动,低速通道(8 ~ 15)由 1MHz 时钟驱动。)
const int sg901 = 25;
int channel2 = 7; // 通道(高速通道(0 ~ 7)由80MHz时钟驱动,低速通道(8 ~ 15)由 1MHz 时钟驱动。)
const int sg902 = 26;
int jiaodu1=0;
int jiaodu2=0;
int calculatePWM(int degree) //定义函数用于输出PWM的占空比
{ //0-180度
//20ms周期内,高电平持续时长0.5-2.5ms,对应0-180度舵机角度,参考上面的180度对应图。
const float deadZone = 6.4;//对应0.5ms(0.5ms/(20ms/256))
const float max = 32;//对应2.5ms(2.5ms/(20ms/256))
if (degree < 0)
degree = 0;
if (degree > 180)
degree = 180;
return (int)(((max - deadZone) / 180) * degree + deadZone); //返回度数对应的高电平的数值
}
String inputString = ""; // 用于存储接收的数据
bool stringComplete = false; // 判断是否接收完毕
int A = 0; // 存储以 'a' 开头的数字
int B = 0; // 存储以 'b' 开头的数字
void setup()
{
Serial.begin(9600);
ledcSetup(channel1, freq, resolution); // 用于设置 LEDC 通道的频率和分辨率。
ledcAttachPin(sg901, channel1); // 将通道与对应的引脚连接
ledcSetup(channel2, freq, resolution); // 用于设置 LEDC 通道的频率和分辨率。
ledcAttachPin(sg902, channel2); // 将通道与对应的引脚连接
duojijiaodu(0);
inputString.reserve(200); // 预留足够的串口接收数据存储空间
}
void loop()
{
while (Serial.available() > 0)
{
inputString += char(Serial.read());
delay(2);
}
if (inputString.length() > 0)
{
Serial.println(inputString);
if (inputString.charAt(0) == 'a') { // 检查是否以'a'开头
A = inputString.substring(1).toInt(); // 截取数字部分并转换为整数
Serial.print("Value stored in A: ");
Serial.println(A);
ledcWrite(channel1, calculatePWM(A));
} else if (inputString.charAt(0) == 'b') { // 检查是否以'b'开头
B = inputString.substring(1).toInt(); // 截取数字部分并转换为整数
Serial.print("Value stored in B: ");
Serial.println(B);
ledcWrite(channel2, calculatePWM(B));
}
inputString= "";
}
}
void duojijiaodu(int a){
if(a==0){
ledcWrite(channel2, calculatePWM(50));
delay(100);
ledcWrite(channel1, calculatePWM(15));
delay(100);
}
if(a==1){
ledcWrite(channel1, calculatePWM(15));
delay(100);
ledcWrite(channel2, calculatePWM(65));
delay(100);
}
if(a==2){
ledcWrite(channel1, calculatePWM(65));
delay(100);
ledcWrite(channel2, calculatePWM(35));
delay(100);
}
if(a==3){
ledcWrite(channel1, calculatePWM(105));
delay(100);
ledcWrite(channel2, calculatePWM(35));
delay(100);
}
if(a==4){
ledcWrite(channel1, calculatePWM(105));
delay(100);
ledcWrite(channel2, calculatePWM(15));
delay(100);
}
}
// 电位器连接到GPIO 34(模拟ADC1_CH6)
const int potPin = 34;
// 用于存储电位器值的变量
int potValue = 0;
void setup() {
Serial.begin(115200);
delay(1000);
}
void loop() {
// 读取电位计值
potValue = analogRead(potPin);
Serial.println(potValue);
delay(500);
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。