LV-MaxSonar-EZ1 Ultrasonic Range Finder with Arduino
[PT]
Nos últimos dois dias estive numa guerra declarada com um sensor ultrasónico da MaxBotix, o modelo LV-MaxSonar-EZ1:

Click na imagem para ver o Datasheet
Este sensor detecta pequenos objectos num intervalo de espaço entre 15cm e 6.5m com algum grau de precisão, e para leitura dos dados podemos utilizar leitura da voltagem (0-5V), leitura do "pulse-width" ou leitura via SerialCom.
Após muito testar e procurar, cheguei a conclusão que o facto de existir pouca informação sobre a leitura via SerialCom em Arduino tem a ver com o facto de que o sensor usa uma medição tipo TTL (os níveis de voltagem variam entre 0 e 5V) mas para o SerialCom tem uma leitura RS232 (em que a voltagem mais baixa dá 1 e a voltagem mais alta dá um 0) e assim não é possível de se usar a ligação por Serial do próprio Arduino. A solução parece passar por se criar um conversor, mas a maioria dos utilizadores mencionam que o trabalho é demasiado para o proveito e como tal, aconselham a ficar pela leitura da voltagem ou do "pulse-width".
Este sensor tem 7 ligações:

- GND: Terra
- +5: VCC
- TX: Serial
- RX: Ligar e desligar o sensor
- AN: Voltagem
- PW: "Pulse-Width"
- BW: Ligar e desligar a comunicação Serial
Como usar a leitura analógica da voltagem
Ligar o GND e o +5 aos pins respectivos no Arduino (ou na breadboard).
Para efeitos de leitura do código escrito, os pins utilizados serão: RX ligado ao pin digital 2 e o AN ligado ao pin analógico 0.
const int AN = 0; const int RX = 2;
A leitura analógica da voltagem é susceptível de obter ruídos e como tal os valores náo são constantes e algumas vezes acontecem leituras completamente descabidas. Após procurar a opinião de vários utilizadores, uma das melhores opções é se obter um valor médio de uma determinada amostra da dados (calcular uma média portanto).
long anVolt, inches, cm; int sum = 0; int avgRange = 60;
No método SETUP só inicializamos a comunicação Serial do Arduino para termos leitura dos dados no monitor e definir o modo de funcionamento dos pins:
void setup()
{
Serial.begin(9600);
pinMode(RX, OUTPUT);
}
No método LOOP vamos recolher as amostras de dados:
for(int = 0; i < avgRange; i++)
{
anVolt = analogRead(AN);
sum += anVolt;
}
Para se calcular a distância (recorde que 1 polegada equivale a 2,54 centimetros:
inches = sum / avgRange; cm = inches * 2.54;
No final do método loop é necessário se fazer um "reset" ao sumatório das amostras e é aconselhável se fazer uma pausa no circuito.
O método loop completo:
void loop()
{
for (int i = 0; i < avgRange; i++)
{
anVolt = analogRead(AN);
sum += anVolt;
}
inches = sum / avgRange;
cm = inches * 2.54;
Serial.print(inches, DEC);
Serial.print("in ,");
Serial.print(cm, DEC);
Serial.print("cm");
Serial.println();
sum = 0;
delay(500);
}
Caso pretenda desligar ou ligar o sensor (por exemplo para poupar bateria), basta enviar um sinal HIGH (ligar) ou LOW (desligar) para o pin RX.
Como utilizar a leitura do "pulse-width"
Ligar o GND e o +5 aos pins respectivos no Arduino (ou na breadboard).
Para efeitos de leitura do código escrito, os pins utilizados serão: RX ligado ao pin digital 2 e o PW ligado ao pin digital 7.
const int PW = 7; const int RX = 2; long pulse, inches, cm;
No método SETUP só inicializamos a comunicação Serial do Arduino para termos leitura dos dados no monitor e definir o modo de funcionamento dos pins:
void setup()
{
Serial.begin(9600);
pinMode(RX, OUTPUT);
pinMode(PW, INPUT);
}
No método LOOP vamos colocar o pin PW a escuta de quando é que passa de HIGH (onda emitida) para LOW (onda recebida). O Arduino tem um método que devolve o tempo em microsegundos que é o pulseIn.
pulse = pulseIn(PW, HIGH);
O "pulse-width" tem uma escala de 147uS por cada polegada, logo é necessário efectuar a conversão:
inches = pulse / 147;
O método LOOP completo será algo deste género:
void loop()
{
pulse = pulseIn(PW, HIGH);
inches = pulse / 147;
cm = inches * 2.54;
Serial.print(inches, DEC);
Serial.print("in ,");
Serial.print(cm, DEC);
Serial.print("cm");
Serial.println();
delay(500);
}
Caso pretenda desligar ou ligar o sensor (por exemplo para poupar bateria), basta enviar um sinal HIGH (ligar) ou LOW (desligar) para o pin RX.
Recorde que é necessário sempre ler o DataSheet do componente.
[EN]
In the last couple days I had a terrific battle with a MaxBotix's LV-MaxSonar-EZ1 Ultrasonic Range Finder:

Click to see the Datasheet
This sensor detects small objects within an interval of space between 15cm and 6.5m with some degree of accuracy, and for reading the data we can use voltage reading (0-5V), reading the "pulse-width" or read via SerialCom.
Following much testing and researching, I came to the conclusion that the fact that there is little information about the reading via SerialCom in Arduino has to do with the fact that the sensor uses a measurement TTL-type (voltage levels between 0 and 5V) but for SerialCom uses the RS232 (in which gives 1 to a lower voltage and higher voltage gives a 0) and so it is not possible to use the bulti-in Arduino's SerialCom. The solution seems to create a converter, but most users mention that it is too much work for the benefit so all of them advise to get the distances by voltage reading or "pulse-width" reading.
This sensor has 7 connectors:

- GND: Ground
- +5: VCC
- TX: Serial
- RX: Sensor On and Off
- AN: Voltage
- PW: "Pulse-Width"
- BW: SerialCom On and Off
How to use the Analog Voltage Reading
Connect GND and +5 to the correct Arduino pins (or breadboard).
For the purpose of clarity, we will use the following pins: RX connected to digital pin 2 and AN connected to analog pin 0.
const int AN = 0; const int RX = 2;
The analog voltage reading is likely to catch noise and as such values are not constant and sometimes misplaced readings are commum. After seeking the opinion of many users, one of the best options is to obtain an average value of a given sample of data (thus calculate an average.)
long anVolt, inches, cm; int sum = 0; int avgRange = 60;
In the SETUP method we will start the Serial communication in order to read some values in the SerialMonitor and we will also declare the pins type:
void setup()
{
Serial.begin(9600);
pinMode(RX, OUTPUT);
}
In the LOOP method we will collect the data samples:
for(int = 0; i < avgRange; i++)
{
anVolt = analogRead(AN);
sum += anVolt;
}
Remember that 1 inch is 2.54 centimeters:
inches = sum / avgRange; cm = inches * 2.54;
In the end we have to reset the samples sum and give the circuit a little break.
The loop method:
void loop()
{
for (int i = 0; i < avgRange; i++)
{
anVolt = analogRead(AN);
sum += anVolt;
}
inches = sum / avgRange;
cm = inches * 2.54;
Serial.print(inches, DEC);
Serial.print("in ,");
Serial.print(cm, DEC);
Serial.print("cm");
Serial.println();
sum = 0;
delay(500);
}
If you want to start or stop the sensor capture (for battery-life purposes for instance), just send an HIGH (on) or LOW (off) to the RX pin.
How to Use the "Pulse-Width" Reading
Connect GND and +5 to the correct Arduino pins (or breadboard).
For the purpose of clarity, we will use the following pins: RX connected to digital pin 2 and PW connected to digital pin 7.
const int PW = 7; const int RX = 2; long pulse, inches, cm;
In the SETUP method we will start the Serial communication in order to read some values in the SerialMonitor and we will also declare the pins type:
void setup()
{
Serial.begin(9600);
pinMode(RX, OUTPUT);
pinMode(PW, INPUT);
}
In the LOOP method we will use an Arduino's method called pulseIn that will returns the time in microseconds between the HIGH-to-LOW or LOW-to-HIGH in a given pin.
pulse = pulseIn(PW, HIGH);
"Pulse-width" has a scale factor of 147uS per inch:
inches = pulse / 147;
The complete LOOP method:
void loop()
{
pulse = pulseIn(PW, HIGH);
inches = pulse / 147;
cm = inches * 2.54;
Serial.print(inches, DEC);
Serial.print("in ,");
Serial.print(cm, DEC);
Serial.print("cm");
Serial.println();
delay(500);
}
If you want to start or stop the sensor capture (for battery-life purposes for instance), just send an HIGH (on) or LOW (off) to the RX pin.
Remember that you should ALWAYS read the component datasheet.
Arduino “Hello World”
[PT]
Todos os programadores e designers que batem umas linhas de código sabem que no inicio de uma qualquer linguagem temos de nos deparar com a mítica impressão da frase "Hello World". No caso da electrónica, trata-se de colocar um LED a piscar.
O micro-controlador Arduino vem equipado com um pequeno LED ligado ao pin 13 (DIGITAL) que iremos colocar a piscar. (Repare na letra L abaixo do 13)

(para conhecer um pouco mais do Arduino, veja os meus slides e os videos da apresentação realizada ao AdobeUserGroup-Portugal sobre Arduino e Flash via GLUE)
A estrutura do código do Arduino é composto por dois métodos obrigatórios:
- setup()
- Que será executado somente uma vez
- loop()
- Que será executado continuamente e enquanto o Arduino tiver corrente
Com o Arduino IDE aberto, os passos serão:
- Ligar o Arduino via USB ao PC
- Verificar no PC/MAC qual o Serial Port em utilização e depois escolher o mesmo no IDE do Arduino
- Tools > Serial Port
- Definir o PIN que iremos usar
-
int ledPin=13;
-
- Definir o método setup()
-
void setup() { //definir um pin digital como Output pinMode(ledPin, OUTPUT); }
-
- Definir o método loop()
-
void loop() { //Atribuir corrente ao led - "Acende" digitalWrite(ledPin, HIGH); //pausa de 100 milisegundos delay(100); //Retirar a corrente ao led - "Apaga" digitalWrite(ledPin, LOW); //pausa de 100 milisegundos delay(100); }
-
E o resultado final deverá de ser o LED13 a piscar a cada 100 milisegundos.
Divirtam-se!
[EN]
All developers and designers who type a few lines of code know that at the beginning of any language we have to encounter the mythical "Hello World" print. In the case of electronics, it is blinking a LED.
Arduino micro-controller has a bult-in LED connected to pin 13 (DIGITAL) and we will make this one blink. (take notice to character L below pin 13)

Arduino programming language have a simple struture, composed by two mandatory methods:
- setup()
- Run only once
- loop()
- Run ad-eternum while Arduino has power
With Arduino IDE ready, lets start:
- Conncet Arduino to PC via USB
- Check in PC/MAC which is the Serial Port used for Arduino and in Arduino IDE choose the same one
- Tools > Serial Port
- Declare which PIN we will use
-
int ledPin=13;
-
- Declare setup() method
-
void setup() { //declare a digital pin as an OUTPUT pin pinMode(ledPin, OUTPUT); }
-
- Declare loop() method
-
void loop() { //voltage HIGH - "Lights On" digitalWrite(ledPin, HIGH); //100 miliseconds break delay(100); //voltage LOW- "Lights Out" digitalWrite(ledPin, LOW); //100 miliseconds break delay(100); }
-
And the final result will be LED13 blinking every 100 miliseconds.
Have fun!
Blog Carnival Announcement
[PT]
Arranquei um Blog Carnival com o tema "WebDevelopment with Plugins", e a 1º edição sairá no final deste mês.
Mas afinal o que é um Blog Carnival?
Um Blog Carnival não é nada mais do que uma "magazine" feita com posts de blogs, em que qualquer pessoa pode submeter os seus artigos.
Por isso, se alguém quiser participar, basta acederem ao site blogcarnival, pesquisarem pela categoria "Technology" com a Keyword "WebDevelopment"...

Depois só têm de clicar em "Submit an article"

E preencher o formulário com:
- Permalink URL do post que escreveram
- o nome do autor
- o email do autor
E no final, se o artigo estiver dentro dos temas e não tiver erros técnicos, será incluido na "magazine".
Este é um óptimo modo de aumentarem as visitas aos vossos blogs, por isso PARTICIPEM !
[EN]
I started a Blog Carnival with the subject of "WebDevelopment with Plugins", and the first edition will be released later this month.
But, what is this Blog Carnival stuff?
A Blog Carnival is just a "magazine" with a bunch of webposts, and anyone may submit an article.
Therefore, if anyone would like to join the Carnival, do a visit to blogcarnival website, do a category search by "Technology" and "WebDevelopment" keyword...

After it, click the "Submit an article" button:

Fill in the small form with:
- Your post Permalink URL
- Author name
- Author email
If your article is inside scope and doesn't present any technical errors, it will be included at the "magazine".
This is a great way to produce blog awareness, what are you waiting for?
Silverlight 101 – The Tools
[PT] [PDF]
Após uma apresentação para o RIAPT - Comunidade Portuguesa de Desenvolvimento de Rich Internet Applications, decidi que o conteúdo da mesma era ajustável a uma pequena série de tutoriais do género "101" (nivel iniciado). Dessa forma, começo aqui a série com a introdução às ferramentas necessárias para o desenvolvimento em Silverlight.
Presentemente estamos na versão 3 da tecnologia Silverlight, com a versão 4 ainda em Beta mas já ao virar da esquina.
O processo de instalação das ferramentas segue uma ordem, que deverá de ser respeitada de forma a garantir que tudo ficará pronto a ser utilizado.
O editor de eleiçãoe para desenvolvimento de aplicações Windows Client, Web, Microsoft Office System, .NET Framework, SQL Server e Windows Mobile (agora com o Windows Phone7, teremos Silverlight também no Mobile). E agora com os programas “WebSite Spark” e “BizSpark” é gratuito durante 3 anos.
Após a instalação do Visual Studio, dever-se-á instalar o Service Pack1 (SP1).
- Visual Web Developer 2008 (gratuito)
Existe a possibilidade de se desenvolver para Silverlight com ferramentas gratuitas, como o Visual Web Developer 2008, graças a pacotes como o “Web Platform Instaler” que incluem:
-
- Internet Information Services (IIS)
- SQL Server Express
- .NET Framework
- Visual Web Developer
- Bem como uma série de soluções “chave na mão”:
- DotNetNuke Community Edition
- Umbraco CMS
- Joomla!
- mojoPortal
- nopCommerce
- Moodle
- ...
Este software é o editor gráfico de eleição para o código XAML. Uma ferramente poderosa tanto para developers como para designers. Dentro do pacote vem incluída a ferramenta “SketchFlow” para rápida prototipagem, mapas de navegação e fluidez da aplicação, layouts dos “screens” e exploração do User eXperience sempre em modo colaborativo com a equipa e o cliente.
Blend permite gerar um workflow quase perfeito entre Designers e Developers, sendo que a solução é partilhada por ambas partes sem que ocorram sobreposições.
Pacote de controlos e componentes para Silverlight desenvolvido pela própria equipa de produto do Silverlight. Este pacote vem adicionar novas funcionalidades tanto para designers como para developers. É interessante referir que o pacote inclui todo o código fonte em regime OpenSource, testes unitários bem como exemplos e documentação. Encontra-se no Codeplex. Alguns controlos:
| AutoCompleteBox | Calendar | ChildWindow |
| DataGrid | DataPager | DatePicker |
| GridSplitter | TabControl | TreeView |
| DockPanel | Expander | WrapPanel |
| NumericUpDown | Accordion | Charting |
| DataForm | TimePicker | TimeUpDown |
| TreeMap | Rating | 11 Themes |
Os célebres projectos “HardRock Cafe Memorabilia”, “Playboy Cover to Cover”, “Zermatt Switzerland Turism” foram elaborados com esta tecnologia que permite ter imagens de alta resolução ou grandes dimensões com uma fluidez incrivel na net. Como o nome refere, é possível se fazer multiplos zooms nas imagens, literalmente “entrando” dentro delas ... Sem dúvida, uma das ferramentas obrigatórias.
O “middle-tier” de eleição para as comunicações entre Silverlight e qualquer modelo de persistência de dados, serviços e “Cloud”.
Uff...todo este processo de instalação das ferramentas mencionadas deverá levar algum tempo a ser concluida.
Como referi, o Silverlight4 está quase ao virar da esquina mas para já podemos “brincar” com a versão Beta e as ferramentas necessárias são:
-
- Visual Studio 2010 Beta2 (atenção: a versão RC não suporta Silverlight)
- Visual Web Developer Express 2010 Beta2
- Expression Blend .NET4 Preview
- Silverlight Toolkit
- WCF RIA Services
O Visual Studio 2010 Beta2 pode correr lado a lado com o Visual Studio 2008, tornando possível o desenvolvimento de soluções Silverlight3 com as ferramentas estáveis. É de notar que .NET RIA Services e WCF RIA Services não correm lado a lado logo, ou estuda .NET RIA Services em Silverlight3 ou WCF RIA Services em Silverlight4.
PRÓXIMO ARTIGO
No momento de se começar um projecto Silverlight surge-nos a primeira grande questão: “Que template do Visual Studio devo de escolher? E se quiser só usar Blend?”
No próximo artigo irei responder a estas questões.
Alguma questão que queiram colocar, poderão fazê-lo no blog.
[EN] [PDF]
After a RIAPT – Portugues Community for Rich Internet Applications Development event, I decided that its content was adjustable to a small series of tutorials "101" (Level Iniciate). Thus, the series beginning here with the introduction to the tools needed to develop in Silverlight.
Currently we are in version 3 of the Silverlight technology, version 4 still in Beta but just around the corner.
The installation process of the tools follows a specific order, which must be respected to ensure that everything will be ready for use.
The editor of choice for developing Windows Client, Web, Microsoft Office System, .NET Framework, SQL Server and Windows Mobile (now with Windows Phone7, Silverlight will also get some legs). And with the”WebsiteSpark” and “BizSpark” programs all this software is free for a 3 years period.
After installing Visual Studio, it should be installed the Service Pack1 (SP1).
- Visual Web Developer 2008 (free)
It is possible to develop for Silverlight with free tools such as Visual Web Developer 2008, thanks to packages like “Web Platform Instaler” which include:
-
- Internet Information Services (IIS)
- SQL Server Express
- .NET Framework
- Visual Web Developer
- As well as a number of “out of the box” solutions:
- DotNetNuke Community Edition
- Umbraco CMS
- Joomla!
- mojoPortal
- nopCommerce
- Moodle
- ...
This software is the visual editor of choice for the XAML code. A powerfull tool for both designers and developers. Within the package comes included with the “SketchFlow” tool for quick prototyping, flow charts, screen layouts and User eXperience prototyping, always collaboratively with the team and the client.
Blend allows for a almost perfect workflow between designers and developers, and the solution is shared by both teams without the occurence of overlapping.
Controls and components package for Silverlight. This package adds new features for both designers and developers. Interestingly, the package includes full open source code, unit tests, samples and documentation. You can find it at Codeplex. A small controls list:
| AutoCompleteBox | Calendar | ChildWindow |
| DataGrid | DataPager | DatePicker |
| GridSplitter | TabControl | TreeView |
| DockPanel | Expander | WrapPanel |
| NumericUpDown | Accordion | Charting |
| DataForm | TimePicker | TimeUpDown |
| TreeMap | Rating | 11 Themes |
Famous projects like “HardRock Cafe Memorabilia”, “Playboy Cover to Cover”, “Zermatt Switzerland Turism” were developed with this technology providing high-resolution images with an incredible smooth experience over the web. As the name states, it is possible to have deeper zooms into the images, literally “entering” in them…without doubt, one of the tools required.
The “middle-tier”of choice for communications between Silverlight and any type of persistent data, services “or Cloud”.
Uff...this whole installation process will take some time to be completed.
As I mentioned, Silverlight4 is just around the corner but for now we may tinker with the Beta version, and the tools required are:
-
- Visual Studio 2010 Beta2 (caution: RC version does not supports Silverlight)
- Visual Web Developer Express 2010 Beta2
- Expression Blend .NET4 Preview
- Silverlight Toolkit
- WCF RIA Services
Visual Studio 2010 Beta2 runs side by side with Visual Studio 2008, making possible the development of Silverlight3 solutions with the “stable” tools. However, .NET RIA Services and WCF RIA Services can not work side by side, so you either study .NET RIA Services with Silverlight3 or WCF RIA Services with Silverlight4.
UPCOMING
When the time comes to start a new Silverlight project, the first big question arises: “Which Visual Studio’s template should I choose? And what if I want to work only with Blend?”
In the next article I will provide some answers for these questions.
Any question or comment, please use the blog.