0

I currently have some code that I found that constantly outputs a value from a digital caliper. However, I want to modify this so that it is inside a function that can return that is returned from show() after the callback is executed. Is there any way that this is possible?

I have tried global variables with no success.

I currently have this:

#!/usr/bin/env python

# caliper.py
# 2015-10-03
# Public Domain

import time

import pigpio

CLOCK=21
DATA=20

g_level=0
g_reading=0
g_bits=0

def show(bits, value):

   inch = value & (1<<23)
   minus = value & (1<<20)

   value = value & 0xfffff

   if inch:
      reading = value / 2000.0
      units = "in"
   else:
      reading = value / 100.0
      units = "mm"

   if minus:
      sign = "-"
   else:
      sign = ""

   print("{} {:.3f} {}".format(sign, reading, units))

def cbf(g, l, t):
   global g_level, g_reading, g_bits
   if g == DATA:
      if l == 0:
         g_level = 1
      else:
         g_level = 0
   elif g == CLOCK:
      if l == pigpio.TIMEOUT:
         if g_bits > 10:
            show(g_bits, g_reading)
            g_reading=0
            g_bits=0
      elif l == 0:
          g_reading = g_reading | (g_level<<g_bits)
          g_bits += 1

pi = pigpio.pi()

pi.set_mode(CLOCK, pigpio.INPUT)
pi.set_mode(DATA, pigpio.INPUT)

cb1 = pi.callback(DATA, pigpio.EITHER_EDGE, cbf)
cb2 = pi.callback(CLOCK, pigpio.EITHER_EDGE, cbf)
pi.set_watchdog(CLOCK, 20) # 20 ms reading timeout

time.sleep(120)

cb2.cancel()
cb1.cancel()
pi.stop()

Is there anyway that this is possible?

Many thanks in advance.

  • It's not clear if the code in your question works or not. Does it correctly show the caliper value? – joan Jul 18 at 17:03
  • @joan yes it does – danwillm Jul 18 at 17:03
0

You could add a global last_reading and adjust show as follows. Then whenever you want the last reading just print last_reading.

last_reading = ""

def show(bits, value):
   global last_reading
   inch = value & (1<<23)
   minus = value & (1<<20)

   value = value & 0xfffff

   if inch:
      reading = value / 2000.0
      units = "in"
   else:
      reading = value / 100.0
      units = "mm"

   if minus:
      sign = "-"
   else:
      sign = ""

   last_reading = "{} {:.3f} {}".format(sign, reading, units)
  • Would this mean keeping the loop but waiting, say 1/2 sec for it to wait and read last_reading outside the loop? – danwillm Jul 18 at 20:05

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.