Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
难以将Python连接到Arduino 基于Python+Arduino的雷达绘图仪 # #**适用于任何输出角度旋转的电机 #**和任何距离传感器(HC-SR04、VL53L0x、激光雷达) # 将numpy作为np导入 导入matplotlib mat_Python_Arduino - Fatal编程技术网

难以将Python连接到Arduino 基于Python+Arduino的雷达绘图仪 # #**适用于任何输出角度旋转的电机 #**和任何距离传感器(HC-SR04、VL53L0x、激光雷达) # 将numpy作为np导入 导入matplotlib mat

难以将Python连接到Arduino 基于Python+Arduino的雷达绘图仪 # #**适用于任何输出角度旋转的电机 #**和任何距离传感器(HC-SR04、VL53L0x、激光雷达) # 将numpy作为np导入 导入matplotlib mat,python,arduino,Python,Arduino,难以将Python连接到Arduino 基于Python+Arduino的雷达绘图仪 # #**适用于任何输出角度旋转的电机 #**和任何距离传感器(HC-SR04、VL53L0x、激光雷达) # 将numpy作为np导入 导入matplotlib matplotlib.use('TkAgg') 将matplotlib.pyplot作为plt导入 从matplotlib.widgets导入按钮 导入串行、系统、全局 导入serial.tools.list_端口 端口=列表(serial.tool

难以将Python连接到Arduino 基于Python+Arduino的雷达绘图仪 # #**适用于任何输出角度旋转的电机 #**和任何距离传感器(HC-SR04、VL53L0x、激光雷达) # 将numpy作为np导入 导入matplotlib matplotlib.use('TkAgg') 将matplotlib.pyplot作为plt导入 从matplotlib.widgets导入按钮 导入串行、系统、全局 导入serial.tools.list_端口 端口=列表(serial.tools.list\u ports.comports()) 对于端口中的p: 印刷品(p) #找到Arudino端口,选择一个,然后开始与它通信 ############################################ # def端口_搜索(): 如果sys.platform.startswith('win'):#Windows 端口=['COM{0:1.0f}'。范围(1256)内ii的格式(ii)] 印刷品(“同性恋”) 其他: raise EnvironmentError('计算机与pyserial不兼容') arduinos=[] 对于端口中的端口:#循环以确定是否可访问 如果len(端口拆分('Bluetooth'))大于1: 打印(“GI”) 持续 尝试: ser=串行。串行(端口) 塞尔克洛斯() 如果我们可以打开它,就把它看作是一个阿杜迪诺。 打印(“GF”) 除了(OSError,serial.SerialException): 打印(“GH”) 通过 返回arduinos arduino\u端口=端口搜索() ser=serial.serial()#匹配Arduino上的波特率 ser.port=arduino_端口[0] ser.baudrate=9600 ser.flush()#清除端口 # ############################################ #启动交互式打印工具并 #使用虚拟数据绘制180度图以开始 ############################################ # 图=plt.图(facecolor='k') win=fig.canvas.manager.window#figure window screen_res=win.wm_maxsize()#用于以后的窗口格式化 dpi=150.0#图形分辨率 fig.set_dpi(dpi)#设置图形分辨率 #极坐标图属性和初始条件 ax=fig.add_子图(111,polar=True,facecolor='#006d70') 最大设定位置([-0.05,-0.05,1.1,1.05]) r_max=100.0#可以根据传感器的范围进行更改 ax.set_ylim([0.0,r_max])#要显示的距离范围 ax.set_xlim([0.0,np.pi])#受伺服范围(0-180度)限制 ax.勾选参数(axis='two',colors='w') 最大网格(颜色=w',α=0.5)#网格颜色 ax.set_rticks(np.linspace(0.0,r_max,5))#显示5种不同的距离 ax.set_thetagrids(np.linspace(0.0180.0,10))#显示10个角度 角度=np.arange(0,181,1)#0-180度 θ=角度*(np.pi/180.0)#到弧度 距离=np.one((len(angles),)#虚拟距离,直到收到真实数据 pols,=ax.plot([],线型='',标记=o',标记面颜色=w', MarkerEdge颜色='#EFEFEF',MarkerEdge宽度=1.0, markersize=10.0,alpha=0.9)#用于雷达点的点 line1,=最大绘图([],color='w',线宽=4.0)#扫臂绘图 #图列报调整 图设置尺寸英寸(0.96*(屏幕分辨率[0]/dpi),0.96*(屏幕分辨率[1]/dpi)) plot_res=图。获取_window_extent()。边界#用于居中的窗口范围 wm_几何体('+{0:1.0f}+{1:1.0f}'\ 格式(屏幕分辨率[0]/2.0)-(绘图分辨率[2]/2.0), (屏幕分辨率[1]/2.0)-(绘图分辨率[3]/2.0))#居中绘图 图canvas.toolbar.pack_-forget()#移除工具栏以获得清晰的演示文稿 图画布设置窗口标题(“Arduino雷达”) 图canvas.draw()#循环前绘制 axbackground=fig.canvas.copy_from_bbox(ax.bbox)#background在循环期间保留 ############################################ #停止程序的按钮事件 ############################################ def停止_事件(事件): 全球停车场 停止布尔=1 程序停止=图添加轴([0.85,0.025,0.125,0.05]) pstop=按钮(prog_stop_ax,'stop Program',color='fcfc',hovercolor='w') pstop.on_单击(停止事件) #关闭窗口的按钮 def关闭_事件(事件): 全球停止,关闭 如果停止,请执行以下操作: plt.close(“全部”) 停止布尔=1 关闭布尔=1 关闭轴=图添加轴([0.025,0.025,0.125,0.05]) 关闭按钮(关闭按钮,“关闭绘图”,颜色='#fcfc',hovercolor='w') 关闭,但单击时(关闭事件) 图2(图3) ############################################ #在有限循环中,不断更新 #180度雷达,接收Arduino数据 ############################################ # 开始单词,停止单词,关闭单词=假,假,假 尽管如此: 尝试: 如果停止编程:#停止程序 图canvas.toolbar.pack_configure()#显示工具栏 如果关闭布尔:#关闭雷达窗口 plt.close(“全部”) 打破 ser_bytes=ser.readline()#读取Arduino串行数据 解码字节=序列字节。解码('utf-8')#将数据解码为utf-8 数据=(已解码的_字节。替换('\r','')。替换('\n','') 印刷品(“137”) 如果开始输入单词: 对于数据中的ii.split(','): 持续 VAL=浮动(二) 打印(“11”) 如果len(vals)r_max: dist=0.0#测量值大于r#u max,可能不准确 打印(“145”) 距离[内部(角度)]=距离 如果角度%5==0:#每5度更新一次 印刷品(“148”) pols.set_数据(θ,dists) 图canvas.restore_区域(axbackground) ax.draw_艺术家(pols) 第1行。设置数据(np.重复((角度*(np.pi/180.0)),2), np.linspace(0.0,r_max,2)) ax.draw_艺术家(第1行) 图canvas.blit(ax.bbox)#仅复制数据 图canvas.flush_events()#为下一个绘图刷新 其他: 如果数据==‘雷达启动’:#在Arduino上启动单词 start_word=True#等待Arduino输出start word 打印('雷达启动…') 打印(“10”) 其他: 持续 除键盘中断外: plt.close(“全部”) 打印('键盘中断') 打破
# Python + Arduino-based Radar Plotter
#
# ** Works with any motor that outputs angular rotation
# ** and with any distance sensor (HC-SR04, VL53L0x,LIDAR)
#
import numpy as np
import matplotlib

matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import serial, sys, glob
import serial.tools.list_ports



ports = list(serial.tools.list_ports.comports())
for p in ports:
    print (p)

# Find Arudino ports, select one, then start communication with it
############################################
#
def port_search():
    if sys.platform.startswith('win'):  # Windows
        ports = ['COM{0:1.0f}'.format(ii) for ii in range(1, 256)]
        print ("Gay")
    else:
        raise EnvironmentError('Machine Not pyserial Compatible')

    arduinos = []
    for port in ports:  # loop through to determine if accessible
        if len(port.split('Bluetooth')) > 1:
            print("GI")
            continue

        try:
            ser = serial.Serial(port)
            ser.close()
            arduinos.append(port)  # if we can open it, consider it an arduino
            print ("GF")
        except (OSError, serial.SerialException):
            print("GH")
            pass
    return arduinos


arduino_ports = port_search()
ser = serial.Serial()# match baud on Arduino
ser.port = arduino_ports[0]
ser.baudrate = 9600
ser.flush()  # clear the port
#
############################################
# Start the interactive plotting tool and
# plot 180 degrees with dummy data to start
############################################
#
fig = plt.figure(facecolor='k')
win = fig.canvas.manager.window  # figure window
screen_res = win.wm_maxsize()  # used for window formatting later
dpi = 150.0  # figure resolution
fig.set_dpi(dpi)  # set figure resolution

# polar plot attributes and initial conditions
ax = fig.add_subplot(111, polar=True, facecolor='#006d70')
ax.set_position([-0.05, -0.05, 1.1, 1.05])
r_max = 100.0  # can change this based on range of sensor
ax.set_ylim([0.0, r_max])  # range of distances to show
ax.set_xlim([0.0, np.pi])  # limited by the servo span (0-180 deg)
ax.tick_params(axis='both', colors='w')
ax.grid(color='w', alpha=0.5)  # grid color
ax.set_rticks(np.linspace(0.0, r_max, 5))  # show 5 different distances
ax.set_thetagrids(np.linspace(0.0, 180.0, 10))  # show 10 angles
angles = np.arange(0, 181, 1)  # 0 - 180 degrees
theta = angles * (np.pi / 180.0)  # to radians
dists = np.ones((len(angles),))  # dummy distances until real data comes in
pols, = ax.plot([], linestyle='', marker='o', markerfacecolor='w',
                markeredgecolor='#EFEFEF', markeredgewidth=1.0,
                markersize=10.0, alpha=0.9)  # dots for radar points
line1, = ax.plot([], color='w', linewidth=4.0)  # sweeping arm plot

# figure presentation adjustments
fig.set_size_inches(0.96 * (screen_res[0] / dpi), 0.96 * (screen_res[1] / dpi))
plot_res = fig.get_window_extent().bounds  # window extent for centering
win.wm_geometry('+{0:1.0f}+{1:1.0f}'. \
                format((screen_res[0] / 2.0) - (plot_res[2] / 2.0),
                       (screen_res[1] / 2.0) - (plot_res[3] / 2.0)))  # centering plot
fig.canvas.toolbar.pack_forget()  # remove toolbar for clean presentation
fig.canvas.set_window_title('Arduino Radar')

fig.canvas.draw()  # draw before loop
axbackground = fig.canvas.copy_from_bbox(ax.bbox)  # background to keep during loop


############################################
# button event to stop program
############################################

def stop_event(event):
    global stop_bool
    stop_bool = 1


prog_stop_ax = fig.add_axes([0.85, 0.025, 0.125, 0.05])
pstop = Button(prog_stop_ax, 'Stop Program', color='#FCFCFC', hovercolor='w')
pstop.on_clicked(stop_event)


# button to close window
def close_event(event):
    global stop_bool, close_bool
    if stop_bool:
        plt.close('all')
    stop_bool = 1
    close_bool = 1


close_ax = fig.add_axes([0.025, 0.025, 0.125, 0.05])
close_but = Button(close_ax, 'Close Plot', color='#FCFCFC', hovercolor='w')
close_but.on_clicked(close_event)

fig.show()

############################################
# inifinite loop, constantly updating the
# 180deg radar with incoming Arduino data
############################################
#
start_word, stop_bool, close_bool = False, False, False
while True:
    try:
        if stop_bool: # stops program
            fig.canvas.toolbar.pack_configure() # show toolbar
            if close_bool: # closes radar window
                plt.close('all')
            break
        ser_bytes = ser.readline() # read Arduino serial data
        decoded_bytes = ser_bytes.decode('utf-8') # decode data to utf-8
        data = (decoded_bytes.replace('\r','')).replace('\n','')
        print ("137")

        if start_word:
            for ii in data.split(','):
                continue
            vals = float(ii)
            print ("11")
            if len(vals)<2:
                print ("141")
                continue
            angle,dist = vals # separate into angle and distance
            if dist > r_max:
                dist = 0.0 # measuring more than r_max, it's likely inaccurate
                print ("145")
            dists[int(angle)] = dist

            if angle % 5 ==0: # update every 5 degrees
                print ("148")
                pols.set_data(theta,dists)
                fig.canvas.restore_region(axbackground)
                ax.draw_artist(pols)

                line1.set_data(np.repeat((angle*(np.pi/180.0)),2),
                   np.linspace(0.0,r_max,2))
                ax.draw_artist(line1)

                fig.canvas.blit(ax.bbox) # replot only data
                fig.canvas.flush_events() # flush for next plot
        else:
            if data =='Radar Start': # start word on Arduino
                start_word = True # wait for Arduino to output start word
                print('Radar Starting...')
                print ("10")
            else:
                continue



    except KeyboardInterrupt:
        plt.close('all')
        print('Keyboard Interrupt')
        break