EPx professional blog and repository for braindumps

2009/08/28

PyS60: more fun with N85 accelerometer and rotation sensors

I am no longer surprised about how many accelerometer-related iPhone applications have been created. This thing is really fun and addictive to play with. It has been very pleasant to exercise the brain's L2 cache and remember high-school Physics classes.

Unfortunately, there will be no time to deep discussion of this topic in upcoming Python for Series 60 course, in PythonBrasil event. So FWIW I will post some extra information here, where any interested party can find it.

In that video I made some days ago, I stated that accelerometer applet was lacking gravity compensation. First thing I had to discover, is why gravity induces a opposite-sign reading on accelerometers. That's why:



When the phone is accelerated e.g. by your hand, the seismic weight keeps "behind" the frame. The circuit is wired to measure this kind of acceleration. But, when gravity acceleration is being measured, the opposite happens:


Since the phone is not moving, the gravity pulls the weight to the same direction as the acceleration vector, giving a inverted-sign reading.

Having understood this "feature" of accelerometers, I could work on gravity compensation, so my graphical acceleration applet could discount gravity from readings. First I need to take a "sample" of gravity force, since N85 sensors return accelerometer values in an arbitrary unit. I did it the laziest way possible:


# detect gravity value
# for this, cell phone is expected to over a table,
# perfectly horizontal, and steady
e32.ao_sleep(.5)
g = accel.z
print "gravity = %d" % g


From now on, every Z axis accelerometer can be subtracted by "g", in order to get a gravity-free acceleration.

Of course, this is valid only while the cell phone is kept horizontally to the ground. If you tilt it in a different way, the gravity effect will spread through all axis. And, to detect tilt angles, I need to read the rotation sensor too.

After some trail-and-error based on common sense, I found the following formulas to calculate the gravity force for each axis:


# Get raw accelerometer measures
ax, ay, az = accel.x, accel.y, accel.z
# Calculate gravity force based on tilt angles
gz = g * math.sin(rx) * abs((-math.cos(ry)))
gx = g * math.sin(ry) * abs(math.sin(rz))
gy = g * math.cos(rx) * abs(math.cos(rz))
# Discount gravity from original measures
ax = ax - gx
ay = ay - gy
az = az - gz
# Now we have gravity-free accelerometer measures in ax, ay, az

I am not 100% sure those formulas are right; I can just say that they worked, that is, they allowed me to show only "true" acceleration forces, regardless of tilt. Also, I know that a matrix multiplication would be opportune, but honestly I never learnt matrixes very well :)

Sometimes the accelerometer applet gave spurious readings, flashing big acceleration values briefly. While debugging this, I saw that rotation sensors returned -1 at some readings, breaking down that gravity discount calculations. I chose to ignore all sensor data on -1 angles, and the spurious flashes were gone.

I have made a series of pictures to show how the accelerometer and rotation axis "feel" on the phone. Let's begin with accelerometers, which are simpler to understand:



The axis are relative to the cell phone; it is obvious, but very easy to forget -- after playing too much time with the phone over a table, numbers feel funny for a while when you put it straight up.

When acceleration happens in the direction of the arrow, the measure will be positive. Z axis is positive when phone is accelerated towards front. As we saw, gravity will be perceived as opposite-sign measures.

At least for me, the rotation axis are more difficult to "get", so I made several pictures in order to understand it better:



The axis are the same as the acceleration axis. The circular arrows try to show the tilt direction that increases the angle (by the way, they are clockwise for all three axis). The measured angles for this position are: X=90º, Y=180º and Z=undefined (may return any angle).

The "North" (0º) position for the X axis is when cell phone is upright, like in the following picture:



Note that, in this case, the Y axis becomes undefined. Here we have a limitation of these rotation sensors: they are not gyroscopes, so they depend on gravity to read the angle. When two axis get parallel to the ground, the third one becomes undefined.

The origin (0º) for the Y axis is when the cell phone is e.g. on a flat table, face down:



In the following example, cell phone rests on its right side, and so the Y axis reads 270º:




The origin for Z axis is, like for the X axis, the phone in upright position. Z axis detects "yaw" rotation, like the following picture shows:



The "undefined axis" problem disappears when phone is tilted (neither perpendicular nor parallel to the ground). In the example above, as we add yaw to the phone, Y axis tends to resolve to 270º (assuming that phone is perfectly vertical in X and Y axis).

When the phone has left yaw, Y resolves to 90º:



And finallly, an example of X axis rotation:



DYI INS

Unfortunately, relative rotation plus acceleration is not enough input for a inertial navigation system (INS). That's too bad, I was willing to write something like this, despite the low precision of rotation sensors (15º). A true, three-dimentional INS system (which can estimate position and altitude) needs 3 accelerometers and 3 gyroscopes (or one gyroscope with 3 gimbals).

Just to illustrate the impossibility: if the cell phone undergoes a circular trajectory parallel to the ground, the perceived centrifugal acceleration can't be distinguished from a linear acceleration, because the change in heading angle is not known. The INS wouldn't know if it is going somewhere or if it is walking in circles!

We can only integrate the acceleration if we guarantee an one-dimensional trajectory. Like a straight line, or a train that runs on a predefined track. And we must strap down the phone to the vehicle in a predefined position and angle.

One possibility would be to integrate GPS data with sensors, but the very objective of an INS is to navigate without the need of a GPS... fail!

Some cell phones (including Nokia ones) have a magnetometer sensor (compass). This allows for a two-dimensional INS. If we add some simplifying assumptions e.g. that vehiche is a car and will never have a "roll" angle (except in case of accident :) I think it is even possible to have a 3D INS, without gyros.

2009/08/24

Divertindo-se com o Mercado Livre

Você é nerd? Foi bom aluno de Física no 2o grau? Está triste, desanimado? Gostaria de rir um pouco mas na só passa programa ruim na TV? SEUS PROBLEMAS ACABARAM! Chegou o Mercado Livre, que lhe proporciona inúmeras formas de diversão, à custa da burrice e sem-noçãozisse alheias!

1) Perguntas sem-noção

Inversores, e principalmente painéis solares, são alvo constante de gente sem-noção que pretende livrar-se da conta de luz ou do gato, e acha que descobriu a pólvora quando vê o anúncio.

Já vi mais de um dono de LAN house querendo usar energia solar. Um deles tinha 17 Pentium IV e ar-condicionado, e pediu um orçamento. Deu 40 mil. Ficou barato ainda, deve ter sido subdimensionado. Um dia nublado, e adeus Counter-Strike.

Outro queria alimentar um freezer a partir de um inversor de 1500W, e ainda por cima reclamou porque o inversor exigia uma bateria de 200Ah. Disse que o inversor era "ineficiente".

Alimentar geladeira e ar-condicionado com energia solar... Com o custo dos painéis solares, é melhor comprar uma locomotiva usada e usar como gerador estacionário. Pelo menos o cara ia poder vender energia para o resto do quarteirão.

Quanto maior a excentricidade do cenário perguntado, maior a probabilidade da pergunta ser complementada por: "...e você garante o funcionamento, né?".

Ok, vamos colar algumas perguntas reais para não pensarem que estou inventando isso:

1. Esse dispositivo (AUXILIAR DE PARTIDA BLACK & DECKER 450AMP - 12V ) pode ser ligado ao painel solar? 2. Quantos paineis solares são necessários, para carregá-lo totalmente, num local com IUV de 11


se eu quiser por uma placa solar na minha casa pra suprir a energia de 2 ar-condicionados 10.000 btu's sem ser split, dos antigos. que ficam ligados cada 1 por dia 10h??? + 1 microondas 220v,1 geladeira duplex 410L 220v, 1 tv 21" , 1 tv 29" e 1 tv 42" que ficam ligadas cada uma 9h por dia


(Outro painel solar) Bom dia, p começar não conheço muito bem esse sistema, mas qual a capacidade deste kit, pois preciso de agua quente nos banheiros (2), e a instação é simples? eu mesmo posso fazer?


(Inversor) Boa tarde! Eu quero dar de presente um inverter para meu pai ir pescar. Ele vai levar um freezer e lampadas. Ele queria levar duas baterias e um carregador que é ligado na rede 110v, para usar uma bateria enquanto carrega a outra e vice-versa. É possivel?


OLÁ AMIGO! ESSE INVERSOR LIGADO A UMA BATERIA DE 100Ah COM SEUS 1000W DE POTENCIA SENDO UTILIZADO A PLENA CARGA FUNCIONA POR QTO TEMPO?


(Painel solar para repetidor Wifi, que gasta pouquinho) Olá! Achei muito caro esta brincadeira. Será que 3 desta de 100 não resolve o problema (falta 40W)? A árvore é formada com um conjunto de LEDs, gostaria que ele tivesse um sistema de carregamento durante o dia, e que consumisse a carga a noite. Você têm alguma coisa mais barata? Obrigado pela atenção!


(Painel solar para repetidor Wifi, que gasta pouquinho) Caro Vendedor, necessito de fazer funcionar uma árvore de natal de 340 w, a 127V, durante 10 horas por dia. Você tem algo que possa me atender? Qual é a configuração? Grato.


(Inversor de pequena potência, para notebooks etc.) Gostaria de ligar um aspirador de pó no carro. aspirador electrolux a20. esse inversor aguenta? se não, teria um que aguentasse?


2) Sniper de anúncios

Outra fonte de diversão, categoria "cagueta/sinistro", é a caça ao anúncio safado. Seja produto falsificado ("HiPhones" e "Nokia N95 mini"), classificado na categoria errada, ou principalmente anunciando preço de R$ 3 mas especificando no corpo do anúncio que o preço é R$ 999 para fraudar a comissão do Mercado Livre.

Em particular na seção de celulares, os três tipos de anúncios bichados são comuns, e proporcionam "caça" abundante. Seria legal se o ML desse um crédito de comissão para os denunciantes. Só não é atividade muito aconselhável para quem mora no Rio de Janeiro, porque a maioria dos anúncios safados são de lá. Vai que algum "mano' se irrite e resolva ir atrás de você :)

3) Qualificações e usuários banidos

Na categoria "humor negro" está o arquivo de qualificações, em particular para usuários já banidos do ML que deram o calote em um monte de gente antes de sumir. Tanto os escritos das vítimas quanto as réplicas são engraçadas:

"DESONESTO não comprou, aguardou 20 dias, e fez uma proposta de troca, e queria que eu enviase primeiro meu produto, enquanto sua conta já estava até inabilitada"


"O comprador desistiu da compra, alegando que não iria pagar o frete. Nosso anúncio era claro. POR NÃO HONRAR O LANCE QUE DEU, NÃO RECOMENDAMOS ESTE USUÁRIO."

Réplica: Como é que vc faz isso cmigo cara?vc é um nojento seu monstro, me nagativou, n existe isso n cara, EU QUE NÃO RECOMENDO A VC A NINGUEM!!!!!


"depositei o dinheiro e o vendedor n mando o cabo e nenhum email ainda estou esperando comtato q vergonha em vendedor vende um cabo de 25 reais e dah o calote!!"

Playing with accelerometer sensors in Python for Series 60

I was preparing some code snippets for the upcoming PythonBrasil event and the PyS60 course. I had written an example for sensors (accelerometer and tilt), but I realized that dumping sensor numeric data on console is difficult to interpret, in particular because the XYZ axis are relative to the cell phone rather than absolute in space (the thing does not have a gyroscope within, after all).

Rainy Saturday nights are really inspiring. I began to tweak the original accelerometer/tilt sensor example, trying to make the output more interesting and meaningful. Here is the result:



As I say in video, tilt sensor precision is fifteen degrees, so the N85 is still not good enough to drive my ICBM missile into North Korea or Cuba :) The accelerometer is more fine-grained: it returns an integer value around 60 for gravity, and it never goes up 119 in absolute value, which suggests it has a 1/60g resolution and +/-2g range.

Code can be found at http://epx.com.br/artigos/snippets.

2009/08/21

Curso de Python para Série 60 na PythonBrasil

A PythonBrasil está se aproximando. Nos dias 10 a 12 de setembro, a comunidade Python Brasil estará em Caxias do Sul/RS.

O INdT marcará presença com alguns cursos: Python para celulares Série 60, Python para Maemo e Python/Qt. Os amigos da UFCG também estarão lá apresentando o BRisa, uma biblioteca UPnP feita em puro Python, e possivelmente a única biblioteca UPnP do mundo que realmente funciona :)

Pessoalmente, vou apresentar o curso de Python para Série 60. Acho que esta é a terceira edição do curso na PytbonBrasil. Os slides estão devidamente atualizados, quem quiser ir puxando e dando uma olhada, e até mesmo tirando dúvidas, aqui estão as versões OpenOffice e MS-Office:

http://epx.com.br/artigos/pys60_curso.odp
http://epx.com.br/artigos/pys60_curso.ppt

Peço desculpas antecipadas pela feiúra dos slides; eu sou péssimo piloto de Powerpoint e não tenho paciência para aprender a mexer direito. Felizmente, o curso foi ministrado pelo Osvaldo Santana no ano passado, e dessa forma a edição deste ano "herdou" um template decente ao invés do assustador template do OpenOffice.

Por outro lado, fiz um esforço sério em diminuir a quantidade de slides "socados de letrinhas", colocando mais exemplos de código e imagens em seu lugar.

Preparando-se para o curso

Ainda não sei que infra-estrutura vou encontrar no local do evento. Assim, estou presumindo que não há nenhuma exceto Internet, e os participantes trarão notebooks. O "equipamento ideal" para aproveitar ao máximo o curso é:

* computador equipado com Bluetooth, ou com dongle Bluetooth funcionando
* celular Nokia Série 60 3rd ou 5th Edition
* cabo USB do celular
* acesso à Internet.

O mais importante é possuir o celular e ter Bluetooth, para poder brincar com o Python e instalar pacotes. Os demais itens são contornáveis. O cabo USB dá acesso ao cartão de memória como se fosse um pendrive, o que eventualmente facilita "plantar" um script Python sem ter de criar um pacote. O acesso à Internet é interessante para poder consultar a documentação do PyS60, que é apenas online no momento.

Bluetooth às vezes é meio chato de configurar. Vou abordar a instalação do PyS60 no celular e a conexão do terminal via Bluetooth, mas quem quiser treinar isso antes com base nos slides, já eliimina uma potencial fonte de aborrecimento.

O sistema operacional do seu computador pode ser Windows, Linux ou Mac OS X. No Windows é preciso instalar o Python 2.5 que ele não possui "de fábrica", mas por outro lado só ele roda o emulador Symbian.

Eu vou levar pendrive com os softwares necessários ao andamento do curso, mas quem quiser adiantar o processo de instalação, aí vai a lista:

* Todos os arquivos do Python para Série 60 (https://garage.maemo.org/project/pys60)

* Usuários do Windows: Python 2.5.4 (tem de ser 2.5, não pode ser 2.6!)

* Usuários do Windows que queiram instalar o emulador Symbian: S60 3rd Edition SDK for C++ (Feature Pack FP1 ou FP2), encontrável no Forum Nokia.

2009/08/17

Making a car charger for N85 cell phone out of a "CA-101" cable

Newest Nokia cell phones can be charged via USB, even the wall charger has a Micro-USB plug. Since I wanted to charge the phone in the car, I bought a USB adapter for the car -- those ones that go into the cigarrete lighter socket and supply 5V for devices that can draw power via USB.

First, it was a FAIL: the CA-101 cable does not charge the cell phone just by connecting to a USB power source. The phone expects the USB handshake to actually happen, and then it draws power from USB. It even asked if it should use PC Suite or Mass Storage protocol.

But I had read somewhere that Nokia's wall charger "hints" the phone that it is a dummy voltage source just by shorting the USB data pins. Since I had two "cloned" CA-101 cables that I had bought from DX, I decided to try to build a "charger cable" by myself. It would be just a matter of shorting the data wires at phone connector's side.

Of course, the things went more complicated than expected. Those "generic" cables bought from DX do not follow the USB convention of wire colors (green and white for data, red and black for power). Once I opened the outer insulation, there was no black wire, there was a blue wire instead. Hmmm... too good I have a multimeter. Indeed the colors were non-standard: green and blue were data, white and red were power.

Finally, SUCCESS: the phone charges via USB and no longer asks about USB protocols. It behaves exactly like if it were plugged to the wall charger.

I guess the next step is to open up the USB adapter and short the data pins in there, in order to satisfy all devices that possibly understand shorted data wires as a dummy power source. Luckily I bought two USB adapters, so I can spare one for this experiment :)

And then I can throw that modded cable in trash; I am not comfortable about passing 500mA or more through that cable with incredibly thin wires and that unsoldered wire junctions that I made, which are kept together just by duct tape :)