舵机效果演示视频

目录

1 Arduino 舵机

2 Arduino 超声波传感器

3 舵机+测距传感器

4 Python 绘制动态雷达


1 Arduino 舵机

接线图:

执行代码:

#include <Servo.h>#define  ServoPin  3
Servo baseServo;
int angle_s;int sign;void setup() {baseServo.attach(ServoPin); // 初始化舵机angle_s = 180;baseServo.write(angle_s);sign=1;
}void loop() {while(true){baseServo.write(angle_s);angle_s+=1;}while (true) {baseServo.write(angle_s);     // 舵机转动到angle角度Serial.print("angle: ");   // 在控制台打印出 angle: 180\nSerial.println(angle_s);angle_s += sign;               // 角度增加或减少if (angle_s >= 180 || angle_s <= 0) {     // 当angle转到180°时,i=-1,开始递减; sign *= -1; //sign=sign*-1              // 当angle转到0°时,  i=1, 开始递增;}}}

2 Arduino 超声波传感器


#include <SPI.h>
#define  trigPin   6  //超声波模块的Trig 6#
#define  echoPin   5  //超声波模块的echo 5#// 超声波模块
long duration;
int distance;int calculateDistance(){ //超声波测距后,将距离换算成厘米数,反回。digitalWrite(trigPin, LOW); delayMicroseconds(2);digitalWrite(trigPin, HIGH); delayMicroseconds(10);digitalWrite(trigPin, LOW);duration = pulseIn(echoPin, HIGH); distance= duration*0.034/2;return distance;
}void setup() {pinMode(trigPin, OUTPUT); //超声波模块发射pinMode(echoPin, INPUT); //超声波模块接收 Serial.begin(9600);}void loop() {distance = calculateDistance();Serial.println(distance); }

3 舵机+测距传感器

//#include <SPI.h>
#include <Servo.h>// 超声波模块
#define  trigPin   6  //超声波模块的Trig 6#
#define  echoPin   5  //超声波模块的echo 5#
long duration;
int d;// 舵机模块
#define  ServoPin  3  //底座舵机端口 3#
Servo myServo;
int angle_;
int i = 1;void setup() {Serial.begin(9600);myServo.attach(ServoPin); //初始化舵机pinMode(trigPin, OUTPUT); //超声波模块发射pinMode(echoPin, INPUT); //超声波模块接收}void loop() {while (1) {delay(300);// 开启舵机myServo.write(angle_);Serial.print("a:");Serial.print(angle_);Serial.print(";");// 计算距离d = calculateDistance();Serial.print("d:");Serial.println(d);angle_ += i;if (angle_ >= 180 || angle_ <= 0) {i *= -1;}}}int calculateDistance() {
//超声波测距后,将距离换算成厘米数,反回。
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
d = duration * 0.034 / 2;
return d;
}

4 Python 绘制动态雷达

from plot8 import sub_plot_c
import randompl = sub_plot_c()for i in range(0,180):d = random.randint(0, 40)pl.update(angle=i, c=45, Clockwise=False, alpha=0.1, distance=d)pl.draw_img()pl.clear()for i in range(180,0,-1):d = random.randint(0, 40)pl.update(angle=i, c=45, Clockwise=True, alpha=0.1, distance=d)pl.draw_img()pl.clear()

from matplotlib import colors, pyplot as plt
import math
import numpy as np
import random# 目标:每扫描一个角度的点, 替换该点, 其他的保留class sub_plot_c:def __init__(self):self.x = 0self.x_list = []self.y_list = []# 底线高度self.base_height = 0# 雷达图半径长度self.r_length = 800self.fig = plt.figure(figsize=(16, 10))    # 1500 * 1000    w = 1.5hself.n = 1500 / 1000self.angle = 20self.c = 30self.Clockwise = False     # 逆时针 pre在左, 顺时针 pre在右# 扫描透明度self.alpha = 1.0# 图像背景self.backgroud_inside = "#0A2B56"self.backgroud_outside = "#1675CC"self.line_color = 'white'self.sector = 'white'# 标记点类型self.mark_s = ['o','<','>','s','p','*','+','D','d']self.mark_col = ['#E9E7D0', '#49AED5', 'blue']# 每个角度上存储一种标记self.mark_dict = {}     #[angle, [distance, mark_s, mark_c,]]self.current_distance = 30self.max_distance = 30self.mark_scale = self.r_length / self.max_distanceself.count = 0self.ax = self.fig.add_subplot()plt.ion()def update(self, angle, c, Clockwise, alpha, distance):self.angle = angleself.c = cself.Clockwise = Clockwiseself.alpha = alphaself.current_distance = distance# 交由外部清空def clear(self):plt.pause(0.1)         # 动画延迟plt.ioff()             # 关闭画图的窗口plt.clf() def draw_img(self):     # 画固定图形# 底线plt.plot([-self.r_length, self.r_length], [self.base_height, self.base_height], color=self.line_color)    # x1,x2  y1,y2# 半圆, 弧度0-pi, 整圆, 弧度0-2*pitheta = np.linspace(0, math.pi,180*3)# 2*pi*r, x,y为数组x,y = np.cos(theta)*self.r_length, np.sin(theta)*self.r_lengthy += self.base_height# plt.plot(x, y, color='black')# 画外部背景x_bg = np.linspace(-self.r_length, self.r_length, 100)y_circle_bg = np.sqrt(1-(x_bg/self.r_length)*(x_bg/self.r_length)) * self.r_lengthy_circle_bg += self.base_height# 画内圆背景plt.fill_between(x_bg, self.base_height, y_circle_bg, facecolor=self.backgroud_inside, interpolate=True)# 画外圆线1plt.plot(x, y, color=self.line_color, linewidth=1)# 画外圆线2   x_2,y_2 = np.cos(theta)*self.r_length*0.8, np.sin(theta)*self.r_length*0.8y_2 += self.base_heightplt.plot(x_2, y_2, color=self.line_color, linewidth=1)# 画外圆线3  x_3,y_3 = np.cos(theta)*self.r_length*0.6, np.sin(theta)*self.r_length*0.6y_3 += self.base_heightplt.plot(x_3, y_3, color=self.line_color, linewidth=1)# 画外圆线4  x_4,y_4 = np.cos(theta)*self.r_length*0.4, np.sin(theta)*self.r_length*0.4y_4 += self.base_heightplt.plot(x_4, y_4, color=self.line_color, linewidth=1)# 画外圆线5  x_5,y_5 = np.cos(theta)*self.r_length*0.4, np.sin(theta)*self.r_length*0.4y_5 += self.base_heightplt.plot(x_5, y_5, color=self.line_color, linewidth=1)########################################   画扇形 start  #################################################### pre, end两条线, 前后线在来回摆动的过程中会发生位置的互换,   # 图示标出x_pre_angle = round(math.cos(math.radians(self.angle)),2)y_pre_angle = round(math.sin(math.radians(self.angle)),2)# 扇形角度angle_sec = self.angle + self.c if  self.Clockwise else self.angle - self.cx_end_angle = round(math.cos(math.radians(angle_sec)),2) y_end_angle = round(math.sin(math.radians(angle_sec)),2) # 五种状态: # 1. pre在第二象限, end在第一象限, 扇形面积 = (圆-pre) - (end-base_height);# 2. pre,end都在第二象限, 扇形面积 = (圆-pre) - (圆-end);# 3. pre,end都在第一象限, 扇形面积 = (圆-pre) - (圆-end);# 4. end 与 90°重合, 扇形面积 = (圆-pre)# 5. pre 与 90°重合, 扇形面积 = (圆-end)x_pre = x_pre_angle * self.r_lengthy_pre = y_pre_angle * self.r_lengthx_end = x_end_angle * self.r_lengthy_end = y_end_angle * self.r_length# 构建填充数据集if self.Clockwise :if self.angle + self.c <= 180:             # 解决夹角过小,无法填充满的问题x_left = x_endx_right = x_preelse:x_left = -self.r_lengthx_right = x_preelse:if self.angle >= self.c:x_left = x_prex_right = x_endelse:x_left = x_prex_right = self.r_lengthif max([x_pre, x_end]) < 0:x_right = 0elif min([x_pre, x_end]) > 0:x_left = 0x = np.linspace(x_left, x_right, 100)# x=sqrt(1-sin(theta)^2)*r   (x/r)^2 = 1 - sin(theta)^2    sin(theta)^2 = 1-(x/r)^2    sin(theta) = sqrt(1-(x/r)^2)  y=sqrt(1-(x/r)^2)*r# pre边的斜率if x_pre != 0:k_pre_line = ((y_pre + self.base_height) -(0 + self.base_height)) / (x_pre-0)y_pre_line = k_pre_line * x y_pre_line += self.base_height# 圆周的描点# x=sqrt(1-sin(theta)^2)*r   (x/r)^2 = 1 - sin(theta)^2    sin(theta)^2 = 1-(x/r)^2    sin(theta) = sqrt(1-(x/r)^2)  y=sqrt(1-(x/r)^2)*ry_circle = np.sqrt(1-(x/self.r_length)*(x/self.r_length)) * self.r_length# end边的斜率if x_end != 0:k_end_line = ((y_end+self.base_height) -(0+self.base_height)) / (x_end-0)y_end_line = k_end_line * x y_end_line += self.base_height# 加上向上偏移y_circle += self.base_heightx_temp = x - 1 if self.Clockwise else  x + 1# 1.if (x_pre_angle < 0 and x_end_angle > 0) or (x_pre_angle > 0 and x_end_angle < 0):plt.fill_between(x, y_pre_line, y_circle, facecolor=self.sector, interpolate=True, alpha = self.alpha)plt.fill_between(x_temp, self.base_height, y_end_line, facecolor=self.backgroud_inside,interpolate=True)# 2. elif x_pre_angle < 0 and x_end_angle < 0:plt.fill_between(x, self.base_height, y_circle, facecolor=self.sector, interpolate=True, alpha = self.alpha)if self.Clockwise:x_temp_2 =   x + 1plt.fill_between(x_temp_2, y_pre_line, y_circle, facecolor=self.backgroud_inside,interpolate=True)plt.fill_between(x_temp, self.base_height, y_end_line, facecolor=self.backgroud_inside,interpolate=True)else:x_temp_2 =   x - 1plt.fill_between(x_temp, y_end_line, y_circle, facecolor=self.backgroud_inside,interpolate=True)plt.fill_between(x_temp_2, self.base_height, y_pre_line, facecolor=self.backgroud_inside,interpolate=True)# 3.elif x_pre_angle > 0 and x_end_angle > 0:plt.fill_between(x, self.base_height, y_circle, facecolor=self.sector, interpolate=True, alpha = self.alpha)if self.Clockwise:x_temp_2 =   x + 1plt.fill_between(x_temp_2, self.base_height, y_pre_line, facecolor=self.backgroud_inside,interpolate=True)plt.fill_between(x_temp, y_end_line, y_circle, facecolor=self.backgroud_inside,interpolate=True)else:x_temp_2 =   x - 1plt.fill_between(x_temp, self.base_height, y_end_line, facecolor=self.backgroud_inside,interpolate=True)plt.fill_between(x_temp_2, y_pre_line, y_circle, facecolor=self.backgroud_inside,interpolate=True)# 4.elif x_end_angle == 0:plt.fill_between(x, y_pre_line, y_circle, facecolor=self.sector, interpolate=True, alpha = self.alpha)# 5.elif x_pre_angle == 0:plt.fill_between(x, y_end_line, y_circle, facecolor=self.sector, interpolate=True, alpha = self.alpha)print(x_pre_angle, x_end_angle, )plt.fill_between(x, 0, self.base_height, facecolor=self.backgroud_outside, interpolate=True)########################################   画扇形 end  #################################################### 画外圆背景plt.fill_between(x_bg, y_circle_bg, 1000, facecolor=self.backgroud_outside, interpolate=True)# 画下面的背景plt.fill_between(x_bg, 0, self.base_height, facecolor=self.backgroud_outside, interpolate=True)# 画刻度表示plt.fill_between(x_bg, y_circle_bg, 1000, facecolor=self.backgroud_outside, interpolate=True)# 画数据标识plt.fill_between(x_bg, 0, self.base_height, facecolor=self.backgroud_outside, interpolate=True)# 画刻度线标识 从0到180度, 每20°标记一下for angle_text in range(0, 181, 20):x_text = round(math.cos(math.radians(angle_text)),2) * self.r_lengthy_text = round(math.sin(math.radians(angle_text)),2) * self.r_lengthx_text -= 8y_text += self.base_height + 2plt.text(x_text, y_text, str(angle_text),fontsize=12, color = '#38C0B0')# 记录数据plt.text(-self.r_length, 950, 'Randar Scan: ',fontsize=25, color = 'white')plt.text(-self.r_length + 340, 950, 'ON',fontsize=25, color = 'white')plt.text(-self.r_length, 900, 'Pluse: ',fontsize=20, color = 'white')plt.text(-self.r_length + 160, 900, 'S2',fontsize=20, color = 'white')plt.text(-self.r_length, 860, 'current_angle: ',fontsize=15, color = 'white')plt.text(-self.r_length + 270, 860, str(self.angle),fontsize=15, color = 'white')plt.text(-self.r_length, 820, 'current_distance: ',fontsize=15, color = 'white')plt.text(-self.r_length + 270, 820, str(self.current_distance),fontsize=15, color = 'white')plt.text(-self.r_length, 780, 'current_count: ',fontsize=15, color = 'white')plt.text(-self.r_length + 270, 780, str(self.angle),fontsize=15, color = 'white')# 画标记点s = random.randint(0, len(self.mark_s)-1)c = random.randint(0, len(self.mark_col)-1)# plt.plot(100, 100, self.mark_s[s], color=self.mark_col[c])#############################  根据距离画点 start  ####################################### 如果当前点的距离没发生变化, 则不更新# 如果当前点的距离大于30,则画空值, 如果小于30,则位置信息全部更新#[angle, [distance, mark_s, mark_c,]]if self.angle not in self.mark_dict.keys():if self.current_distance <= self.max_distance:self.mark_dict[self.angle] = [self.current_distance, self.mark_s[s], self.mark_col[c]]self.count += 1else:self.mark_dict[self.angle] = [0, self.mark_s[s], self.mark_col[c]]if self.mark_dict[self.angle][0] != self.current_distance:if self.current_distance > self.max_distance:self.mark_dict[self.angle] = [self.current_distance, "", self.mark_col[c]]self.count -= 1else:self.mark_dict[self.angle] = [self.current_distance, self.mark_s[s], self.mark_col[c]]if self.mark_dict[self.angle][0]:self.count +=1# 打印出所有点for k,v in self.mark_dict.items():x_mark = round(math.cos(math.radians(k)),2) * v[0] * self.mark_scaley_mark = round(math.sin(math.radians(k)),2) * v[0] * self.mark_scaleplt.plot(x_mark, y_mark, v[1], color=v[2])plt.axis('off')plt.xlim(-self.r_length, self.r_length)plt.ylim(0, 1000)def release():plt.show()

Arduino+Python 测距雷达相关推荐

  1. [ Arduino+Python ] 做一个串口屏,显示CPU使用率

     Arduino 和 Python 虽然是不同的编程语言,但并不影响共同实现一个制作.(传统说法就是一个在上位机编程,一个给下位机编程) 只需要下图所示的两个常见零件 UNO 和 LCD 盾板( 2. ...

  2. arduino python firmate_processing firmata协议及数组训练

    要求: 最初想法:绘制一个图形,通过图形的变化或者鼠标点击什么图案,arduino上面的led灯亮暗变换. 因为想熟练数组的运用,所以在绘制图形的时候想通过数组来绘制图形,但是我发现如果一味的想运用上 ...

  3. 管道无损检测python_基于PYTHON的多通道漏磁检测系统设计

    基于 PYTHON 的多通道漏磁检测系统设计 * 李广凯 , 周庆祥 , 肖君武 [摘 要] 针对钢管漏磁检测中存在单通道探头检测效率低,缺陷定量困难,仪 器不便携带等难题,根据漏磁检测原理设计了一套 ...

  4. 图片 标记 软件_如何设计软件功能标记

    图片 标记 软件 A previous company had a problem: our deploys were thousands of lines in size, took nearly ...

  5. 编程一直犯低级错误怎么办_大多数学生在学习编程时犯的错误

    编程一直犯低级错误怎么办 We grew up hearing that every individual is different, but surprisingly, I have seen hu ...

  6. xbox 0x_Xbox Series X之路

    xbox 0x I have been a PlayStation owner, with one exception, since the release of Sony's venerable f ...

  7. raspberrypi python传感器_Raspberry Pi和Arduino读取串行传感器d

    我有一个电压传感器连接到我的Arduino uno,它又连接到我的树莓皮3.我想抓住传感器的信息在乒乓式的方式从阿杜诺到树莓派.我将通过cronjob上的Python脚本发送一个字符来唤醒它,并将传感 ...

  8. python和arduino串口通信_利用串行通信实现python与arduino的同步

    我有一个需要:使用arduino将伺服电机移动到某个位置并在该位置停止 让一个由python控制的相机在那个位置获取图像 当图像被采集到时,伺服机构应该移动到一个对称的位置 这个序列重复N次 所以我尝 ...

  9. python arduino c_从Python向Arduino LCD发送一个字符串

    我想用python在arduinolcd16x2上显示一个字符串,但是我遇到了串行通信的问题.在 以下是Arduino中运行的代码: Arduino代码#include LiquidCrystal l ...

最新文章

  1. mysql导出excel命令,在命令行导出MySQL数据到excel表
  2. 网站性能分析(下)-让网站并行加载但顺序执行JS
  3. C++ Primer 5th笔记(chap 18 大型程序工具)noexcept
  4. c# linq的差集,并集,交集,去重【转】
  5. 不会部署并调试SpringBoot源码?一看必会IDEA操作
  6. poj2752Seek the Name, Seek the Fame【kmp next数组应用】
  7. AWS 挂了 11 个小时:因多处光缆被挖断
  8. Excel用控件动态控制图表
  9. 微信小程序的统一服务消息 uniformMessage.send
  10. C#使用WebProxy实现代理访问webservice
  11. HTML5期末大作业:动漫电网站设计——动漫电影《你的名字》(7页) HTML+CSS大作业: 动漫电网页制作作业_动漫电网页设计...
  12. 【图像分割】基于方向谷形检测实现静脉纹路分割附MATLAB代码
  13. stm32智能小车设计(1)——硬件选型思路
  14. 联合利华营销||轻扬是如何突出重围做到无懈可击的?
  15. mysql8.0 安装与卸载
  16. 创建一个数据库,包括四个表:学生表(Student)、课程表(Course)、成绩表(Score)以及教师信息表(Teacher)
  17. Shader Graph 小草顶点动画
  18. 跟踪算法(一)光流法跟踪
  19. 贝叶斯预测模型 (数学原理与推导)
  20. 芯片巨头恩智浦的前世今生

热门文章

  1. Mysql多表关联不走索引的原因
  2. 分别画出奥运五环和四个矩形
  3. Java多线程 -- 线程的优先级
  4. 单千兆网卡+esxi6.5 +爱快+黑群晖 打造家庭千兆网络及nas 观看4K无码高清电影
  5. ECharts 地图使用
  6. screw 一颗螺丝钉的使命
  7. php电子报账系统,我校财务网上自助报账系统上线运行
  8. FineReport_文本切换图表
  9. [性格][管理]《九型人格2》 -- 唐·理查德·里索(美)、拉斯·赫德森(美)
  10. 头条算法题:产品经理,程序员任务调度、用户喜好值算法等等