Arduino é uma plataforma eletrônica de hardware livre. Baseada em um microcontrolador Atmel AVR com suporte de entrada/saída embutido. O principal objetivo da plataforma é criar ferramentas acessíveis, de baixo custo e fáceis de serem utilizadas.
Neste post, será apresentado um modo de comunicação entre uma aplicação Microsoft .NET e um hardware Arduino.
O hardware utilizado é composto por: uma placa Arduino Leonardo, uma protoboard de 864 furos, um display LCD 16×2, um potenciômetro de 10Ω, dois Leds (verde e vermelho) e dois resistores de 300Ω.
Algumas fotos do modelo construído:
Foto 1 – Arduino Leonardo |
Foto 2 – Protoboard |
Nesse exemplo faremos uso de dois blocos de código: o primeiro bloco consiste de código C para a placa Arduino e o segundo bloco consiste de um código em C# para a console que fará a comunicação com o hardware Arduino.
Nosso desafio será definir uma lógica em linguagem C que espere por entradas vindas por entradas seriais. Ao mesmo tempo, o código C# irá conectar-se ao hardware Arduino e lhe enviar informações por meio de uma porta serial.
A lógica do exemplo será: uma console gerenciada irá requisitar uma cor (verde ou vermelho) que quando informada, será enviada via uma porta serial para o hardware Arduino. Quando recebida a cor, o hardware Arduino irá acender um Led com a cor escolhida e desligar o Led da cor oposta. Caso uma entrada inválida seja feita, então o hardware Arduino continuará alternando as cores entre verde e vermelho.
O código do hardware Arduino é listado abaixo (comentários no código detalham a implementação):
// Library used to load common functions to LCD display #include <LiquidCrystal.h> // Display // Using pins 12, 11, 5, 4, 3 and 2 LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // Red LED connected to pin number 13 const int redLedPin = 13; // Green LED connected to pin number 06 const int greenLedPin = 6; void setup() { // Start serial port at 9600 bps // Pay attention to C# code, you have to connect to the same port. Serial.begin(9600); // Setup RED LED pinMode(redLedPin, OUTPUT); // Setup GREEN LED pinMode(greenLedPin, OUTPUT); } int inByte = 0; int pinToTurnOn = 0; int pinToTurnOff = 0; void loop() { // Read the Serial/USB input inByte = Serial.read(); // If 'Red' was selected if (inByte == 'R') { showMessage("Selected color:", "\tRED"); pinToTurnOn = redLedPin; pinToTurnOff = greenLedPin; } // If 'Green' was selected else if (inByte == 'G') { showMessage("Selected color:", "\tGREEN"); pinToTurnOn = greenLedPin; pinToTurnOff = redLedPin; } else if (inByte > -1){ pinToTurnOn = 0; pinToTurnOff = 0; } if (pinToTurnOn > 0 && pinToTurnOff > 0){ // Turn off the oposite color turnOffPin(pinToTurnOff); // Blink the selected color turnOnPin(pinToTurnOn); delay(1000); turnOffPin(pinToTurnOn); delay(1000); } else { // Warning message showMessage("No input yet", (String)inByte); // Blink colors // Show RED LED turnOnPin(redLedPin); delay(1000); turnOffPin(redLedPin); delay(1000); // Show GREEN LED turnOnPin(greenLedPin); delay(1000); turnOffPin(greenLedPin); delay(1000); } } // Turn on Led on a specific pin void turnOnPin(int pin) { digitalWrite(pin, HIGH); } // Turn off Led on a specific pin void turnOffPin(int pin) { digitalWrite(pin, LOW); } // Show a text message on a LCD Display void showMessage(String line1, String line2){ lcd.begin(16, 2); lcd.setCursor(0,0); lcd.print(line1); lcd.setCursor(0,1); lcd.print(line2); }
O código da console é listado abaixo (comentários no código detalham a implementação):
using System; using System.IO.Ports; class Program { private static SerialPort _port; static void Main(string[] args) { // By default, connections to Arduino have the same port name, 'COM3'. // Pay attention if your hardware has a different name. // We are connecting to port number 9600. _port = new SerialPort("COM3") { BaudRate = 9600 }; // If you have 'Arduino Leonardo' (like me), so you have to // enable 'DtrEnable'. It's a not limitation, or something like this. // It's just a configuration 'by default'. _port.DtrEnable = true; // Open connection to Arduino hardware. _port.Open(); do { Console.WriteLine(":: Choose a color: "); Console.WriteLine("\tG - Green"); Console.WriteLine("\tR - Red"); string input = Console.ReadLine(); if (input == "exit") break; if (!string.IsNullOrWhiteSpace(input)) // Send just one charactere to Arduino hardware. _port.Write(input.ToUpper()[0].ToString()); Console.WriteLine(); } while (true); // Close connection to Arduino hardware. _port.Close(); } }
Meu kit foi comprado na http://robocore.net/. O site contém diferentes kits básicos e componentes que podem ser adicionados a sua solução.
FH
Referências:
http://pt.wikipedia.org/wiki/Arduino