Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Saturday, February 8, 2014

OpenMV Update: MicroPython, More I/O, uSD and Lots of Other Things!

Time for another update, sorry this took me so long, I've been very busy working on OpenMV, the good news is I have lots of new features implemented! There's a new (smaller :D) hardware revision with more I/O (USART/I2C and SPI) and a uSD socket, MicroPython support, an IDE for the camera, and for those of you who have been wondering, I'm working with Michael Shimniok from Bot-Thoughts on doing a Kickstarter campaign for OpenMV, soon, hopefully, you will be able to get one for a very reasonable price :) so stay tuned!

Okay, so on the software side, you've probably heard of the MicroPython project, if not make sure to check it out, basically MicroPython is very efficient, lightweight Python VM for microcontrollers, the plan was to script the camera with Lua/eLua but MP has some really neat features already implemented, so long story short, I've decided to script the camera with MP... after lots of work, I managed to get MP running on OpenMV, and wrote some MP bindings to export the subsystems of OpenMV to Python, eventually it will be completely controlled with Python.

So how this works so far, basically, on reset OpenMV runs a default Python script with the old serial camera interface (receive commands from the serial port, process and return result) but it also shows up as a small USB storage device where you can copy your own Python script(s), reset and it runs that instead of the default script.. In addition to that, you can also "talk" to the camera directly using a Python shell over the com port while watching the framebuffer in realtime :)

I've also combined all those nice features into a single "IDE" for convenience, written with Python, PyGTK and PyUSB. The IDE has a Python shell, a framebuffer viewer, and it can run scripts or save them to flash:


Moving on to the hardware, the new revision is 1.0x1.30 inches, it has a tiny uSD socket (which will be available to Python user code) USART, SPI and I2C broken out on the main 2.54mm header and a separate 2mm SWD debugging header.. There's also a switch, which will be used for boot or reset.
Here are some pics of the 3rd (2nd?) revision:



Compared to the old one:



That's it for now, please let me know if you have any comments :) thanks!
Read more ...

Wednesday, July 11, 2012

Portable SDR with Olinuxino for Tracking Wildlife

I was working on a project for a biologist friend of mine, that involved tracking RF tag implants on wildlife, using an SDR DVB-T dongle. He wanted a portable solution to be placed near the sprainting places of Otters(Lutra lutra), the main subject of the study, where they regularly come to deposit scent marks.

An RF tag is implanted on the animal which sends pulses on a frequency unique for each tag, this way we're able to tell them apart, this is what a cheap RF tag looks like,  this one has a frequency of 148.354Mhz
Software defined radio (SDR) became a bit more accessible recently, when a kernel hacker discovered that DVB-T dongles based on the RTL2832U chip can be used as a cheap SDR, since the chip allows transferring the raw samples to the host. Since the project was on a tight budget that seemed like a perfect solution...

The osmocom project provides a user space driver for the dongle, I started with pyrtlsdr, a Python binding for librtlsdr, and pylab for signal processing of the samples collected by the SDR, to compute and plot the PSD, that last spike corresponds to the signal of the RF tag above:

Finally, I ported everything to an olinuxino ARM-based board running Linux, a script runs on boot and logs the detected frequencies to file on SD card for later processing, the board still hasn't been tested in the field yet, I'm still working out some issues with the power management.
Read more ...

Tuesday, August 3, 2010

How To Read SMS Messages From Huawei E620 Modem

I always wanted to read SMS messages from my Huawei modem on Linux but unfortunately It seems that they only support Microsatan Winblows...

Anyway, while I was trying to read /dev/ttyUSB2, I was connecting a usb gadget with serial over usb, I got a of bunch of gibberish messages, I found out, beside the fact that the usb gadget didn't work :D, that the Huawei supports serial over usb ! it also seems that I have been in a cave, hence the bad reception, because people have been playing with this for decades :)

Cool I can finally read the messages without playing solitaire !

Huawei AT commands
While the modem is connected it keeps sending statistics which include the connection duration, upload/download rates and signal strength:
DSFLOWRPT:000054F0,00000622,00000D89,00000000006FD555,00000000017D4579,0000BB80,0000FA00
DSFLOWRPT:000054F2,00000000,00000000,00000000006FD555,00000000017D4579,0000BB80,0000FA00
RSSI:4
DSFLOWRPT:000054F4,0000001F,0000007B,00000000006FD594,00000000017D466F,0000BB80,0000FA00
RSSI:4
DSFLOWRPT:000054F6,00000000,00000000,00000000006FD594,00000000017D466F,0000BB80,0000FA00
It also supports a subset of the AT commands, I googled for Huawei AT commands, It seems that every model (or perhaps Vendor) supports a different set of AT commands, but "they" don't publicly provide this information !
Anyway, most of them support dialling numbers, notifications, reading/sending SMS messages... Which means that you can easily turn your machine into an SMS gateway  ;) !
I'm only interested in a subset of the commands:
AT+CMGF=1
AT+CSCS="UCS2"
AT+CMGL="ALL" 
AT+CMGS="phone number" "message" <ctr+z>
The first command, enables the text mode for other commands, second one sets the encoding to UCS2, I set it to UCS2 to unifiy all the output from the Huawei so I can parse both English and Arabic messages, but there are other options try AT+CSCS=?.

The third one retrieves the list of messages and the last one sends out an SMS, but I haven't tried this one because I didn't have any credit left :)

Python Script
After a some attempts with minicom and ipython, I quickly put together a small python script to read the SMS messages, it's crappy but it works:
#!/usr/bin/env python
import serial

port = serial.Serial(baudrate=115200, port='/dev/ttyUSB2', timeout=5)
port.open()
port.write('AT+CMGF=1\r\n')      #set text mode
port.write('AT+CSCS="UCS2"\r\n') #set encoding to UCS2
port.write('AT+CMGL="ALL"\r\n')  #get all messages

def __decode(str):
    ustr = u''
    str = str.strip().replace('"', '')
    for i in range(len(str)):
        if not i % 4:
            ustr += unichr(int(str[i:i+4], 16))
    return ustr

gotmsg = False

while(1):
    line = port.readline()
    if line.startswith('+CMGL'):
        info = line.split(',')
        print 'message#%s from %s date %s time %s %s'     \
              %(info[0].split(':')[1], __decode(info[2]), \

info[4], info[5], __decode(port.readline()))
        gotmsg = True
    if gotmsg and line.startswith('OK'): break


Damn it ! more bills :(
message# 7 from 1011161051159710897116 date "10/07/23 time 16:59:55+12"
 عميلناالعزيز:نحيط سيادتكم علمابضرورة سدادفاتورتكم خلال48ساعة نظرا لانتهاء موعد 
message# 8 from 1011161051159710897116 date "10/07/23 time 16:59:55+12"
www.etisalat.com.eg استحقاقها وذلك لضمان استمرارالخدمة,كما يمكنكم السدادعن طريق موقع اتصالات
message# 9 from 1011161051159710897116 date "10/07/23 time 16:59:55+12"
 في حالةالسداديرجى تجاهل الرسالة
Read more ...

Monday, July 5, 2010

RN-41 Bluetooth Module

Recently I've been playing with the RN-41 bluetooth module from sparkfun, this module is really easy to use, it requires just a couple of connections to work and implements the SPP (bluetooth serial profile) with TTL levels so it's perfect for a pic project :) This is a little how-to on configuring and interfacing with the RN-41 module.
The circuit
This is a typical pic microcontroller circuit with a 3.3v voltage regulated power supply, the pic is running at 4Mhz, connected to the pic's serial port is the RN-41 module, rx->tx and tx->rx. I also wired a 16x2 LCD to print text sent to the RN-41.
Programming the pic
Alright we have the hardware ready now we need to program the pic to read from the RN-41 and print to the LCD, I used the CCS compiler, here's the code

#include <16f876.h>
#use delay(clock=4000000)     /*4Mhz*/
#use RS232(BAUD=9600, XMIT=PIN_C6, RCV=PIN_C7, STREAM=COM_A) 
#fuses XT, NOWDT, NOPROTECT, NOLVP 
#include "flcd.c"            /*flex lcd driver/

char buf[16];
int8 have_string = 0;

/*serial port interrupt service routine*/
#int_rda
void sp_isr()
{ 
    fgets(buf, COM_A);  
    have_string = 1;
}

void main(void)
{
    enable_interrupts(global);    /*enable interrupts*/
    enable_interrupts(int_rda);   /*enable serial port interrupts*/
   
    lcd_init();
    delay_ms(100); /*must delay after initiating the lcd*/
   
    while (1) {             
       if (have_string) {
          have_string = 0;         
          printf(lcd_putc, "\f%s", buf);
       }
    }
}
The code is pretty easy, but anyway, we first enable global and serial port interrupts so we get an interrupt whenever we receive data, you can poll the serial port instead but you should use interrupts because they free up the processor to do other stuff.

Inside the isr, we read a string from the serial port and set the have_string flag which is continuously checked in the main loop, when we have a string we print it to the lcd. After programming the pic, last step is configuring the RN-41.

Configuring the Module
The RN-41 module can be configured either locally, over the serial port, or remotly, over the air, I think the later approach is easier, so that's what I will be doing, I will use python to connect to the RN-41 since it's a lot more faster than doing so in C.

First we need a bdaddr and a channel to connect to the RN-41 module, so go ahead connect the power to the circuit, open a terminal and type:
$hcitool scan
Scanning ...
    00:06:66:04:11:94    FireFly-1194

$sdptool records 00:06:66:04:11:94
Service Name: SPP
Service RecHandle: 0x10000
Service Class ID List:
  "Serial Port" (0x1101)
Protocol Descriptor List:
  "L2CAP" (0x0100)
  "RFCOMM" (0x0003)
    Channel: 1
Language Base Attr List:
  code_ISO639: 0x656e
  encoding:    0x6a
  base_offset: 0x100
...
And we have the bdaddr and channel, time to configure the RN-41, the RN-41 has two modes of operation, a command mode and a data mode to configure the RN-41 we need to enter the command mode and we have to do so within then config time window, 60 seconds by default, open the python interpreter and:
import bluetooth
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect(('00:06:66:04:11:94', 1))  # bdaddr, spp channel
sock.send('$$$')                        # config mode, within 60 of connecting
sock.send('ST,255\r\n')                 # enables continuous configuration
sock.send('SU,9600')                    # set baudrate to 9600bps 
sock.send('---\r\n')                    # switch back to data mode 
sock.send('Hello World !\r\n')          # send some text to test
And we're done have fun :)

Notes:
  • The 10k pot controls the LCD contrast.
  • Continous configuration allows you to enter the config mode at any time, if you don't use it don't forget to enter the config mode within the config time window.
  • The flcd driver can be found somewhere at  the CCS forums
  • If you're going to use the same pins for the LCD this is my configuration:
#define LCD_DB7   PIN_B7
#define LCD_DB6   PIN_B6
#define LCD_DB5   PIN_B5
#define LCD_DB4   PIN_B4
#define LCD_E     PIN_B1
#define LCD_RS    PIN_B0
Read more ...