Connect Scratch X and Digispark with a bottle

bottle_scratchx_min.jpg

A brief description of the title

things to do

I want to do some introductory programming with Digispark's RGB Shield (not LED Shield), so it's a great introduction to programming from Scratch (ScratchX) to Digispark To operate. ** * When you actually do it, please do it at your own risk. ** **

Flow of operation

Set up a local server at http: // localhost: 9000 with + bottle.

environment

Digispark

libusb USB library Windows(Win7)

OSX(El Capitan 10.11)

brew install libusb

Linux(Ubuntu14.04)

sudo apt-get install libusb-dev

Python ** * The version was 3.5.0 under any environment **

  easy_install pip
  pip install bottle pyusb
SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="05df", MODE="0664", GROUP="plugdev"

And restarted.

Web browser

ScratchX runs on Flash Player, so any browser that runs Flash Player should work.

program

app.py Build a + bottle local server and receive RGB data from javascript running on ScratchX.

#!python
#-*-coding:utf-8-*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division


# for bottle
from bottle import route, run, template, request, response, static_file

# for scratchx
import usb
import sys
sys.path.append("..")
from arduino.usbdevice import ArduinoUsbDevice

theDevice = None

@route("/")
def top():
    return '''
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  <a href="http://scratchx.org/?url=http://localhost:9000/main.js">ScratchX</a>
</body>
</html>
'''

@route("/<filepath:path>")
def server_static(filepath):
    return static_file(filepath, root="./")

@route("/blink")
def blink():
    theDevice = ArduinoUsbDevice(idVendor=0x16c0, idProduct=0x05df)

    red = request.query.get('red')
    green = request.query.get('green')
    blue = request.query.get('blue')

    print("red:{}, green:{}, blue:{}".format(red, green, blue))

    red = int(mapping(red))
    green = int(mapping(green))
    blue = int(mapping(blue))

    theDevice.write(ord("s"))
    theDevice.write(red)
    theDevice.write(green)
    theDevice.write(blue)

    print("mred:{}, mgreen:{}, mblue:{}".format(red, green, blue))

def mapping(arg):
    arg = float(arg)
    if arg < 0:
        return 0
    elif arg > 100:
        return 255
    else:
        return arg * 0.01 * 255

if __name__ == '__main__':
    run(host="localhost", port=9000, debug=True, reloader=True)

main.js

(function(ext){
  var device = null;

  ext._deviceConnected = function(dev){
    if(device) return;
    device = dev;
    console.log(device);
    device.open();
  };

  ext._deviceRemoved = function(dev){
    if(device != dev) return;
    device = null;
  };

  ext._shutdown = function(){
    if(device) device.close();
    device = null;
  };

  ext._getStatus = function(){
    if(!device) return {status: 1, msg: 'digiUSB disconnected'};
    return {status: 2, msg: 'digiUSB connectd'};
  };

  ext.blink = function(r, g, b){
    $.ajax({
      type: "GET",
      url: "http://localhost:9000/blink",
      dataType: "script",
      data: {
        red: r,
        green: g,
        blue: b
      }
    });
  };

  var descriptor = {
    blocks: [
      ["",  "red: %n, green: %n, blue: %Shine with n", "blink",
       "100", "100", "100"]
    ],
    menus: {},
    url: 'http://localhost:9000'
  };

  var hid_info = {type: 'hid', vendor: 0x16c0, product: 0x05df};
  console.log(ScratchExtensions.register('DigiUSB', descriptor, ext, hid_info));
})({});

Operation procedure

Directory
|- arduino/
|- app.py
|- main.js

Finally

Reference page etc.

Recommended Posts

Connect Scratch X and Digispark with a bottle
Install Python 2.7.9 and Python 3.4.x with pip.
A memo with Python2.7 and Python3 on CentOS
Connect a lot of Python or and and
[Python] A quick web application with Bottle!
Cut out and connect images with ImageMagick
Implement a model with state and behavior
Build a Python + bottle + MySQL environment with Docker on RaspberryPi3! [Trial and error]
Building a python environment with virtualenv and direnv
Create a game UI from scratch with pygame2!
Build a virtual environment with pyenv and venv
Launch a web server with Python and Flask
Compile and run Rust with a single command
Connect realsense D435 to a PC with ubuntu 16.04 installed and save depth videos with python
Try making a simple website with responder and sqlite3
Display serial number columns and variables with Bottle template
Build a python virtual environment with virtualenv and virtualenvwrapper
Create a native GUI app with Py2app and Tkinter
Let's make a simple game with Python 3 and iPhone
Create a batch of images and inflate with ImageDataGenerator
I made a LINE BOT with Python and Heroku
Build a python virtual environment with virtualenv and virtualenvwrapper
Conv in x direction and deconv in y direction with chainer
Let's make a Mac app with Tkinter and py2app
Create a 3D model viewer with PyQt5 and PyQtGraph
Take a look at profiling and dumping with Dataflow
What you can and cannot do with Tensorflow 2.x
Deploy a real-time web app with swampdragon x apache
Create a machine learning environment from scratch with Winsows 10
Template for Bottle when deploying with Github and Bitbucket
[Linux] Create a self-signed certificate with Docker and apache
Build a numerical calculation environment with pyenv and miniconda3
A learning roadmap that allows you to develop and publish services from scratch with Python