非原创,
引用自:https://techtutorialsx.com/2018/10/19/esp32-esp8266-arduino-protocol-buffers/
对上述英文技术博客做了总结:
1. 先去这个网站下载最新的Nanopb 包
https://jpa.kapsi.fi/nanopb/download/
2.解压,解压之后如下图
3.在Arduino的libraries目录下,C:\Users\{yourUserName}\AppData\Local\Arduino15\libraries
新建Nanopb文件夹, 把上述pb开头的7个文件复制进来
4.在第2步解压后的generator-bin目录下新建proto_files文件夹,并在proto_files文件夹下创建test.proto文件,内容如下:
syntax = "proto3"; message TestMessage { int32 test_number = 1; }
5. 在上述generator-bin目录下打开cmd窗口,执行命令
protoc --nanopb_out=. proto_files/test.proto
执行命令后,proto_files 目录下多了两个文件 test.pb.h 和 test.pb.c
6. 在arduino的主程序.info文件的目录下创建src文件夹,将test.pb.h和test.pb.c复制到src文件夹下
7. arduino的主程序.info文件测试,代码如下
#include "src/test.pb.h" #include "pb_common.h" #include "pb.h" #include "pb_encode.h" void setup() { Serial.begin(115200); uint8_t buffer[128]; TestMessage message = TestMessage_init_zero; pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); message.test_number = 540; bool status = pb_encode(&stream, TestMessage_fields, &message); if (!status) { Serial.println("Failed to encode"); return; } Serial.print("Message Length: "); Serial.println(stream.bytes_written); Serial.print("Message: "); for(int i = 0; i<stream.bytes_written; i++){ Serial.printf("%02X",buffer[i]); } } void loop() { uint8_t buffer[128]; TestMessage message = TestMessage_init_zero; pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); message.test_number = 540; bool status = pb_encode(&stream, TestMessage_fields, &message); if (!status) { Serial.println("Failed to encode"); return; } Serial.print("Message Length: "); Serial.println(stream.bytes_written); Serial.print("Message: "); for(int i = 0; i<stream.bytes_written; i++){ Serial.printf("%02X",buffer[i]); } delay(3000); }
标签:protobuf,proto,ESP32,pb,文件夹,使用,test,Serial,include From: https://www.cnblogs.com/qiyu/p/18641276