忍者ブログ
[26]  [27]  [28]  [29]  [30]  [31]  [32]  [33]  [34]  [35]  [36
×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

関数定義でロジックを分解し構造化でコーディング


import RPi.GPIO as GPIO
import time
LedPin = 11    # pin11 --- led
BtnPin = 12    # pin12 --- button

#セットアップ
def setup():
GPIO.setmode(GPIO.BOARD)       # ピンの番号を使用
GPIO.setup(LedPin, GPIO.OUT)   # 11を出力
GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)    
            # 12を入力, プルアップで使用
   GPIO.output(LedPin, GPIO.HIGH)

#繰り返し
def loop():
while True:
if GPIO.input(BtnPin) == GPIO.LOW:  
print '...led on'
time.sleep(0.1)
GPIO.output(LedPin, GPIO.LOW)  # led on
else:
print 'led off...'
time.sleep(0.1)
GPIO.output(LedPin, GPIO.HIGH) # led off

#後始末
def destroy():
GPIO.output(LedPin, GPIO.HIGH)     # led off
   GPIO.cleanup()                     

#スタートロジック
if __name__ == '__main__':     # Program start 
setup()
try:
loop()
except KeyboardInterrupt:  # 'Ctrl+C' is pressed
destroy()

拍手

PR
準備もできたので

LEDをON OFFしてみましょう

これでONOFFができた
http://xxx.xxx.xxx.xxx:8080でweb表示



from webob import Request, Response  #WebObの読み込み
import RPi.GPIO as GPIO

#HTMLの記載
html = """<h1> kusoneko:%d</h1>
<form method="post">
<h1>
<input type="submit" name="button" value="ON">
<input type="submit" name="button" value="OFF">
</h1>
</form>
"""
count = 0
#GPIOの設定
bcmled = 12
GPIO.setmode(GPIO.BOARD) #BOARD 12 BCM 18
GPIO.setup(bcmled,GPIO.OUT) #出力
class WebApp(object):
    def __call__(self, environ ,start_response):
        global html,count
        req=Request(environ)
        if req.path=='/':
            button = req.params.get('button','') #buttonの読み込み
            if (button=='ON'):
                GPIO.output(bcmled, 1)
                count=1
            if (button=='OFF'):
                GPIO.output(bcmled, 0)
                count=0
            resp = Response(html % count)
        else:
            resp = Response()
        return resp(environ, start_response)
application = WebApp()
if __name__== '__main__':
    from wsgiref.simple_server import make_server
    port=8080
    httpd= make_server('', port, application)
    print('Http on port %s.' % port)
    try:
      httpd.serve_forever()
    except KeyboardInterrupt:
      GPIO.cleanup()
      
------------------------------------------------------------
テキストを入力させたい時は
------------------------------------------------------------
HTMLの部分を書き換えて

html = """
<form method="post">State:
<input type="text" name = "state" value = "%s">
<input type="submit" name="button" value ="Set">
</form>
"""
形は同じ
        req = Request(environ)
        if req.path == '/':
            state = int(req.params.get('state', '0'))


全ソースは
import time
import RPi.GPIO as GPIO
from webob import Request, Response
bcmled = 12
GPIO.setmode(GPIO.BOARD) #BOARD 12 BCM 18
GPIO.setup(bcmled,GPIO.OUT) #出力
#htmlteigi
html = """
<form method="post">State:
<input type="text" name = "state" value = "%s">
<input type="submit" name="button" value ="Set">
</form>
"""
class WebApp(object):
    def __call__(self, environ, start_response):
        req = Request(environ)
       # print ('req: %s...' % req.path )
        if req.path == '/':
            state = int(req.params.get('state', '0'))
            GPIO.output(bcmled, state)
            resp = Response(html % str(state))
        else:
            resp = Response()
                        
        return resp(environ ,start_response)
                        
application = WebApp() 
if __name__ == '__main__':
  from wsgiref.simple_server import make_server
  port = 8080
  httpd = make_server('',port,application)
  print ('serving http port %s...' % port)
                        
  try:
    httpd.serve_forever() #serverkidou
  except KeyboardInterrupt:
    GPIO.cleanup()



拍手

まずはHelloworldから

from webob import Request, Response #webObの読み込み

#htmlの定義
html = """
<html>
<head>
<title>test</title>
</head>
<body>
<h1>hello woard</h1>
</body>
</html>
"""
def application(environ, start_response):
    resp = Response(html)
    return resp(environ, start_response)
if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    port =8080
    server = make_server('',port,application)
    server.serve_forever()

で表示されました


次にON OFFのテスト

#webTest
from webob import Request, Response
html = """<h1> 結果:%d</h1>
<form method="post">
<input type="submit" name="button" value="たす">
<input type="submit" name="button" value="ひく">
</form>
"""
count= 0
class WebApp(object):
    def __call__(self, environ ,start_response):
        global html,count
        req=Request(environ)
        if req.path=='/':
            button = req.params.get('button','')
            if (button=='たす'):
                count=count + 1
            if (button=='ひく'):
                count = count -1
            resp = Response(html % count)
        else:
            resp = Response()
        return resp(environ, start_response)
application = WebApp()
if __name__== '__main__':
    from wsgiref.simple_server import make_server
    port=8080
    httpd= make_server('', port, application)
    print('Http on port %s.' % port)
    httpd.serve_forever()

数字がアップダウンします

拍手

単体でなくWebからLチカ操作に挑戦



pythonにwebObを組み込む

1.https://python.org/pypi/webObにアクセスして
最新(現在は1.6.1)のWebOb-1.6.1.tar.gzをダウンロード

2.pi/Downloadsにダウンロードされる

3.Xarchiverで解凍 /home/piに
 WebOb-1.6.1というディレクトリが出来上がり

4.インストール
  cd WebOb-1.6.1
  sudo python3 setup.py install

で準備完了

phytonではWSGI(Web Server Gateway Interface)が利用可能で
これを起動する事で簡易なサーバーとして利用できる


拍手

センスハットでお遊び開始

まずは下準備

sudo apt-get update
sudo apt-get install sense-hat
sudo pip-3.2 install pillow

で温度と湿度を表示するプログラム

from sense_hat import SenseHat
try:
  while True:
    sense = SenseHat()
    #get temp
    temp = sense.get_temperature()
    temp = round(temp,1)
    #print "Temp:" + str(temp)
    hub = sense.get_humidity()
    hub = round(hub,1)
    sense.show_message("T:" + str(temp),scroll_speed = 0.2)
    sense.show_message("H:" + str(hub),scroll_speed = 0.2)
except KeyboardInterrupt:
    sense.clear()
    sense.set_rotation(0)
    sense.show_message("good by")

結果は簡単だが、温度は変、、、、

拍手

カレンダー
03 2025/04 05
S M T W T F S
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
フリーエリア
最新CM
[03/10 DORA]
最新TB
プロフィール
HN:
dorabu
性別:
非公開
バーコード
ブログ内検索
P R
Copyright © ドラブーのアンドロイドとIoTなブログ All rights reserved. / Template by 四季. / Material by てんせん.

忍者ブログ [PR]