element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      • Japan
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Vietnam
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Raspberry Pi
  • Products
  • More
Raspberry Pi
Raspberry Pi Forum PIFACECAD : how to handle keys events btw 2 scripts ?
  • Blog
  • Forum
  • Documents
  • Quiz
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Raspberry Pi to participate - click to join for free!
Featured Articles
Announcing Pi
Technical Specifications
Raspberry Pi FAQs
Win a Pi
Raspberry Pi Wishlist
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • State Not Answered
  • Replies 2 replies
  • Subscribers 674 subscribers
  • Views 507 views
  • Users 0 members are here
  • pifacecad
  • piface_control_and_display
  • raspberry_pi
  • keys
  • raspeberry_pi_accessories
  • piface_control_&_display
  • piface_control&display
  • piface_control
  • piface
Related

PIFACECAD : how to handle keys events btw 2 scripts ?

Former Member
Former Member over 11 years ago

Hi all,

 

Proud new owner of a PiFace CAD, I'm trying to create a script that would "rule them all"... like a tiny OS... I explain image

I'm trying to create a main script that would give a "menu like interface" using the Question Method, easily understandable and useable by new comers (like myself).

 

What I'm trying to achieve with this little project is to be able to use some of the exemples given with the PiFaceCAD (Sysinfo, hangman, weather, tweets...),

with an interface that could be ran straigth out of the box and easily understandable (clear & commented) so it could be tweaked and modified with no knowledge of python.

 

So the project (at least that's how I see it, I may be wrong), would be centered around a main scrypt (the "OS", here called MainExecute.py) that would display the menu like interface,

handle some keys events and launch other scripts/shell commands.

 

here is the code of MainExecute.py (the main script)...

 

#!/usr/bin/env python3

import subprocess
import pifacecad
import sys
PY3 = sys.version_info[0] >= 3
if not PY3:
    print("The script only works with `python3`, try using `python3 MainExecute.py`.")
    sys.exit(1)

from time import sleep
from pifacecad.tools.question import LCDQuestion

cad = pifacecad.PiFaceCAD()

GET_IP_CMD = "hostname --all-ip-addresses"
GET_INFOS_CMD = "python3 sysinfo.py"

def run_cmd(cmd):
    return subprocess.check_output(cmd, shell=True).decode('utf-8')

def get_my_ip():
    return run_cmd(GET_IP_CMD)[:-1]

def get_infos():
##    listener.deactivate()
    return run_cmd (GET_INFOS_CMD)


if __name__ == "__main__":
    
        question = LCDQuestion(question="What do u want?",answers=('My IP','Sys Infos','Hangman', 'Exit'))

        while True:
            answer_index = question.ask()
        
            if answer_index == 0:
                cad.lcd.clear()
                cad.lcd.write("{}\n".format(get_my_ip()))
                sleep(5)
                     
            if answer_index == 1:            
                cad.lcd.clear()
                get_infos()
                     
            else:
                cad.lcd.clear()
                cad.lcd.write("ByeBye")
                print("Byebye")

 

(since I'm not a programmer, I made this script by taking bits and pieces from different scripts found online, so this code isnt clean neither optimised, if you feel like "touching it up" to make it all nice and clean, feel free to do so image)

 

so far, so good... the script launches, the shell commands work, I can get the IP, launch the Sysinfo script, navigate through the menu using the rocking switch BUT

I can't get the keys events interupts from button 0 to 3 to work properly (I've cleaned up the code of my "attempts" in the sake of readibility).

 

Here is the SysInfos.py script that's called by MainExecute.py (it's the just a slightly modified version of the script given as an exemple with the PifaceCAD...)

 

#!/usr/bin/env python3
import sys
import subprocess
import pifacecad
from time import sleep
##from threading import Barrier ## I was messing aroung with barrier to see what it does, havent figured it out yet... :/

cad = pifacecad.PiFaceCAD()

UPDATE_INTERVAL = 10  # 60 * 5 = 5 mins
GET_IP_CMD = "hostname --all-ip-addresses"
GET_TEMP_CMD = "/opt/vc/bin/vcgencmd measure_temp"
TOTAL_MEM_CMD = "free | grep 'Mem' | awk '{print $2}'"
USED_MEM_CMD = "free | grep '\-\/+' | awk '{print $3}'"

temperature_symbol = pifacecad.LCDBitmap(
    [0x4, 0x4, 0x4, 0x4, 0xe, 0xe, 0xe, 0x0])
memory_symbol = pifacecad.LCDBitmap(
    [0xe, 0x1f, 0xe, 0x1f, 0xe, 0x1f, 0xe, 0x0])
temp_symbol_index, memory_symbol_index = 0, 1

def run_cmd(cmd):
    return subprocess.check_output(cmd, shell=True).decode('utf-8')

def get_my_ip():
    return run_cmd(GET_IP_CMD)[:-1]

def get_my_temp():
    return run_cmd(GET_TEMP_CMD)[5:9]

def get_my_free_mem():
    total_mem = int(run_cmd(TOTAL_MEM_CMD))
    used_mem = int(run_cmd(USED_MEM_CMD))
    mem_perc = used_mem / total_mem
    return "{:.1%}".format(mem_perc)

def wait_for_ip():
    ip = ""
    while len(ip) <= 0:
        sleep(1)
        ip = get_my_ip()

def show_sysinfo():
    while True:
        cad.lcd.clear()
        cad.lcd.write("{}\n".format(get_my_ip()))
        cad.lcd.write_custom_bitmap(temp_symbol_index)
        cad.lcd.write(":{}C ".format(get_my_temp()))
        cad.lcd.write_custom_bitmap(memory_symbol_index)
        cad.lcd.write(":{}".format(get_my_free_mem()))
        sleep(UPDATE_INTERVAL)
##        sys.exit(0) ## doesnt quits the script, doesnt work 

if __name__ == "__main__":
    cad.lcd.blink_off()
    cad.lcd.cursor_off()

    if "clear" in sys.argv:
        cad.lcd.clear()
        cad.lcd.display_off()
        cad.lcd.backlight_off()
    else:
        cad.lcd.store_custom_bitmap(temp_symbol_index, temperature_symbol)
        cad.lcd.store_custom_bitmap(memory_symbol_index, memory_symbol)
        cad.lcd.backlight_on()
        cad.lcd.write("Waiting for IP..")
        wait_for_ip()
        show_sysinfo()

 

So, here are the reasons why I come before you :

 

I'd like to be able to use button 4 as a "quit/go back to menu" button (quits whatever the script is doing and go back to the begin of MainExecute.py) from "anywhere" (from a shell command acting like a CTRL+C, from another script... ).

And I'd like to be able to use buttons from 0 to 3, depending on the need of the running script/shell command (a press on btn0 would display the ipV6 adress when running the IP shell command, or would display some other infos while running SysInfos.py, for exemple...)

 

Sorry for the long thread, I could have summit it in few words by saying "I have 2 scripts, and I'd like to be able to quit 1 to go to the other by a press of a button", but I thought that giving you the whole picture would be better image

 

thanks in advance all

 

AP

  • Sign in to reply
  • Cancel
  • Former Member
    0 Former Member over 11 years ago

    Hi Alain,

     

    I did this with 2 while loops of the LCDQuestion tool.

     

    The first

    Mquestion = LCDQuestion(question="Auswahl:",answers=('Drucken','Testdruck','Neustart','Beenden'),selector='#',cad=cad)
    while True:
        main_index = Mquestion.ask()

     

    and this way I go out of the first loop and shutdown.

    if main_index == 3:
                cad.lcd.clear()
                cad.lcd.write("Schalte Aus!!")
                cad.lcd.backlight_off()
                sleep(1)
                cad.lcd.backlight_on()
                sleep(1)
                cad.lcd.backlight_off()
                cad.lcd.clear()
                cad.lcd.display_off()
                shutdown()
                break

     

    Inside this I have a second loop, where I read files_list from an USB stick to print out on my Kiosk Printer.

    Pquestion = LCDQuestion(question="Auswahl Drucken:",answers= file_list,selector='>',cad=cad)

     

    The second while loop can depend until a key is pressed and you make a break and go back to the main menue.

     

    The LCDQuestion is linked to the 3 switches 5,6 and 7 .of the 3-position navigation switch.

    https://github.com/piface/pifacecad/blob/master/pifacecad/tools/question.py

     

     

    # wait for user input
            listener = pifacecad.SwitchEventListener(self.cad)
            listener.register(7, pifacecad.IODIR_ON, self.next_answer)
            listener.register(6, pifacecad.IODIR_ON, self.previous_answer)
            listener.register(5,
                              pifacecad.IODIR_ON,
                              self.select_answer_switch_pressed)

     

     

    So if we want to change the the buttons used we can do this here.

    Better I think is to change the question.py to overwrite the 3 key numbers

     

    def__init__(self,question,answers,selector=">",cad=None, switch_pressed=5, previous_answer=6, next_answer=7 ):
            self.question = question
            self.answers = answers
            self.selector = selector
            self.switch_pressed= switch_pressed
    
            self.previous_answer= previous_answer
    
            self.next_answer=next_answer


    And the user input

     

    # wait for user input
            listener = pifacecad.SwitchEventListener(self.cad)
            listener.register(next_answer, pifacecad.IODIR_ON, self.next_answer)
            listener.register(previous_answer, pifacecad.IODIR_ON, self.previous_answer)
            listener.register(switch_pressed,
                              pifacecad.IODIR_ON,
    self.select_answer_switch_pressed)

     

    If you have any more ideas please let me know.

     

    Thomas

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Former Member
    0 Former Member over 11 years ago in reply to Former Member

    Hi Thomas,

     

    thanks for your help... I'm gonna try your solution tonight and I'll get back to you

    to tell you how well it went image

     

    thanks again image

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube