Voltmeter
The Python program running on the computer or Raspberry Pie follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | #!/bin/python3
# Lets import the requred libraries
import serial # Needed to read from the serial port
from tkinter import * # sudo apt-get install python3-tk, needed to create the GUI
from tkinter import messagebox # Needed to display a message bos with an error message
# Constants
SERIAL_PORT = '/dev/ttyUSB0' # This is the USB port we're using
SERIAL_RATE = 4800 # This is the baudrate from the PIC
# Variables
global R1 # Resistor; GND to PIC input
global R2 # Resistor; Input power to PIC input
global vout # Voltage fromthe voltage divider and into the PIC
global vin # Voltage calculated from the Vout, Voltage in to the voltage divider
# Make the main window
window = Tk() # This creates a window
window.title("DVM") # Set the title of the window
window.geometry('270x250') # Set the size of the window
# Functions
# This function ends the program
def quit():
window.quit()
# This function read voltage and do the calculations. If the USB port is not found,
# an error message is displayed
def read_volt():
R1 = 100600 # Measured with multimeter to get a bit more accurate. Std value = 100000
R2 = 9950 # Measured with multimeter to get a bit more accurate. Std value = 10000
try:
ser = serial.Serial(SERIAL_PORT, SERIAL_RATE) # Assign
reading = ser.readline() # Read the AD value from the PIC
vout = (int(reading)* 5.0) / 1024.0 # Calculate AD back to voltage
vin = vout / (R2/(R1+R2)) # Calculate original voltage
new_volt = ('{0:0.2f}'.format(vin)) # Format the new_voltage to two decimals
lbl_volt.config(text=new_volt) # Setting the text on the label
lbl_volt.after(600, read_volt) #
except:
print ('Not found')
messagebox.showerror('Not found','''\
Cannot find USB to TTL
Hit OK to exit.''')
sys.exit()
# Make and place labels
lbl_header = Label(window, text="Digital voltmeter", font=("Helvetica", 26))
lbl_header.place(x=130, y=30, anchor="center")
lbl_volt = Label(window, text="0.00", font=("DSEG7 Classic", 48))
lbl_volt.place(x=120, y=120, anchor="center")
# Make and place buttons
btn_quit = Button(window, text="Quit", command=quit)
btn_quit.place(relx=0.5, y=200, anchor="center")
#This is needed to "autorun" this function, remove () and it will no "autorun"
btn_start = Button(window, text="Start", command=read_volt())
#btn_start.place(relx=0.5, y=200, anchor=W)
# Run the mainloop
window.mainloop()
# ASCIL drawing of the voltage divider
# | <- input voltage
# |
# |
# --
# || <- R2
# --
# |
# +- <- To PIC
# |
# --
# || <- R1
# --
# |
# |
# | <- to GND
|