Wednesday, 23 July 2014

Quick note: Raspberry Pi WiFI client configuration (tested with ralink RT5370)

I recently purchased a WiFi dongle as the new addition for my Raspberry Pi, this cheap and amazing piece of work from ebay is a 150M USB WiFi Wireless Adapter LAN, with a 2dBi de-attachable Antenna and the well-known ralink rt5370 Chip, for only 3€ (at the purchase time) what else could you ask for?


OK, it took a while to arrive to Spain as it was sent from China, but the product was worth the wait!



Not only worked flawlessly with the Raspberry Pi (mine is mounted on the wall next to my desk, sometimes I put it behind my monitor as the enclosure is VESA-compatible, see previous post), but also worked out-of-the-box for my LG 47LA640S Smart TV, saving me from having to buy an "official" overpriced WiFI USB dongle (30€, 6 times the value!) or adding yet-another wireless router to connect my TV over ethernet.

To enable the Raspberry Pi to connect to an AP with a static IP address, just add this to your /etc/network/interface file:

allow-hotplug wlan0

auto wlan0


iface wlan0 inet static
address 192.168.1.232
netmask 255.255.255.0
gateway 192.168.1.1

dns-nameserver 8.8.8.8


wpa-ssid "SSID-example-replace-yours-here"

wpa-psk "replace-your-WPA-password"

This will work as long as your AP has WPA/WPA2 security and is not hidden.

A 3D printed Raspberry Pi VESA mount

The Barcelona Activa folks at the Parc Tecnològic Barcelona Nord has opened a 3D printing space, available for the lucky people working in its facilities, featuring the amazingly cheap and cool BCN3D+ printer and the well-known MakerBot.

After a quick lessonand browsing through Thingiverse, I quickly found that the Raspberry Pi was a hot item with plenty of designs available to further enhance the Rpi experience,so I took this thing (a VESA-mount enclosure for the Raspberry Pi) and did a quick test ride.

There are plenty of tutorials and available free available software on 3D printing, so I'm going to skip this and leave a 3D printing walkthrough for a future post.

I ran the .STL file over the GCode Analyzer to see how my case was to be printedand how much time will it take to print (about 2 hours, just the case without the top-lid), and then copy the GCODE into a SD card, put it in the BCN3D+, calibrate (grumble, grumble), and the result is shown below.







The Raspberry Pi fits quite nice in the enclosure, I only had to remove a loose thread or two to connect the HDMI connector, I have not printed the top-cover as I intend to connect many things to the device, so I'm not sure yet what space should I leave for the cabling and maybe use the cover as a base mount for a sensor, etc.

I'm planning on sticking the Rpi behind my monitor and avoid seeing all the cables on top of my desk, also it serves OK to hang on a wall... good thing is that the Raspberry fits in the enclosure, but with little effort it can be pulled off, allowing a quick swap.

Wednesday, 25 June 2014

How to fix GIT error: object file is empty (from Stack Overflow)

Source (and all credits):
Stack Overflow: how to fix git error object file is empty

This saved me from a lot of googling and trial/error, I was getting the following error:

error: object file .git/objects/31/65329bb680e30595f242b7c4d8406ca63eeab0 is empty
fatal: loose object 3165329bb680e30595f242b7c4d8406ca63eeab0 (stored in .git/objects/31/65329bb680e30595f242b7c4d8406ca63eeab0) is corrupt


Maybe caused by powering off my VM sandbox while syncing or some other weirdness, normally with a very low impact as you can always do a git clone, but as I had some changes done locally on my working branch that I didn't want to miss/re-do, this saved my day. The original answer with full comments can be found at the link above, the brief version is:

cp -a .git .git-old
git fsck --full
# Remove empty files by using "rm", continue until none is left and the "missing blob" starts showing
git reflog
# It will show "fatal: bad object HEAD"
tail -n 2 .git/logs/refs/heads/master
# Identify parent of last commit (the one HEAD is pointing to), easily recognizable as it will show up twice
git show commit_parent
git update-ref HEAD commit_parent
git fsck --full
# There are some blobs left from outdated index, nuke and carry on
rm .git/index
git reset
# There should be only references to "dangling blobs", these are not errors, continue
git status
git add .
git commit -m "Recovering from lost objects"
And done.

Tuesday, 17 June 2014

Enabling USB audio card in Raspberry Pi

The Raspberry Pi has an on-board audio jack, but the on-board audio is generated by a PWM output with little filtering done, but the sound quality, volume, and recording capabilities can be added by using a USB sound card (these are pretty cheap too).

I bought 4€ USB sound card from Amazon, but pretty much any other can be used, it has a stereo output and has a MIC input, which is perfect for voice-controlled projects (like the one I'm currently working on, remember Jarvis?).  The audio card features an USB 2.0 type A connector and it powers up from the USB 5VDC power supply.  I have not measured the current consumption (yet).


Preparing the installation


I'm running Raspbian-based RetroPie on a USB stick, the following should not change anything from your configured settings, however this installation can be done on any Raspbian-based images.
sudo apt-get update
sudo apt-get upgrade

After 5-10 minutes you should have your OS upgraded and ready to go.


Recognizing the USB audio card


Sources:

ALSA driver by default does not allows the USB audio card to be sound device #0 (default), to change this we need to edit the /etc/modprobe.d/alsa-base.conf (as sudo) and change the following line (normally commented-out):

#options snd-usb-audio index=-2

Remove the comment and change index to 0

options snd-usb-audio index=0

After rebooting or restarting ALSA, the audio card should be listed as the default sound device.

As pointed out in Adafruit, there are different supported chipsets, mine was a C-Media based (CM108).


pi@raspberrypi ~ $ dmesg | grep C-Media
3.352853] usb 1-1.2: Manufacturer: C-Media Electronics Inc. 
3.370053] input: C-Media Electronics Inc. 
USB PnP Sound Device as /devices/platform/bcm2708_usb/usb1/1-1/1-1.2/1-1.2:1.3/input/input0
3.386302] hid-generic 0003:0D8C:013C.0001: input,hidraw0: USB HID v1.00 Device [C-Media Electronics Inc. 
USB PnP Sound Device] on usb-bcm2708_usb-1.2/input3
pi@raspberrypi ~ $ lsusb
Bus 001 Device 002: ID 0424:9512 Standard Microsystems Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp.
Bus 001 Device 004: ID 0d8c:013c C-Media Electronics, Inc. CM108 Audio Controller
Bus 001 Device 005: ID 125f:c13a A-DATA Technology Co., Ltd.
pi@raspberrypi ~ $ cat /proc/asound/cards
0 [Device]: USB-Audio - USB PnP Sound Device
C-Media Electronics Inc. USB PnP Sound Device at usb-bcm2708_usb-1.2, full spee
1 [ALSA]: BRCM bcm2835 ALSbcm2835 ALSA - bcm2835 ALSA bcm2835 ALSA
pi@raspberrypi ~ $ aplay -L
Discard all samples (playback) or generate zero samples (capture)
sysdefault:CARD=Device
USB PnP Sound Device, USB Audio
Default Audio Device
front:CARD=Device,DEV=0
USB PnP Sound Device, USB Audio
Front speakers
surround40:CARD=Device,DEV=0
USB PnP Sound Device, USB Audio
4.0 Surround output to Front and Rear speakers
surround41:CARD=Device,DEV=0
USB PnP Sound Device, USB Audio
4.1 Surround output to Front, Rear and Subwoofer speakers
surround50:CARD=Device,DEV=0
USB PnP Sound Device, USB Audio
5.0 Surround output to Front, Center and Rear speakers
surround51:CARD=Device,DEV=0

USB PnP Sound Device, USB Audio
5.1 Surround output to Front, Center, Rear and Subwoofer speakers
surround71:CARD=Device,DEV=0
USB PnP Sound Device, USB Audio
7.1 Surround output to Front, Center, Side, Rear and Woofer speakers
iec958:CARD=Device,DEV=0
USB PnP Sound Device, USB Audio
IEC958 (S/PDIF) Digital Audio Output
sysdefault:CARD=ALSA
bcm2835 ALSA, bcm2835 ALSA
Default Audio Device
pi@raspberrypi ~ $ arecord -l
**** List of CAPTURE Hardware Devices ****
card 0: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio]
 Subdevices: 1/1
 Subdevice #0: subdevice #0

The last step is adding the following configuration to the asound.conf file, used by ALSA.
pi@raspberrypi ~ $ cat /etc/asound.conf
pcm.!default {
 type plug
 slave {
   pcm "hw:0,0"
 }
}
ctl.!default {
 type hw
 card 0
}

Testing the setup

I have hooked the USB audio card with a TPA2005D1 audio amplifier (roughly 6€) from Sparkfun and a 0.5 Watt  magnetic speaker.  I have to work on the sound quality to reduce some noise, change the audio amplifier's resistors to increase the gain, maybe throw in a potentiometer to allow changing the volume, and use speakers with a higher wattage.


To test the installation we can use the built-in functions provided by the OS.
pi@raspberrypi ~ $ speaker-test
speaker-test 1.0.25
Playback device is default
Stream parameters are 48000Hz, S16_LE, 1 channels
Using 16 octaves of pink noise
Playback open error: -16,Device or resource busy
Had to close the emulationstation scripts running, then I was able to hear the sound:


pi@raspberrypi ~ $ speaker-test -c2 -D hw:0,0
speaker-test 1.0.25
Playback device is hw:0,0
Stream parameters are 48000Hz, S16_LE, 2 channels
Using 16 octaves of pink noise
Rate set to 48000Hz (requested 48000Hz)
Buffer size range from 96 to 262144
Period size range from 48 to 131072
Using max buffer size 262144
Periods = 4
was set period_size = 65536
was set buffer_size = 262144
0 - Front Left
1 - Front Right
Time per period = 5.564981
0 - Front Left
1 - Front Right
Time per period = 5.559085
0 - Front Left
1 - Front Right
And to test the recording I just connected a detachable mic from a headset.
pi@raspberrypi ~ $ arecord -d 10 test.wav
Recording WAVE 'test.wav' : Unsigned 8 bit, Rate 8000 Hz, Mono
^CAborted by signal Interrupt...

$ aplay test.wav
Playing WAVE 'test.wav' : Unsigned 8 bit, Rate 8000 Hz, Mono

Wednesday, 28 May 2014

How to generate source code documentation in TinyOS (nesdoc)

TinyOS uses Nesdoc to generate documentation from source code (as Doxygen does), to build the documents (found later in $TOSROOT/doc folder under your platform name) just type (and replace with your platform's name):
make platform docs
This should go smoothly but... there are small things to tweak, for example:

error: StorageVolumes.h: No such file or directory
If you include the STM25P component (external flash memory support), if fails locating StorageVolumes.h file, as this file is generated in build time from the definitions in your platform's target file (at tos/support/make):

VOLUME_FILE = volumes-stm25p.xml
VOLUME_ALLOCATOR ?= tos-storage-stm25p
One quick work-around is to previously build the application and then copy the generated StorageVolumes.h file from the resulting build/platform location to your application path, then run the make docs command again.

I did found the following errors:

Traceback (most recent call last):
  File "/usr/lib/tinyos/nesdoc/archive.py", line 352, in <module>
    doc.writexml(ifile)
  File "/usr/lib/python2.7/xml/dom/minidom.py", line 1751, in writexml
    node.writexml(writer, indent, addindent, newl)
  File "/usr/lib/python2.7/xml/dom/minidom.py", line 816, in writexml
    node.writexml(writer, indent+addindent, addindent, newl)
  File "/usr/lib/python2.7/xml/dom/minidom.py", line 816, in writexml
    node.writexml(writer, indent+addindent, addindent, newl)
  File "/usr/lib/python2.7/xml/dom/minidom.py", line 816, in writexml
    node.writexml(writer, indent+addindent, addindent, newl)
  File "/usr/lib/python2.7/xml/dom/minidom.py", line 816, in writexml
    node.writexml(writer, indent+addindent, addindent, newl)
  File "/usr/lib/python2.7/xml/dom/minidom.py", line 812, in writexml
    self.childNodes[0].writexml(writer, '', '', '')
  File "/usr/lib/python2.7/xml/dom/minidom.py", line 1040, in writexml
    _write_data(writer, "%s%s%s" % (indent, self.data, newl))
  File "/usr/lib/python2.7/xml/dom/minidom.py", line 297, in _write_data
    writer.write(data)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 244-245: ordinal not in range(128)


Just edit archive.py (see error log for details on its location and change:
--- /usr/lib/tinyos/nesdoc/archive_old.py
+++ /usr/lib/tinyos/nesdoc/archive.py
@@ -1,4 +1,5 @@
 # -*- python -*-
+# -*- coding: utf-8 -*- 
 # Copyright (c) 2005 Intel Corporation
 # All rights reserved.
 #
@@ -43,6 +44,7 @@
 from nesdoc.graph import generate_graph
 from nesdoc.html import *
 import os
+import codecs

 def check(x):
   if not x:
@@ -292,7 +294,7 @@
       refd.appendChild(qnameidx[qname].cloneNode(True))
     doc.appendChild(copy)
-    ifile = file(filename, "w")
-    doc.writexml(ifile)
+    ifile = file(filename, "wb")
+    doc.writexml(codecs.open(filename, 'wb', 'utf-8'), encoding='utf-8')
     doc.unlink()
     ifile.close(

And this one:

Traceback (most recent call last):
  File "/usr/lib/tinyos/nesdoc/genhtml.py", line 96, in <module>
    generate_component(ixml.documentElement)
  File "/usr/lib/tinyos/nesdoc/components.py", line 91, in generate_component
    ht.pdoc(idoc)
  File "/usr/lib/tinyos/nesdoc/html.py", line 149, in pdoc
    self.p(self.escape_email(val))
  File "/usr/lib/tinyos/nesdoc/html.py", line 51, in p
    self.f.write(s)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 2-3: ordinal not in range(128)

As done above, edit the html.py file with the following: 

--- /usr/lib/tinyos/nesdoc/html_old.py
+++ /usr/lib/tinyos/nesdoc/html.py
@@ -48,7 +48,7 @@
     if self.at0:
       self.f.write(" " * self.ind)
       self.at0 = False
-    self.f.write(s)
+    self.f.write(s.encode('utf-8'))

   # print a string and end the line
   def pln(self, s): 

Afterwards the documentation can be viewed and navegated through by browsing the generated index.html file at $TOSROOT/doc/nesdoc/platform:

Nesdoc output: components, interfaces and wirings

Sunday, 25 May 2014

Stumbled on (2): What most Schools don't teach

I wasn't able to post anything last Sunday due to my daughter's birthday, so this week stumbling upon arrives a bit late, anyway today I found a video interesting to show to non-coders and specially to parents and youngsters: this new world is more about bits than atoms, coding and programming it is not reserved only to Computer Science majors, but to anyone willing to learn... sadly neither my school or college taught me how to code, so I was a late bloomer and an autodidact (now I code for a living), perhaps the video below can give you more reasons to start early.

What most Schools don't teach (core.org)

Some of the biggest names in tech and Hollywood have joined forces in a new video for Code.org, a non-profit focused on computer programming education, to encourage students to take coding classes.

First stumbled by Alicia1321.
Source: Code.org

Monday, 12 May 2014

Using Telecom Design's TD120x as a SIGFOX gateway with a Z1 mote


As mentioned in an earlier post, I recently got a demo kit from SIGFOX and finally I had some time to start playing with.

I had a head start and told that the starter kit was based on Telecom Design TD1204, which provides a serial AT-based modem to allow communication over a serial link, so it made easier testing using software tools like PuTTY, Hercules and then moving to a Zolertia Z1 mote to drive the TD1204 over its serial port (at the end of the post!).

Note: You need to have a device registered in the TelecomDesign cloud or the SigFox backend for some of the following steps, but nevertheless is is interesting to watch and to take a peep inside.

 

SIGFOX Back-end


I started by browsing the web-based SIGFOX backend, by clicking on the Device tab (as shown below) we can see the devices associated to our account, my starter kit device appears listed there.



I work in Barcelona, so I was interested in checking if my workplace is under SIGFOX coverage area, so by clicking the Location tab at the left it is shown an approximate coverage map.  (btw, I have tried pushing a message while at home in Cerdanyola del Vallès, but it didn't reach the network, but generally in Barcelona the coverage is OK).  At first glance it made more sense to me to represent the light blue area as a circle rather than using a square, but as I'm not sure of how this is modeled, it is fine as it is at the moment.


 Then the moment of truth, let's see what happens when I long-press-and-hold the button... once or twice to be sure, the message board is updated showing the content of the test message... I don't understand what the data means (180c62, 190c62), but I have a good idea about the rest of the fields...


  • Delay: Time (in seconds) elapsed since the message was triggered and then received by the network station.
  • TAP: Station receiving the message, as these stations are fairly identified you can get the estimated location of your device (a way estimated location).
  • RSSI: Received Strength Signal Indication: as shown we have values ranging from -124/-128dBm, as it was already discussed in my previous post, the sensitivity value is expected to be quite low, as the wireless range is favored by the low data rate and bandwidth.  In the  TD1204 EB page the sensitivity value is stated to be close to -126dBm, as we are using a 5dBi external antenna we can expect a boost (in one occasion I got a RSSI value of -132dBm, so this approximation seems to be OK).
  • Signal (dB)
  • Freq (MHz): channel used in the transmission, as shown above the channel is changed for every retransmission attempt.
  • Rep: Numbers of retransmission attempts needed for the packet to actually arrive to the network.
  • Callbacks: Event triggered upon receiving the packet, below is an example of the callback generated by the user-button event (an email is sent every time to a given email address):
          [OK] - TAP 0146 - 1 second
     200 -
     {device} (name@mail.com)

The maximum transmission power of the radio transceiver is 14dBm (for the TD1204 DK), but it would be interesting to check if SIGFOX allows devices to be on the ETSI G3 sub-band (869.4-869.65 MHz 500mW), one thing pending to confirm (in my previous post I assumed so).

 

Hands-on: connecting SIGFOX to a Z1 mote 


So OK, enough of using the user button and the backend (we will return to this later when setting callbacks and stuff), now let's move to the meaty part of the testing: sending a custom string message.  After checking the TD 1204 reference manual, I found the required serial settings to connect the starter kit to the PC:
  • Speed 9600 bps.
  • 8 data bits.
  • 1 stop bit.
  • No parity, no hardware/software flow control.
I first tested the serial communication using Hercules and the result was OK as expected (remember to add a carriage return at the end of the string, more information about the command/response expected format is found in the TD1204 reference manual, section 2.4).

.

After verifying the serial communication then I moved to wiring the starter kit to the Z1 mote.

At first It seemed a good idea to cut-off the male USB connector of an USB male to mini-USB cable, strip the wires and solder those to the Z1 mote, wiring D+/D- to the UART1's RX/TX (P3.7/P3.6), and power the starter kit by soldering GND/VCC to the Z1's USBGND/USB+5V (requiring to power the Z1 through its micro-USB port)... but this was a rather bad idea, as I noticed when connecting the TD1204 to the PC that it uses a FTDI chip, which are normally slaves thus requiring a master to communicate.  The Z1 mote has a CP210x serial-to-USB converter too, but my original intention was to use raw serial communication using a free UART port of the Z1 mote, so its USB port (wired to UART0) can be kept as a programming/debugging port, avoiding to use the JTAG port instead.


So the next logical step (off course, without a doubt) was to void the warranty and take a peek inside the demo kit... I love voiding warranties :-)

Finding the FTDI reference (FT232R-L package) chip was easy, as suspected there's a battery charger/Modem enabling circuit, a 1000mAh LiPo battery and the user button on one side, on the other we can see a TD1202 radio transceiver and AT-modem (sending an AT&V command is also a good way to find out about board-specifics).




Next I needed to locate the serial RX/TX lines going to the TD1202 transceiver to bypass the FTDI, following the FTDI pin-out and the PCB trace I noticed there were 2 0Ohm resistors standing between the FTDI and the modem, a nice gesture as it only required to apply a little heat and lift-up the resistors instead of cutting the PCB.  

The location of the RX (red), TX (white) and GND (black) pads are shown above, as well as the location of the resistors.  We cross-wired the Z1 and TD1202 RX/TX lines, and the DGND pin of the Z1 to GND.


I could also directly power the TD1202 using the Z1's 3.3V power reference, but honestly I was more interested in testing the communication between the Z1 and the board, than worrying about how to power the device, so I kept using the mini-USB port to power up the TD1202 through the 5V delivered by the Z1 connected via USB as shown below... a work to be done later is to replace the LiPo battery with one that has a larger capacity, and hook it up to a solar panel, but that's material for another post.

 

I used a logic analyser to verify the communication between the Z1 and the TD1202 was OK, and programmed the Z1 mote using TinyOS with a simple serial test sending an AT\n command every second, hoping to receive the AT command echoed back and an OK from the AT-modem, the result is shown below.


Here's the snippet of code used for the test.  The TMP102 temperature sensor callback event is shown on purpose, it will be used later to forward temperature readings from the mote.


Maybe someday I'll write a driver in Contiki/TinyOS to allow a more flexible and API-like way to communicate with the TD120x, or just port my sub-1GHz based mote to native support SIGFOX, but for preliminary testing sending raw strings is acceptable.

As the serial communication is asserted I can dump now the logic analyser and just print out the responses from the TD120x to console by modifying the code, adding a first print after boot to check out device information such as version.


Z1 with a SIGFOX interface


After checking the TD120x documentation the command to send data is quite straightforward:
AT$SS=[HEX1][HEX2]... [HEX12]

As mentioned before, up to 12 bytes can be sent in any transaction, more than enough for sending a 16-bit temperature reading from the Z1's built-in TMP temperature sensor.

The sending command expects a number of even hexadecimal "symbols" to be sent, meaning if you have 0x123 the modem will return an error, as it expects something like 0x0123.  All data should be sent encoded as hexadecimal, and leading zeroes might be needed depending on your data format.

After wiring my temperature sensor callbacks to be forwarded to SIGFOX the following messages were received, showing the mote was close to 28.5ºC at the moment of the test.  Most of my messages are being sent close to the 868Mhz frequency, maybe SIGFOX operates solely on the G1 sub-band?



The code used for testing is available at Github.

Wrapping up...


If you like to outgrown the demo, you could add more motes and add radio communication, and use the TD120x-enabled mote as a Gateway with dual wireless interface: sub-1GHz and 2.4Ghz, allowing to forward messages to SIGFOX while locally using other network topologies and protocols, not limited by SIGFOX packet size/throughput, only pushing important data and events such as alarms, periodic readings and others.

So this is the end of the post, I still need to test the callbacks and customising the TD120x using the SDK ,but this post has grown too much already, so I'll leave more for later.