Co-op SNEK Online Mac OS

Snekboard's Crowd Supply Campaign

Snekboard has garnered a lot of interest from people who have seen itin operation. Josh Lifton, a fellow Portland resident and co-founderof Crowd Supply, suggested thatperhaps we could see how much interest there was for this hardware bybuilding a campaign.

Getting Things Together

We took pictures, made movies, built spreadsheets full of costestimates and put together the Snekboard story, includingdemonstrations of LEGO models running Snekcode. It took a couple of months to get ready to launch.

Time to fill in some gaps in our gaming history with Evoland, a game that covers a console era we skipped over (going straight from Atari 2600 to original Xbox, with all the intervening time gaming on the C64, the Amiga,. Tux Paint for macOS. Tux Paint for macOS comes as three disk image (.dmg) files.One contains main program (Tux Paint), another contains the configuration program (Tux Paint Config.) for parents and teachers; copy both of them to your hard drive's Applications folder.

Launching the Campaign

The Snekboard campaignlaunched while I was at LCA getting ready totalk about snek.

Interest is Strong

We set a goal of $4000, which is enough to build 50 Snekboards. Wemet that goal after only two weeks and still have until the first ofMarch to get further support.

Creating Teaching Materials

We've been teaching programming in our LEGO robotics class for a longtime. I joined the class about 15 years ago and started withLEGO Logoon an Apple II, and more recently using C++ with Arduinohardware.

That's given us a lot of experience with what kinds of robots workwell and what kinds of software the students are going to be able tounderstand and enjoy experimenting with. We've adapted the models andsoftware to run on Snekboard using Snek and have started writing uphow we're teaching that and putting those up on the sneklang.orgdocumentation page.

Free Software / Free Hardware

All of the software running on Snekboard is free; Snek is licensedunder the GPL, CircuitPython uses theMIT license.

The Snekboard designs are also freely available; that uses theTAPR Open Hardware License.

All of the tools we use to design snekboard are also free;we use gEDA project tools.

Hardware and software used in education need to be free and open sothat people can learn about how they work, build modified versions andshare those with the world.

Posted Fri Jan 31 16:21:02 2020

Linux.conf.au 2020

I just got back from linux.conf.au 2020 onSaturday and am still adjusting to being home again. I had theopportunity to give three presentations during the conference andwanted to provide links to the slides and videos.

Picolibc

My first presentation was part of the Open ISA miniconf on Monday. Isummarized the work I've been doing on a fork of Newlib calledPicolibc which targets 32- and 64- bit embedded processors.

Snek

Wednesday morning, I presented on my sneklanguage, which is a small Python designed forintroducing programming in an embedded environment. I've been usingthis for the last year or more in a middle-school environment (grades5-7) as a part of a LEGO robotics class.

X History and Politics

Bradley Kuhn has been encouraging me to talkabout the early politics of X and how that has shaped my views on thebenefits of copyleft licenses in building strong communities,especially in driving corporate cooperation and collaboration. I wouldhave loved to also give this talk as a part of theCopyleft Conference being held inBrussels after FOSDEM, but I won't be at that event. This talk spansthe early years of X, covering events up through 1992 or so.

Posted Tue Jan 21 15:02:01 2020

Snekboard v0.2 Update

I've built six prototypes ofsnekboard version0.2. They're working great and I'm happy with the design.

New Motor Driver

Having discovered that theTI DRV8838 wasn't up to drivingthe LegoPower Functions Medium motor (8883)because of it's start-up current draw, I went back and reworked thesnekboard circuit to useTI DRV8800 instead. Thatcontroller can provide up to 2.8A and doesn't have any trouble withthis motor.

The DRV8800 is larger than the DRV8838, so it took a bit of re-wiringto fit them on the circuit board.

New Power Source Selector

In version 0.1, I was using twoDFLS130L Schottky diodesto automatically select between the on-board lithium polymer battery and USB topower the board. That 'worked', except that there was enough leakageback through them that when the USB connector was unplugged, thebattery charge indicator LEDs both lit up, which left me with thechoice of disabling those indicators or draining the battery.

To fix that, I found an automatic power selector (with current limit!)part, the TPS2121. This shouldavoid frying the board when you short the motor controller outputs,although those also have current limiting circuits. Defense in depth!

One issue I found was that this circuit draws current even when theoutput is disconnected, so I changed the power switch from a SPST toDPST and now control USB and battery power separately.

CircuitPython

I included aW25Q16 2MB NOR flash chipon the board so that it could also runCircuitPython.Before finalizing the design, I thought it might be a good idea toactually get that running.

I've submitted apull requestwith the necessary changes. I hope to see that merged at some point,which will allow users to select between CircuitPython andsnek.

Smoothing Speed Changes

While the 9V supply on snekboard is designed to supply plenty ofcurrent for the motors, if you ask it to suddenly change how much itis producing, it places a huge load on the battery. When this happens,the battery voltage drops below the brown-out value for the SoC andthe board resets.

I experimented with how to resolve this by ramping the power up anddown in the snek application. That worked great; the motors couldeasily switch from full speed in one direction to full speed in theother direction.

Instead of having users add code to every snek application, I decidedto move this functionality down into the snek implementation. I didthis by modifying the PWM and direction pins values in a functioncalled from the timer interrupt. This lets the application continue torun at full speed, while the motor controller slowly adjusts itsoutput. No more resets when switching from full forward to fullreverse.

Future Plans

I've got the six v0.2 prototypes that I'll be able to use in for theupcoming class year, but I'm unsure of whether there would be enoughinterest in the broader community to have more of them made. Let meknow if you'd be interested in purchasing snekboards; if I get enoughresponses, I'll look at running them through Crowd Supply or similar.

Posted Sun Jul 28 13:20:36 2019

SnekBoard and Lego

I was hoping to use some existing boards for snek+Lego, but I haven'tfound anything that can control 9V motors. So, I designedSnekBoard.

(click on the picture to watch the demo in motion!)

Here's the code:

SnekBoard Hardware

SnekBoard is made from:

  1. SAMD21G18A processor. This is the same chip found in many Arduinoboards, including some from Adafruit. It's a ARM Cortex M0 with256kB of flash and 32kB of RAM.

  2. Lithium Polymer battery. This uses the same connector found onbatteries made by SparkFun and Adafruit. There's a battery chargeron the board powered from USB so it will always be charging whenconnected to the computer.

  3. 9V boost power supply. Lego motors for the last many years haverun on 9V. Instead of using 9V worth of batteries, using a boostregulator means the board can run off a single cell LiPo.

  4. Four motor controllers for Lego motors and servos. The currentboards use a TI DRV9938, which provides up to 1.5A.

  5. Two NeoPixels

  6. Eight GPIOs with 3.3V and GND available for each one.

  7. One blue LED.

Getting SnekBoard Built

The SnekBoard PCBs arrived from OshPark a few days ago and I got themassembled and running. OshPark now has an associated stencil service,and I took advantage of that to get a stainless stencil along with theboards. The DRV8838 chips have small enough pads enough that myhome-cut stencils don't work reliably, so having a 'real' stencilreally helps. I ordered a 4mil stencil, which was probably toothick. They offer 3mil, and I think that would have reduced some ofthe bridging I got from having too much paste on the board.

Flashing a Bootloader on SnekBoard

I forked the Adafruit UF2 boot loaderand added definitions for this board. The version of GCC provided inDebian appears to generate larger code than the newest upstreamversion, so I wasn't able to add the NeoPixel support, but the bootloader is happy enough to use the blue LED to indicate status.

STLink V2 vs SAMD21

I've got an STLink V2 SWD dongle which I use on all of my Arm boardsfor debugging. It appears that this device has a limitation in how itcan access memory on the target; it can either use 8-bit or 32-bitaccesses, but not 16-bit. That's usually just fine, but there's oneregister in the flash memory controller on the SAMD21 which requiresatomic 16-bit accesses.

The STLinkV2 driver for OpenOCD emulates 16-bit accesses using two8-bit accesses, causing all flash operations to fail. Fixing this waspretty simple, the 2 bytes following the relevant register aren'tused, so I switched the 16-bit access to a 32-bit access. That solvedthe problem and I was able to flash the bootloader. I've submitted anOpenOCD patch including this upstream andpushed the OpenOCD fork to github.

Snek on the SnekBoard

Snek already supports the target processor; all that was needed forthis port was to describe the GPIOs and configure the clocks. Thisport is on the master branch of the snek repository.

All of the hardware appears to work correctly, except that I haven'ttested the 16MHz crystal which I plan to use for a more precise timesource.

SnekBoard and Lego Motors

You can see a nice description of pretty much every motor Lego hasever made on Philo's web site.I've got a small selection of them, including:

  1. Electric Technic Mini-Motor 9v (71427)

In testing, all of them except the Power Functions Medium motor workgreat. That motor refused to start and just sat on the bench whinging(at about 1kHz). Reading through the DRV8838 docs, I discovered thatif the motor consumes more than about 2A for more than 1µs, the chipwill turn off the output, wait 1ms and try again.

So I hooked the board up to my oscilloscope and took a look and here'swhat I saw:

The upper trace is the 9V rail, which looks solid. The lower trace isthe motor control output. At 500µs/div, you can see that it's cyclingevery 1ms, just like the chip docs say it will do in over currentsituations.

I zoomed in to the very start of one of the cycles and saw this:

This one is scaled to 500ns/div, and you can see that the power ishigh for a bit more than 1µs, and then goes a bit wild before turningoff.

So the Medium motor draws so much current at startup that the DRV8838turns it off, waits 1ms and tries again. Hence the 1kHz whine heardfrom the motor.

I tried to measure the current going into the motor with my DVM, butwhen I did that, just the tiny additional resistance from the DVMcaused the motor to start working (!).

Swapping out the Motor Controller

I spent a bunch of time looking for a replacement motor controller;the SnekBoard is a bit special as I want a motor controller that takesdirection and PWM instead of PWM1/PWM2, which is what you usually findon an H-bridge set. The PWM1/PWM2 mode is both simpler and moreflexible as it allows both brake and coast modes, but it requires twoPWM outputs from the SoC for each controller. I found the DRV8876,which provides 3.5A of current instead of 1.5A. That 'should' beplenty for even the Medium motor.

Future Plans

I'll get new boards made and loaded to make sure the updated motorcontroller works. After that, I'll probably build half a dozen or soin time for class this October. I'm wondering if other people wouldlike some of these boards, and if so, how I should go about makingthem available. Suggestions welcome!

Posted Sat Jun 29 17:57:59 2019

Snek 1.0

I've released version 1.0 of Snek today.

Features

  • Python-inspired. Snek is a subset of Python: learning Snek isa great way to start learning Python.

  • Small. Snek runs on an original Arduino Duemilanove board with32kB of ROM and 2kB of RAM. That's smaller than theApollo Guidance Computer

  • Free Software. Snek is licensed under theGNU General Public License (v3 or later).You will always be able to get full source code for the system.

Ports

Hosts

Documentation

Read the Snek manual online or in PDF form:

Posted Sun Jun 9 15:48:51 2019

Snek Adopts More Python Scoping

Python's implicit variable declarations are tricky and Snek had themslightly wrong. Fixing this meant figuring out how they work inPython, then figuring out the simplest possible expression to make theresult fit in the ROM.

Local Variable Declaration

Local variables are declared in Python either as formal parameternames, or by placing them on the left hand side of a simple assignmentoperator:

There are three local variables in function foo — a, b and c.

Global Variable Declaration

Global variables are declared in Python in one of two ways:

1) A simple assignment at global scope

2) A simple assignment in a function which also has a 'global' statement including the same name

This defines both 'a' and 'b' as globals.

Global Variable Usage

Global variables can be used within functions withoutexplicitly declaring them.

You may be explicit about a's scope using a 'global' statement

These two forms are equivalent, unless you also include an assignmentexpression with a on the LHS (left hand side):

is not the same as

as the former declares a new local, 'a', and leaves the globalunchanged while the latter changes the global value.

Local Variable Usage

Python3 does whole-function analysis to figure out whether a name islocal or not. If there is any assignment of a name within a function,that name references a local variable. Consider the following:

The function 'foo' references the global named 'a', while the function'bar' attempts to reference the local named 'a' before it has beenassigned a value and, hence, generates an error.

Snek doesn't do this whole-function analysis, so 'bar' uses the global'a' in the first statement as it hasn't yet reached the definition of'a' as a local variable.

Augmented Assignments

Python Augmented Assignment statementsare similar to C's Compound assignment operators — +=, *=, /=,etc. The Python reference has this to say about them:

'An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect.'

Because they work similar to assignment statements, they can declare anew variable in the current scope, if no such name has been included inprevious assignment, global or non-local statements. Also, because theyreference the variable on the RHS (right hand side), they need thatvariable to have already been defined before this statement executes.

Co-op

Scoping in Snek

Because Snek doesn't do whole-function analysis, it can't 'see' laterassignments in a function, and so a function with ause-before-assignment generates the following (non-Pythonic) result:

Fixing this would require additional tracking within the compiler,which I may add at some point, but for now, saving memory duringcompilation seems useful.

Snek Augmented Assignments

While Snek doesn't currently handle the general case ofuse-before-assignment involving separate statements, the simpler casewith augmented assignments doesn't require saving any state duringcompilation and seems like something more useful to catch as withoutit, you would get:

The value of 'a' is left as 12 because the augmented assignmentfetches 'a' first, which finds the global variable 'a', but then whenit assigns the resulting value, it creates a new local variable 'a',just as if this code looked like:

Checking this case requires adding a special-case for augmentedassignment within a function to see if the name has been declared orincluded in 'global' statement in the function.

Posted Sun May 26 18:02:06 2019

ItsyBitsy Snek — snek on the Adafruit ItsyBitsy

I got an ItsyBitsy board fromAdafruit a few days ago. This board is about as minimal anArduino-compatible device as I can imagine. All it's got is an AtmelATmega 32U4 SoC, one LED, and a few passive components.

I'd done a bit of work with the 32u4 under AltOS a few years ago whenBdale and I built a 'companion' board called TeleScience forTeleMetrum to try and measure rocket airframe temperatures inflight. So, I already had some basic drivers for some of theperipherals, including a USB driver.

USB Adventures

The 32u4 USB hardware is simple, and actually fairly easy to use. TheAltOS driver used a separate thread to manage the setup messages onendpoint 0. I didn't imagine I'd have space for threading on thisdevice, so I modified that USB driver to manage setup processing fromthe interrupt handler. I'd done that on a bunch of other USB parts, sowhile it took longer than I'd hoped, I did manage to get it working.

Then I spent a whole bunch of time reducing the code size of thisdriver. It started at about 2kB and is now almost down to 1kB. It's abit less robust now; hosts sending odd setup messages may getunexpected results.

The last thing I did was to add a FIFO for OUT data. That's because wewant to be able to see ^C keystrokes even while Snek is executingcode.

Reset as longjmp

On the ATmega 328P, to reset Snek, I just reset the whole chip. Niceand clean. With integrated USB, I can't reset the chip without losingthe USB connection, and that would be pretty annoying. ResettingSnek's state back to startup would take a pile of code, so instead, Igathered all of the snek-related .data and .bss variables by changingthe linker script. Then, I wrote a reset function that does prettymuch what the libc startup code does and then jumps back to main:

I still need to write code to reset the GPIO pins.

Development Environment

To flash firmware to the device, I stuck the board into a proto boardand ran jumpers from my AVRISP cable to the board.

Next, I hooked up a FTDI USB to Serial converter to the 32u4 TX/RXpins. Serial is always easier than USB, and this was certainly thecase here.

Finally, I dug out my trusty Beagle USB analyzer. This lets me seeevery USB packet going between the host and the device and isinvaluable for debugging USB issues.

You can see all of these pieces in the picture above. They're sittingon top of a knitting colorwork pattern of snakes and pyramids, which Imay have to make something out of.

Current Status

Code for this part is on the master branch, which is available on myhome machine as well as github:

I think this is the last major task to finish before I release snekversion 1.0. I really wanted to see if I could get snek running onthis tiny target. It's nearly there; I want to squeeze a few morethings onto this chip.

Posted Mon May 20 00:17:45 2019

Snek and Neopixels

(click on the picture to see the movie)

Adafruit sells a bunch of things using theNeopixel name thatincorporate Worldsemi WS2812Bfull-color LEDs with built-in drivers. These devices use a 1-wire link toprogram a 24-bit rgb value and can be daisy-chained to connect as manydevices as you like using only one GPIO.

Bit-banging Neopixels

The one-wire protocol used by Neopixels has three signals:

  • Short high followed by long low for a 0 bit
  • Long high followed by a short low for a 1 bit
  • Really long low for a reset code

Short pulses are about 400ns, long pulses are around 800ns. The resetpulse is anything over about 50us.

I'd like to use some nice clocked signal coming out of the part togenerate these pulses. A SPI output would be ideal; set the bit rateto 400ns and then send three SPI bits for each LED bit, either 100 or110. Alas, none of the boards I've got connect the Neopixels to a pinthat can be used as for SPI MOSI.

As a fallback, I tried using DMAC to toggle the GPIO outputs. Alas, onthe SAMD21G part included in these boards, the DMAC controller can'tactually write to the GPIO control registers. There's a missingconnection inside the chip.

So, like all of the examples I found, I fell back to driving the GPIOregisters directly with the processor, relying on a carefully writtensequence of operations to get the timing within the tolerance requiredby the Neopixels. I have to disable interrupts during this process toavoid messing up the timing though.

Current Snek Neopixel API

Co-op Snek Online Mac Os X

I looked at the Circuit Python Neopixel APIto see if there was anything I could adapt for Snek. That API uses3-element tuples for the R,G,B values, and then places those in alist, one for each pixel in the chain. That seemed like a good idea.However, that API also has a lot of allocation churn, with new colorsbeing created in newly allocated lists. Doing that with Snek wouldprobably be too slow as Snek uses a garbage collector for allocation.

Co-op Snek Online Mac Os Catalina

So, we'll allow mutable lists inside of a list or tuple, then Neopixelcolors can be changed by modifying the value within the per-Neopixellists.

Snek doesn't have objects, so we'll just create a function to sendcolor data for a list of Neopixels out a pin. We'll use the existingSnek GPIO function, talkto, to select the pin. Finally, I'm usingcolor values from 0-1 instead of 0-255 to make this API work more likethe other analog interfaces.

That make the first Neopixel a not-quite-blinding red. Now we can turnit green with:

You can, of course, use tuples like with Circuit Python:

This does allocate a new list though.

Co-op Snek Online Mac Os X Training

Snek on Circuit Playground Express

As you can see in the pictures above, Snek is running on theAdafruit Circuit Playground Express.This board has a bunch of built-in hardware. At this point, I've gotthe buttons, switches, lights and analog input sensors (temperatureand light intensity) all working. I don't have the motion sensor oraudio bits going. I'll probably leave those pieces until after Snekv1.0 has been released.

Posted Tue May 14 17:02:06 2019

Snek and the Amusement Park

(you can click on the picture to watch the model in action)

Here's an update to my previous post about Snek in a balloon. We alsohooked up a Ferris wheel and controlled them both with the sameArduino Duemilanove compatible board. This one has sound so you canhear how quiet the new Circuit Cube motors are.

Posted Fri May 10 16:45:16 2019

Snek on the Arduino Mega 2560 Rev3

The Arduino Mega 2560 Rev3 islarger in almost all ways than the ATmega328P based Arduinoboards. Based on the ATMega 2560 SoC, the Mega has 256K of flash, 8Kof RAM and 4K of EEPROM. The processor and peripherals are compatiblewith the ATMega 328P making supporting this in Snek pretty easy.

ATMega238P to ATMega2560 changes

All that I needed to do for Snek to compile for the Mega was to adjustthe serial port code to use the Mega register names. gcc-avr prefixesall of the USART registers with 'USART0' for the 2560 instead of'USART'. With that change, Snek came right up on the board.

Co-op Snek Online Mac Os X Emulator

GPIO Changes

To get the Arduino Mega pins all working, I had to add definitions forall 70 of them. That's a lot of pins! I took the definitions from theArduino sources and matched up all of the PWM outputs as well.

USB Serial Adventures

The Arduino Duemilanove uses an FTDI USB to Serial converter chip,while the Arduino Mega uses an ATmega 16u2 SoC. The FTDI exposes acustom USB device while the ATmega16u2 implements a standard CDC ACMdevice.

The custom USB device provides full serial control, including supportfor selecting XON/XOFF flow control. The CDC ACM standard only exposesconfiguration for RTS/CTS flow control, but doesn't provide any way toask for XON/XOFF flow control.

The Arduino programming protocol requires a transparent 8-bit datapath; because the CDC ACM standard doesn't provide a way to turnXON/XOFF on and off, the ATmega 16u2 never does XON/XOFF.

Snek needs XON/XOFF flow control to upload and download code over theserial link.

I was hoping to leave the ATmega 16u2 code and ATmega 2560 boot loaderalone. This would let people use Snek on the Arduino Mega withoutneeding a programming puck. And, in fact, Snek works just fine. But,you can't use Snekde with the Mega because getting and putting code tothe device ends up with corrupted data.

So, I changed the ATmega 16u2code to enable XON/XOFF whenever the baud rate is below 57600 baud,left Snek running at 38400 baud while the boot loader uses 115200baud. The result is that when Snek runs, there is XON/XOFF flowcontrol, and when the boot loader runs, there is not.

Results

With the extra ROM, I was able to include all of the mathfunctions. With the extra RAM, the heap can be 6kB. So much space!

Co-op Snek Online Mac Os Download

Posted Thu May 2 20:45:35 2019