简体   繁体   中英

How to assign keyboard keys to a GPIO command in Python Raspberry PI

I am trying to make a Raspberry Pi robot using Python and I don't really know how to use curses to assign a key to a movement. I am very new to this and would like some help.

I wrote my try at the code below:

import RPi.GPIO as GPIO
import curses 
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7,GPIO.OUT)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
try: 
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    stdscr.keypad(1)
    while 1:
        c = stdscr.getch()
        if c == ord('p'):
             stdscr.addstr("")
        elif c == 37:
            GPIO.output(7,False)
            GPIO.output(11,True)
            GPIO.output(13,False)
            GPIO.output(13,True)

finally: 
    curses.nocbreak(); stdscr.keypad(0)l curses.echo
    curses.endwin()
    GPIO.cleanup()

I keep getting the following error:

Traceback (most recent call last):
File "/home/pi/ROBOT_FINAL.py", line 26, in <module>
curses.nocbreak(); stdscr.keypad(0); curses.echo()
error: must call initscr() first

Please help

Thanks, Aryan

Looking at your code, it looks like an error occurs inside of your try block . Unfortunately, I can only assume at the moment, that the error happens during the curses.initscr() call. Your finally block is always execute, even if an error occurred.

To diagnose this further: Can you add a except to your try block and print the error?

If you see an error like AttributeError: 'Module' object has no attribute 'initscr' , then you probably named your python script curses . Rename it and delete the 'curses.pyc' file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM