Skip to content

Instantly share code, notes, and snippets.

@danjperron
Created August 1, 2023 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danjperron/8b5f82d95ae705f4981c3f17734a2858 to your computer and use it in GitHub Desktop.
Save danjperron/8b5f82d95ae705f4981c3f17734a2858 to your computer and use it in GitHub Desktop.
pico PIO frequency reader
'''
*
*
* The MIT License (MIT)
*
* Copyright (c) 2023 Daniel Perron
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
'''
''' this is a program to read the duration of the high pulse in micro-second '''
from rp2 import PIO, asm_pio
from machine import Pin, mem32
import math
import utime
@asm_pio()
def FREQ_TRIGGER_PIO():
set(x,0)
label('loopH1')
jmp(x_dec,'loopH2')
label('loopH2')
nop()
nop()
jmp( pin, 'loopH1')
mov(isr,x)
push()
set(x,0)
label('loopH3')
jmp(x_dec,'loopH4')
label('loopH4')
nop()
jmp( pin, 'loopH1')
jmp( 'loopH3')
print("start")
thePin = machine.Pin(14,Pin.IN,Pin.PULL_UP)
clock = 125_000_000
sm = rp2.StateMachine(0)
sm.init(FREQ_TRIGGER_PIO, freq=clock,
in_base = thePin, jmp_pin = thePin)
sm.active(1)
count =0
#clean first delay
sm.get()
sm.get()
sum=0.0
sumSquare=0.0
freqMin = 120.0
freqMax = 0.0
while count<3600:
freq = (clock / 4)/(0xfffffffe - sm.get())
if freq>freqMax:
freqMax=freq
if freq<freqMin:
freqMin=freq
sum+= freq
sumSquare += (freq * freq)
count+=1
average= sum/count
sumOfVariance = sumSquare - ( sum * average)
stdev = math.sqrt(sumOfVariance / ( count -1))
print("Statistique de la ligne de puissance 60Hz sur ",count, " cycles")
print("moyenne (Hz): {:2.4f} +/- {:0.4f}".format(sum/count,stdev))
print("Minimum (Hz): ",freqMin)
print("Maximum (Hz): ",freqMax)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment