Hi, I have a raspberry pi and was wondering if it was possible to detect button presses from a webpage in python. I have a robot arm and can control it using this code:

#!/usr/bin/env python

#ROBOT ARM CONTROL PROGRAM

# MoveArm(1,[0,1,0]) @Rotate base anti-clockwise
# MoveArm(1,[0,2,0]) @Rotate base clockwise
# MoveArm(1,[64,0,0]) @Shoulder up
# MoveArm(1,[128,0,0]) @Shoulder down
# MoveArm(1,[16,0,0]) @Elbow up
# MoveArm(1,[32,0,0]) @Elbow down
# MoveArm(1,[4,0,0]) @Wrist up
# MoveArm(1,[8,0,0]) @ Wrist down
# MoveArm(1,[2,0,0]) @Grip open
# MoveArm(1,[1,0,0]) @Grip close
# MoveArm(1,[0,0,1]) @Light on
# MoveArm(1,[0,0,0]) @Light off

#Use sudo pip install pyusb for usb.core

import usb.core, usb.util, time, sys

class MaplinRobot:
    def __init__(self):
        self.usb_vendor_id=0x1267
        self.usb_prod_id=0x000
        self.rctl = usb.core.find(idVendor=self.usb_vendor_id, idProduct=self.usb_prod_id) #Object to talk to the robot
        self.duration=1.0 # Duration (In seconds) for each action. Defaults to 1 second

        self.moves={
        'bac' : [0,1,0], #Base Anti Clockwise
        'bc' : [0,2,0],  #Base Clockwise
        'su': [64,0,0],  #Shoulder Up
        'sd': [128,0,0], #Shoulder Down
        'eu': [16,0,0],  #Elbow Up
        'ed': [32,0,0],  #Elbow Down
        'wu': [4,0,0],   #Wrist Up
        'wd': [8,0,0],   #Wrist Down
        'go': [2,0,0],   #Grip Open
        'gc': [1,0,0],   #Grip Close
        'lo': [0,0,1],   #Light On
        'lof': [0,0,0],  #Light Off
        'stop': [0,0,0], #Stop everything
        }

    def SetVendorId(self,vid):
        self.usb_vendor_id = vid


    def SetProdID(self,pid):
        self.usb_prod_id = pid


    def StopArm(self):
        if self.CheckComms():
            self.rctl.ctrl_transfer(0x40,6,0x100,0,self.moves['stop'],1000) #Send stop command  
            return True
        else:
            return False


    def CheckComms(self):
        '''Checks that the arm is connected and we can talk to it'''
        try:
            if self.rctl != None:
                return True
            else:
                print "Couldn't talk to the arm.\n"
                return False
        except usb.core.USBError:
            print "USB communication error.\n"
            return False

    def MoveArm(self,t,cmd):
        try:
            #Check that we can send commands to the arm
            if self.CheckComms():
                #We can send stuff
                print "Sending command %s\n" %cmd
                self.rctl.ctrl_transfer(0x40,6,0x100,0,self.moves[cmd],1000) #Send command
                time.sleep(t) #Wait 
                self.StopArm()
                print "Done.\n"
                return True
            else:
                return False

        except KeyboardInterrupt:
            print "ctrl-c pressed. Stopping the arm"
            self.StopArm()
            return False

        except usb.core.USBError:
            print "USB communication error.\n"
            return False

#This is how you move the arm
s = MaplinRobot()
s.MoveArm(t=2.0, cmd='bac')  #It moves the base anti-clockwise for 2 seconds

I want to be able to control it from a webpage so when a button is pressed on a webpage, python detects it and sends a command to the arm. I'm not sure how to do it because I'm still new to Python so any help will be appreciated.

Thank You In Advance!

What kind of webserver and web framework are you using?

I'm using apache on a raspberry pi and I don't know what web framework is.

A web framework is a set of interconnected libraries and interfaces that allow you to work with web pages in a more structured manner than the default Python library does (actually, in most languages, there isn't any standard library for HTML and HTTP at all; Python has only a very basic one). Typical web frameworks for Python include Django (probably the most widely used), web2py, Zope, and TurboGears.

Here is a very simple example using the microframework bottle (install with pip for example)

# -*-coding: utf8-*-
# webrobot.py

from bottle import get, post, request
from bottle import route, run

@get('/movearm')
def movearm_form():
    return '''<form method="POST" action="/movearm">
                Move the arm <input type="submit"/>
              </form>'''

@post('/movearm')
def movearm_submit():
    from robotprogram import robotinstance
    robotinstance.move_arm(t=2.0, cmd='bac')
    return "<p>Arm moved !</p>"

run(host='localhost', port=8383, reloader=True)

Launch this script, then visit the bottle webserver at http://localhost:8383/movearm . Here I assume that I can import a robot instance with from robotprogram import robotinstance. Adapt this to your case. I used a mock object

# robotprogram.py
class Robot(object):
    def move_arm(self, *args, **kwd):
        print("HELLO")
        pass

robotinstance = Robot()

Bottle can also use your apache server, as described here.

This is what I've done so far thanks to Gribouillis :

#!/usr/bin/env python
# -*-coding: utf8-*-
# webrobot.py



#ROBOT ARM CONTROL PROGRAM

# MoveArm(1,[0,1,0]) @Rotate base anti-clockwise
# MoveArm(1,[0,2,0]) @Rotate base clockwise
# MoveArm(1,[64,0,0]) @Shoulder up
# MoveArm(1,[128,0,0]) @Shoulder down
# MoveArm(1,[16,0,0]) @Elbow up
# MoveArm(1,[32,0,0]) @Elbow down
# MoveArm(1,[4,0,0]) @Wrist up
# MoveArm(1,[8,0,0]) @ Wrist down
# MoveArm(1,[2,0,0]) @Grip open
# MoveArm(1,[1,0,0]) @Grip close
# MoveArm(1,[0,0,1]) @Light on
# MoveArm(1,[0,0,0]) @Light off

#Use sudo pip install pyusb for usb.core

import usb.core, usb.util, time, sys

class MaplinRobot:
    def __init__(self):
        self.usb_vendor_id=0x1267
        self.usb_prod_id=0x000
        self.rctl = usb.core.find(idVendor=self.usb_vendor_id, idProduct=self.usb_prod_id) #Object to talk to the robot
        self.duration=1.0 # Duration (In seconds) for each action. Defaults to 1 second

        self.moves={
        'bac' : [0,1,0], #Base Anti Clockwise
        'bc' : [0,2,0],  #Base Clockwise
        'su': [64,0,0],  #Shoulder Up
        'sd': [128,0,0], #Shoulder Down
        'eu': [16,0,0],  #Elbow Up
        'ed': [32,0,0],  #Elbow Down
        'wu': [4,0,0],   #Wrist Up
        'wd': [8,0,0],   #Wrist Down
        'go': [2,0,0],   #Grip Open
        'gc': [1,0,0],   #Grip Close
        'lo': [0,0,1],   #Light On
        'lof': [0,0,0],  #Light Off
        'stop': [0,0,0], #Stop everything
        }

    def SetVendorId(self,vid):
        self.usb_vendor_id = vid


    def SetProdID(self,pid):
        self.usb_prod_id = pid


    def StopArm(self):
        if self.CheckComms():
            self.rctl.ctrl_transfer(0x40,6,0x100,0,self.moves['stop'],1000) #Send stop command  
            return True
        else:
            return False


    def CheckComms(self):
        '''Checks that the arm is connected and we can talk to it'''
        try:
            if self.rctl != None:
                return True
            else:
                print "Couldn't talk to the arm.\n"
                return False
        except usb.core.USBError:
            print "USB communication error.\n"
            return False

    def MoveArm(self,t,cmd):
        try:
            #Check that we can send commands to the arm
            if self.CheckComms():
                #We can send stuff
                print "Sending command %s\n" %cmd
                self.rctl.ctrl_transfer(0x40,6,0x100,0,self.moves[cmd],1000) #Send command
                time.sleep(t) #Wait 
                self.StopArm()
                print "Done.\n"
                return True
            else:
                return False

        except KeyboardInterrupt:
            print "ctrl-c pressed. Stopping the arm"
            self.StopArm()
            return False

        except usb.core.USBError:
            print "USB communication error.\n"
            return False


from bottle import get, post, request
from bottle import route, run

@get('/bac')
def movearm_form():
    return '''<form method="POST" action="/bac">
                Move the arm <input type="submit"/>
              </form>'''

@post('/bac')
def movearm_submit():
    s = MaplinRobot()
    s.MoveArm(t=0.5, cmd='bac')
    return("Arm Moved")

@get('/bc')
def bc_form():
    return '''<form method="POST" action="/bc">
                Move the arm <input type="submit"/>
              </form>'''

@post('/bc')
def bc_submit():
    s = MaplinRobot()
    s.MoveArm(t=0.5, cmd='bc')
    return("Arm Moved")

run(host='192.168.0.19', port=8080, reloader=True)

bac = Base Anti-Clockwise and bc = Base Clockwise and t=0.5 means turn for half a second.

I've got the arm to move when I click submit on 192.168.0.19:8080/bc but I want multiple buttons on one page and when I click it I don't want the button to go and the text "Arm Moved" to pop up. I want to be able to click multiple buttons e.g. Light on, Light Off, Shoulder Up .etc and the arm moves straight away. And is it possible to move the arm continuously if the button is held down?

Thanks in advance to everyone who replies :)

Did you consider using a GUI such as tkinter to implement the controls ? GUIs make a difference between a button press and button release.

Gribouillis, I think the OP wants to control it via a web browser - so Tkinter won't help.

Yes, I want to control it using a web browser.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.