Skip to content

Tag: C

Morse Code Translator with Arduino

You write in your computer, sends a message thought USB and Arduino translates it into a Morse code.

Just a Arduino board with a buzzer connected at the digital output 12 (one wire in the ground and the other in the 12).

Arduino

I tried to make the code as general as possible so you can easily adapt it for anthers ways of transmitting a Morse code. To do that you just need to rewrite a few functions.

                                                  +-------------------+
                                                  | 3) Interpretation |
                                                  +-------------------+
                                                  |   2) Translation  |
+-------------------+                             +-------------------+
|     Computer      |<========USB (Serial)=======>|     1) Reading    |
+-------------------+                             +-------------------+

  1. Reads a character from Serial. Main function loop().
  2. Translate a ascii char into a Morse code using a reference table. A letter ‘K’ becomes a string word “-.-“. Function say_char().
  3. Interpret the Morse word as light and sound. Mostly at function say_morse_word(). The Interpretation needs 5 functions to say all Morse words, dot(), dash(), shortgap(), mediumgap() and intragap().

For a more details on Morse code I strongly recommend the English Wikipedia article on it.

int led = 13;                   // LED connected to digital pin 13
int buzzer = 12;                // buzzer connected to digital pin 12
int unit = 50;                  // duration of a pulse

char * morsecode[] = {
    "-----",  // 0
    ".----",  // 1
    "..---",  // 2
    "...--",  // 3
    "....-",  // 4
    ".....",  // 5
    "-....",  // 6 
    "--...",  // 7
    "---..",  // 8
    "----.",  // 9
    "---...", // :
    "-.-.-.", // ;
    "",       // < (there's no morse for this simbol)
    "-...-",  // =
    "",       // > (there's no morse for this simbol)
    "..--..", // ?
    ".--._.", // @
    ".-",     // A
    "-...",   // B
    "-.-.",   // C
    "-..",    // D
    ".",      // E
    "..-.",   // F
    "--.",    // G
    "....",   // H
    "..",     // I
    ".---",   // J
    "-.-",    // K
    ".-..",   // L
    "--",     // M
    "-.",     // N
    "---",    // O
    ".--.",   // P
    "--.-",   // Q
    ".-.",    // R
    "...",    // S
    "-",      // T
    "..-",    // U
    "...-",   // V
    ".--",    // W
    "-..-",   // X
    "-.--",   // Y
    "--.."    // Z
};

void setup() {
  pinMode(led, OUTPUT);
  pinMode(buzzer, OUTPUT);
  Serial.begin(9600);
}

void say_morse_word(char * msg){
  int index = 0;
  while(msg[index]!='\0'){
    // say a dash
    if(msg[index]=='-'){
      dash();
    }
    // say a dot
    if(msg[index]=='.'){
      dot();
    }
    // gap beetween simbols
    intragap();
    index++;
  }
}

// beep
void beep(int time){
  int i;
  int t = 100; // period of the wav. bigger means lower pitch.
  int beepduration = (int)((float)time/t*1800);
  digitalWrite(led, HIGH);
  for(i=0;i='0')&&(letter<='Z')&&(letter!='<')&&(letter!='>')){
    Serial.print(morsecode[letter-'0']);
    Serial.print(' ');
    say_morse_word(morsecode[letter-'0']);
    shortgap();
  } else {
    if(letter==' '){
      Serial.print(" \\ ");
      mediumgap();
    }else{
      Serial.print("X");
    }
  }
}

void loop(){
  if(Serial.available()){
    say_char((char)Serial.read());
  }
}

Additionally you can put another function to say entire strings, like say_string(“HELLO WORLD”)

void say_string(char * asciimsg){
  int index = 0;
  char charac;  
  charac = asciimsg[index];
  while(charac!='\0'){
    say_char(morsecode[charac-'0']);
    Serial.println(morsecode[charac-'0']);
    charac = asciimsg[++index];
    shortgap();
  }
}

You can use the Arduino IDE itself or any other program that talks with the serial port USB.

arduino interface

C Gaussian Elimination Implementation

A simple gaussian elimination implemented in C.

To simplify, I hard coded the linear system

10 x1 + 2 x2 + 3 x3 + 4 x4 = 5
6 x1 + 17 x2 + 8 x3 + 9 x4 = 10
11 x1 + 12 x2 + 23 x3 + 14 x4 = 15
16 x1 + 17 x2 + 18 x3 + 29 x4 = 20

into the AB float matrix.

/* 
 * Description: Solve a hard coded linear system by gaussian elimination
 * Author: Silveira Neto
 * License: Public Domain
 */

#include 
#include 

#define ROWS 4
#define COLS 5

/**
 * Linear System, Ax = B
 *
 * 10*x1 +  2*x2 +  3*x3 +  4*x4 = 5
 *  6*x1 + 17*x2 +  8*x3 +  9*x4 = 10
 * 11*x1 + 12*x2 + 23*x3 + 14*x4 = 15
 * 16*x1 + 17*x2 + 18*x3 + 29*x4 = 20
 */
float AB[ROWS][COLS] = {
    {10,  2,  3,  4,  5},
    { 6, 17,  8,  9, 10},
    {11, 12, 23, 14, 15},
    {16, 17, 18, 29, 20}
};

/* Answer x from Ax=B */
float X[ROWS] = {0,0,0,0};

int main(int argc, char** argv) {
    int row, col, i;

    /* gaussian elimination */
    for (col=0; col

Before the gaugassian elimination, AB is

10  2  3  4  5
 6 17  8  9 10
11 12 23 14 15
16 17 18 29 20

and after it is

10.00000 0.00000 0.00000 0.00000 2.82486 
0.00000 15.80000 0.00000 0.00000 3.92768 
0.00000 0.00000 15.85443 0.00000 3.85164 
0.00000 0.00000 0.00000 14.13174 3.35329 

that corresponds to

10 x1 = 2.82486
15.80000 x2 = 3.92768
15.85443 x3 = 3.85164
14.13174 x4 = 3.35329

The solution vector is X = (x1, x2, x3, x4). We get it by X=B/A.

The program output, X, is

0.28249 0.24859 0.24294 0.23729

Benchmarking:
I'm this serial implementation over one node of our cluster, a machine with 4 processors (Intel Xeon 1.8 Ghz) and 1Gb RAM memory. I tried random systems from 1000 to 5000 variables and got the average time.

gaugassian elimination serial

JavaFX, rectangular collision detection

[youtube]NRwRTHPGg6M[/youtube]

In a game I wrote some years ago we handled simple rectangular collisions. Given the points:

We did:

// returning 0 means collision
int collision(int ax, int ay, int bx, int by, int cx, int cy, int dx, int dy){
	return ((ax > dx)||(bx < cx)||(ay > dy)||(by < cy));
}

I'll show here a little demo about how implement simple rectangular collisions on JavaFX.
First I created a movable rectangle using the same idea of draggable nodes I already had posted before.

import javafx.input.MouseEvent;
import javafx.scene.geometry.Rectangle;

public class MovableRectangle extends Rectangle {
    private attribute startX = 0.0;
    private attribute startY = 0.0;

    public attribute onMove = function(e:MouseEvent):Void {}

    override attribute onMousePressed = function(e:MouseEvent):Void {
        startX = e.getDragX()-translateX;
        startY = e.getDragY()-translateY;
        onMove(e);
    }

    override attribute onMouseDragged = function(e:MouseEvent):Void {
        translateX = e.getDragX()-startX;
        translateY = e.getDragY()-startY;
        onMove(e);
    }
}

In the main code I some important things:

  • colide, a color that represents the collision effect. White means no collision and gray means collision.
  • rec1 and rec2, the two rectangles that can collide.
  • checkcollision() the function that checks and handles a possible collision.

Here is the main code:

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.geometry.Rectangle;
import javafx.scene.paint.Color;
import javafx.input.MouseEvent;

var colide = Color.WHITE;

function checkcollision():Void {
    if (
        (rec1.getBoundsX() > rec2.getBoundsX() + rec2.getWidth()) or
        (rec1.getBoundsX() + rec1.getWidth() < rec2.getBoundsX()) or 
        (rec1.getBoundsY() > rec2.getBoundsY() + rec2.getHeight()) or 
        (rec1.getBoundsY() + rec1.getHeight() < rec2.getBoundsY())
    ) {
        colide = Color.WHITE
    } else {
        colide = Color.LIGHTGRAY
    }
}

var rec1: MovableRectangle = MovableRectangle {
    x: 10, y: 10, width: 50, height: 60, fill: Color.RED
    onMove: function(e:MouseEvent):Void {
        checkcollision()
    }
}

var rec2: MovableRectangle = MovableRectangle {
    x: 100, y: 100, width: 70, height: 30, fill: Color.BLUE
    onMove: function(MouseEvent):Void {
        checkcollision()
    }
}
Frame {
    title: "Rectangular Collisions", width: 300, height: 300
    closeAction: function() { 
        java.lang.System.exit( 0 ); 
    }
    visible: true

    stage: Stage {
        fill: bind colide
        content: [rec1, rec2]
    }
}

Try it via Java Web Start:

Java Web Start

Some considerations:

  • You can use rectangular collisions to create bounding boxes to handle collisions in more complex shapes or sprites. Is a common approach in 2d games to avoid more expensive calculations.
  • There are space for optimizations.
  • In this case I'm using only two objects. Some problems raises when I have N objects to handle.

More generally, we can code:

function collission(ax, ay, bx, by, cx, cy, dx, dy): Boolean {
    return not ((ax > dx)or(bx < cx)or(ay > dy)or(by < cy));
}

function hitnode(a: Node, b:Node): Boolean{
    return (collission(
        a.getBoundsX(), a.getBoundsY(),
        a.getBoundsX() + a.getWidth(), a.getBoundsY() + a.getHeight(),
        b.getX(), b.getY(),
        b.getX() + b.getWidth(), b.getY() + b.getHeight()
    ));
}

This way we can pass just two bounding boxes to hitnode and easily check collision of a node against a list of bounding boxes nodes.
Using the same approach I also wrote this function to test if a Node is inside another Node:

function inside (ax, ay, bx, by, cx, cy, dx, dy):Boolean{
    return ((ax > cx) and (bx < dx) and (ay > cy) and (by < dy));
}

function insidenode(a:Node,b:Node):Boolean{
    return (inside(
        a.getBoundsX(), a.getBoundsY(),
        a.getBoundsX() + a.getWidth(), a.getBoundsY() + a.getHeight(),
        b.getBoundsX(), b.getBoundsY(),
        b.getBoundsX() + b.getWidth(), b.getBoundsY() + b.getHeight()
    ));
}

Soon I'll post game examples showing how to use this method and others collission detection methods.

Downloads:

Anúncio do NetBeans 6.5 Beta

O Netbeans.org anunciou a disponibilidade do NetBeans IDE 6.5 Beta. Abaixo a tradução do anúncio:

O NetBeans IDE 6.5 introduz várias novas funcionalidades, incluindo uma IDE robusta para PHP, deputação de JavaScript para o Firefox e IE, e suporte a Groovy e Grails. Esse lançamento também inclui várias melhorias para o desenvolvimento em Java, Ruby e Rails, e C/C++. Dentre as melhorias no Java destacam-se: suporte nativo ao Hibernate, importação de projetos do Eclipse, e compilação no salvamento.

Links:

Outros destaques:

  • PHP
    • Completação de código
    • Consertos rápidos e checagem semântica
    • Suporte a FTP
    • Depuração com Xdebug
    • Suporte a Web Services populares
  • Ajax/JavaScript
    • Suporte a depuração no Firefox e IE
    • Monitoramento cliente de HTTP
    • Vêm com as bibliotecas mais populares de JavaScript
  • Java
    • Suporte a Groovy/Grails
    • Compilação/Deploy no momento do salvamento
    • Importação e sincronização de projetos do Eclipse
    • Suporte nativo a Hibernate
    • Gerador de CRUD JSF agora com Ajax
  • Banco de Dados
    • Melhorias no editor
  • C/C++
    • Melhorias na completação de código e destaque de erros
    • Desenvolvimento remoto
  • Ruby
    • Suporte aos Testes Ruby
    • Melhoria no suporte a Rake
  • GlassFish V3 “Prelude”
    • Menor tamanho, inicialização e deployment mais rápido
    • Suporte a scripting, inclusive jRuby

O NetBeans IDE 6.5 final está planejado para ser lançado em Outubro de 2008. Como sempre, é bem vindo e nós encorajamos seu feedback sobre sua experiência usando a IDE NetBeans. Visite nossas listas de email ou faça uma postagem no seu blog.

Pointers to functions in C++

I need to implements some codes in C++. Just remembering some concepts like pointers to functions.

A simple example:

#include <stdlib.h>
#include <iostream>

using namespace std;

double evalFunction(double (*f)(double), double param){
    return f(param);
}

double function(double x){
    return x/2;
}

int main(int argc, char** argv) {
    cout << function(5.0) << endl;
    cout << evalFunction(function, 5.0) << endl;
    return (EXIT_SUCCESS);
}

Gerando permutações

Muitas vezes para resolver uma única instância de um problema é mais rápido ataca-lo com força bruta do que encontrar um algoritmo geral com uma boa ordem de complexidade. Permutações são de grande utilidade nesse tipo de abordagem.

Permutações em Prolog:

Esse é um código em Prolog que o Wladimir Araujo passou na cadeira de IA.

select(X, [X|Xs], Xs).
select(X, [Y|Ys], [Y|Zs]) :- select(X, Ys, Zs).

permutar([], []).
permutar(Xs, [Z|Zs]) :-
    select(Z, Xs, Ys),
    permutar(Ys, Zs).

Permutações em Python:
Esse é um código de um certo Michael Davies que eu tirei daqui. Ele gera uma lista com todas as permutações de uma lista. Muito bonitinho. :)

def all_perms(str):
    if len(str) <=1:
        yield str
    else:
        for perm in all_perms(str[1:]):
            for i in range(len(perm)+1):
                yield perm[:i] + str[0:1] + perm[i:]

Um exemplo de uso:

>>> for p in all_perms(['a','b','c']):
	print p
['a', 'b', 'c']
['b', 'a', 'c']
['b', 'c', 'a']
['a', 'c', 'b']
['c', 'a', 'b']
['c', 'b', 'a']

Outras implementações:
Em outras linguagens o código para gerar permutações geralmente é muito grande, então eu preferi deixar alguns links.