如何从函数中显示返回值?

时间:2014-03-16 02:54:55

标签: javascript jquery python

我正在尝试从光电池获取传感器值并将值返回到网页。 但是,由于传感器值经常变化,我尝试只显示lightstate。然而,这不起作用。我该怎么办?

以下是我的完整脚本:http://pastebin.com/yKLt3mJN 这是python函数:

@cherrypy.expose
def sensor(self):

    import RPi.GPIO as GPIO, time, os

    DEBUG = 1
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(11, GPIO.OUT)

    def RCtime (RCpin):
        reading = 0
        GPIO.setup(RCpin, GPIO.OUT)
        GPIO.output(RCpin, GPIO.LOW)
        time.sleep(1)

        GPIO.setup(RCpin, GPIO.IN)
        # This takes about 1 millisecond per loop cycle
        while (GPIO.input(RCpin) == GPIO.LOW):
            reading += 1
        return reading

    while True:
        sensorvalue= RCtime(12)

        if sensorvalue > 1000:
            print "switch on light"
            GPIO.output(11, True) #switch on
            lightstate ="On"
            time.sleep(1)
        else:
            print "switch off light"
            GPIO.output(11, False) #switch off
            lightstate ="Off"
            time.sleep(1)

        print sensorvalue # Read RC timing using BCM pin #18, physical pin 12

    return lightstate

这是HTML:

 <a id="photocell"; href="#">Sensor Controlled Lighting</a>
 <p id="photocellvalue"></p>

这是jQuery:

$('#photocell').click(function(){
                        $.post('/sensor').done(function (reply) {
                            $('#photocellvalue').empty().append(reply);});
                    });

1 个答案:

答案 0 :(得分:1)

这会每秒调用一次服务器,并在第二次单击时取消调用:

var interval = null;
$('#photocell').click(function(){
  if (interval) {
    clearInterval(interval);
    interval = null;
  } else {
    interval = setInterval(function() {
      $.post('/sensor').done(function (reply) {
        $('#photocellvalue').empty().append(reply);
      });
    }, 1000);
  }
});