SlideShare a Scribd company logo
Python on a Chip
                  PyMite, a Python Virtual Machine



                                                      Jeremy Stott
                                                jeremy@stott.co.nz


Kiwi Pycon 2011              Python on a Chip             jeremy@stott.co.nz
Microcontrollers

• Programming Microcontrollers is
  fun!

• You can build your own toys / evil
  robots

• Even getting lights to blink is fun

• Usually programmed in C,
  sometimes C++




                         http://lighttrees.com/wordpress/archives/category/sculpture
 Kiwi Pycon 2011              Python on a Chip                      jeremy@stott.co.nz
What's wrong with C?!
                                                    #include <stdio.h>
                                                    int l;int main(int o,char **O,
• Nothing is wrong with C                           int I){char c,*D=O[1];if(o>0){
                                                    for(l=0;D[l               ];D[l
                                                    ++]-=10){D    [l++]-=120;D[l]-=
• It's up to the programmer to write good           110;while    (!main(0,O,l))D[l]
                                                    +=   20;    putchar((D[l]+1032)
  code                                              /20   )    ;}putchar(10);}else{
                                                    c=o+      (D[I]+82)%10-(I>l/2)*
                                                    (D[I-l+I]+72)/10-9;D[I]+=I<0?0
• Programmers may suffer from object                :!(o=main(c/10,O,I-1))*((c+999
                                                    )%10-(D[I]+92)%10);}return o;}
  oriented withdrawal syndrome

• Prolonged use of C may cause
  inappropriate outbursts of semi-colons;

• You can't do [Python reference] in C


                                           http://www0.us.ioccc.org/years.html#2001
  Kiwi Pycon 2011           Python on a Chip                       jeremy@stott.co.nz
Introducing: Python-On-A-Chip

●
    http://code.google.com/p/python-on-a-chip/
●
    A project developing PyMite, a Python Virtual Machine
      designed to run on Microcontrollers
●
    A small growing group > 256 mailing list members
●
    Uses 55KB of ROM and 5KB of RAM for "Hello World!"
●
    License:
        ●
            Tools: GNU LGPL v2.1 (Lesser GPL)
        ●
            Virtual Machine: GPL v2 (Non Commercial)


    Kiwi Pycon 2011          Python on a Chip          jeremy@stott.co.nz
Features
It Does:

• Support integers, floats, lists, dicts, functions, modules,
  classes, generators, decorators and closures

• Support 25 out of 29 keywords and 89 out of 112 byte codes
  from Python 2.6

• Stackless green threads

It Doesn't:

• Have a built in compiler

• Support any of Python's standard libraries
 Kiwi Pycon 2011           Python on a Chip            jeremy@stott.co.nz
25 out of 29 Keywords?

PyMite supports the following set of Python's keywords
      and          assert      break           class       continue
      def          del         elif            else        for
      from         global      if              import      in
      is           lambda      not             or          pass
      print        raise       return          while       yield

PyMite does not support these keywords
    except  exec   finally   try

However, they are working on Exceptions




 Kiwi Pycon 2011                Python on a Chip                  jeremy@stott.co.nz
No Standard Libraries?

Instead of supporting Python's libraries, PyMite offer its own set
of modules. Some of which have the same name as their
Python counterparts.
 
PyMite Modules
    dict   func   list   string   sys
As well as many built in functions
      abs(x), bytearray(seq), bytearray(len), chr(i),
      eval(co), globals(), id(o), len(obj), locals(), 
      map(f,s), ord(c), pow(x,y), range(...), sum(s),
      type(obj)




 Kiwi Pycon 2011           Python on a Chip           jeremy@stott.co.nz
Other Interesting Bits

• PyMite only supports 8-bit character strings, so no
  Unicode

• PyMite supports 32-bit signed integers, floats (if
  enabled) but not longs

• You can't override type operators. Eg '__add__()'
  doesn't override '+'




 Kiwi Pycon 2011        Python on a Chip          jeremy@stott.co.nz
Installing under Ubuntu 11.04

The easiest way to get PyMite is to check it out using Mercurial:
$ hg clone https://code.google.com/p/python-on-a-chip/

Install Python 2.6, setuptools and virtualenv
$ sudo apt-get install python2.6 python-setuptools
$ sudo easy_install virtualenv

Create the virtual environment and activate it
$ virtualenv -p python2.6 --no-site-packages ./pymite
$ source pymite/bin/activate




 Kiwi Pycon 2011           Python on a Chip          jeremy@stott.co.nz
Windows?  Almost

Download GNU Make, Python 2.6, SetupTools, and VirtualEnv
http://gnuwin32.sourceforge.net/packages/make.htm
http://www.python.org/getit/releases/2.6.6/
http://pypi.python.org/pypi/setuptools

Install and add their paths to your Path Environment Variable
c:Python26
c:Python26Scripts
c:Program FilesGnuWin32bin

Install and activate VirtualEnv
> easy_install.exe virtualenv
> virtualenv.exe --no-site-packages c:pymite
> c:pymiteScriptsactivate.bat

And then you install a C compiler...
 Kiwi Pycon 2011           Python on a Chip         jeremy@stott.co.nz
Interactive Prompt

To compile for the desktop and launch the interactive prompt
$ make ipm

(make sure you have activated the Python2.6 VirtualEnv)
Test it out
ipm> class Robot():
....     def walk(self, direction):
....         print "Walking %s" % (direction,)
....
ipm> pybot = Robot()
ipm> pybot.walk("to the shops")
Walking to the shops




 Kiwi Pycon 2011            Python on a Chip              jeremy@stott.co.nz
Microcontrollers?

mBed Microcontroller

• 32-bit ARM Processor

• Built-in USB interface

• Powered via USB

• Implements a Mass Storage Device, so programming is as
  easy as copying the binary onto the Flash drive

• Many peripherals eg Ethernet, USB, Can, SPI, etc…

• Online Compiler
 Kiwi Pycon 2011           Python on a Chip     jeremy@stott.co.nz
Kiwi Pycon 2011   Python on a Chip   jeremy@stott.co.nz
Robots!

m3pi from Pololu


•Easy to set up

•Ideal for getting started

•Cost:
– m3pi Robot $150 USD

– mbed Micro $60 USD

•Surprisingly Fast!!


 Kiwi Pycon 2011             Python on a Chip   jeremy@stott.co.nz
What about Wireless?

Nobody likes to follow their robot around with a laptop…

The m3pi has a handy slot for a Digi Zigbee module.

But these $35 WiFi modules fit in the same slot:

RN-XV from Roving Networks
http://rovingnetworks.com/XVee.php

• Have the same pin-out
• Support WPA2
• Make the project awesome!


 Kiwi Pycon 2011               Python on a Chip       jeremy@stott.co.nz
Putting it all together

Compile PyMite for the mbed target
$ make PLATFORM=mbed

Import the resulting .zip archive into the mbed IDE

Import the m3pi library into the mbed IDE

Compile and save the binary onto the mbed microcontroller

Turn on the Robot and connect to the ipm using a python
socket
$ tools/ipm.py –-ipaddress 192.168.1.3 –-port 2000




 Kiwi Pycon 2011          Python on a Chip            jeremy@stott.co.nz
Thank You




                  Any Questions?




Kiwi Pycon 2011      Python on a Chip   jeremy@stott.co.nz

More Related Content

What's hot (20)

PDF
pyconjp2015_talk_Translation of Python Program__
Renyuan Lyu
 
PDF
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
David Beazley (Dabeaz LLC)
 
PDF
PyPy London Demo Evening 2013
Carl Friedrich Bolz
 
PDF
Python Developer Certification
Vskills
 
ODP
Python and Machine Learning
trygub
 
PDF
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
Tsundere Chen
 
PDF
Writing Fast Code (JP) - PyCon JP 2015
Younggun Kim
 
PDF
Tensorflow 2.0 and Coral Edge TPU
Andrés Leonardo Martinez Ortiz
 
PDF
Notes about moving from python to c++ py contw 2020
Yung-Yu Chen
 
PPTX
Mixing C++ & Python II: Pybind11
corehard_by
 
PDF
Take advantage of C++ from Python
Yung-Yu Chen
 
PPTX
AI Machine Learning Complete Course: for PHP & Python Devs
Amr Shawqy
 
PDF
Android and cpp
Joan Puig Sanz
 
PDF
Introduction of python
ShehabAldeenFadelall
 
PPTX
Boost.Python: C++ and Python Integration
GlobalLogic Ukraine
 
PDF
Python in Action (Part 1)
David Beazley (Dabeaz LLC)
 
PDF
Python Workshop
Mantavya Gajjar
 
PPTX
Golang iran - tutorial go programming language - Preliminary
go-lang
 
PDF
Pascal script maxbox_ekon_14_2
Max Kleiner
 
PDF
Про асинхронность / Максим Щепелин / Web Developer Wargaming
Python Meetup
 
pyconjp2015_talk_Translation of Python Program__
Renyuan Lyu
 
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
David Beazley (Dabeaz LLC)
 
PyPy London Demo Evening 2013
Carl Friedrich Bolz
 
Python Developer Certification
Vskills
 
Python and Machine Learning
trygub
 
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
Tsundere Chen
 
Writing Fast Code (JP) - PyCon JP 2015
Younggun Kim
 
Tensorflow 2.0 and Coral Edge TPU
Andrés Leonardo Martinez Ortiz
 
Notes about moving from python to c++ py contw 2020
Yung-Yu Chen
 
Mixing C++ & Python II: Pybind11
corehard_by
 
Take advantage of C++ from Python
Yung-Yu Chen
 
AI Machine Learning Complete Course: for PHP & Python Devs
Amr Shawqy
 
Android and cpp
Joan Puig Sanz
 
Introduction of python
ShehabAldeenFadelall
 
Boost.Python: C++ and Python Integration
GlobalLogic Ukraine
 
Python in Action (Part 1)
David Beazley (Dabeaz LLC)
 
Python Workshop
Mantavya Gajjar
 
Golang iran - tutorial go programming language - Preliminary
go-lang
 
Pascal script maxbox_ekon_14_2
Max Kleiner
 
Про асинхронность / Максим Щепелин / Web Developer Wargaming
Python Meetup
 

Similar to Python on a chip (20)

PDF
Writing a Python C extension
Sqreen
 
PDF
What is Python? (Silicon Valley CodeCamp 2015)
wesley chun
 
PDF
What is Python? (Silicon Valley CodeCamp 2014)
wesley chun
 
PDF
PyCon2022 - Building Python Extensions
Henry Schreiner
 
PDF
Python and Pytorch tutorial and walkthrough
gabriellekuruvilla
 
PDF
What is Python?
wesley chun
 
PDF
05 python.pdf
SugumarSarDurai
 
PPTX
Python and its Applications
Abhijeet Singh
 
PDF
Pythonanditsapplications 161121160425
Sapna Tyagi
 
PPTX
Python on pi
swee meng ng
 
PDF
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdf
ssuser8b3cdd
 
PDF
Python in a real life
Vladimir Filonov
 
PDF
PySide
OpenBossa
 
PDF
Why "Hello World" is a Massive Operation - From Python code to Stack Virtual ...
Richard Rowland
 
PDF
Open frameworks 101_fitc
benDesigning
 
PDF
Startup Camp - Git, Python, Django session
Juraj Michálek
 
PDF
Qt for Python
ICS
 
PDF
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
Pôle Systematic Paris-Region
 
PDF
Introduction to the rapid prototyping with python and linux for embedded systems
Naohiko Shimizu
 
PDF
Возможности интерпретатора Python в NX-OS
Cisco Russia
 
Writing a Python C extension
Sqreen
 
What is Python? (Silicon Valley CodeCamp 2015)
wesley chun
 
What is Python? (Silicon Valley CodeCamp 2014)
wesley chun
 
PyCon2022 - Building Python Extensions
Henry Schreiner
 
Python and Pytorch tutorial and walkthrough
gabriellekuruvilla
 
What is Python?
wesley chun
 
05 python.pdf
SugumarSarDurai
 
Python and its Applications
Abhijeet Singh
 
Pythonanditsapplications 161121160425
Sapna Tyagi
 
Python on pi
swee meng ng
 
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdf
ssuser8b3cdd
 
Python in a real life
Vladimir Filonov
 
PySide
OpenBossa
 
Why "Hello World" is a Massive Operation - From Python code to Stack Virtual ...
Richard Rowland
 
Open frameworks 101_fitc
benDesigning
 
Startup Camp - Git, Python, Django session
Juraj Michálek
 
Qt for Python
ICS
 
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
Pôle Systematic Paris-Region
 
Introduction to the rapid prototyping with python and linux for embedded systems
Naohiko Shimizu
 
Возможности интерпретатора Python в NX-OS
Cisco Russia
 
Ad

Recently uploaded (20)

PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
July Patch Tuesday
Ivanti
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
Ad

Python on a chip

  • 1. Python on a Chip PyMite, a Python Virtual Machine Jeremy Stott [email protected] Kiwi Pycon 2011 Python on a Chip [email protected]
  • 2. Microcontrollers • Programming Microcontrollers is fun! • You can build your own toys / evil robots • Even getting lights to blink is fun • Usually programmed in C, sometimes C++ http://lighttrees.com/wordpress/archives/category/sculpture Kiwi Pycon 2011 Python on a Chip [email protected]
  • 3. What's wrong with C?! #include <stdio.h> int l;int main(int o,char **O, • Nothing is wrong with C int I){char c,*D=O[1];if(o>0){ for(l=0;D[l ];D[l ++]-=10){D [l++]-=120;D[l]-= • It's up to the programmer to write good 110;while (!main(0,O,l))D[l] += 20; putchar((D[l]+1032) code /20 ) ;}putchar(10);}else{ c=o+ (D[I]+82)%10-(I>l/2)* (D[I-l+I]+72)/10-9;D[I]+=I<0?0 • Programmers may suffer from object :!(o=main(c/10,O,I-1))*((c+999 )%10-(D[I]+92)%10);}return o;} oriented withdrawal syndrome • Prolonged use of C may cause inappropriate outbursts of semi-colons; • You can't do [Python reference] in C http://www0.us.ioccc.org/years.html#2001 Kiwi Pycon 2011 Python on a Chip [email protected]
  • 4. Introducing: Python-On-A-Chip ● http://code.google.com/p/python-on-a-chip/ ● A project developing PyMite, a Python Virtual Machine designed to run on Microcontrollers ● A small growing group > 256 mailing list members ● Uses 55KB of ROM and 5KB of RAM for "Hello World!" ● License: ● Tools: GNU LGPL v2.1 (Lesser GPL) ● Virtual Machine: GPL v2 (Non Commercial) Kiwi Pycon 2011 Python on a Chip [email protected]
  • 5. Features It Does: • Support integers, floats, lists, dicts, functions, modules, classes, generators, decorators and closures • Support 25 out of 29 keywords and 89 out of 112 byte codes from Python 2.6 • Stackless green threads It Doesn't: • Have a built in compiler • Support any of Python's standard libraries Kiwi Pycon 2011 Python on a Chip [email protected]
  • 6. 25 out of 29 Keywords? PyMite supports the following set of Python's keywords     and      assert    break     class     continue     def      del       elif      else      for     from     global    if        import    in     is       lambda    not       or        pass     print    raise     return    while     yield PyMite does not support these keywords     except  exec   finally   try However, they are working on Exceptions Kiwi Pycon 2011 Python on a Chip [email protected]
  • 7. No Standard Libraries? Instead of supporting Python's libraries, PyMite offer its own set of modules. Some of which have the same name as their Python counterparts.   PyMite Modules     dict   func   list   string   sys As well as many built in functions     abs(x), bytearray(seq), bytearray(len), chr(i),     eval(co), globals(), id(o), len(obj), locals(),      map(f,s), ord(c), pow(x,y), range(...), sum(s),     type(obj) Kiwi Pycon 2011 Python on a Chip [email protected]
  • 8. Other Interesting Bits • PyMite only supports 8-bit character strings, so no Unicode • PyMite supports 32-bit signed integers, floats (if enabled) but not longs • You can't override type operators. Eg '__add__()' doesn't override '+' Kiwi Pycon 2011 Python on a Chip [email protected]
  • 9. Installing under Ubuntu 11.04 The easiest way to get PyMite is to check it out using Mercurial: $ hg clone https://code.google.com/p/python-on-a-chip/ Install Python 2.6, setuptools and virtualenv $ sudo apt-get install python2.6 python-setuptools $ sudo easy_install virtualenv Create the virtual environment and activate it $ virtualenv -p python2.6 --no-site-packages ./pymite $ source pymite/bin/activate Kiwi Pycon 2011 Python on a Chip [email protected]
  • 10. Windows?  Almost Download GNU Make, Python 2.6, SetupTools, and VirtualEnv http://gnuwin32.sourceforge.net/packages/make.htm http://www.python.org/getit/releases/2.6.6/ http://pypi.python.org/pypi/setuptools Install and add their paths to your Path Environment Variable c:Python26 c:Python26Scripts c:Program FilesGnuWin32bin Install and activate VirtualEnv > easy_install.exe virtualenv > virtualenv.exe --no-site-packages c:pymite > c:pymiteScriptsactivate.bat And then you install a C compiler... Kiwi Pycon 2011 Python on a Chip [email protected]
  • 11. Interactive Prompt To compile for the desktop and launch the interactive prompt $ make ipm (make sure you have activated the Python2.6 VirtualEnv) Test it out ipm> class Robot(): ....     def walk(self, direction): ....         print "Walking %s" % (direction,) .... ipm> pybot = Robot() ipm> pybot.walk("to the shops") Walking to the shops Kiwi Pycon 2011 Python on a Chip [email protected]
  • 12. Microcontrollers? mBed Microcontroller • 32-bit ARM Processor • Built-in USB interface • Powered via USB • Implements a Mass Storage Device, so programming is as easy as copying the binary onto the Flash drive • Many peripherals eg Ethernet, USB, Can, SPI, etc… • Online Compiler Kiwi Pycon 2011 Python on a Chip [email protected]
  • 14. Robots! m3pi from Pololu •Easy to set up •Ideal for getting started •Cost: – m3pi Robot $150 USD – mbed Micro $60 USD •Surprisingly Fast!! Kiwi Pycon 2011 Python on a Chip [email protected]
  • 15. What about Wireless? Nobody likes to follow their robot around with a laptop… The m3pi has a handy slot for a Digi Zigbee module. But these $35 WiFi modules fit in the same slot: RN-XV from Roving Networks http://rovingnetworks.com/XVee.php • Have the same pin-out • Support WPA2 • Make the project awesome! Kiwi Pycon 2011 Python on a Chip [email protected]
  • 16. Putting it all together Compile PyMite for the mbed target $ make PLATFORM=mbed Import the resulting .zip archive into the mbed IDE Import the m3pi library into the mbed IDE Compile and save the binary onto the mbed microcontroller Turn on the Robot and connect to the ipm using a python socket $ tools/ipm.py –-ipaddress 192.168.1.3 –-port 2000 Kiwi Pycon 2011 Python on a Chip [email protected]
  • 17. Thank You Any Questions? Kiwi Pycon 2011 Python on a Chip [email protected]