viernes, 22 de abril de 2016

The chains are broken

Roaming the streets
All on my own
Can't find the answers while sitting at home

Carry your faith
And keep it along
The whole world is crushing
You're not alone!

Give up the tricks
Pull down your mask
No one is watching
You are free at last

Money isn't real
Check how you feel
Visit your friends
Cook them a meal

Future is strange
The path is wide open
Ideas converge
When the chains are broken

The chains are broken

viernes, 31 de julio de 2015

Discrete signal denoising

Given a stream of bits, we need to find the change of state and it's length.
  1    0(4)
  0    1(4)
  1    0(4)

Fig. 1: Stream of data unaffected by noise, 3 flanks detected
Unfortunately, some bits may be affected by noise.
  0            0     
  0            0
  0      X     1  0(2) 
  0            0  1(1)
  1            1  0(1)
  1      X     0  1(1)
  1            1  0(1)
  1            1
  0            0  1(2)
  0            0 
  0      X     1  0(2)
  0            0  1(1)
  1            1  0(1)
  1            1

Fig. 2: Stream of data affected by 3 random bits, 9 flanks detected

This random bits of noise scramble our data. We need to remove them.

We define that a state transition will not count as such unless a certain threshold is reached.

A naive method for solving this would be to buffer the data in a long buffer, and then loop over it cleaning bits which not reach the threshold.

Instead, we propose a simple state machine.

We introduce a couple of concepts: Working state, Count and Threshold.

Now, insted of a long buffer and iterating over it, our state machine has a boolean variable and two counters. Here is an example of our algorithm in action.

  0    0    0     0      
  -    -    -     -      
  0    0    1           
  0         2           
  0         3           
  0         4           
  1               1       
  0         6           
  0         7           
  1               1       
  1               2       
  1    1    3             0(7) 
  0               1       
  0               2       
  1         6           
  1         7           
  1         8           
  0               1       
  0               2       
  0    0    3             1(8) 

Fig. 3: A noisy sample is denoised
Now a little python to test our algorithm
working = '0' 
count = 0 
transition = 0 
threshold = 2 
stream = "000010011100111000" 
for reading in stream: 
   if reading == working: 
       count += 1 
       if transition: 
           count += transition 
           transition = 0 
       transition += 1 
       if transition > threshold: 
           print working, count # --> Called once per transition 
           count = transition 
           transition = 0 
           working = reading

#0 7
#1 8

#Fig. 4: Denoise algorithm and it's output

martes, 18 de noviembre de 2014

LED as sensor

Led as sensor

Controlled by Arduino, we are using a single yellow led as both light and sensor of light.
Five times per second we reverse the polarity of the led, charging it.
If there is light, photons are going to interact with the electrons discharging it faster.

We then measure the time it takes for the digit pin to read a logical 0.
If this zero is reached before some threshold time, we know there is light.
If it takes a lot of time, there are no photons helping our electrons cross the band gap of the diode.

 Arduino Code

// This example shows one way of using an LED as a light sensor.
// You will need to wire up your components as such:
//           + digital11
//           |
//           <
//           > 180 ohm resistor
//           <
//           |
//           |
//         -----
//          / \  LED, maybe a 5mm, clear plastic is good
//         -----
//           |
//           |
//           + digital12
// What we are going to do is apply a positive voltage at LED N Side and
// a low voltage at LED P Side. This is backwards for the LED, current will
// not flow and light will not come out, but we will charge up the 
// capacitance of the LED junction and the Arduino pin.
// Then we are going to disconnect the output drivers from LED P Side and
// count how long it takes the stored charge to bleed off through the 
// the LED. The brighter the light, the faster it will bleed away to 
// LED N Side.

#define LED_N_SIDE 11
#define LED_P_SIDE 12
#define MAX_COUNT 180

void setup()

void lightMode()
  // Turn the light on

void sensorMode()
  // Apply reverse voltage, charge up the pin and led capacitance

  // Isolate the LED N Side of the diode
  // Turn off internal pull-up resistor

boolean isDark = true;

void loop()
  if (isDark)

  isDark = true;
  for( byte j = 0; j < MAX_COUNT; j++ )
    if ( digitalRead(LED_N_SIDE) == 0 ) 
      isDark = false;

I became first aware of this technique browsing through the Arduino Playground I tried implemented it with different leds and resistences but I could not make it work.

Then I found LED as a Light AND a Light Sensor - Arduino controlled which made this possible.
Special thanks to Ido Gendel for his code and patience.

sábado, 12 de abril de 2014

Arduino Web RGB

I created this simple python-Flask app to inteface with my Arduino.

I worked with an Arduino Nano mounted on a breadboard.
You can get an idea on how to wire yours reading this fritzing project.

The barebones of this project goes like this.

First we create route on our flask app to handle requests to the root of our webserver.

from flask import Flask
from flask import send_file
app = Flask(__name__)

def index():
    return send_file('templates/index.html')

if __name__ == '__main__':'')

The file we have as index.html has the following script to get where the user has clicked, get the pixel information, and send it thru ajax back to our python app via the /color route.

    $( "#colorpicker" ).on( "click", function(e) {
        var pixelData = this.canvas
                            .getImageData(e.offsetX, e.offsetY, 1, 1)
        var hex = rgbToHex( pixelData[0], pixelData[1], pixelData[2]);
        $.post('/color', { color: hex });
function componentToHex(c) {
    var hex = c.toString(16);
    return hex.length == 1 ? "0" + hex : hex;

function rgbToHex(r, g, b) {
    return componentToHex(r) + componentToHex(g) + componentToHex(b);

Now, the route listening on /color receives the color, compacts the color information using only the two most significant bits of each color component, and sends it to the Arduino connected via serial.

import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)

def send_value( value ):
    char = str( chr( value ) )
    ser.write( char )

def rgb_to_6bit( rgb ):
    return int('00' + bin(int(rgb[0:1], 16))[2:].zfill(4)[0:2]
                + bin(int(rgb[2:3], 16))[2:].zfill(4)[0:2]
                + bin(int(rgb[4:5], 16))[2:].zfill(4)[0:2], 2)

@app.route('/color', methods=['GET', 'POST'])
def color():
    if request.method == 'POST':
        color = request.form['color']
        send_value( rgb_to_6bit( color ) )

Finally, the Arduino is listening all the time for any incoming information.
When it receives something, it converts the compacted RGB color into analog values, and controls the analog pins of the board with the proper value.

const int GREEN = 9;
const int BLUE = 10;
const int RED = 11;

const int rgb_val[] = { 0x00, 0x40, 0x80, 0xff };
const char mask = 3;
int rgb[3];

void six_bit_to_rgb( char color, int * rgb )
    char tmp;
    int i;
    tmp = color;
    for (i = 2; i >= 0; i--) {
        rgb[ i ] = 0xff - rgb_val[ tmp & mask ];
        tmp = tmp >> 2;

void setup()
  // initialize the serial communication
  // initialize the pins as an output
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);

void loop() {
  byte rgb6bit;

  // check if data has been sent from the computer
  if (Serial.available()) {
    // read the most recent byte (which will be from 0 to 255):
    rgb6bit =;
    six_bit_to_rgb( rgb6bit, rgb );
    // set the brightness of the LED:
    analogWrite(RED, rgb[0]);
    analogWrite(GREEN, rgb[1]);
    analogWrite(BLUE, rgb[2]);

Full python and Arduino code at

domingo, 19 de mayo de 2013

Night wish

Sin abrigo recorre las calles desiertas.
Detrás de el una tormenta.
La ciudad duerme. Las palomas duermen. Los perros duermen, incluso los grillos duermen.
La oscuridad esta despierta.

Camina por el barrio, sin apuro y sin mirar atrás. Muchas casas con persianas bajas y puertas cerradas.
Alegres colores pero ningun rostro amigo. El parpadeo de un tubo de luz lo acompaña por unos metros y su zumbido media cuadra más.

Dobla la esquina, esta cerca, un poco más. El amanecer todavía esta lejos, pero sabe que debe apurarse. El tiempo puede traicionarlo y no puede volver con las manos vacías.
Revisa sus bolsillos. Todo en orden. No falta nada. No falta nada?
No hubiese estado de más una campera en este momento. Y si algo más faltara? No es momento de corregir, ya el pasado esta atrás, y un único destino hacia adelante.

Lleva lo más importante entre sus dedos. Como si se fuese a perder lo atesora y lo guarda celosamente de la mirada de los vecinos, aunque no hay nadie de quien esconderse.
Por fin, el viaje parece llegar a su fin. A la distancia una luz indica que su viaje no fue en vano. Esta travesía que inicio como un capricho, y se convirtió de a poco en una necesidad esta por encontrar su fin justificado.

Última cuadra, es acá? Es acá.
20 metros, abierto? Abierto.
Dinero? En mano.
Cruza la puerta billete en mano. En 5 pasos pasos llega al mostrador.
En que lo puedo ayudar? Pregunta una voz del otro lado.

Phillips común.