1
#!/usr/bin/python
#Python 3.7.3
# Attempting to plot the ADC values coming from the PICO
# Program contains only necessary lines of code for testing plot routine
# The Raspberry PI Pico is connected to the Raspberry PI B+ via USB cable
# Plot the detected flaw return from a 200uS, 20000hZ pulse burst
# fired at a rep rate of 10 pulses per second.
# The plot updates the data but scrolls to the left like a strip chart.
# This is not desirable. Must show plot similar to an Oscilloscope.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import threading
import board
import analogio
import time
from tkinter import *
import numpy as np
from numpy import array, sign, zeros

master = Tk()

####   Setup the tk canvas   #############
master.geometry('800x600') 
master.configure(bg='#2B3D3C')   # Custom background color(Midnight Forest)
master.attributes('-fullscreen',False)# Set to True to fill screen
title = Label(master, text="PICO PLOTTING TEST", bg="gray20",
              relief=RAISED,bd=3,fg="deep sky blue",
              font=("helvetica 12")) 
title.pack()

#################################################################
###   CREATE THE PLOT CANVAS   ##################################
#################################################################
c = Canvas(master,relief=SUNKEN,bd=5.5, #  DEFINE THE CANVAS ON PROGRAM POWER UP
width=573,height=465, bg="#2B3D3C")     ## SET SIZE AND COLOR OF THE PLOT CANVAS ###
c.place(x=100, y=25)                    ## Placing the canvas

fig = plt.figure(figsize = (5.71, 4.14))
fig.patch.set_facecolor('#2B3D3C')   #sets the plot window border color

canvas = FigureCanvasTkAgg(fig, master)   
canvas.draw()
canvas.get_tk_widget().place(x= 107.5, y= 58)    

plot1 = fig.add_axes((0, 0, 1, 1)) # Fills Window #
plot1.patch.set_facecolor('#2B3D3C')

##  SET MAJOR TICKS TO SHOW EVERY 20  ###  
plot1.xaxis.set_major_locator(MultipleLocator(50))
plot1.yaxis.set_major_locator(MultipleLocator(50))

###  SET MINOR TICKS TO SHOW EVERY 5. (20/4 =5)
plot1.xaxis.set_minor_locator(AutoMinorLocator(2))
plot1.yaxis.set_minor_locator(AutoMinorLocator(2))

###  TURN ON GRID FOR BOTH MAJOR AMD MINOR TICKS AND STYLE THEME  ###
plot1.grid(which='major', color='grey', linestyle='-')
plot1.grid(which='minor', color='darkgray', linestyle=':')

########  SETTING THE BORDER AND THE MINOR TICKS  #######################

plot1.patch.set_edgecolor("white")
plot1.patch.set_linewidth('1')
plot1.set_axisbelow(True)


### Parameters   ##################
x_len = 300                   # Number of points to display
y_range = [-20,300]              # Range of possible Y values to display

xs = list(range(0, 300))
ys = [0] * x_len
plot1.set_ylim(y_range)

###  Initialize communication with the pico
reading = analogio.AnalogIn(board.ADC0)

###   Create plot line
line, = plot1.plot(xs, ys, color= "yellow")

### Get ADC Analog values from the PICO
analog_value = analogio.AnalogIn(board.ADC0)

def get_voltage(raw):
    return (raw * 3.3) / 4095

def plot():    #### Set thread
    def animate(i, ys):
        # Read data from Pico
        raw = analog_value.value
        volts = get_voltage(raw)

        #   Add y to list
        ys.append(volts)

        #   Limit y list to set number of items
        ys = ys[-x_len:]

        #   Update line with new y values
        line.set_ydata(ys) 
        print("ADC:", volts) 
        return line,

    ### Set up plot to call animate() function
    ani = animation.FuncAnimation(fig, animate, fargs=(ys,),interval=.1, blit=True)
    plt.show()

print("thread starting")
t = threading.Thread(name='plot', target=plot)
t.setDaemon(True)
t.start()    

####  Create Quit Button
Bbutton_1 = Button(master, text = 'Quit',
        command= quit) ## QUIT #############
Bbutton_1.config(cursor='arrow')
Bbutton_1.config(bd=25, relief=RAISED)
Bbutton_1.config(bg='black', fg='white')
Bbutton_1.config(font=('helvetica', 10,"bold"))
Bbutton_1.place(x=1, y=515)

master.mainloop()
6
  • 1
    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
    – Community Bot
    Sep 28 at 20:41
  • Simply put I need to capture 400 microseconds of ADC output once every 100 milliseconds and plot the result. The program now captures continuously and plots all points similar to a strip chart recorder. My x-axis time factor is not correct in relation to y-data.
    – R Bowles
    Sep 28 at 22:57
  • what is preventing you from stopping the data capture?
    – jsotola
    Sep 28 at 23:39
  • My x-axis which is the time base seems to run for an infinite amount of time. This allows my changing y data to be plotted as if I were inputting the data into a chart recorder and plotting on a paper strip which would go until it ran out of paper or the unit was turned off. The data or return pulse is 400 microseconds in width. .1 to 3.3volts in amplitude and occurs every 100 milliseconds which is the rep rate. I want the return plot to be displayed as the same on a scope set at 200 microseconds.
    – R Bowles
    Sep 29 at 0:06
  • I defy anyone to decode the above mess. Try writing modular code and assigning one task to a module. In addition if you ignore the author's warning and include both RPi.GPIO and gpiozero you are just making things more difficult.
    – Milliways
    Sep 29 at 4:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.