C++
1.获取时间戳
1.chrono
#include <chrono>
auto time = chrono::system_clock::now(); // 获取代码结束时的时间戳
计算时间差
CString runTime;
runTime.Format(_T("%d"), chrono::duration_cast<chrono::microseconds>(finish - start) / 1000);
2.SYSTEMTIME
CString strTime;
SYSTEMTIME systime;
GetLocalTime(&systime);
strTime.Format("%02d:%02d:%02d:%03d", systime.wHour, systime.wMinute, systime.wSecond, systime.wMilliseconds);
2.数据写入TXT
#include <fstream>
FILE *file;
file = fopen("send.txt", "a");
fprintf(file, "%s\t 0x%08x\t", currTime, ID);
fclose(file);
3.十六进制与十进制转换
a.一位十六进制转换为十进制
int HexChar(char c)
{
if((c>='0') && (c<='9'))
return c-0x30;
else if((c>='A') && (c<='F'))
return c-'A'+10;
else if((c>='a') && (c<='f'))
return c-'a'+10;
else
return 0x10;
}
b.两位十六进制数转换为十进制
int Str2Hex(CString str)
{
int len = str.GetLength();
if(len == 2)
{
int a= HexChar(str[0]);
int b =HexChar(str[1]);
if(a==16 || b==16 )
{
AfxMessageBox("Format error");
return 256;
}
else
{
return a*16+b;
}
}
else
{
AfxMessageBox("input length must be 2");
return 256;
}
}
c.将int整数分割到数组
int i=?;
char data[32];
sprintf(data, "%016X", i);
std::string out;
int d = 7;
for (char c : data)
{
out += c;
if (out.size() == 2)
{
CString str5 = out.c_str();
if (d >= 0)
sendbuf->Data[d] = Str2Hex(str5);
d--;
out.clear();
}
}
4.数据类型转换
a.CString -> float、int
CString str;
str.Format(_T("%3.1f%%"), xxx);
CString str=“1234”;
int num = _ttoi(str);
b.Byte与int ,double 转
https://blog.csdn.net/sunnyfans/article/details/8286906
1.Byte与int
uint8_t ary[4] = { 176,4,0,0 };
int value;
//低位在前,高位在后
value = (int)((ary[0] & 0xFF)
| ((ary[1] << 8) & 0xFF00)
| ((ary[2] << 16) & 0xFF0000)
| ((ary[3] << 24) & 0xFF000000));
std::cout << value << std::endl;
2.Byte与double
uint8_t lat[8] = {0};
memcpy(lat, canMsg.Data, canMsg.DataLength);
memcpy(&gpsInfo.lat, lat, sizeof(double));
5.多线程
#include <thread>
std::thread CAN1Thread(&CDemoCANDlg::CAN1sendDataThread_, this, 0, begin1, num1, id1);
std::thread CAN2Thread(&CDemoCANDlg::CAN2sendDataThread_, this, 1, begin2, num2 ,id2);
CAN1Thread.join();
CAN2Thread.join();
//类中开启最好用detach脱离主线程
std::thread CAN1Thread(&CDemoCANDlg::CAN1sendDataThread_, this );
CAN1Thread.detach();
https://blog.csdn.net/weixin_39603908/article/details/110453554
6.队列 deque
#include <deque>
std::deque< [ struct ]> Can1MsgQueue;
7.函数返回vector
1.头文件中声明一个vector
std::vector<int> spivec;
2.声明一个函数用于外部获取返回
std::vector<int> test(int i);
3.类中给 retvec赋值并返回
std::vector<int> SPI::test(int i)
{
for(int j=0; j<i ;j++)
spivec.push_back(j);
return spivec;
}
4.外部函数调用
SPI spi;
std::vector<int > tvec=spi.test(100);
std::cout<<"tvec.size()="<<tvec.size()<<std::endl;
QT
安装QT
sudo apt-get install qt5-default qt5-qmake g++ qtcreator
生成可执行文件
在pro文件中加入
QMAKE_LFLAGS += -no-pie
查看可执行文件依赖及其路径:
ldd [可执行文件名]
数据类型转换
QString & string
1.QString转换String
string s = qstr.toStdString();
2.String转换QString
QString qstr2 = QString::fromStdString(s);
选指定目录下的文件
QDir dir( path);
//QDir dir(QDir::currentPath());//当前文件路径
QString filtername = "*.bin";
QStringList filter;
filter << filtername;
dir.setNameFilters(filter);
QStringList Neuronindex = dir.entryList();
for(int i=0;i< Neuronindex.size();i++)
qDebug()<<Neuronindex.at(i);
qDebug()<<QString::number(Neuronindex.size());
QString split() & mid()
QStringList strList=str.split(“/”);
QString str;
str.mid(开始,取的长度);
QString compare
QString::compare(“ab”,“ab”); //值为0;
QT-ROS
1.寻找qtcreator路径
2.打开: sudo gedit org.qt-project.qtcreator.desktop
3.修改: Exec=bash -c “source /opt/ros/melodic/setup.bash;qtcreator”
QT文件操作
判断文件是否存在并创建
QSring logPath="/home/xx"
void MainWindow::logCreated()
{
logPath+="/log";
QDir dirlog(logPath);
if(!dirlog.exists())
{
dirlog.mkdir(logPath);
qDebug()<<"log 文件夹创建成功";
}
logPath+= "/"+QDateTime::currentDateTime().toString("yyyy-MM-dd");
qDebug()<<"logPath="<<logPath;
QDir dir(logPath);
if(!dir.exists())
{
dir.mkdir(logPath);
qDebug()<<QDateTime::currentDateTime().toString("yyyy-MM-dd")<<"文件夹创建成功";
}
}
按行读取文件数据
QFile file(strPath+"/upList.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
return 0;
}else{
while(!file.atEnd()){
QByteArray line = file.readLine();
QString str(line);
upList<<str.mid(0,str.size()-1);
}
QFile::remove(strPath+"/upList.txt");
}
写入文件数据
void MainWindow::logInfo(QString logName,QString strInfo)
{
QDateTime dt = QDateTime::currentDateTime();
QString strPath=logPath+"/"+logName+".log";
// 文件位置
QFile file(strPath);
if(!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)){
return;
}
// 文件流
QTextStream stream(&file);
// 输入内容
stream << dt.toString("yyyy-MM-dd-hh-mm-ss")<<" : "<<strInfo<<"\n";
file.close();
}
ROS
1.安装ros
2. 创建一个ros工作空间
https://blog.csdn.net/xx970829/article/details/123160267
1. 创建一个工作空间:
//创建工作空间
mkdir -p ~/catkin_ws/src
//初始化
cd ~/catkin_ws/src
catkin_init_workspace
//编译
cd ~/catkin_ws/
catkin_make
//添加环境变量
source devel/setup.bash
2. 创建一个工功能包:
cd ~/catkin_ws/src
// 功能包命名为:my_first_cpp
catkin_create_pkg [name] std_msgs rospy roscpp
3.配置节点
//如果没有其他依赖,只需修改biuld
//找到 “Declare a C++ executable”
//将“add_executable()”的注释取消
add_executable(${PROJECT_NAME}_node src/my_first_cpp_node.cpp)
//将“add_dependencies()”的注释取消
add_dependencies(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
//将“target_link_libraries()”的注释取消
target_link_libraries(${PROJECT_NAME}_node
${catkin_LIBRARIES}
)
//然后编译
catkin_make
//假设其节点名为“other_node”
add_executable(other_node src/other_node.cpp )
target_link_libraries(other_node ${catkin_LIBRARIES} )
3.订阅、发布节点
std_msgs
发布
#include "ros/ros.h"
#include "std_msgs/String.h"
1.sheng ming
ros::NodeHandle n;
ros::Publisher CAN1_pub;
str_pub = n.advertise<std_msgs::String>("/strMsg",100);
2.
std_msgs::String strMsg;
strMsg.data="xxxxxx";
str_pub.publish(strMsg);
订阅
ros::NodeHandle n;
ros::Subscriber sub;
sub = n.subscribe<std_msgs::String>("/strMsg", 10, subCallback);
void subCallback(const std_msgs::String::ConstPtr& msg);
sub_mm = n.subscribe<std_msgs::String>("/mmvMsg", 10, &mmv_Analyst::subCallback,this);
4.ROS参数
https://blog.csdn.net/Kalenee/article/details/85019830
1.cpp
bool boolLight;
ros::param::get("/boolLight", boolLight);
ros::param::set("lightState", true);
2.roslaunch param
<rosparam file="$(find perception)/config/Param.yaml" command="load" />
cpp:
n.param<float>("perceptionParam/timeCycle", timeCycle, 0.04);
n.param<float>("perceptionParam/cycleThr", cycleThr, 3);
n.param<vector<float>>("perceptionParam/camTriggerDisVec", camTriggerDisVec, vector<float> {30, 20, 15, 10, 7, 5, 3});
3.wai bu she zhi
openLight -> rosparam set /openLight true
closeLight -> rosparam set /openLight false
5.roslaunch
<launch>
<rosparam file="$(find perception)/config/Param.yaml" command="load" />
<-- node调用方式为:<node pkg="功能包名" type="可执行文件名" name="重定义名"/-->
<node name="CAN_analyst" pkg="perception" type="CAN_analyst" output="screen"/>
<node name="mmv_analyst" pkg="perception" type="mmv_analyst" output="screen"/>
</launch>
Ubuntu
1.安装cmake
sudo apt-get install cmake
sudo apt-get install cmake-curses-gui
sudo apt-get install cmake-qt-gui
2.cmake安装、卸载软件
mkdir build
cd build
cmake ..
make -j16
sudo make install
//指定目录
sudo make install DESTDIR=/usr/local/vtk1.7
//卸载
方1.sudo make uninstall
方2.sudo xargs rm < install_manifest.txt
方3.sudo rm -r [文件夹名]
3. json
安装
方1:nlohmann/json
https://download.csdn.net/download/xx970829/87174406
#include "json.hpp"
using json = nlohmann::json;
方2:
sudo apt-get install libjsoncpp-dev
#include <jsoncpp/json/json.h>
CMakeLists.txt配置
1.build后面加入
set(JSON_INCLUDE_DIR ${CMAKE_CURRENT_LIST_DIR}/../thirdParty/json)
2.include_directories中加入
${JSON_INCLUDE_DIR}
用法
https://blog.csdn.net/fuhanghang/article/details/115305968
1.数据赋值
json canMsgJson;
canMsgJson["fdcanx"]=currentCanMsg.fdcanx;
canMsgJson["DataLength"]=currentCanMsg.DataLength;
canMsgJson["IdType"]=currentCanMsg.IdType;
canMsgJson["Rsvd"]=currentCanMsg.Rsvd;
canMsgJson["Id"]=currentCanMsg.Id;
canMsgJson["Data"]=currentCanMsg.Data;
2. json转字符串
std_msgs::String strMsg;
strMsg.data=canMsgJson.dump();
3. 字符串转转json
json canMsgJson=json::parse(msg->data.c_str());
canMsgJson.at("fdcanx").get_to(canMsg.fdcanx);
canMsgJson.at("DataLength").get_to(canMsg.DataLength);
canMsgJson.at("IdType").get_to(canMsg.IdType);
canMsgJson.at("Rsvd").get_to(canMsg.Rsvd);
canMsgJson.at("Id").get_to(canMsg.Id);
canMsgJson.at("Data").get_to(canMsg.Data);
4.查找软件路径
whereis [软件名]
5.复制、移动、查找、删除文件
查找
sudo find / -name libQVTKWidgetPlugin.so动态链接库的路径
复制
sudo cp -a [原文件路径+文件名] [目标文件路径]
移动
sudo mv [原文件路径+文件名] [目标文件路径]
删除
sudo rm -r [文件夹名]
6.root
进入root : su root
更新root密码: sudo passwd root
7. home扩容
https://blog.csdn.net/w20178556/article/details/120575904
8.bash脚本
#!/bin/bash
gnome-terminal -- bash -c 'source /opt/ros/melodic/setup.bash && roscore'&
gnome-terminal -- bash -c 'source /home/xx/catkin_ws/devel/setup.bash && rosrun mmw mmw_node'&
gnome-terminal -- bash -c 'source /home/xx/catkin_ws/devel/setup.bash && rosrun control ctrl_node'&
vim
o -> 光标下面插入行
i -> 光标处开始编辑
esc -> 退出编辑
:wq! -> 强制保存退出
https://blog.csdn.net/weixin_44368437/article/details/126173588
重启网络
sudo nmcli networking off
sudo nmcli networking on
VScode
1.安装vscode
https://code.visualstudio.com/Download
https://blog.csdn.net/qq_40660130/article/details/116229710#:~:text=ubuntu%20%E4%B8%8B%20%E5%AE%89%E8%A3%85VS%20Code%20%E5%AE%89%E8%A3%85%20%E8%BF%87%E7%A8%8B%201.%E4%B8%8B%E8%BD%BD%20VS,%EF%BC%9A%20sudo%20dpkg%20-i%20code_1.37.0-1565227985_amd64.deb%20%E7%84%B6%E5%90%8E%E7%AD%89%E5%BE%85%20%E5%AE%89%E8%A3%85%20%E5%AE%8C%E6%88%90%E3%80%82
sudo dpkg -i code_1.68.1-1655262036_arm64.deb
解决国内下载慢的问题:
将下载链接中的“https://az764295.vo.msecnd.net”改为“https://vscode.cdn.azure.cn”
复制原下载链接
如:https://az764295.vo.msecnd.net/stable/b3e4e68a0bc097f0ae7907b217c1119af9e03435/code_1.78.2-1683731010_amd64.deb
改为:https://vscode.cdn.azure.cn/stable/b3e4e68a0bc097f0ae7907b217c1119af9e03435/code_1.78.2-1683731010_amd64.deb
2.Astyle
1.sudo apt install astyle
2.vscode 插件
3.插件setting
"astyle.cmd_options": [
"--style=google", //风格格式和缩进
"--indent=spaces=4", //缩进4个空格
"--convert-tabs",
"--align-pointer=name",
"--align-reference=name",
"--keep-one-line-statements",
"--pad-header",
"--pad-oper", //操作符两端插入一个空格
],
"astyle.additional_languages": [
"c",
"cpp",
],
"[cpp]": {
"editor.defaultFormatter": "chiehyu.vscode-astyle"
}
MFC
1.MessageBox
1.常见用法
MessageBox(“open Dev failed”);
2.显示字符串
MessageBox(str, “输入的内容是”, MB_OK);
3.选择判断
int x = MessageBox("xxxxxxxxxxx, "标题", MB_ICONQUESTION | MB_YESNO);
if(x==7){
...
}
elas{
...}
- MFC中
AfxMessageBox(“send error\n”);
2.线程
1.声明
typedef struct MyParam
{
//VCI_CAN_OBJ sendbuf_[1];
BYTE Data[8];
UINT ID;
int canIndex;
CString currTime;
int runTime = 0;
int num = 0;
float sleep=0;
std::chrono::time_point<std::chrono::system_clock> clockTime;
}param;
static UINT newThread(void *param);
2.
AfxBeginThread(newThread, (void*)&Param, THREAD_PRIORITY_TIME_CRITICAL, 0);
PCL
打开、保存PCD
pcl::io::savePCDFileASCII("allCloud.pcd", *cloud);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr newCloud (new pcl::PointCloud<pcl::PointXYZRGB>);
if (pcl::io::loadPCDFile("allCloud.pcd", *newCloud) < 0)
{
qDebug()<<"点云文件不存在!";
return ;
}
pcl_viewer
sudo apt-get install pcl-tools
类型转换
1.转指针
cloud.meakShared()
python
1.读取、显示图像
img = cv2.imread(“./data/3.jpg”)
cv2.imshow(“img”, img)
cv2.waitKey(0)
2.数组与图像互转
数组转图像
img_array=np.array(img)
图像转数组
img_thresh = Image.fromarray(np.uint8(th_array))
from PIL import Image
img_thresh =np.asanyarray(th_array,dtype=np.uint8)
3.BGR、LAB互转
BGR2LAB
img_lab= cv2.cvtColor(img,cv2.COLOR_BGR2LAB)
LAB2BGR
img_bgr= cv2.cvtColor(img,cv2.COLOR_LAB2BGR)
4.通道分割、合并
分割
L,A,B=cv2.split(img_lab)
合并
img_lab=cv2.merge([L,A,B])
5.灰度化、阈值分割
img_gray= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_blurred = cv2.GaussianBlur(img_gray, (3, 3), 0)
img_thresh = cv2.threshold(img_blurred, 200, 255, cv2.THRESH_BINARY)[1]
6.腐蚀、膨胀
img_thresh = cv2.erode(img_thresh, None, iterations=3)
img_thresh = cv2.dilate(img_thresh, None, iterations=3)