Controlling an Arduino over the web using Django framework

Arduino Code

Arduino code –

int light= 12;
int dim_light = LED_BUILTIN;
int num = 0;
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()) {
    char c = Serial.read();
    if(c=='a') {
      digitalWrite(light, HIGH);
      Serial.println("Light ON");
    } else if(c=='b') {
      digitalWrite(light, LOW);
      Serial.println("Light OFF");
    } else if(c=='c') {
      int val = analogRead(A0);
      Serial.print("Air ");
      Serial.println(val);
    } /*else if(c >= '0' && c <='9') {
      int val = c - '0';
      num = num*10 + val;
    } else if(c=='d') {
      if(num < 0 || num > 255) {
        Serial.println("ERR VALUE");
      } else {
        analogWrite(dim_light,num);
        Serial.print("DIM ");
        Serial.println(num);
        num = 0;
      }
    } */
  }
}

Getting started with Django

Basic Django codes –

$ python -m django --version

$ django-admin startproject mysite

$ python manage.py runserver

$ python manage.py runserver 8080

$ python manage.py startapp myproject

Intro Python Codes

# /myproject/urls.py
from django.conf.urls import url
from . import views

urlpatterns = [
    url('', views.index, name='index'),
]
# /myproject/views.py
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")
# /mysite/urls.py
from django.contrib import admin
from django.conf.urls import url
from django.conf.urls import include

urlpatterns = [
    url('myproject/', include('myproject.urls')),
    url('admin/', admin.site.urls),
]

Controlling an Arduino using Django

# /myproject/urls.py
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^ON/$', views.turnON, name='turnON'),
    url(r'^OFF/$', views.turnOFF, name='turnOFF'),
    url(r'^AIR/$', views.getAir, name='getAir'),
]
# /myproject/views.py
from django.http import HttpResponse
import serial
ser = serial.Serial('/dev/ttyUSB0',9600)

def index(request):
	return HttpResponse("""<h1>Project Server</h1>
		<a href="./ON/">ON</a> | 
		<a href="./OFF/">OFF</a> | 
		<a href="./AIR/">AIR QUALITY</a>""")

def turnON(request):
	ser.write("a")
	s = ser.readline()
	return HttpResponse(s)

def turnOFF(request):
	ser.write("b")
	s = ser.readline()
	return HttpResponse(s)

def getAir(request):
	ser.write("c")
	s = ser.readline()
	return HttpResponse(s)