Documente Academic
Documente Profesional
Documente Cultură
C# e Arduino - Parte 1
Uma interface entre o arduino e um computador muitas vezes
importante durante o desenvolvimento de projeto ou para
controle de dispositivos atravs de uma interface grfica.
Pode-se usar uma aplicao no computador para Aquisio e
exibio de dados em forma de grfico durante algum
experimento em laboratrio ou estudo. Como j foi visto aqui
no artigo sobre o Arduino Uno e sobre comunicao Serial
com Arduino, a comunicao entre a placa e o computador
feira atravs de uma porta serial emulada atravs do driver
da USB. J foi exibido aqui uma aplicao de comunicao
serial desenvolvida com a plataforma JAVA. Neste artigo
vamos ensinar como desenvolver uma aplicao para
Windows usando a plataforma .Net usando o ambiente Visual
Studio da Microsoft, com a linguagem C#. Ser desenvolvido
um terminal simples, onde se poder enviar e receber
caracteres atravs de uma interface grfica. Esse artigo
tambm servir de base para desenvolvermos uma aplicao
envolvendo botes e outros elementos visuais.
Voc pode baixar a verso express dessa ferramenta
diretamente no site da plataforma. Selecione a opo Express
2013 for Windows Desktop. Aps o download faa a
instalao, que um processo bem simples porm um pouco
demorado, basta seguir os passos de instalao.
Ao Iniciar o Visual Studio ser exibida sua tela inicial e para
iniciar um novo projeto deve-se acessar o menu FILE > New
Project. Como vamos trabalhar com a linguagem C#, deve-se
selecionar a opo Visual C# no menu lateral. Agora vamos
iniciar o passo a passo pra criar nossa aplicao:
1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3
3
using
using
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Threading.Tasks;
System.Windows.Forms;
System.IO.Ports; // necessrio para ter acesso as portas
namespace interfaceArduinoVS2013
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void atualizaListaCOMs()
{
int i;
bool quantDiferente; //flag para sinalizar que a quantidade de portas mudou
i = 0;
quantDiferente = false;
//se a quantidade de portas mudou
if (comboBox1.Items.Count == SerialPort.GetPortNames().Length)
{
foreach (string s in SerialPort.GetPortNames())
{
if (comboBox1.Items[i++].Equals(s) == false)
{
quantDiferente = true;
}
}
}
else
{
quantDiferente = true;
}
//Se no foi detectado diferena
if (quantDiferente == false)
{
return;
//retorna
}
//limpa comboBox
comboBox1.Items.Clear();
//adiciona todas as COM diponveis na lista
foreach (string s in SerialPort.GetPortNames())
{
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4
5
4
6
4
7
4
comboBox1.Items.Add(s);
8
}
4
//seleciona a primeira posio da lista
9
comboBox1.SelectedIndex = 0;
5
}
0 }
5 }
1
5
2
5
3
5
4
5
5
5
6
5
7
5
8
5
9
6
0
6
1
6
2
6
3
6
4
1
2
3
4
5
6
7
8
9
1
0
1
1
using
using
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Threading.Tasks;
System.Windows.Forms;
System.IO.Ports; // necessrio para ter acesso as portas
namespace interfaceArduinoVS2013
{
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
}
4
}
0
4
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5
0
5
1
5
2
5
3
5
4
5
5
5
6
5
7
5
8
5
9
6
0
6
1
6
2
6
3
6
4
6
5
6
6
6
7
6
8
6
9
1
2
3
4
5
6
7
8
9
10
11
using
using
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Threading.Tasks;
System.Windows.Forms;
System.IO.Ports; // necessrio para ter acesso as portas
12 namespace interfaceArduinoVS2013
13 {
14
public partial class Form1 : Form
15
{
16
public Form1()
17
{
18
InitializeComponent();
19
timerCOM.Enabled = true;
20
}
21
22
private void atualizaListaCOMs()
23
{
24
int i;
25
bool quantDiferente; //flag para sinalizar que a quantidade de portas mudou
26
27
i = 0;
28
quantDiferente = false;
29
30
//se a quantidade de portas mudou
31
if (comboBox1.Items.Count == SerialPort.GetPortNames().Length)
32
{
33
foreach (string s in SerialPort.GetPortNames())
34
{
35
if (comboBox1.Items[i++].Equals(s) == false)
36
{
37
quantDiferente = true;
38
}
39
}
40
}
41
else
42
{
43
quantDiferente = true;
44
}
45
46
//Se no foi detectado diferena
47
if (quantDiferente == false)
48
{
49
return;
//retorna
50
}
51
52
53
//limpa comboBox
54
comboBox1.Items.Clear();
55
56
//adiciona todas as COM diponveis na lista
57
foreach (string s in SerialPort.GetPortNames())
58
{
59
comboBox1.Items.Add(s);
60
}
61
//seleciona a primeira posio da lista
62
comboBox1.SelectedIndex = 0;
63
}
64
65
private void timerCOM_Tick(object sender, EventArgs e)
66
{
67
atualizaListaCOMs();
68
}
69
70
private void btConectar_Click(object sender, EventArgs e)
71
{
72
if (serialPort1.IsOpen == false)
73
{
74
try
75
{
76
serialPort1.PortName =
77
78
79
80
comboBox1.Items[comboBox1.SelectedIndex].ToString();
81
serialPort1.Open();
82
83
}
84
catch
85
{
86
return;
87
88
}
89
if (serialPort1.IsOpen)
90
{
91
btConectar.Text = "Desconectar";
92
comboBox1.Enabled = false;
93
94
95
}
96
}
97
else
98
{
99
10
try
0
{
10
serialPort1.Close();
1
comboBox1.Enabled = true;
10
btConectar.Text = "Conectar";
2
}
10
catch
3
{
10
return;
4
}
10
5
}
10
}
6
}
10
}
7
10
8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using
using
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Threading.Tasks;
System.Windows.Forms;
System.IO.Ports; // necessrio para ter acesso as portas
namespace interfaceArduinoVS2013
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timerCOM.Enabled = true;
}
private void atualizaListaCOMs()
{
int i;
bool quantDiferente; //flag para sinalizar que a quantidade de portas mudou
i = 0;
quantDiferente = false;
//se a quantidade de portas mudou
if (comboBox1.Items.Count == SerialPort.GetPortNames().Length)
{
foreach (string s in SerialPort.GetPortNames())
{
if (comboBox1.Items[i++].Equals(s) == false)
{
quantDiferente = true;
}
}
}
else
{
quantDiferente = true;
}
//Se no foi detectado diferena
if (quantDiferente == false)
{
return;
//retorna
51
}
52
53
//limpa comboBox
54
comboBox1.Items.Clear();
55
56
//adiciona todas as COM diponveis na lista
57
foreach (string s in SerialPort.GetPortNames())
58
{
59
comboBox1.Items.Add(s);
60
}
61
//seleciona a primeira posio da lista
62
comboBox1.SelectedIndex = 0;
63
}
64
65
private void timerCOM_Tick(object sender, EventArgs e)
66
{
67
atualizaListaCOMs();
68
}
69
70
private void btConectar_Click(object sender, EventArgs e)
71
{
72
if (serialPort1.IsOpen == false)
73
{
74
try
75
{
76
serialPort1.PortName =
77
78 comboBox1.Items[comboBox1.SelectedIndex].ToString();
serialPort1.Open();
79
80
81
}
82
catch
83
{
84
return;
85
86
}
87
if (serialPort1.IsOpen)
88
{
89
btConectar.Text = "Desconectar";
90
comboBox1.Enabled = false;
91
92
}
93
}
94
else
95
{
96
97
try
98
{
99
serialPort1.Close();
10
comboBox1.Enabled = true;
0
btConectar.Text = "Conectar";
10
}
1
catch
10
{
2
return;
10
}
3
10
}
4
}
10
5
10
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
6
{
10
if(serialPort1.IsOpen == true) // se porta aberta
7
serialPort1.Close();
//fecha a porta
10
}
8
10
9
11
0
11
}
1
}
11
2
11
3
11
4
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using
using
using
using
using
using
using
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Threading.Tasks;
System.Windows.Forms;
System.IO.Ports; // necessrio para ter acesso as portas
namespace interfaceArduinoVS2013
{
public partial class Form1 : Form
{
string RxString;
public Form1()
{
InitializeComponent();
timerCOM.Enabled = true;
}
private void atualizaListaCOMs()
{
int i;
bool quantDiferente; //flag para sinalizar que a quantidade de portas mudou
i = 0;
quantDiferente = false;
//se a quantidade de portas mudou
if (comboBox1.Items.Count == SerialPort.GetPortNames().Length)
{
foreach (string s in SerialPort.GetPortNames())
{
if (comboBox1.Items[i++].Equals(s) == false)
{
quantDiferente = true;
}
}
}
else
{
quantDiferente = true;
}
//Se no foi detectado diferena
if (quantDiferente == false)
{
return;
//retorna
}
//limpa comboBox
comboBox1.Items.Clear();
//adiciona todas as COM diponveis na lista
foreach (string s in SerialPort.GetPortNames())
{
comboBox1.Items.Add(s);
}
//seleciona a primeira posio da lista
comboBox1.SelectedIndex = 0;
}
private void timerCOM_Tick(object sender, EventArgs e)
{
atualizaListaCOMs();
70
}
71
72
private void btConectar_Click(object sender, EventArgs e)
73
{
74
if (serialPort1.IsOpen == false)
75
{
76
try
77
{
78
serialPort1.PortName =
79 comboBox1.Items[comboBox1.SelectedIndex].ToString();
80
serialPort1.Open();
81
82
}
83
catch
84
{
85
return;
86
87
}
88
if (serialPort1.IsOpen)
89
{
90
btConectar.Text = "Desconectar";
91
comboBox1.Enabled = false;
92
93
}
94
}
95
else
96
{
97
98
try
99
{
10
serialPort1.Close();
0
comboBox1.Enabled = true;
10
btConectar.Text = "Conectar";
1
}
10
catch
2
{
10
return;
3
}
10
4
}
10
}
5
10
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
6
{
10
if(serialPort1.IsOpen == true) // se porta aberta
7
serialPort1.Close();
//fecha a porta
10
}
8
10
private void btEnviar_Click(object sender, EventArgs e)
9
{
11
if(serialPort1.IsOpen == true)
//porta est aberta
0
serialPort1.Write(textBoxEnviar.Text); //envia o texto presente no textbox Enviar
11
}
1
11
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs
2 e)
11
{
3
RxString = serialPort1.ReadExisting();
//le o dado disponvel na serial
11
this.Invoke(new EventHandler(trataDadoRecebido)); //chama outra thread para
4 escrever o dado no text box
11
}
5
11
private void trataDadoRecebido(object sender, EventArgs e)
6
{
11
textBoxReceber.AppendText(RxString);
7
}
11
8
11
9
12
0
12
1
12
2
12
3
12
4
12
5
12
}
6 }
12
7
12
8
12
9
13
0
13
1
13
2
13
3
13
4
1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
void setup()
{
Serial.begin(9600); //inicia comunicao serial com 9600
}
void loop()
{
if(Serial.available())
//se algum dado disponvel
{
char c = Serial.read(); //le o byte disponivel
Serial.write(c);
//retorna o que foi lido
}
}
1
2
3
4
5
6
7
8
9
1
/*
* comandos via serial
* inverte o estado do led conctado a sada 13 do arduino quando recebe o caracter 'A'
pela serial
*/
const int LED = 13;
void setup() {
Serial.begin(9600); //configura comunicao serial com 9600 bps
pinMode(LED,OUTPUT); //configura pino do led como sada
}
0
1
1
1
2
1 void loop() {
3 if (Serial.available()) //se byte pronto para leitura
1 {
4
switch(Serial.read())
//verifica qual caracter recebido
1
{
5
case 'A':
//caso 'A'
1
digitalWrite(LED,!digitalRead(LED)); //inverte estado do LED
6
break;
1
}
7 }
1 }
8
1
9
2
0
Concluso sobre a
Serial C# e Arduino
Comunicao
Referncias
SerialPort Class
Classe SerialPort
Sobre o Autor:
Fbio Souza
Postagens Relacionadas
O
primeiro
passo
retirar
o textBoxEnviar e
o textBoxReceber, deixando a interface da seguinte forma:
Programao para
comunicao serial
aplicao
de
1
2
3
4
serialPort1.Write("A");
if(btLigar.Text== "Ligar")
btLigar.Text = "Desligar";
1
0
1
1
else
{
1
2
btLigar.Text = "Ligar";
1
3
}
}
1
4 }
1
5
if(serialPort1.IsOpen == true)
serialPort1.Write("T");
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10 using System.IO.Ports; // necessrio para ter acesso as portas
11
12 namespace interfaceArduinoVS2013
13 {
14
15
16
17
string RxString;
18
19
public Form1()
20
21
InitializeComponent();
22
timerCOM.Enabled = true;
23
24
25
26
27
int i;
28
bool quantDiferente;
29
30
i = 0;
31
quantDiferente = false;
32
33
34
if (comboBox1.Items.Count == SerialPort.GetPortNames().Length)
35
36
37
38
if (comboBox1.Items[i++].Equals(s) == false)
39
40
quantDiferente = true;
41
42
43
44
else
45
46
47
48
quantDiferente = true;
}
49
50
if (quantDiferente == false)
51
52
return;
53
//retorna
54
55
//limpa comboBox
56
comboBox1.Items.Clear();
57
58
59
60
61
comboBox1.Items.Add(s);
62
63
64
comboBox1.SelectedIndex = 0;
65
66
67
68
69
70
atualizaListaCOMs();
}
71
72
73
74
if (serialPort1.IsOpen == false)
75
76
try
77
78
79
serialPort1.PortName =
comboBox1.Items[comboBox1.SelectedIndex].ToString();
serialPort1.Open();
80
81
82
catch
83
84
return;
85
86
87
if (serialPort1.IsOpen)
88
89
btConectar.Text = "Desconectar";
90
comboBox1.Enabled = false;
91
92
93
94
else
95
96
97
try
98
99
serialPort1.Close();
10
0
comboBox1.Enabled = true;
btConectar.Text = "Conectar";
10
1
}
catch
10
2
10
3
return;
}
10
4
10
5
10
6
10
}
}
10
8
{
if(serialPort1.IsOpen == true) // se porta aberta
10
9
serialPort1.Close();
}
11
0
11
1
11
2
//fecha a porta
11
3
11
7
11
8
11
9
12
0
12
1
12
2
12
3
12
4
12
5
12
6
12
7
btLigar.Text = "Desligar";
}
else
{
btLigar.Text = "Ligar";
12
8
}
}
12
9
}
13
0
13
1
13
2
if(serialPort1.IsOpen == true)
13
3
13
4
13 }
5
13
6
13
7
13
8
13
9
14
0
14
1
14
2
14
3
14
4
14
5
14
6
14
7
14
serialPort1.Write("T");
}
}
8
14
9
15
0
15
1
15
2
Serial.begin(9600);
1 }
0
void loop() {
1
1 if (Serial.available()) //se byte pronto para leitura
1
2
1
3
1
{
switch(Serial.read())
{
case 'A':
1
5
//caso 'A'
1
6
case 'T':
1
7
Serial.println(valor_AD);
1
8
1
9
break;
}
}
2
0
2
1
2
2
2
3
2
4
//MEDIA DE LEITURAS
valor_leituras += analogRead(A0);
i++;
if(i==16)
{
i = 0;
2
5
2
6
valor_AD = valor_leituras>>4;
valor_leituras = 0;
}
2
7
2 }
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
Concluso
Desenvolver uma interface grfica para comunicao serial e
controle com Arduino bem simples utilizando a
plataforma .Net. Voc pode criar botes e indicadores e
facilmente interagir com Arduino. A partir do exemplo
apresentado voc poder desenvolver interfaces para
controlar o seu Arduino e exibir valores no seu computador de
uma forma fcil e rpida.
Espero que este artigo possa ser a porta de entrada para suas
aplicaes grficas interagindo com o Arduino. Conte para ns
as suas experincias com essa plataforma.