1、C:\px4\Firmware\msg中添加mytopic.msg,在文件裏聲明你的存放數據的結構體成員變量(注意:僅僅是成員變量。如結構體爲structmyuorb_test_s{uint16 r};,那麼.msg文件中就寫uint16 r 就可以了)。
好吧那我們就寫uint16 b;// rand()需要無符號整形
2、文件寫好了在當前文件夾中的CMakeList.txt編譯腳本文件中添加我們的msg,還是打開虛擬機在裏面寫吧。(要怎麼備份是個問題,直接副本好了ps:win10還沒去設置改後綴名的鬼東西,差點把txt當成msg)註冊後,在編譯固件時會自動生成myuorb_test.h文件,該文件裏定義了數據結構體mytopic_s及ORB_DECLARE。
3、要在代碼中使用主題,首先添加頭文件:
#include <uORB/topics/topic_name.h>
①在/Firmware/src/modules中創建文件夾mytopic_test,打開,裏面新建CMakeLists.txt
參照px4_simple_app的寫法:
px4_add_module(
MODULEmodules__mytopic_test
MAIN mytopic_test
STACK_MAIN2000
COMPILE_FLAGS
-Os //這個我看別的module有我就加了,還是去掉吧
SRCS
mytopic_test.cpp //我們新建的源文件
DEPENDS
platforms__common
)
②新建mytopic_test.cpp,從px4_simple_app.c裏面copy過來一些東西,改一些東西:
//包含頭文件
#include <px4_config.h>
#include <px4_tasks.h>
#include <px4_posix.h>
#include <unistd.h>
#include <stdio.h>
#include <poll.h>
#include <string.h>
#include <uORB/uORB.h>
#include <uORB/topics/mytopic.h> //這是我們定義的主題
//這裏要加extern "C",不然編譯的時候會說你沒有聲明這個main函數,但是px4_simple_app裏面是沒有的。鬱悶
extern "C"__EXPORT int mytopic_test_main(int argc, char *argv[]);
int mytopic_test_main(int argc, char *argv[]) //主函數
{
PX4_INFO("Hello Sky!This is my topic test!!!"); //打印
//publish data
//先訂閱獲取句柄mytopic_sub→與ID關聯
intmytopic_sub = orb_subscribe(ORB_ID(mytopic));
structmytopic_s rd; //定義類型爲mytopic_s的結構體變量rd
rd.b=rand()%100;// 0~100取隨機數,然後賦值給結構體rd中的成員變量b
// 之前的 uint16 b
//調用公告接口定義orb_advert_t類型的 mytopic_pub句柄→與ID關聯
orb_advert_t mytopic_pub = orb_advertise(ORB_ID(mytopic), &rd);
orb_publish(ORB_ID(mytopic), mytopic_pub, &rd);//publish
PX4_WARN("the new data is: \t%d",rd.b);//把此時生成的隨機數b打印
//rd的b
boolupdated;
structmytopic_s rdreceive;//定義結構體類型爲mytopic_s的結構體變量
orb_check(mytopic_sub,&updated); //檢查有沒有更新,
//有更新返回updated爲ture
if(updated)
{
//把更新的數據返回到rdreceive中,從b→b,不一樣的b
orb_copy(ORB_ID(mytopic),mytopic_sub,&rdreceive);
//打印從我們的topic獲取的數據b, rdreceive的b
PX4_WARN("the updated data is: \t%d",rdreceive.b);
}
else
{
PX4_WARN("data is not updated");
}
PX4_INFO("exiting");
return0;
}
測試結果如下: