[PYTHON] When you access the web server, L Chika with Arduino

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

When you access the web server, L Chika with Arduino
When you access the web server, L Chika (HTTPS compatible) with Arduino
I made you to express the end of the IP address with L Chika
Remote L Chika with pigpio
Access the host SQL Server with python27 / pyodbc on the container
Reload the server set up with gunicorn when changing the code
When you want to adjust the axis scale interval with APLpy
Try L Chika with raspberry pi
[Web server] A story when I investigated because I could not access nginx
VS Code freezes & PC crashes when I start the server with go
[https proxy with squid] Eliminate the error when accessing the web server that does not chain the intermediate CA certificate.
Access the Docker Remote API with Requests
Start the web server in the current directory
Behavior when returning in the with block
Web server for browser testing with Mocha
Download files on the web with Python
When changing the table name with flask_migrate
RaspberryPi L Chika with Python and C #
[C, C ++, Python, JavaScript] L Chika with Edison
Publish the current directory on the web server
Turn off the dialog that appears when you enter Linux with Remote Desktop
When I tried to change the root password with ansible, I couldn't access it.