Teclado Matricial e Multiplexação
Teclados são geralmente utilizados em aplicações na qual o usuário precisar interagir com um sistema, como computadores, calculadoras, controles remotos entre outros. Imagine que desejamos utilizar um teclado com 64 botões em nossa aplicação. Caso cada botão seja ligado diretamente a um pino do microcontrolador, gastaríamos 64 pinos o que tornaria a implementação dessa interface, em uma placa Uno por exemplo, impossível. Para evitar este problema podemos conectar as teclas no formato de matriz 8×8 gastando agora apenas 16 pinos e utilizar uma técnica chamada multiplexação para realizar a leitura das teclas. Para demonstrar essa técnica de leitura utilizaremos um teclado matricial de membrana 4×4 junto com um Arduino.
Esse tutorial requer conhecimento em assuntos explicados em posts anteriores. Caso tenha dificuldades em acompanhar os assuntos abordados aqui, confira alguns de nossos tutoriais anteriores:
[toc]
O Teclado Matricial
Este teclado como o nome indica é formado de botões organizados em linhas e colunas de modo a formar uma matriz. Quando pressionado, um botão conecta a linha com a coluna na qual está ligado. A figura 1 ilustra a ligação matricial.
O teclado matricial possui a seguinte pinagem:
- Pino 1 (Esquerda) – Primeira Linha (L1)
- Pino 2 – Segunda Linha (L2)
- …
- Pino 5 – Primeira Coluna (C1)
- …
- Pino 8 – Quarta Coluna (C4)
A Multiplexação
Essa técnica consiste no compartilhamento do mesmo barramento por vários dispositivos, entretanto apenas um deles utilizará o barramento por vez. No caso do teclado matricial, os barramentos serão as linhas do teclado e os dispositivos as colunas. Logo devemos permitir que apenas uma coluna se ligue as linhas por vez. Para desconectarmos as colunas que não devem ser lidas devemos configurá-las como entradas (alta impedância).
Mão à obra – Algoritmo de varredura simples
Componentes utilizados
Para esse projeto usaremos os seguintes componentes:
Programação
No início os pinos conectados as linhas serão configurados como entradas com pull up e as colunas como entradas (alta impedância). A varredura consiste em ativar uma coluna por vez (saída em nível lógico baixo) e checar se houve uma alteração nas linhas. Caso uma alteração em uma linha seja identificada, o bounce da tecla deve ser devidamente tratado para que possamos finalmente afirmar que o botão foi pressionado.
const uint8_t row_size = 4; // Quantidade de linhas. const uint8_t col_size = 4; // Quantidade de colunas. const uint8_t row_pin[row_size] = {4, 5, 6, 7}; // Pinos que estão ligados as linhas. const uint8_t col_pin[col_size] = {8, 9, 10, 11}; // Pinos que estão ligados as colunas. const char keys[row_size][col_size] = { // Mapa de teclas do teclado. { '1', '2', '3', 'A' }, { '4', '5', '6', 'B' }, { '7', '8', '9', 'C' }, { '*', '0', '#', 'D' } }; bool stable[row_size][col_size]; // Guarda o último estado estável dos botões. bool unstable[row_size][col_size]; // Guarda o último estado instável dos botões. uint32_t bounce_timer; // Executa o algoritmo de varredura simples. void scan() { for (uint8_t e = 0; e < col_size; ++e) { // Varre cada coluna. pinMode(col_pin[e], OUTPUT); digitalWrite(col_pin[e], 0); // Habilita a coluna "c". for (uint8_t r = 0; r < row_size; ++r) { // Varre cada linha a procura de mudanças. if (changed(r, e)) { // Se houver uma mudança de estado. Serial.print(keys[r][e]); Serial.print(" : "); // Imprime a tecla que sofreu a alteração Serial.println(stable[r][e]); // e seu estado atual. } } pinMode(col_pin[e], INPUT); // Desabilita a coluna "c". } } // Checa se o estado do botão foi alterado além de tratar os efeitos de sua trepidação. bool changed(const uint8_t& row, const uint8_t& col) { bool now = digitalRead(row_pin[row]); // Lê o estado do botão na linha especificada. if (unstable[row][col] != now) { // Checa se houve mudança. bounce_timer = millis(); // Atualiza timer. unstable[row][col] = now; // Atualiza estado instável. } else if (millis() - bounce_timer > 10) { // Checa o tempo de trepidação acabou. if (stable[row][col] != now) { // Checa se a mudança ainda persiste. stable[row][col] = now; // Atualiza estado estável. return 1; } } return 0; } void setup() { Serial.begin(9600); // Configura o estado inicial das linhas como entradas com pull up. for (uint8_t r = 0; r < row_size; ++r) { pinMode(row_pin[r], INPUT_PULLUP); } // Configura o estado inicial das linhas como entradas. for (uint8_t c = 0; c < col_size; ++c) { pinMode(col_pin, INPUT); } // Define estado inicial dos botões; for (uint8_t c = 0; c < col_size; ++c) { for (uint8_t r = 0; r < row_size; ++r) { stable[r] = 1; } } } void loop() { scan(); }
Pressionando várias teclas
Quando pressionamos 3 ou mais teclas um efeito conhecido como tecla fantasma pode ocorrer, vamos observar a animação a seguir para entender o porquê:
Infelizmente os problemas não acabam por aqui. Caso a tecla fantasma seja pressionada e em seguida uma das teclas anteriores for solta, a tecla que foi solta ainda será considerada como pressionada. Para solucionarmos este problema devemos adicionar um diodo em cada botão para evitar que estes caminhos indesejados sejam formados, como mostra a Figura 4.
Bibliotecas
A biblioteca Keypad é uma biblioteca especializada no interfaceamento de teclados matriciais. Seu algoritmo de varredura consegue detectar se uma tecla esta apertada, solta ou sendo segurada, entre outras funções.
Exemplo de aplicação
#include <Keypad.h> const uint8_t row_size = 4; // Quantidade de linhas. const uint8_t col_size = 4; // Quantidade de colunas. const uint8_t row_pin[row_size] = {4, 5, 6, 7}; // Pinos que estão ligados as linhas. const uint8_t col_pin[col_size] = {8, 9, 10, 11}; // Pinos que estão ligados as colunas. const char keys[row_size][col_size] = { // Mapa de teclas do teclado. { '1', '2', '3', 'A' }, { '4', '5', '6', 'B' }, { '7', '8', '9', 'C' }, { '*', '0', '#', 'D' } }; Keypad keypad = Keypad(makeKeymap(keys), row_pin, col_pin, row_size, col_size); void setup() { Serial.begin(9600); } void loop() { char key = keypad.getKey(); // Retorna a última tecla que foi apertada. if (key != NO_KEY) Serial.println(key); // Imprime tecla na porta serial. }
Fechamento
Esperamos que tenham gostado, deixe seu comentário com duvidas, sugestões ou com a foto ou vídeo de seu projeto!! Compartilhe à vontade.
If you want to obtain a good deal from this piece of writing then you have to apply these methods
to your won blog.
Very descriptive post, I enjoyed that a lot. Will there be a part
2?
Hello, I think your blog might be having browser compatibility issues.
When I look at your blog in Opera, it looks fine but when opening in Internet Explorer, it has
some overlapping. I just wanted to give you a quick heads up!
Other then that, fantastic blog!
I’m amazed, I have to admit. Seldom do I come across a blog that’s both equally educative and entertaining, and without a doubt, you’ve
hit the nail on the head. The issue is something that too few folks are
speaking intelligently about. I’m very happy I found this in my
search for something relating to this.
Hi there! This post couldn’t be written any better! Looking
at this post reminds me of my previous roommate! He continually kept preaching about this.
I’ll send this article to him. Pretty sure he’s going to have a very good read.
I appreciate you for sharing!
Greetings! Very useful advice within this article!
It’s the little changes that will make the greatest changes.
Thanks a lot for sharing!
Today, I went to the beachfront with my kids. I found a sea shell and gave it to my 4 year old daughter and
said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed.
There was a hermit crab inside and it pinched her ear. She never wants to go back!
LoL I know this is entirely off topic but I had to tell someone!
Wow that was strange. I just wrote an very long comment but after I clicked submit my comment didn’t appear.
Grrrr… well I’m not writing all that over again. Anyhow,
just wanted to say excellent blog!
Have you ever considered writing an ebook or guest authoring on other websites?
I have a blog centered on the same topics you discuss and would love
to have you share some stories/information. I know my
audience would value your work. If you are even remotely
interested, feel free to send me an e-mail.
Excellent post. Keep writing such kind of information on your blog.
Im really impressed by it.
Hello there, You’ve performed an incredible job.
I will definitely digg it and in my opinion recommend to my
friends. I’m sure they’ll be benefited from this web site.
Hi there to all, how is everything, I think every one is getting more from this web site,
and your views are fastidious in favor of new users.
Nice post. I was checking constantly this weblog and I
am inspired! Very useful information specifically the ultimate section :) I maintain such information a lot.
I used to be looking for this certain info for
a very lengthy time. Thanks and best of
luck.
Thank you, I have just been searching for information approximately this topic for a while and yours is the
greatest I’ve discovered till now. But, what about the bottom line?
Are you sure concerning the source?
My developer is trying to persuade me to move to .net from PHP.
I have always disliked the idea because of the costs.
But he’s tryiong none the less. I’ve been using Movable-type on a variety of websites for about a year and am concerned about switching to another platform.
I have heard great things about blogengine.net.
Is there a way I can import all my wordpress posts into it?
Any kind of help would be greatly appreciated!
With havin so much content do you ever run into any problems of plagorism or copyright violation? My website has a lot of unique
content I’ve either written myself or outsourced but it appears
a lot of it is popping it up all over the internet without my
agreement. Do you know any methods to help prevent content from being stolen? I’d really appreciate it.
Hello exceptional blog! Does running a blog like this require a lot of work?
I’ve absolutely no knowledge of computer programming however I had been hoping to start my own blog in the near
future. Anyways, should you have any recommendations or tips for new blog owners
please share. I understand this is off topic however I simply wanted to ask.
Cheers!
Oh my goodness! Incredible article dude! Thank you so much, However I am encountering issues with your RSS.
I don’t understand the reason why I cannot join it.
Is there anybody else getting the same RSS issues?
Anybody who knows the solution can you kindly respond?
Thanks!!
The other day, while I was at work, my sister stole my
iPad and tested to see if it can survive a 40 foot drop, just so she can be a youtube sensation. My
iPad is now broken and she has 83 views. I know this is completely off topic but I had to share it with someone!
I’ve read a few excellent stuff here. Definitely value bookmarking for revisiting.
I surprise how so much attempt you place to make such a great informative website.
Great beat ! I wish to apprentice at the same time as you amend your site, how can i subscribe for a weblog website?
The account aided me a applicable deal. I were tiny bit acquainted of this your broadcast provided bright clear idea
Hello there I am so thrilled I found your site, I really found
you by error, while I was looking on Aol for something else, Anyways I am here now
and would just like to say many thanks for a remarkable post and a all round enjoyable blog (I also love the theme/design), I don’t have time to go
through it all at the moment but I have bookmarked it and also
added your RSS feeds, so when I have time I will be back to read
a lot more, Please do keep up the excellent work.
Greetings! I’ve been reading your site for some time now and finally got the courage to go ahead and give you a shout out from
Lubbock Tx! Just wanted to mention keep up the excellent work!
Hi there just wanted to give you a quick heads up. The
text in your post seem to be running off the screen in Opera.
I’m not sure if this is a formatting issue or something to do with browser compatibility but I thought I’d post to let you know.
The layout look great though! Hope you get the problem resolved soon. Kudos
Hi there i am kavin, its my first time to commenting anywhere,
when i read this article i thought i could also create comment due to this brilliant piece of writing.
I’m not sure why but this website is loading incredibly
slow for me. Is anyone else having this issue or is it a problem on my end?
I’ll check back later and see if the problem still exists.
Piece of writing writing is also a excitement, if you be familiar with after that
you can write otherwise it is difficult to write.
Can I just say what a comfort to discover an individual who genuinely knows what they’re talking about over the internet.
You certainly know how to bring an issue to light and make it important.
A lot more people should look at this and understand this side
of the story. It’s surprising you’re not more popular because you surely possess the gift.
Muito bom o artigo! Os diodos usados em teclados matriciais devem sempre ser de silício e de comutação rápida, 4ns. Ou seja, 1N4148, 1N914 por exemplo. Estou fazendo manutenção em um órgão de uma igreja e enquanto não chega um circuito integrado obsoleto, que localizei um na Franca, estou implementando um Arduino MEGA que será ligado no teclado matricial original do órgão 8×8. A conexão USB do Arduino será conectada a um Macbook que ira disparar os arquivos SAMPLES com os sons de órgãos de tubo.
qualquer diodo
Cara muito bom o artigo, parabéns!!!
Tem dois erros de compilação no primeiro programa.
Na linha 58 deveria ser assim:
pinMode(col_pin[c], INPUT);
e na linha 64 deveria ser:
stable[r][c] = 1;
Estou fazendo um projeto que irei utilizar um teclado matricial e um Display LCD e um arduino nano,
O que estou bolando é uma máquina de contar peças, fiz uma programação com uma barreira óptica, o que eu quero chegar nesse projeto, é a utilização do teclado matricial para controlar o proprio display LCD, teria algum email para enviar o projeto ?
Qual o diodo você utilizou no esquema?