I think that this kind of thing makes both cats and scoops, but I wrote it using a web framework called bottle.py and pySerial. Since it is possible that the content is on the Web and the hardware is localhost, the ʻAccess-Control-Allow-Origin` header is added to support CORS (Cross-Origin Resource Sharing).
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)
When the arduino side receives the character string "1" serially, it lights up for 1 second.
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;
}
}
}
Both bottle.py and pySerial can be installed with pip on Mac.
pip install bottle
pip install pyserial
Recommended Posts