LoginSignup
8
7

More than 3 years have passed since last update.

WebサーバにアクセスするとArduinoでLチカ

Last updated at Posted at 2015-01-10

この手のは猫も杓子も作ってるかと思いますが、bottle.pyというWebフレームワークとpySerialを使って書いてみました。コンテンツはWeb、ハードウェアはlocalhostというケースも考えられるので、CORS(Cross-Origin Resource Sharing)対応としてAccess-Control-Allow-Originヘッダを付けています。

import serial
import sys
from bottle import response,route,run

try:
    ser = serial.Serial('/dev/tty.usbmodem1451',9600)
except OSError:
    ser = False
except:
    print sys.exc_info()[0]
    raise

@route('/arduino/<command>')
def arduino(command):
    response.set_header('Access-Control-Allow-Origin','*')
    if ser:
        ser.write(command)
        line = ser.readline()
        return line
    else:
        return "arduino is not connected"

run(host="localhost",port=8946,debug=True)

arduino側はシリアルで文字列「1」を受け取ると1秒だけ光ります。

byte c = 0;

void setup(){
  Serial.begin(9600);
  pinMode(13,OUTPUT);
}

void loop(){
  while (Serial.available()){
    c = (int)Serial.read();
    //Serial.flush();
    switch(c){
      case 49://1
        digitalWrite(13,HIGH);
        delay(1000);
        digitalWrite(13,LOW);
        break;
    }
  }
}

bottle.pyもpySerialもMacならpipでインストールできます。

pip install bottle
pip install pyserial

※追記※
Githubに登録しました
https://github.com/usopyon/bottle_serial

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7