Difference between revisions of "TiLDA MKe"

From Electromagnetic Field
Jump to navigation Jump to search
Line 114: Line 114:
  
 
==Making the badge Arduino shield compatible==
 
==Making the badge Arduino shield compatible==
To make the badge Arduino shield compatible you'll need to solder simple strips of header pins (FIXME: Link to part) onto the back of the badge. This diagram (FIXME: DIAGRAM, LINK IT!) shows the placement.
+
To make the badge Arduino shield compatible you'll need to solder simple strips of header pins onto the back of the badge.  
 +
You need the following headers
 +
{| class="wikitable"
 +
|-
 +
! Qty !! Type !! Use !! Rapid part
 +
|-
 +
| 1 || 2x03 Male || SPI ||
 +
|-
 +
| 2 || 1x08 Female || Power, Analog pins ||
 +
|-
 +
| 2 || 1x10 Female || Digital pins ||
 +
|-
 +
| 1 || 2x08 Male || Ethernet ||
 +
|}
 +
This diagram (FIXME: DIAGRAM, LINK IT!) shows the placement.
  
 
==Interesting things to play with==
 
==Interesting things to play with==

Revision as of 12:01, 29 November 2014

Front
Front

Why MKe?

EMF 2014 Badge

The main aim of the 2014 badge is to give camp attendees an interesting bit of hardware to play with during the camp and experiment with afterwards. We designed an Arduino compatible platform to allow easy reuse and access, and have published all code and design files.

Battery Warning

A very last minute battery (and connector) change on the badge due to a supplier problem meant two issues arose with the badge during EMF:

  • Always make sure to plug your battery in the right way round! The new battery connector allows you to connect it backwards. We did our best to mitigate this, but connecting it incorrectly will destroy the power management controller and prevent the badge from charging or running from the battery. It will still function perfectly using USB power. "Red" and "Black" are written next to the connector - please make sure to plug it in correctly.
  • Be careful not to short the battery connector wires! The new battery connector slightly exposes the wires when the battery is plugged in. If a metal object shorts the two wires, it can result in extreme battery damage. If we'd known this was such an issue before the event we would have applied protective material to it - we suggest covering the exposed connector in tape, sugru, blu-tack, or some other insulating material. Alternatively, simply unplug the battery when your badge is not in use!

My badge is broken!

Due to the aforementioned supplier issues it is possible that you may have received a faulty badge, or it may have been damaged by connecting the battery backwards. If you badge will not turn on when it has been plugged in with a MicroUSB cable (and the power switch on the back is set to "USB"), or something else seems wrong with it, please email badge@emfcamp.org and we'll try to fix or replace your badge.

Basic post-event features

We made sure that the badge has a few features to play with once the event is over. More will be added over time as attendees submit changes to us.

Back
  • Torch mode - Press the light button next to the screen. It will only light up fully if it's hung upside down to avoid blinding
  • Snake
  • Tetris

But of course the point of the badge is to modify it and use it for other interesting things! The following sections describe how to update the firmware on the badge, how to use it as a simple arduino, and how to write your own code for the main badge firmware.

Getting help

The EMF 2014 badge is a complex piece of hardware and software, however remember that you can just treat it as an Arduino if you find it all too daunting.

If you get stuck and need advice, there's an active IRC chatroom you can join to ask for advice, or if you're really stuck you can email us on badge@emfcamp.org.

How to update the badge software & program the badge

The badge software has been substantially updated since EMF, fixing bugs and removing features that will no longer work now you're away from our radio network. You should update your badge before starting to play with it any further. If you've never used an Arduino before this might be tricky - ask an Arduino-literate friend to help you, or drop by your nearest hackspace and ask for advice.

The badge is Arudino Due compatible, so some of their instructions may help you if you have problems.

Set up your environment

  • Plug your badge into your computer via a MicroUSB cable. Make sure the power switch on the back is set to "USB".
  • Download Arduino IDE 1.5.7 from http://arduino.cc/en/main/software#toc3
  • Download the TiLDA firmware code from https://github.com/emfcamp/Mk2-Firmware
  • Start the Arduino IDE.
  • Now you have to change the sketchbook-folder to be the folder you just cloned or downloaded. To do this use File -> Preferences -> “Set Sketchbook location”. On MacOS, this is Arduino -> Preferences.
  • Restart the Arduino IDE.
  • Open sketch “EMF2014”.
  • Set Tools -> Board to MKe v0.333 (RTOS Core).
  • Set Tools -> Port to correct port for the Arduino
    • On MacOS this is will start /dev/tty.usbmodem with 4 digits, and change for each port
    • On Linux this is usually /dev/ttyACM0 but may be a higher number if you have other USB Serial devices
  • Hit the upload button
  • Wait
  • Your badge should now be running the latest TiLDA firmware!

Programming the badge as an Arduino

The badge is completely Arduino Due compatible, simply set the board type to "MKe v0.333(Arduino Core)" upload normal Arduino code and the badge will function. However if you want to use any of the more complex hardware on the badge (such as the screen and radio) we recommend programming it using our FreeRTOS framework documented below.

Below is a version of the standard blink sketch that will flash the RX and TX LEDs

 void setup() {
   pinMode(PIN_LED_TX, OUTPUT);
   pinMode(PIN_LED_RX, OUTPUT);
 }
 
 void loop() {
     digitalWrite(PIN_LED_TX, HIGH);
     digitalWrite(PIN_LED_RX, LOW);
     delay(1000);
     digitalWrite(PIN_LED_TX, LOW);
     digitalWrite(PIN_LED_RX, HIGH);
     delay(1000);
 }

If you do program the badge with simple Arduino code but wish to switch back to our official firmware, simply change the sketch to "EMF2014" (and if needed set the board type back to "MKe v0.333 (RTOS Core)") and upload again.

To make the badge Arduino shield compatible, follow these instructions.

Programming the badge in FreeRTOS

Your first “Hello world” app

There’s a “HelloWorldApp.cpp” file in which you can play around. In order for it to show up on the Homescreen you have to uncomment line 51 in AppManager.cpp and flash the changed code to the badge. Great app pull requests are appreciated!

If you are still using the Arduino IDE at this point, note that it will not let you edit the .cpp and .h files that are needed to create Apps for the badge. To force the IDE to re-compile/re-read any files you've edited using an external editor, make sure to go to the File -> Preferences dialog box, and check the "Use external editor" checkbox.

Why are things so different from standard Arduino code?

We’re using a library called FreeRTOS that allows us to multitask - something that’s normally not possible with standard Arduino code. This allows us to run multiple tasks at the same time. FreeRTOS uses preemptive scheduling to switch between the task. Due to this we have to be very careful about how we do some things. For example we can’t just define interrupts for buttons in every task (imagine the mess!) or write to the serial port directly (your task might stop in the middle of the message).

We’ve also spent quite a lot of time to make the built-in components as easy to use as possible without having every task to write lots of boilerplate code. If you feel like using the build-in components on the badge, chances are we already wrote a wrapper for them that is already used by one of the other tasks.

Have a look at the “Documentation” section in this document for a full list of API functions. You will avoid a lot of headaches if you stick to those.

Code structure

  • FreeRTOS has the concept of “Tasks” which work like threads. We’ve wrappered them in a class called “Task” (for background stuff) and “Apps” (for foreground, one-at-a-time things)
  • Everything needs to be in the main EMF2014 folder. Subfolders are not allowed. This is an Arduino IDE restriction :(

Debugging and Gotchas

  • The USB serial is set up to 115200 baud. There are lots of terminals that can connect to them. See below for how to enable the debug logging.
  • If you can’t revive a badge you can short the two erase pins and press the reset button while holding it down.
  • Avoid busy waiting, use FreeRTOS queues and Tilda::delay() instead
  • Don’t use low level functions like interrupts or serial ports directly unless you really, really know how FreeRTOS will handle them. For general logging you can use Tilda::log()
  • If sending code to the badge using the Arduino IDE "Upload" button fails, even though the /dev/ttyACM0 (linux com port) is there, just retry, twice if neccessary.

Your own wireless badge network

DIY TiLDA Badge Network has instructions on how to setup your own private badge network using a RaspberryPi and two Ciseco radios.

Contribute

Send us a pull request via GitHub - We’ll do our best to review and merge the good ones during EMF so others can use them.

Using the badge hardware

The badge has a plethora of hardware built in for you to play with, everything from accelerometers and gyroscopes to hidden ethernet headers! Breaking it all down is too much detail for this document, however we'll call out some things we built in that you might want to play with.

Remember the badge is Arduino Due compatible, and we broke out nearly all the features of the ARM chip so you can access them. Anything the Due can do, the TiLDA can do!

Making the badge Arduino shield compatible

To make the badge Arduino shield compatible you'll need to solder simple strips of header pins onto the back of the badge. You need the following headers

Qty Type Use Rapid part
1 2x03 Male SPI
2 1x08 Female Power, Analog pins
2 1x10 Female Digital pins
1 2x08 Male Ethernet

This diagram (FIXME: DIAGRAM, LINK IT!) shows the placement.

Interesting things to play with

Most of the interesting things are on the back of the badge. They're clearly marked in white. This diagram of the back should allow you to locate them. Some of the following require extra parts to be added to your badge.

  • Full Arduino R3 shield compatible pins (Requires soldering the headers on the back of the badge)
  • Pins either side of the lanyard holes for conductive thread (D19, D18, GND, 3V3)
  • Infrared transmitter on the front (Pin shortcut IR_TX_PWM)
  • Infrared receiver on the front (Pin shortcut IR_RX, Part Vishay TSOP75238TT available from digikey and Farnell )
  • Piezo buzzer (Pin shortcut PIEZO or PIEZO_PWM)
  • On-board ethernet (not available on the Due) - requires breakout module (eBay: Elechouse Taijiuino Ethernet PHY DM9161 Module)
  • MPU-6050 3-axis Accelerometer and 3-axis gyro (IMUTask.cpp and the MPU6050 library)
  • 128x64 pixel backlit LCD display (JHD12864, see here for docs)
  • Ciseco SRF Radio
  • PowerPOD NCP1402 interface, used to generate 5V from 3V3 battery supply power (needed for some shields)
  • MicroSD adapter breakout (Molex 1050270001 available from digikey)
  • Compass (magnetometer) breakout (HMC HMC5883L-TR available from digikey and Farnell)
  • Reprogramming headers for the 868Mhz CC1110 radio module
  • 1 megabit flash module (Part S25FL216K0PMFI011)
  • SPI breakout
  • 2x RGB LEDs on the front
  • FTDI header (shared with SRF Radio)
  • JTAG header (Part M50-3500542 available form Farnell

Included hardware

The following hardware has been included on the badge.

  • Atmel ATSAM3X8E
    • This is the same chip as the Arduino Due and gives us the base platform for the badge
    • 32bit ARM Cortex M3 * 84MHz
    • 512KBytes Flash RAM
    • 96KBytes of SRAM
  • A 128x64 pixel monochrome LCD display
  • Ciseco SRF Radio
    • 868Mhz RF Transceiver
    • Simple UART interface
    • Low power sleep mode
  • MPU-6050 3-axis Accelerometer and 3-axis gyro
    • I2C interface
    • Tri-Axis angular rate sensor (gyro) with a sensitivity up to 131 LSBs/dps and a full-scale range of ±250, ±500, ±1000, and ±2000dps
    • Tri-Axis accelerometer with a programmable full scale range of ±2g, ±4g, ±8g and ±16g
    • Digital Motion Processing™ (DMP™) engine offloads complex MotionFusion, sensor timing synchronisation and gesture detection
  • PMIC & LiPo
  • Joystick, 4 way with click
  • Buttons
  • RGB LEDs
  • IR Transmitter
  • Arduino Headers
  • Pads for wearable tech

Useful Hacks!

3d printable & laser-cuttable badge case

Draft 3d print-able and laser-able case files here

Convert images to TiLDA bitmap format

  • A Python script (via @trotmaster99) that converts a monochrome bitmap image into a format suitable for the Tilda can be found here.
  • A similar script in Perl to create TiLDA MKe fullscreen bitmaps from XBM: -

xbm2mke.pl by User:Msemtd

#!perl -w
use strict;
# Little script to convert a regular XBM to TiLDA MKe bitmap
# only tested with fullscreen bitmaps!
# Hot file handle magic...
select((select(STDERR), $| = 1)[0]);
select((select(STDOUT), $| = 1)[0]);
sub t(@);
sub d($);
sub chug($);
my $f = shift;
#~ $f = 'blankish.xbm' if not $f;
if(not defined $f or not $f =~ /^(.*)\.xbm$/i){
    die "Usage: gimme an XBM file dude!\n";
}
my $name = $1;
t "Reading file '$f'...";
my $data = chug($f);
t "OK";
my @lines = split /^/, $data;
@lines = grep{chomp; s/^\s+//; s/\s+$//; length;} @lines;
#~ t d \@lines;
my($width, $height) = (0,0);
my @head = @lines[0..5];
foreach(@head){
    if(/_width\s+(\d+)/){$width = $1;}
    if(/_height\s+(\d+)/){$height = $1;}
}
t "width x height = $width x $height";
my @k;
foreach(@lines){ push @k, split /,/; }
@k = grep { s/^.*(0x[0-9A-Fa-f]{1,2}).*$/$1/o; /(0x[0-9A-Fa-f]{1,2})/o } @k;
#~ t d \@k;
my $bc = scalar(@k);
t "Pulled out $bc hex bytes";
if($bc != $width * $height / 8) {
    die "byte count $bc does not match that expected for w x h";
}
t "OK - reorder bytes for MKe bitmap";
my $wb = int($width/8) + (($width & 0x07) ? 1: 0);
t "width in whole bytes for $width pixels = $wb";
my @mke;
for(my $col = 0; $col < $wb; $col++){
    for(my $row = $height - 1; $row >= 0; $row--){
        my $idx = ($row * $wb) + $col;
        my $val = $k[$idx];
        #~ t "Column $col + Row $row = idx $idx = $val";
        push @mke, $val;
    }
}
my $out = "static const uint8_t ".uc($name)."_BM[] = {\n"
	."    $width, // width\n"
	."    $height , // height\n";
#~ $out .= join(", ", @mke);
while(scalar @mke){
	$out .= join(", ", splice(@mke, 0, 16)).",\n";
}
$out .= "};\n";
# meh, just print it out
t $out;

sub t(@) {
    foreach (@_) {
       print STDOUT "$_\n";
    }
}
sub d($) {
    require Data::Dumper;
    my $s = $_[0];
    my $d = Data::Dumper::Dumper($s);
    $d =~ s/^\$VAR1 =\s*//;
    $d =~ s/;$//;
    chomp $d;
    return $d;
}
sub chug($) {
  my $filename = shift;
  local *F;
  open F, "< $filename" or die "Couldn't open `$filename': $!";
  local $/ = undef;
  return <F>;
}  # F automatically closed


Source

All the source code and designs are on openly available on Github:

If you want to help, point your IRC client to #tilda on Freenode.

Firmware Documentation

Debugging

Enabling the USB serial debug log messages

To enable the debug logging you must uncomment the following line in hardware/emfcamp/sam/libraries/debug/debug.h

// Enable debug task and output
// #define DEBUG 1

Tilda::log(String text)

This logs “text” to the serial console. To read it connect to it via the Arduino IDE Serial Monitor. Don’t use “SerialUSB.println” or similar -- it’s not thread-safe and you might end up with utter nonsense.

Debugging using the JTAG interface

The JTAG interface on the board provides powerful debugging facilities like breakpoints, backtraces, dumping memory, inspecting variables, checking task states, catching exeptions etc. To make this to work requires additional hardware and software, see TiLDA Debugging using JTAG.

Buttons

The badge has 8 buttons: Up, Down, Left, Right, Center (on the joystick), A, B and Light. You can use arduino-style “digitalRead(BUTTON_RIGHT)” to read the current status of any button, but you can’t define your own interrupt (because we already did that). This doesn’t mean you can’t wait for a certain button to be pressed, it just means you have to approach it slightly differently:

Example: A simple app displaying the button code

void ButtonApp::task() {
    ButtonSubscription allButtons = Tilda::createButtonSubscription(LIGHT | A | B | UP | DOWN | LEFT | RIGHT | CENTER);

    while(true) {
        Button button = allButtons.waitForPress(1000);
        if (button == A) {
            debug::log(“You pressed button A”);
        } else if (button == LEFT) {
            debug::log(“You pressed LEFT”);
        } else if (button == NONE) {
            debug::log(“No button has been pressed in 1000ms”); 
        }
    }
}


ButtonSubscription Tilda::createButtonSubscription(<buttons>)

Registers a subscriptions for a defined set of buttons and returns a ButtonSubscription. Multiple Buttons can be combined via “|” (see example above). One button can not be subscribed by more than 10 subscriptions (which shouldn’t really happen, but keep it in mind).

Don’t use this function in a constructor, it requires FreeRTOS to be running. Using it inside the task() function is the only safe place for it.

Button ButtonSubscription::waitForPress(TimeInTicks timeout)

This is normally called in a loop. It causes the task to block until one of the buttons has been pressed. If the timeout occurs before any button has been pressed “NONE” will be returned.

ButtonSubscription::waitForPress()

The same as above, but without the timeout.

ButtonSubscription::clear()

This should be called after an App has been suspended, just before it’s going to be resumed. It causes the Queue to be cleared which could otherwise lead to buttons being reported that have been pressed while other apps were in the foreground. Have a look at the FlashLightApp for an example.

LEDs

Tilda::setLedColor(Led led, Color color);

Tilde::setLedColor(Color color);

Sets the color of all or one led. Color is an object that takes red, green and blue as a value between 0 and 255 each. If no led is defined both leds will be set to the same color.

Example: A simple color-changing task

void ColorfulTask::task() {
    while(true) {
        Tilda::setLedColor(LED1, {255, 0, 0}); // Red
        Tilda::setLedColor(LED2, {0, 255, 0}); // Green
        Tilda::delay(300);
        Tilda::setLedColor(LED1, {0, 255, 0}); // Green
        Tilda::setLedColor(LED2, {0, 0, 255}); // Blue
        Tilda::delay(300);
        Tilda::setLedColor(LED1, {0, 0, 255}); // Blue
        Tilda::setLedColor(LED2, {255, 0, 0}); // Red
        Tilda::delay(300);
    }
}

Display

The Display Library is based on GLCDv3 (http://playground.arduino.cc/Code/GLCDks0108), docs (http://code.google.com/p/glcd-arduino/source/browse/trunk/glcd/doc/GLCD_Documentation.pdf) but adapted to support our screen. The Init routine is called in the setup, and the LCDTask takes care of ensuring the screen is updated every 40ms if required (Unlike the original GLCD library, screen updates are decoupled from the graphics routines.)

Also available is M2tklib (https://code.google.com/p/m2tklib/) which is a nice toolkit library. Further details on using this will come later, but expect the main loop to be handled for you, and just passing the menu structure you require for your app.

Right now, you can call the GLCD functions directly with GLCD.DrawBitmap() for example. This is going to change to be accessed through the GUITask class in the near future, to ensure only one task at a time writes to the screen. Expect this to be simply GUITask in place of GLCD, along with a registering a redraw call back to GUITask. The bitmap format, by the way, is rather unconventional but there are a couple of utility scripts to convert popular formats down in the hacking section below - you can grab the SponsorsApp.h as an example and swap out the bitmap array with one of your choosing.

Extra features that are included, GLCD.SetRotation() will handle rotation of the screen for you, and GLCD.CurrentWidth() and GLCD.CurrentHeight will give you the correct Width and Height for the current orientation. GLCD.Width and GLCD.Height constants are not available, and the GLCD predefined Text areas will not be rotated for you, if you require this define your own text areas.

Note that one function was not ported to the badge version of GLCD, "Printf", you'll have to cope without it.

Sound

There's a fully working Piezo on board!

IMU

Tilda::getOrientation

returns " ORIENTATION_HELD", "ORIENTATION_RIGHT" (joystick to the right of the screen), "ORIENTATION_HUNG" or "ORIENTATION_LEFT"

Flash Storage

We have 2mb of flash storage, but we're not using it in the main firmware - Please get this working!

Data: Schedule

Tilda::getDataStore().getSchedule(day, location)

Date: Weather Forecast

Tilda::getDataStore().getWeatherForecast()

Radio

There's no way of sending messages in the current version of the firmware, sorry :(

Time

Tilda::delay(uint16_t delayInMs)

Works like Arduino’s delay(), but is FreeRTOS-safe. It’s safe to use this function before FreeRTOS has started.

tilda::getClock()

Returns an instance of https://github.com/MarkusLange/Arduino-Due-RTC-Library/blob/master/rtc_clock.h

Settings

uint16_t tilda::getBadgeId()

Battery

float TiLDA::getBatteryVoltage()

Returns the current voltage as a float

uint8_t TiLDA::getBatteryPercent()

Returns the current voltage as a percentage

uint8_t TiLDA::getChargeState()

Returns the charge state

0 Charging 1 Not Charging