1

第二次更新

差不多好了!!但收到“ValueError:尝试使用未打开的端口”

File "c:\Python27\lib\site-packages\flask\app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)

File "c:\Python27\lib\site-packages\flask\app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))

File "c:\Python27\lib\site-packages\flask\app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()

File "c:\Python27\lib\site-packages\flask\app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)

File "c:\Python27\lib\site-packages\flask\app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()

File "c:\Python27\lib\site-packages\flask\app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)

File "G:\OverAir\arduino\server.py", line 19, in light_off
board.output([pin])

File "G:\OverAir\arduino\arduino.py", line 16, in output
self.__sendData(len(pinArray))

File "G:\OverAir\arduino\arduino.py", line 56, in __sendData
while(self.__getData()[0] != "w"):

File "G:\OverAir\arduino\arduino.py", line 61, in __getData
return self.serial.readline().rstrip('\n')

File "c:\Python27\lib\site-packages\serial\serialwin32.py", line 221, in read
if not self.hComPort: raise portNotOpenError

ValueError: Attempting to use a port that is not open

更新

下面@Blender 答案中的代码可能是正确的。我现在遇到的问题是我收到 “SerialException:无法打开端口 COM5:[错误 5] 访问被拒绝”。

但是,如果我单独运行我的原始 on.py 或 off.py 脚本,它可以正常工作......我看不出新代码是如何工作的......除非它尝试打开 COM5 两次?

结束更新

我尝试使用 Flask 运行多个 python 函数或单独的 .py 脚本;为了生成单独的 URL。只是试图打开/关闭在本地运行的 Arduino。

例如,我有 on.py 和 off.py 并想构建 sever.py。所以,当我打开 127.0.0.1:5000/on 它运行 on.py,同样 127.0.0.1:5000/off 运行 off.py,

几个小时后,我才决定将这两个.py函数都添加到server.py中,但是它当然不起作用……我想我只是不明白参数的用法。

真的提前谢谢你!

## Open a serial connection with Arduino.

from time import sleep
from arduino import Arduino

from flask import Flask


b = Arduino("COM5",9600)
pin = 13
num = 5

ON = Flask("Light_ON")
OFF = Flask("Light_OFF")


def LightON():
    #declare output pins as a list/tuple
    b.output([pin])
    b.setHigh(pin)
    b.close()
    return 'Light is ON'

def LightOFF():
    #declare output pins as a list/tuple
    b.output([pin])
    b.setLow(pin)
    return 'Light is OFF'

@ON.route('/ON')
@OFF.route('/OFF')

ON.run()
OFF.run()  //I know this doesn't run, just not sure how to include it.
4

1 回答 1

0

像这样的东西应该工作:

from arduino import Arduino
from flask import Flask

app = Flask('light_control')
board = Arduino('COM5', 9600)
pin = 13

@app.route('/on')
def light_on():
    board.output([pin])
    board.setHigh(pin)
    board.close()

    return 'Light is ON'

@app.route('/off')
def light_off():
    board.output([pin])
    board.setLow(pin)
    # board.close() ???

    return 'Light is OFF'

if __name__ == '__main__':
    app.debug = True
    app.run()
于 2013-01-26T07:15:42.447 回答