Posts Tagged ‘python’

Using GPIOs on NanoPi NEO 2 Board with BakeBit Starter Kit

May 21st, 2017 10 comments

NanoPi NEO 2 is a tiny 64-bit ARM development board powered by Allwinner H5 processor. FriendlyELEC sent me a couple of NEO 2 samples together with their BakeBit Start Kit with a NanoHat and various modules via GPIOs, analog input or I2C. I’ve already tested both Armbian with Linux 4.11 and Ubuntu Core Qt with Linux 3.10, and ran a few benchmarks on NanoPi NEO 2. You would normally prefer to use the Armbian image with Linux mainline since it provided better performance, but at the time I was told GPIO support was not there.

Configuring NanoPi NEO 2 board with BakeBit library

So this week-end, when I decided to test GPIO support and BakeBit Starter Kit, I decided to follow this advice, especially image is still the recommended one in the Wiki. So I went with that image.

I’ll use Python examples from Bakebit library, but if you prefer something similar to WiringPi, you may consider using WiringNP library directly instead of using Bakebit. Since NanoHat Hub comes with header with digital I/O (including 2 PWM), analog input, I2C and UART interfaces, I’ll make sure I try samples for all interfaces I have hardware for. FriendlyELEC did not include a module with a UART interface, so I’ll skip that one.

I followed instructions in BakeBit wiki from a terminal which you can access from the serial console or SSH. First, we need to retrieve the source code:

Then we can start the installation:

The last line will install the following dependencies:

  • python2.7           python2.7
  • python-pip         alternative Python package installer
  • git                        fast, scalable, distributed revision control system
  • libi2c-dev           userspace I2C programming library development files
  • python-serial     pyserial – module encapsulating access for the serial port
  • i2c-tools              This Python module allows SMBus access through the I2C /dv
  • python-smbus   Python bindings for Linux SMBus access through i2c-dev
  • minicom             friendly menu driven serial communication program
  • psutil                   a cross-platform process and system utilities module for n
  • WiringNP           a GPIO access library for NanoPi NEO

This will take a while, and after it’s done, the board will automatically reboot.

We can check if everything is properly running, but try out one of the Python scripts:

hmm, python-smbus was supposed to be installed via the installation script. Let’s try to install it manually:

Running the command again with verbose option shows the download URL is not valid:

So I went to looking for another python-smbus library in case the name has changed, and I finally installed the pysmbus:

I could go further, but the I2C bus was not detected:

So maybe the driver needs to be loaded. But running sudo modprobe i2c_sunxi it does nothing, and I could notice the .ko file is missing from the image…

So let’s try to build the source code for the board following the Wiki intructions:

We also need to install required build packages…

… download gcc-linaro-aarch64.tar.xz toolchain, and copy it to lichee/brandy/toolchain directory (do not extract it, it will be done by the build script).

Now we can try to build the kernel for NanoPi NEO 2 (and other Allwinner H5 boards).

and it failed with more errors possible related to CROSS_COMPILE flag. There must be a better solution… FriendlyELEC guys might not work on Saturday afternoon, and while I did contact them, I decided to try one of their more recent images with Linux 4.11 available here.

Let’s pick since it has a similar name, and is much newer (released 3 days ago). I repeated the installation procedure above, and …

Success! Albeit after 4 to 5 hours of work… Let’s connect hardware to ind out whether it actually works, and not just runs.

Analog Input and Digital Output – Sound Sensor Demo

The simplest demo would be to use the LED module, but let’s do something more fun with the Sound Sensor demo I found in BakerBit Starter Kit printed user’s manual, and which will allow us to use both digital output with the LED module connected to D5 header, and analog input with the Sound sensor module connected to A0 header. Just remember the long LED pin is the positive one.

You can run the code as follows:

I changed the source a bit including the detection threshold, and timing to make it more responsive:

The LED will turn on each time the the sound level (actually analog voltage) is above 1.46V.

PWM and Analog Input – Servo and Rotary Angle Sensor Demo

We can test PWM output using the Servo module connected to D5 header, and control it using the rotary angle sensor module connected the A0 analog input header .

Click to Enlarge

The sample for the demo runs fine, and use the potentiometer is detected:

However, the servo is not moving at all. Raspberry Pi relies on rpi-config to enable things like I2C and other I/Os, and I noticed npi-config in the Wiki for NEO 2. So I ran it, and sure enough PWM was disabled.

So I enabled it, and answered Yes when I was asked to reboot. The only problem is that it would not boot anymore, with the system blocked at:

So maybe something went wrong during the process, so I re-flashed the Ubuntu image, reinstalled BakeBit, and re-enabled PWM0. But before rebooting, I checked the boot directory, and noticed boot.cmd, boot.scr, and the device tree file (sun50i-h5-nanopi-neo2.dtb) had been modified. The DTB looks fine, as I could decode it, and find the pwm section:

Let’s reboot the board. Exact same problem with the boot stuck at “Starting kernel…”. So there’s something wrong with the way npi-config modifies one or more of the files. With hindsight, I should have made a backup of those three files before enabling PWM the second time… I’ll give up on PWM for now, and ask FriendlyELEC to look into it.

I2C and Analog Input – OLED UI controlled with Joystick

The final test I’ll use the I2C OLED display module connected to one of the I2C headers, together with the analog joystick module connected to A0 header.

Click to Enlarge

Let’s run the sample for the demo:

It works, but there’s a bit of a lag, and the sample may have to be improved to better detect various states. I’ll show what I mean in the video below.

The bad parts are that documentation is not up-to-date, enabling PWM will crash the image, and while the Python sample do demonstrate IO capabilities, they should probably be improved to be more responsive. The good part is that we’re getting there, the hardware kit is a really nice, and I think the documentation and software should become much better in June, as FriendlyELEC has shown to be responsive to the community issues.

What? Python sucks? You can use C language with GPIOs too

If Python is not your favorite language, FriendlyELEC also provided some C languages samples in the C directory:

As we’ve seen above, Bakebit library appears to rely on WiringNP, and you’d normally be able to list the GPIOs as follows:

The utility is not too happy about seeing an Allwinner H5 board. But maybe the library in the board is not up-to-date, so I have built it from source:

and run the gpio sample again:

Excellent! It’s not quite a work-out-of-box experience, but NanoPi NEO 2 can be used with (most) GPIOs.

My adventures with NanoPi NEO 2 board are not quite done, as I still have to play with NanoHat PCM5102A audio add-on board, which I may end up combining with a USB microphone to play with Google Assistant SDK, and I’m expecting NanoPi NAS Kit v1.2 shortly. I’ll also update this post once PWM is working.

Top Programming Languages & Operating Systems for the Internet of Things

May 19th, 2017 3 comments

The Eclipse foundation has recently done its IoT Developer Survey answered by 713 developers, where they asked  IoT programming languages, cloud platforms, IoT operating systems, messaging protocols (MQTT, HTTP), IoT hardware architectures and more.  The results have now been published. So let’s have a look at some of the slides, especially with regards to programming languages and operating systems bearing in mind that IoT is a general terms that may apply to sensors, gateways and the cloud, so the survey correctly separated languages for different segments of the IoT ecosystem.

Click to Enlarge

C and C++ are still the preferred languages for constrained devices, and developers are normally using more than one language as the total is well over 100%.

Click to Enlarge

IoT gateways are more powerful and resourceful (memory/storage) hardware, so it’s no surprise higher level languages like Java and Python join C and C++, with Java being the most used language with 40.8% of respondents.

Click to Enlarge

When it comes to the cloud with virtually unlimited resources, and no need to interface with hardware in most cases, higher level languages like Java, JavaScript, Node.js, and Python take the lead.

Click to Enlarge

When it comes to operating systems in constrained IoT devices, Linux takes the lead with 44.1%, in front of bare metal (27.6%) and FreeRTOS (15.0 %). Windows is also there in fourth place probably with a mix of Windows IoT core, Windows Embedded, and WinCE.

Click to Enlarge

Linux is the king of IoT gateways with 66.9% of respondent using it far ahead of Windows in second place with 20.5%. They have no chart for the cloud, probably because users just don’t run their own Cloud servers, but relies on providers. They did ask specifically about the Linux distributions used for IoT projects, and the results are a bit surprising with Raspbian taking the lead with 45.5%, with Ubuntu Core following closely at 44.4%.

Click to Enlarge

Maybe Raspbian has been used during the prototyping phase or for evaluation, as most developers (84%) have been using cheap development boards like Arduino, BeagleBone or Raspberry Pi. 20% also claim to have deployed such boards in IoT solutions.

Click to Enlarge

That’s only a few slides of the survey results, and you’ll find more details about Intel/ARM hardware share, messaging & industrial protocols, cloud solutions, wireless connectivity, and more in the slides below.

Via Ubuntu Insights

GPU Accelerated Object Recognition on Raspberry Pi 3 & Raspberry Pi Zero

April 30th, 2017 5 comments

You’ve probably already seen one or more object recognition demos, where a system equipped with a camera detects the type of object using deep learning algorithms either locally or in the cloud. It’s for example used in autonomous cars to detect pedestrian, pets, other cars and so on. Kochi Nakamura and his team have developed software based on GoogleNet deep neural network with a a 1000-class image classification model running on Raspberry Pi Zero and Raspberry Pi 3 and leveraging the VideoCore IV GPU found in Broadcom BCM283x processor in order to detect objects faster than with the CPU, more exactly about 3 times faster than using the four Cortex A53 cores in RPi 3.

They just connected a battery, a display, and the official Raspberry Pi camera to the Raspberry Pi boards to be able to recognize various objects and animals.

The first demo is with Raspberry Pi Zero.

and the second demo is on the Raspberry Pi 3 board using a better display.

Source code? Not yet, but he is thinking about it, and when/if it is released it will probably be found on his github account, where there is already py-videocore Python library for GPGPU on Raspberry Pi, which was very likely used in the demos above. They may also have used TensorFlow image recognition tutorials as a starting point, and/or instructions to install Tensorflow on Raspberry Pi.

If you are interested in Deep Learning, there’s a good list of resources with links to research papers, software framework & applications, tutorials, etc… on Github’s .

$30 BakeBit Starter Kit Adds Sensors & Buttons to Your NanoPi NEO & NEO Air Boards

January 20th, 2017 1 comment

FriendlyElec (previously FriendlyARM) launched NanoPi NEO and then NanoPi NEO Air board as respectively Ethernet and WiFi/Bluetooth connected boards for IoT applications. But so far, there was no ecosystem around the board, you had to use your own sensor modules, and write your own software to control them. This has now changed with the launch a BakeBit Starter Kit with twelve sensor modules, a NanoHat Hub add-on board designed for NanoPi boards, as well as BakeBit Library to control the hardware.

NanoPi NEO with NanoHat and Two Modules

The NanoHat Hub plugs into the two NanoPi NEO headers and provide 12 headers with 3x I2C interfaces, 3x analog interfaces, 2x UART interfaces, and 4x digital interfaces among which D3 and D5 support PWM, compatible with SeeedStudio Grove modules. You then have a choice of 12 modules to connect to the NanoHat Hub:

  • OLED Module
  • Ultrasonic Module
  • Green LED Module
  • Red LED Module
  • LED Bar Module
  • Rotary Angle Sensor Module
  • Joystick Module
  • Sound Sensor Module
  • Button Module
  • Light Sensor Module
  • Buzzer Module
  • Servo Module

BakeBit Starter Kit – Click to Enlarge

But now that you have your hardware setup with multiple module, you still need to program the thing, and that’s where BitBake library, based on Grove Pi, comes into play, as it allows you to program the module easily with Python programming. More details can be found in the Wiki for BakeBit NanoHat and modules.

BakeBit Starter Kit is now sold for $29.99 (promotion), but if you already have Grove modules, you could also simply purchase NanoHat Hub for $12.99. Bear in mind that Chinese New Year is around the corner, so any order passed after January 24th and beyond, will be processed after the holidays around February 6th. [Update: The company has also released a $9.99 NanoHat PCM5102A audio board for NanoPi Boards]

39 Euros FiPy Board Supports Sigfox, LoRa, LTE Cat M1/NB1, Bluetooth 4.2, and WiFi (Crowdfunding)

November 24th, 2016 1 comment

Long range LPWAN solutions have just started to hit the market, and there are so many standards such as Sigfox and LoRa that it’s difficult to know who will eventually be the winner, or if different standards will co-exist over the long term, and in a general sense it might not be so easy to decide which one is best suited to your project without experimenting first. Pycom has a solution to this problem, as they’ve made a board similar to LoPy with WiFi, Bluetooth, and LoRa, but instead included 5 long and short range IoT protocols: Sigfox, LoRa, LTE Cat M1 & Cat NB1, Bluetooth, and WiFi.

pycom-fipy-boardPycom FiPy board specifications:

  • SoC – Espressif ESP32 dual core Tensilica L108 processors @ up to 160 MHz with BT 4.2 and WiFi
  • System Memory – 4MB RAM
  • Storage – 8MB flash memory
  • Connectivity
    • WiFi 802.11 b/g/n @ 16 Mbps up to 1 km range & Bluetooth 4.2 with common u.FL antenna connector and chip antenna
    • LoRa and Sigfox transceiver
      • common u.FL antenna connector, RF switch
      • Lora
        • 868 MHz (Europe) at +14dBm maximum
        • 915 MHz (North and South America, Australia and New Zealand) at +20dBm maximum
        • Node range up to 40 km, nano-gateway range up to 22 km (max 100 nodes).
        • Power Consumption – 10mA Rx, 28mA Tx
      • Sigfox
        • Maximum Tx power – +14dBm (Europe), +22dBm (America), +22dBm (Australia and New Zealand)
        • Node range up to 50km
        • Operating Frequencies
          • RCZ1 – 868MHz (Europe)
          • RCZ2 – 902MHz (US, Canada and Mexico)
          • RCZ3 – (Japan and Korea)
          • RCZ4 – 920 – 922MHz (ANZ, Latin America and S-E Asia)
        • Power Consumption
          • Sigfox (Europe) – 17mA in Rx mode, 47mA in Tx mode and 0.5uA in standby
          • Sigfox (Australia, New Zealand and South America) – 24mA in Rx mode, 257 mA in Tx mode and 0.5uA in standby
    • Cellular LTE CAT M1/NB1 transceiver
      • u.FL antenna connector and nano SIM socket
      • Operating frequencies – 34 bands supported from 699 to 2690MHz
      • 3GPP Release 13 LTE Advanced Pro
      • Peak power estimations – Tx current = 420mA peak @ 1.5Watt Rx current = 330mA peak @ 1.2Watt
  • Expansion – 2x 14 pin headers with UART, 2x SPI, 2x I2C, I2S, SDIO, 8x 12-bit ADC, 2x 8-bit DACs, up to 16 PWMs, up to 22 GPIOs
  • Misc – WS2812 RGB LED, reset switch, 32 KHz RTC (in SoC)
  • Dimensions – 55 x 20 x 3.5 mm
  • Temperature Range – -40 to 85 degrees Celsius
  • Certifications – CE, FCC,  Sigfox network certification, LoRa Alliance certification, LTE-M CAT M1/NB1 cellular –  global networks


FiPy name is most probably derived from Five IoT protocols, and microPython support. As the board is compatible with WiPy, LoPy and SiPy you can use the usual Pymakr IDE and Pymate Mobile app to write your program and control the board. The company has also introduced two new add-on boards:

  • PySense board with an ambient light sensor, a barometric pressure sensor, a humidity sensor, a 3-axis 12-bit accelerometer, and a temperature sensor, as well as a micro SD card, a micro USB port, and a LiPo battery charger
  • PyTrack board with a GNSS + Glonass GPS and a 3-axis accelerometer, as well as a micro SD card, a micro USB port, and a LiPo battery charger. This can be very useful to track moving assets such as cars or bicycles.

FiPy and PyTrack

The project has just launched on Kickstarter as already surpassed its 25,000 Euros funding target. Most early bird rewards are gone, but you can pledge 39 Euros for FiPy board,  59 Euros (Early bird) for PySense Kit, 65 Euros (Early bird) for PyTrack kit, optionally adding 7 Euros for a Sigfox/Lora antenna, and 7 Euros more for an LTE-M cellular antenna. Shipping adds 8 to 25 Euros depending on the selected rewards, and delivery is scheduled for April 2017. Just a warning for users who are not based in the US or Europe: please make sure you comply with your country regulations, especially in terms of frequency used, as such nodes will have multiple kilometers range, and you may not want to break the law, and possibly get a visit from your local police or military…

A Closer Look at Ingenu RPMA Alternative to LoRa or Sigfox LPWAN Standards & RPMA Development Kit

November 20th, 2016 6 comments

I’ve recently started to write a bit more about long range LPWAN standards for IoT applications, especially LoRa and Sigfox, as commercial networks are being launched, and relatively low cost hardware platforms are being introduced to the market. There are also other highly expected standards such as Weightless and LTE Cat M that will bring more competition to the market. Ingenu RPMA (Random Phase Multiple Access) is another available standard that’s been in deployment for a while, and based on an earlier comparison of  long range LPWAN standards, it comes with long range, supports up to 384,000 nodes per “sector”, operates in the unlicensed 2.4 GHz ISM band, and offers high combined uplink and downlink bandwidth than competitors. Ingenu recently contacted me and provided some more details and information about their technology and development kit.

One of the documents includes an “independent analysis completed by ABI Research, Inc.” comparing features of Sigfox, LoRa, EC-GSM-IoT, MB-IoT, LTE Cat-M1,  and RPMA.

Click to Enlarge

Click to Enlarge

All standards can have node powered by a battery for over 10 years, but based on that table RPMA does seems to have some advantages in terms of coverage, capacity, throughput, security level, scalability, and mobility support.

Click to Enlarge

Click to Enlarge

Those charts are extracted from the Ingenu’s marketing documents, so they’ll obviously show RPMA in a positive light. However it does seems that if you have lots of nodes, and bandwidth requirements higher than what can be delivered by LoRa or Sigfox, RPMA appears to be a potentially better solution. The 2.4 GHz band is normally quite busy, so I wonder if there could be some limitations here, and some countries may also have restrictions on the emitted power. RPMA deployments started in 2011, so they already have an installed base on several continents for industrial, agricultural, and security applications, which includes 38 Private Networks as well as the “Machine Network” in North & South America, EMEA, and APAC regions.

ingenu-rpma-networksSupport in the Asia Pacific regions is certainly a plus, as this week a French company wanted to send me their Sigfox & LoRa sensors kits for evaluation, but they had nothing working in South East Asia, so it will be for a little later.

The company can provide RPMA devkit to their customers in order to get started and evaluate the technology.

Click to Enlarge

Click to Enlarge

Ingenu RPMA development kit key features and specifications:

  • MCU – NXP Kinetis K20 ARM Cortex-M4 MCU @ 50 MHz
  • Connectivity
    • nanoNode RPMA radio module (NODE103)
      • Wireless Frequency – 2.4 GHZ ISM
      • Bandwidth – 1 MHz
      • Modulation – Dynamic Direct Sequence Spread Spectrum (D-DSSS)
      • Access Point Capacity – Up to 64,000 nodes in star topology
      • Typical Power – Tx: 800 mW; Rx: 250 mW
    • u-Blox GPS module
  • Expansion – Header with analog & digital GPIOs and UART
  • Debugging – JTAG header, UART for serial debugging
  • Battery Life – Up to 20+ years
  • Power Supply – 5V/1A power supply to DC jack (J204), 2.2 to 3.6V DC batteries to J201 header
  • Dimensions – 107 x 68 x 13 mm
  • Temperature Range – 0°C to 85°C
  • Certifications – FCC, IC, ETSI, and others (pending) for some specific countries

The rACM (reference Application Communication Module) tools are used to control the kit, and since they are written in Python it will work on Windows, Mac OS X or Linux. Communication occurs over a REST API or Advanced Message Queuing Protocol (AMQP) open standard messaging protocol, and devices can be managed through a platform called Intellect. Quick Start Guides are also provided to customers to show how to set up pulse meters, UART, GPIO, and more…


You’d use the devkit with RPMA networks such as the Machine Network. You can check network coverage on Ingenu to find out if it is available in your location. If there’s no network in your location, but a network is expected soon, you can still evaluate RPMA technology by getting an Exploration Kit with two RPMA devkits and a rental RPMA access point. The latter gives some clue about about the use cases for RPMA, as while you can get one or two ~50 Euros LoRa nodes connected it to a LoRaWAN network or setup P2P communication, RPMA apparently requires an access point that expensive enough that it has to be rented. So RPMA is likely most suitable and cost effective for larger scale IoT deployments, and not for smaller or hobbyist’s projects.

You’ll get some more details about the hardware and software, as well as interesting case studies about existing implementations, on the Get Started page, or by directly downloading the Starter Pack with hardware design files, software tools, REST & AMQP source code examples, and documentation.

GR-LoRa is a Reverse-Engineered Open Source Implementation of LoRa PHY

November 15th, 2016 8 comments

LPWAN standards such as LoRa or Sigfox allow you to transmit data over long distance, at ultra low power (up to 10 years on a AA battery), and for free if your use your own network (P2P or gateway), or a few dollars per years if you go through a network provider. The low cost is possible since those standards rely on 900 MHz ISM bands, meaning nobody has to pay millions of dollars to the government to obtain a license fee. Matt Knight looked at LoRa, and while Level 2 and 3 of the protocol (LoRaWan) has public documentation, Level 1 (LoRa PHY) is proprietary and the standard is proprietary.

microchip-rm2903-ettus-b210-sdrSo he decided to reverse-engineer LoRa PHY using Microchip RN2903 based LoRa Technology Mote and Ettus B210 USB software defined radio, and software packages and tools such as Python and GNU Radio to successfully deliver GR-LoRa open source “GNU Radio OOT module implementing the LoRa PHY”.  He presented his work at GNU Radio Conference 2016 on September 15, and the video is worth a watch. He first explains why LPWAN IoT standards are awesome, the motivation about reverse-engineering work (mostly security), the hurdle (e.g. lies in documentation), the results, and work to be done.

You’ll find the presentation and the research paper on Github.

Thanks to Emanuele for the tip.

How to check HTTP Header and Connection Stats from the Command Line

October 3rd, 2016 1 comment

A few days ago, I discussed with somebody whether a file was cached by Cloudflare or not, and this involved getting the HTTP header, and checking for CF-RAY field to see if data is going through one of Cloudflare data centers. This can be done with curl:

In the command above, -s stands for silent so that curl does not show the progress meter, -v stands for verbose to show the header, and -o /dev/null is used to discard the packet load.

You can also use -I option (fetch the HTTP-header only) with curl, which – if all you need is the HTTP header – provides a cleaner output:

I also came across httpstat Python script recently via n0where, doing much of the same thing, except it also adds transfer statistics.
It can be installed by downloading, or better using pip:

Let’s try it with this very blog:

The header is the same as with Curl -I, and for good reason, since httpstat relies on curl, and all curl options (except for -w, -D, -o, -s, -S) can be used with the command line. This script can be useful if you are trying to benchmark and lower TTFB (Time To First Byte), or decrease overall download times from your server.