tag:blogger.com,1999:blog-7543872142789893982024-03-20T00:57:28.360-07:00Mindstorms, Arduino y la conexión de sensoresBlog asociado a una beca de colaboración, llevada a cabo en el Departamento de Ingeniería de Sistemas y Automática de la Universidad de MálagaAzerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.comBlogger32125tag:blogger.com,1999:blog-754387214278989398.post-32741964217740777762011-06-17T02:19:00.000-07:002011-06-17T02:19:41.686-07:00Sensor SCP 1000 y su conexión con Arduino por SPI<span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">El sensor SCP1000 es un sensor de presión barométrica preciso y de alta calidad. En condiciones ideales, es capaz de medir presiones de una capa de aire de 9 centímetros y está pensado para mediciones tales como en altímetros por ejemplo, con un gran rango de temperaturas de funcionamiento que van desde -20 a 70 grados centígrados. La calibración y compensación se realiza internamente, por lo que siempre dispondremos de una medición precisa. El sensor se controla mediante un bus SPI y su consumo puede ser de apenas 4 micro Amperios. El sensor se puede ver en la siguiente figura:</span><br />
<span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span><br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdCYwzPMl512uw3OSab85lD6VEizhuf2R5L9QsEDZMskD1y0SH1D95wAiOy-6fXTUPTDTNBCZ6X2ZxAKTNe_pniyUK_n2Wr9ZDIQyV9KTCJx2aML69PCv8m4vWM0Kg80zWa-PFeE1l522c/s1600/Captura+de+pantalla+2011-06-14+a+las+19.16.44.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span class="Apple-style-span" style="color: black; font-family: Times, 'Times New Roman', serif;"><img border="0" height="181" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdCYwzPMl512uw3OSab85lD6VEizhuf2R5L9QsEDZMskD1y0SH1D95wAiOy-6fXTUPTDTNBCZ6X2ZxAKTNe_pniyUK_n2Wr9ZDIQyV9KTCJx2aML69PCv8m4vWM0Kg80zWa-PFeE1l522c/s200/Captura+de+pantalla+2011-06-14+a+las+19.16.44.png" width="200" /></span></a></div><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span><br />
<b><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">Conexiones realizadas</span></b><br />
<b><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span></b><br />
<style>
<!--
/* Font Definitions */
@font-face
{font-family:"Courier New";
panose-1:2 7 3 9 2 2 5 2 4 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536859905 -1073711037 9 0 511 0;}
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
/* List Definitions */
@list l0
{mso-list-id:1448818088;
mso-list-type:hybrid;
mso-list-template-ids:2057584918 -847460270 201981955 201981957 201981953 201981955 201981957 201981953 201981955 201981957;}
@list l0:level1
{mso-level-start-at:2;
mso-level-number-format:bullet;
mso-level-text:-;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Verdana;
mso-fareast-font-family:"Times New Roman";
mso-bidi-font-family:"Times New Roman";}
@list l0:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level3
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level4
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level5
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level6
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level7
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level8
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level9
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->
</style> <br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif; font-size: small;">Como se ha comentado en el epígrafe anterior, este sensor se va a conectar mediante el protocolo SPI. Las conexiones que se han realizado entre dicho sensor y nuestro sistema de desarrollo han sido las siguientes:<o:p></o:p></span></div><div class="MsoListParagraphCxSpFirst" style="line-height: 150%; text-align: justify; text-indent: -18pt;"></div><ul><li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">Pines de tierra de ambos conectados</span></li>
<li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">Alimentación del sensor al pin de 3,3 de Arduino</span></li>
<li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">Pines MISO y MOSI del protocolo SPI a los pines 50 y 51 de Arduino respectivamente</span></li>
<li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">La señal de reloj, SCK, se ha conectado pin 52 de Arduino</span></li>
<li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">Los pines de indicación de dato listo (DRDY) y de selección del chip (CSB) se han conectado a los pines 30 y 31 de Arduino respectivamente</span></li>
</ul><br />
<br />
<span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span><br />
<b><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">Código implementado</span></b><br />
<span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span><br />
<style>
<!--
/* Font Definitions */
@font-face
{font-family:"Courier New";
panose-1:2 7 3 9 2 2 5 2 4 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536859905 -1073711037 9 0 511 0;}
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
/* List Definitions */
@list l0
{mso-list-id:1448818088;
mso-list-type:hybrid;
mso-list-template-ids:2057584918 -847460270 201981955 201981957 201981953 201981955 201981957 201981953 201981955 201981957;}
@list l0:level1
{mso-level-start-at:2;
mso-level-number-format:bullet;
mso-level-text:-;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Verdana;
mso-fareast-font-family:"Times New Roman";
mso-bidi-font-family:"Times New Roman";}
@list l0:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level3
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level4
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level5
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level6
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level7
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level8
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level9
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->
</style> <br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif; font-size: small;">El código está estructurado de la siguiente forma:<o:p></o:p></span></div><div class="MsoListParagraphCxSpFirst" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"></div><ul><li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">En el apartado de setupo(), se configuran los registros del sensor</span></li>
<li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">En el bucle principal se configura el sensor para que lea en alta resolución, es decir, devolverá 19 bits para la presión y 16 bits para la temperatura. Para obtener la temperatura en grados centígrados, bastará con dividir los 16 bits entre 20</span></li>
<li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">A continuación se lee la temperatura en 2 bytes</span></li>
<li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">Finalmente, se lee la presión en dos partes: primero se leen los 3 bits más altos, y seguidamente los 16 bits más bajos. Estas dos partes se combinan en un long entero desplazando los bits más altos y realizando una OR bit a bit para combinarlos con los 16 más bajos. La humedad en pascales es el resultado de 19 bits dividido entre 4.</span></li>
</ul><br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif; font-size: small;">El código completo se muestra a continuación. Se han dejado los comentarios para simplificar la comprensión del mismo:</span><o:p></o:p></div><br />
<br />
<style>
<!--
/* Font Definitions */
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
-->
</style> <br />
<table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="border-collapse: collapse; border: none; mso-border-alt: solid windowtext .5pt; mso-padding-alt: 0cm 5.4pt 0cm 5.4pt; mso-yfti-tbllook: 1184;"><tbody>
<tr style="mso-yfti-firstrow: yes; mso-yfti-irow: 0; mso-yfti-lastrow: yes;"> <td style="background: #F2F2F2; border: solid windowtext 1.0pt; mso-background-themecolor: background1; mso-background-themeshade: 242; mso-border-alt: solid windowtext .5pt; padding: 0cm 5.4pt 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><div class="MsoNormal" style="line-height: 150%; text-align: justify;">// Incluimos la librería SPI<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">#include <SPI.h><o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">//Direcciones de los registros de la memoria del sensor<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">const int PRESSURE = 0x1F; //3 bits mas significativos de la presion<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">const int PRESSURE_LSB = 0x20; //16 bits menos significativos de la presion<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">const int TEMPERATURE = 0x21; //16 bits de la lectura de temperatura<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">const byte READ = 0b11111100; // Instruccion de lectura del SCP1000<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">const byte WRITE = 0b00000010; // Instruccion de escritura del SCP1000<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">// Pines usados para la conexion con el sensor<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">// El resto ya estan definidos en la libreria SPI<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">const int dataReadyPin = 30;<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">const int chipSelectPin = 31;<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">void setup() {<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> Serial.begin(9600);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Inicializamos la libreria SPI<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> SPI.begin();<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Inicializamos pines dataReady y chipSelect<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> pinMode(dataReadyPin, INPUT);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> pinMode(chipSelectPin, OUTPUT);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> //Configuramos el SCP1000 en config. de bajo ruido<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> writeRegister(0x02, 0x2D);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> writeRegister(0x01, 0x03);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> writeRegister(0x03, 0x02);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Y le damos tiempo al sensor para que se prepare<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> delay(100);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">}<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">void loop() {<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> //Seleccionamos el modo de alta resolucion<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> writeRegister(0x03, 0x0A);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // No hacemos nada hasta que el pin dataReady este alto<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> if (digitalRead(dataReadyPin) == HIGH) {<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> //Leemos la temperatura<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> int tempData = readRegister(0x21, 2);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Convertimos la temp. a Celcius y la mostramos<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> float realTemp = (float)tempData / 20.0;<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> Serial.print("Temp[C]=");<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> Serial.print(realTemp);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Leemos los 3 bits mas altos de la presion<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> byte pressure_data_high = readRegister(0x1F, 1);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> pressure_data_high &= 0b00000111; // Solo hacen falta los bits del 2 al 0<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> //Se leen los 16 bits mas bajos de la presion<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> unsigned int pressure_data_low = readRegister(0x20, 2);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Se combinan las dos partes en un solo numero de 19 bits:<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> long pressure = ((pressure_data_high << 16) | pressure_data_low)/4;<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Mostramos la presion:<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> Serial.println("\tPressure [Pa]=" + String(pressure));<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> }<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">}<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">//Lecturas desde o escrituras hacia los registros del SCP1000<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">unsigned int readRegister(byte thisRegister, int bytesToRead ) {<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> byte inByte = 0; // Byte entrante del SPI<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> unsigned int result = 0; // Resultado a devolver<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> Serial.print(thisRegister, BIN);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> Serial.print("\t");<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // SCP1000 espera el nombre del registro en los 6 bits mas altos<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // del byte. Asi que desplazamos los bits hacia la izq. 2 posiciones<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> thisRegister = thisRegister << 2;<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Combinamos la direccion y la instruccion en un byte<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> byte dataToSend = thisRegister & READ;<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> Serial.println(thisRegister, BIN);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Bajamos el ChipSelct para seleccionar el dispositivo<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> digitalWrite(chipSelectPin, LOW);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Mandamos al dispositivo el registro que queremos leer:<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> SPI.transfer(dataToSend);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Mandamos un valor de 0 para leer el primer byte devuelto<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> result = SPI.transfer(0x00);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Reducimos en uno el numero de bytes restantes por leer<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> bytesToRead--;<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Si quedan bytes por leer<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> if (bytesToRead > 0) {<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Desplazamos el primer byte hacia la izquierda, y obtenemos el 2º byte:<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> result = result << 8;<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> inByte = SPI.transfer(0x00);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Combinamos el byte que acabamos de obtener con el anterior:<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> result = result | inByte;<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Nos queda un byte menos por leer:<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> bytesToRead--;<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> }<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Levantamos el chip-select<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> digitalWrite(chipSelectPin, HIGH);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Devolvemos el resultado<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> return(result);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">}<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">//Mandamos ahora una escritura el dispositivo<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;">void writeRegister(byte thisRegister, byte thisValue) {<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // SCP1000 espera la direccion del registo en los 6 bits mas altos<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // del byte. Asi que desplazamos en 2 posiciones hacia la izquierda<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> thisRegister = thisRegister << 2;<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Combinamos el registro de direccion y la instruccion en un solo byte:<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> byte dataToSend = thisRegister | WRITE;<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Bajamos el chip-select para seleccionar el sensor:<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> digitalWrite(chipSelectPin, LOW);<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> SPI.transfer(dataToSend); //Mandamos la localizacion del registro<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> SPI.transfer(thisValue); //Mandamos el valor a almacenar en el registro<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> // Levantamos el chip-select<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"> digitalWrite(chipSelectPin, HIGH); }<o:p></o:p></div></td> </tr>
</tbody></table><br />
Aquí os dejo una captura de la salida de datos, en la que se ve la presión en grados, la temperatura en pascales y el contenido de los registros leídos en bianrio (simplemente los he dejado como traza, para ver que todo se hace correctamente):<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOT87eusnYX9ODgTNQAevlPxr1ESNiq3iYpoXsqmFppB4tBXc2YASooFee27anaRfze43pA3wS0cf10xMZLIsQQMlAoqdmfb82z1A2SN__Dfrld6vtvKEfSCJIe1FRL07lDjTEmzhC9raS/s1600/Captura+de+pantalla+2011-06-17+a+las+11.14.12.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="137" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOT87eusnYX9ODgTNQAevlPxr1ESNiq3iYpoXsqmFppB4tBXc2YASooFee27anaRfze43pA3wS0cf10xMZLIsQQMlAoqdmfb82z1A2SN__Dfrld6vtvKEfSCJIe1FRL07lDjTEmzhC9raS/s320/Captura+de+pantalla+2011-06-17+a+las+11.14.12.png" width="320" /></a></div><br />
---------------------------------<br />
<b>Referencias:</b><br />
<br />
- Sensor SCP1000: http://www.bricogeek.com/shop/150-sensor-de-presion-barometrica-scp1000.htmlAzerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com2tag:blogger.com,1999:blog-754387214278989398.post-70317883627797858162011-06-12T11:23:00.000-07:002011-06-12T11:23:56.490-07:00Conexión del GPS Venus con conector SMA con Arduino por puerto serie<style>
<!--
/* Font Definitions */
@font-face
{font-family:"Courier New";
panose-1:2 7 3 9 2 2 5 2 4 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536859905 -1073711037 9 0 511 0;}
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoCaption, li.MsoCaption, div.MsoCaption
{mso-style-qformat:yes;
mso-style-next:Normal;
margin-top:0cm;
margin-right:0cm;
margin-bottom:10.0pt;
margin-left:0cm;
mso-pagination:widow-orphan;
font-size:9.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:#4F81BD;
mso-themecolor:accent1;
mso-fareast-language:EN-US;
font-weight:bold;}
p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
/* List Definitions */
@list l0
{mso-list-id:1448818088;
mso-list-type:hybrid;
mso-list-template-ids:2057584918 -847460270 201981955 201981957 201981953 201981955 201981957 201981953 201981955 201981957;}
@list l0:level1
{mso-level-start-at:2;
mso-level-number-format:bullet;
mso-level-text:-;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Verdana;
mso-fareast-font-family:"Times New Roman";
mso-bidi-font-family:"Times New Roman";}
@list l0:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level3
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level4
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level5
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level6
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level7
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level8
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level9
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->
</style> <br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: 'Times New Roman';">Otro de los dispositivos cuya integración se ha probado con Arduino ha sido un receptor GPS de la marca Venus, que se puede apreciar en la siguiente imagen:<o:p></o:p></span></div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh-eFONJNuN9T8ZE72hGkH0MM4-auXxMdrZCFtAHLCrdhR_BC2l-IgeT5fXeqN_nfJ9SaOBQfBM9oY1TksZbtXtiltcyUuaGDmwjMTCQTXmZGnCUpsjMCuY9QPKfKKwR8mCqsJLXN8ZViRe/s1600/4.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh-eFONJNuN9T8ZE72hGkH0MM4-auXxMdrZCFtAHLCrdhR_BC2l-IgeT5fXeqN_nfJ9SaOBQfBM9oY1TksZbtXtiltcyUuaGDmwjMTCQTXmZGnCUpsjMCuY9QPKfKKwR8mCqsJLXN8ZViRe/s1600/4.jpg" /></a></div><div style="text-align: center; text-indent: 27px;"><span class="Apple-style-span" style="font-family: 'Times New Roman';"><span class="Apple-style-span" style="line-height: 24px;"><br />
</span></span></div><div align="center" class="MsoCaption" style="text-align: center;">Figura Receptor GPS Venus con conector SMA<span style="font-family: 'Times New Roman';"><o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: 'Times New Roman';">Se trata de un receptor de gran sensibilidad, que permite la conexión de una antena externa mediante un conector SMA. Se puede configurar para lograr una tasa de refresco de hasta 10 Hz., y permite obtener por el puerto serie cadenas del tipo NMEA-0183, que se explicarán en otro post del blog. La tasa por defecto a la que este dispositivo devuelve datos es de 9600 baudios, pero puede configurarse con una velocidad de hasta 115200 baudios.<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: 'Times New Roman';">El corazón de este GPS es el chip Venus634FLPx, que lleva incorporado un LNC, un reloj en tiempo real y un regulador de tensión. Las características más destacadas son las siguientes:<o:p></o:p></span></div><div class="MsoListParagraphCxSpFirst" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"></div><ul><li><span style="font-family: 'Times New Roman';">51 canales de adquisición y 14 de tracking</span></li>
<li><span style="font-family: 'Times New Roman';">Lleva un chipset SkyTrack</span></li>
<li><span style="font-family: 'Times New Roman';">La frecuencia máxima de actualización es de 10 Hz. aunque viene configurada por defecto a 1 H.</span></li>
<li><span style="font-family: 'Times New Roman';">Lleva LNA integrado</span></li>
<li><span style="font-family: 'Times New Roman';">Se debe alimentar con una tensión de entre 2,7 y 3,3 V.</span></li>
<li><span style="font-family: 'Times New Roman';">Su consumo es de unos 28 mA una vez conectado con los satélites.</span></li>
<li><span style="font-family: 'Times New Roman';">Su sensibilidad es de -161 dBm</span></li>
<li><span style="font-family: 'Times New Roman';">El margen de error al posicionarse es de menos de 2,5 metros</span></li>
<li><span style="font-family: 'Times New Roman';">Si se arranca en frío puede tardar unos 29 segundos en localizarse, mientras que si se arranca en caliente este tiempo se reduce incluso hasta un segundo.</span></li>
<li><span style="font-family: 'Times New Roman';">Soporta antenas tanto activas como pasivas, aunque en el caso de las primeras deberán alimentarse de forma externa.</span></li>
<li><span style="font-family: 'Times New Roman';">Su tamaño es de 3,8x1,8 cm, con lo que es fácilmente integrable.</span></li>
</ul><div><span class="Apple-style-span" style="font-family: 'Times New Roman';"><br />
</span></div><div><style>
<!--
/* Font Definitions */
@font-face
{font-family:"Courier New";
panose-1:2 7 3 9 2 2 5 2 4 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536859905 -1073711037 9 0 511 0;}
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:"MS ゴシック";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1791491579 18 0 131231 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
h3
{mso-style-qformat:yes;
mso-style-link:"Título 3 Car";
mso-style-next:Normal;
margin-top:10.0pt;
margin-right:0cm;
margin-bottom:0cm;
margin-left:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan lines-together;
page-break-after:avoid;
mso-outline-level:3;
font-size:13.0pt;
mso-bidi-font-size:12.0pt;
font-family:"Times New Roman";
mso-fareast-font-family:"MS ゴシック";
mso-fareast-theme-font:major-fareast;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:major-bidi;
mso-fareast-language:EN-US;}
p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
span.Ttulo3Car
{mso-style-name:"Título 3 Car";
mso-style-unhide:no;
mso-style-locked:yes;
mso-style-link:"Título 3";
mso-ansi-font-size:13.0pt;
font-family:"MS ゴシック";
mso-fareast-font-family:"MS ゴシック";
mso-fareast-theme-font:major-fareast;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:major-bidi;
mso-fareast-language:EN-US;
font-weight:bold;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
/* List Definitions */
@list l0
{mso-list-id:1448818088;
mso-list-type:hybrid;
mso-list-template-ids:2057584918 -847460270 201981955 201981957 201981953 201981955 201981957 201981953 201981955 201981957;}
@list l0:level1
{mso-level-start-at:2;
mso-level-number-format:bullet;
mso-level-text:-;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Verdana;
mso-fareast-font-family:"Times New Roman";
mso-bidi-font-family:"Times New Roman";}
@list l0:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level3
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level4
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level5
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level6
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level7
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level8
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level9
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->
</style> <br />
<h3 style="font-family: 'Times New Roman';"><a href="http://www.blogger.com/post-create.do" name="_Toc169529316">Conexiones realizadas</a><o:p></o:p></h3><div class="MsoNormal" style="font-family: 'Times New Roman'; line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: 'Times New Roman';">Las conexiones realizadas son similares a las que se hicieron en el caso del lector RFID, con la diferencia de que en este caso el circuito va alimentado a una tensión de 3,3 V. Por lo tanto:<o:p></o:p></span></div><div class="MsoListParagraphCxSpFirst" style="line-height: 150%; text-align: justify; text-indent: -18pt;"></div><ul style="font-family: 'Times New Roman';"><li><span class="Apple-style-span" style="font-family: Cambria;"><span style="font-family: 'Times New Roman';">Las tierras (pines GND) de dispositivo se conectan entre sí y con cualquiera de los pines de tierra de la placa de Arduino.</span></span></li>
<li><span style="font-family: 'Times New Roman';">El pin TX se conecta con el pin RX0 de Arduino, que en el caso de Arduino Mega 2560 corresponde al pin 0.</span></li>
<li><span style="font-family: 'Times New Roman';">El pin de alimentación de 3,3 V se conecta con el pin de 3,3 V de Arduino.</span></li>
</ul><br />
<h3 style="font-family: 'Times New Roman';"><a href="http://www.blogger.com/post-create.do" name="_Toc169529317">Código implementado</a><o:p></o:p></h3><div class="MsoNormal" style="font-family: 'Times New Roman'; line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: 'Times New Roman';">En el código que se incluye a continuación, simplemente se configura la velocidad a 9600 baudios y se van mostrando los datos que se vayan recibiendo a través del puerto serie:<o:p></o:p></span></div><div class="MsoNormal" style="font-family: 'Times New Roman'; line-height: 150%; text-align: justify; text-indent: 14.2pt;"><br />
</div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="border-bottom-style: none; border-collapse: collapse; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: 'Times New Roman';"><tbody>
<tr style="mso-yfti-firstrow: yes; mso-yfti-irow: 0; mso-yfti-lastrow: yes;"> <td style="background: #F2F2F2; border: solid windowtext 1.0pt; mso-background-themecolor: background1; mso-background-themeshade: 242; mso-border-alt: solid windowtext .5pt; padding: 0cm 5.4pt 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;">char val = 0; //Para almacenar el valor que le llega<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><br />
</div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;">void setup() {<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;"> Serial.begin(9600); // Conectamos al puerto serie<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;">}<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><br />
</div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;">void loop () {<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><br />
</div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;"> char IDstring[13]; //Para almacenar el tag<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;"> int i;<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;"> <o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;"> if (Serial.available() > 0 ) {<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;"> //Serial.println("Datos --> ");<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;"> val = Serial.read(); // Se busca el inicio del codigo<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;"> Serial.print(val);<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;"> if (val=='\r'){<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;"> Serial.println(" ");<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;"> }<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; tab-stops: 28.3pt 56.65pt 85.0pt 113.35pt 141.7pt 170.05pt 198.4pt 226.75pt 255.1pt 283.45pt 311.8pt 340.15pt; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: Helvetica;"> }<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span lang="ES" style="color: windowtext; font-family: Helvetica;">}</span><o:p></o:p></div></td> </tr>
</tbody></table><span style="color: black; font-family: Cambria; font-size: 12pt; line-height: 150%;"><br clear="all" style="mso-special-character: line-break; page-break-before: always;" /> </span> <br />
<div class="MsoNormal" style="font-family: 'Times New Roman'; line-height: 150%; text-align: justify; text-indent: 14.2pt;"><br />
</div></div>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com2tag:blogger.com,1999:blog-754387214278989398.post-6795641188560310572011-06-12T11:07:00.000-07:002011-06-12T11:09:00.643-07:00Arduino y la comunicación SPI<style>
<!--
/* Font Definitions */
@font-face
{font-family:"Courier New";
panose-1:2 7 3 9 2 2 5 2 4 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536859905 -1073711037 9 0 511 0;}
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoCaption, li.MsoCaption, div.MsoCaption
{mso-style-qformat:yes;
mso-style-next:Normal;
margin-top:0cm;
margin-right:0cm;
margin-bottom:10.0pt;
margin-left:0cm;
mso-pagination:widow-orphan;
font-size:9.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:#4F81BD;
mso-themecolor:accent1;
mso-fareast-language:EN-US;
font-weight:bold;}
p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
/* List Definitions */
@list l0
{mso-list-id:1448818088;
mso-list-type:hybrid;
mso-list-template-ids:2057584918 -847460270 201981955 201981957 201981953 201981955 201981957 201981953 201981955 201981957;}
@list l0:level1
{mso-level-start-at:2;
mso-level-number-format:bullet;
mso-level-text:-;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Verdana;
mso-fareast-font-family:"Times New Roman";
mso-bidi-font-family:"Times New Roman";}
@list l0:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level3
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level4
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level5
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level6
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level7
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level8
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level9
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->
</style> <br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: inherit; font-size: small;">En este epígrafe se va a analizar el protocolo de comunicaciones SPI, y se va a ver de qué manera se puede manejar desde el entorno de desarrollo Arduino. En primer lugar se hará un resumen de cómo funciona dicho protocolo, y a continuación se explicarán las distintas funciones disponibles para poder utilizarlo.<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><br />
</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><b style="mso-bidi-font-weight: normal;"><span style="font-family: inherit; font-size: small;">El protocolo SPI<o:p></o:p></span></b></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: inherit; font-size: small;">El protocolo SPI proviene de las siglas en inglés “Serial Peripheral Interface”, y es un estándar de comunicaciones usado principalmente en la transferencia de información entre circuitos integrados en circuitos electrónicos. Se trata de un bus serie de datos para la transferencia síncrona y bidireccional de información. En toda comunicación por SPI deberá haber al menos un dispositivo actuando como maestro, y uno o más actuando como esclavos. Para seleccionar a cada uno de los esclavos existe una línea, denominada “slave select” o “chip select”.<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: inherit; font-size: small;">Las señales del protocolo SPI son las siguientes:<o:p></o:p></span></div><div class="MsoListParagraphCxSpFirst" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"></div><ul><li><span class="Apple-style-span" style="font-family: inherit;">SCLK: Es la señal de reloj, impuesta por el dispositivo maestro.</span></li>
<li><span class="Apple-style-span" style="font-family: inherit;">MOSI: Corresponde a las siglas “Master Output – Slave Input”, es decir, el maestro enviará los datos a través de esta línea y el esclavo los recibirá.</span></li>
<li><span class="Apple-style-span" style="font-family: inherit;">MISO: Corresponde a las siglas “Master Input – Slave Output”, y es la línea por la que los esclavos enviarán datos al dispositivo maestro.</span></li>
<li><span class="Apple-style-span" style="font-family: inherit;">SS: Es la señal de “Slave Select”, es decir, la línea que el maestro activará para indicar al esclavo que se va a establecer la comunicación con él.</span></li>
</ul><span class="Apple-style-span" style="font-family: inherit;"><br />
</span><br />
<div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><o:p></o:p></span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><o:p></o:p></span></div><div class="MsoListParagraphCxSpLast" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><br />
</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;">Habitualmente, el pin MISO del maestro se conecta con el pin MOSI del esclavo, y viceversa. Además, la señal de selección de esclavo suele ser activa a nivel bajo.<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;">A continuación se va a describir con un poco más de detalles cómo funciona el protocolo:<o:p></o:p></span></div><div class="MsoListParagraphCxSpFirst" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"></div><ul><li><span class="Apple-style-span" style="font-family: inherit;">Para iniciar la comunicación, el maestro configura el reloj usando una frecuencia menos o igual a la frecuencia máxima que soporta el esclavo. Estas frecuencias suelen estar en el rango de 1 a 70 MHz.</span></li>
<li><span class="Apple-style-span" style="font-family: inherit;">El maestro a continuación pone a nivel bajo la señal “Slave Select” del esclavo para indicarle que se va a comunicar con él. Si es necesario esperar un tiempo antes de iniciar la comunicación (por ejemplo para permitir una conversión analógico / digital), el maestro esperará al menos ese tiempo antes de proseguir con el intercambio de información.</span></li>
<li><span class="Apple-style-span" style="font-family: inherit;">Durante cada ciclo de reloj se produce una comunicación en los dos sentidos, ya que por una parte el maestro va a mandar un bit a través del pin MOSI y el esclavo lo va recibir, mientras que a la vez el esclavo va a mandar un bit a través de la línea MISO para que el maestro lo reciba.</span></li>
<li><span class="Apple-style-span" style="font-family: inherit;">Cuando ya no quedan datos que transmitir, el maestro deja de accionar la señal de reloj y normalmente vuelve a colocar a nivel alto la señal de “Slave Select” para así deseleccionar al dispositivo.</span></li>
<li><span class="Apple-style-span" style="font-family: inherit;">Cualquier dispositivo que no tenga a nivel bajo su señal de selección, ignorará los movimientos que haya en las líneas MISO y MOSI, con lo que podemos tener distintos dispositivos conectados a esas mismas líneas sin que interfieran en la comunicación. Evidentemente, la señal de “Slave Select” sí debe ser propia de cada dispositivo.</span></li>
<li><span class="Apple-style-span" style="font-family: inherit;">Además de la frecuencia de reloj, el maestro también puede configurar la polaridad y la fase de la señal de reloj con respecto a los datos. La polaridad se suele denominar usando las siglas CPOL, mientras que la fase se suele denominar como CPHA. En la figura inferior se puede ver un diagrama temporal que explica las distintas combinaciones (o modos) que se describen a continuación:</span></li>
</ul><span class="Apple-style-span" style="font-family: inherit;"><o:p></o:p></span><br />
<div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><o:p></o:p></span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><o:p></o:p></span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><o:p></o:p></span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><o:p></o:p></span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><o:p></o:p></span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 72.0pt; mso-add-space: auto; mso-list: l0 level2 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;">o<span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span>Si CPOL = 0, el valor base de la señal de reloj es el nivel bajo.<o:p></o:p></span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 108.0pt; mso-add-space: auto; mso-list: l0 level3 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;">§<span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span>Si CPHA = 0, los datos se capturan en el flanco de subida de la señal de reloj, y se propagan en el flanco de bajada. Este modo se denomina modo 0.<o:p></o:p></span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 108.0pt; mso-add-space: auto; mso-list: l0 level3 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;">§<span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span>Si CPHA = 1, los datos de capturan en el flanco de bajada de la señal de reloj, y se propagan en el flanco de subida. Este modo se denomina modo 1.<o:p></o:p></span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 72.0pt; mso-add-space: auto; mso-list: l0 level2 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;">o<span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span>Si CPOL = 1, el valor base de la señal de reloj es el nivel alto.<o:p></o:p></span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 108.0pt; mso-add-space: auto; mso-list: l0 level3 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;">§<span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span>Si CPHA = 0, los datos de capturan en el flanco de bajada de la señal de reloj, y se propagan en el flanco de subida. Este modo se denomina modo 2.<o:p></o:p></span></div><div class="MsoListParagraphCxSpLast" style="line-height: 150%; margin-left: 108.0pt; mso-add-space: auto; mso-list: l0 level3 lfo1; text-align: justify; text-indent: -18.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;">§<span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span>Si CPHA = 1, los datos se capturan en el flanco de subida de la señal de reloj, y se propagan en el flanco de bajada. Este modo se denomina modo 3.<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><br />
</span></div><span class="Apple-style-span" style="font-family: inherit;"><br />
</span><br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGFauGIlgQ85VefD8vOf3Z7fRC47E3aHApGqxBY2TtEnNl6oX2Kk25BkStvJhxahe0U0VLsmdCVm12Kz8iHRjD6I7jqNSJWsLox1wGq8ep3lIRfYD2uyKG-AbON3gcHv37flnQm4EsBTu0/s1600/3.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span class="Apple-style-span" style="font-family: inherit;"><img border="0" height="186" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGFauGIlgQ85VefD8vOf3Z7fRC47E3aHApGqxBY2TtEnNl6oX2Kk25BkStvJhxahe0U0VLsmdCVm12Kz8iHRjD6I7jqNSJWsLox1wGq8ep3lIRfYD2uyKG-AbON3gcHv37flnQm4EsBTu0/s320/3.jpg" width="320" /></span></a></div><div style="text-align: center;"><span class="Apple-style-span" style="font-family: inherit; line-height: 24px;"><br />
</span></div><div align="center" class="MsoCaption" style="text-align: center;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;">Figura Diagrama temporal del protocolo SPI<o:p></o:p></span></div><div class="MsoNormal"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><br />
</span></div><div class="MsoNormal" style="line-height: 150%;"><b style="mso-bidi-font-weight: normal;"><span style="font-family: inherit; font-size: small;">Funciones disponibles en Arduino<o:p></o:p></span></b></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: inherit; font-size: small;">La gestión del protocolo SPI en Arduino se realiza a través de la librería SPI. Esta interfaz se inicializa automáticamente cuando la librería SPI se incluye en un código. En el caso de Arduino Mega 2560 usando en las pruebas, los pines se inicializan de la siguiente forma:<o:p></o:p></span></div><div class="MsoListParagraphCxSpFirst" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"></div><ul><li><span class="Apple-style-span" style="font-family: inherit;">Pin 50: señal MISO</span></li>
<li><span class="Apple-style-span" style="font-family: inherit;">Pin 51: señal MOSI</span></li>
<li><span class="Apple-style-span" style="font-family: inherit;">Pin 52: señal SCK</span></li>
<li><span class="Apple-style-span" style="font-family: inherit;">Pin 53: Señal SS, aunque se pueden usar otros pines para este fin. Esto puede ser útil por ejemplo en el caso de tener varios dispositivos conectados en un mismo bus.</span></li>
</ul><span class="Apple-style-span" style="font-family: inherit;"><br />
</span><br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: inherit; font-size: small;">La configuración por defecto del protocolo SPI en Arduino establece que el esclavo será él mismo, que se van a transferir en primer lugar los bytes más significativos de cada byte (MSB), que el modo seleccionado es el 0 y se establece la frecuencia de reloj en una cuarta parte de la frecuencia del sistema. Veamos las distintas funciones disponibles para modificar estos parámetros:<o:p></o:p></span></div><div class="MsoListParagraphCxSpFirst" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"></div><ul><li><span class="Apple-style-span" style="font-family: inherit;"><b style="mso-bidi-font-weight: normal;">mode (byte config). </b>Permite modificar el registro de configuración del SPI. Si hay varios dispositivos usando SPI y cada uno necesita un modo distinto, esta función se deberá llamar antes de acceder a cada dispositivo en particular. Veamos dos ejemplos de uso:</span></li>
<ul><li><span class="Apple-style-span" style="font-family: inherit;"><b style="mso-bidi-font-weight: normal;">Spi.mode( (1<<CPOL) | (1<<CPHA) ). </b>Establece el modo 3</span></li>
<li><span class="Apple-style-span" style="font-family: inherit;"><b style="mso-bidi-font-weight: normal;">Spi.mode( (1<<SPR0) ). </b>Configura el reloj SCK a 1/16 la velocidad del reloj del sistema.</span></li>
</ul><li><span class="Apple-style-span" style="font-family: inherit;"><b style="mso-bidi-font-weight: normal;">Byte transfer(byte b). </b>Envía y recibe un byte a través del bus SPI. Por ejemplo:</span></li>
<ul><li><span class="Apple-style-span" style="font-family: inherit;"><b style="mso-bidi-font-weight: normal;">n = Spi.transfer( 0x2A ). </b>Envía el byte 0x2A y devuelve lo que reciba del otro dispositivo.</span></li>
</ul><li><span class="Apple-style-span" style="font-family: inherit;"><b style="mso-bidi-font-weight: normal;">Byte.transfer(byte b, byte delay). </b>Esta función es idéntica a la anterior, sólo que antes de acometer la operación espera un número de microsegundos especificados en el parámetro delay. Es útil cuando hay que esperar un tiempo antes de iniciar una transferencia de datos.</span></li>
</ul><span class="Apple-style-span" style="font-family: inherit;"><br />
</span><br />
<span class="Apple-style-span" style="font-family: inherit;"><br />
</span><br />
<span class="Apple-style-span" style="font-family: inherit;"><br />
</span><br />
<span class="Apple-style-span" style="font-family: inherit;">--------------------------------------------</span><br />
<b><span class="Apple-style-span" style="font-family: inherit;">Referencias:</span></b><br />
<b><span class="Apple-style-span" style="font-family: inherit;"> <br />
<style>
<!--
/* Font Definitions */
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
a:link, span.MsoHyperlink
{mso-style-unhide:no;
mso-style-parent:"";
color:blue;
text-decoration:underline;
text-underline:single;}
a:visited, span.MsoHyperlinkFollowed
{mso-style-noshow:yes;
mso-style-priority:99;
color:purple;
mso-themecolor:followedhyperlink;
text-decoration:underline;
text-underline:single;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
-->
</style> </span></b><br />
<div class="MsoNormal" style="margin-left: 36.0pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><span class="MsoHyperlink"><span style="color: windowtext;">Serial Peripheral Interface Bus (SPI). </span></span><a href="http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus">http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus</a><span class="MsoHyperlink"><span style="color: windowtext;"><o:p></o:p></span></span></span></div><div class="MsoNormal" style="margin-left: 36pt;"><span class="Apple-style-span" style="font-family: inherit; font-size: small;"><span class="MsoHyperlink"><span style="color: windowtext;">SPI Arduino library. </span></span><a href="http://www.arduino.cc/playground/Code/Spi">http://www.arduino.cc/playground/Code/Spi</a></span><span class="MsoHyperlink" style="font-weight: bold;"><span style="color: windowtext;"><o:p></o:p></span></span></div>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com2tag:blogger.com,1999:blog-754387214278989398.post-64284920246575442152011-06-12T10:52:00.000-07:002011-06-12T11:00:21.996-07:00Arduino y la comunicación serie: librería Serial<style>
<!--
/* Font Definitions */
@font-face
{font-family:"Courier New";
panose-1:2 7 3 9 2 2 5 2 4 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536859905 -1073711037 9 0 511 0;}
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
/* List Definitions */
@list l0
{mso-list-id:1448818088;
mso-list-type:hybrid;
mso-list-template-ids:2057584918 -847460270 201981955 201981957 201981953 201981955 201981957 201981953 201981955 201981957;}
@list l0:level1
{mso-level-start-at:2;
mso-level-number-format:bullet;
mso-level-text:-;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Verdana;
mso-fareast-font-family:"Times New Roman";
mso-bidi-font-family:"Times New Roman";}
@list l0:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level3
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level4
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level5
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level6
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level7
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level8
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level9
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->
</style> <br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;">Todas las placas de Arduino disponen de al menos un puerto serie, que permite la comunicación con un ordenador o con otros dispositivos haciendo uso de esta interfaz. Los pines que se usan para la comunicación por puerto serie vienen marcados en la placa con las siglas RX y TX, que corresponden al pin por el que se enviarán los datos, y al pin por el que se recibirán los datos respectivamente.<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;">En el caso que nos ocupa, usaremos el puerto serie no para comunicarnos con un ordenador, sino para poder comunicarnos con determinados sensores. En este epígrafe se expondrán las funciones necesarias para establecer la comunicación e intercambiar datos, y en el capítulo cuarto se verán ejemplos de sensores conectados por el puerto serie.<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><b style="mso-bidi-font-weight: normal;">Conexiones<o:p></o:p></b></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;">Como se ha comentado en la introducción de este epígrafe, se van a usar los pines TX y RX de la placa de Arduino. En las pruebas realizadas se ha usado la placa “Arduino Mega 2560”, la cual dispone de 8 pines destinados para ello, en lugar de los 2 de los que disponen el resto de placas. Estos pines vienen marcados en la placa y son las siguientes parejas (0,1), (14,15), (16,17), (18,19) y (20,21).<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;">Para un correcto funcionamiento, se debe conectar el pin de recepción de la placa (RX) al pin de transmisión del dispositivo externo, y el pin de transmisión de la placa (TX) al pin de recepción de dicho dispositivo. Además, para comunicar el sistema de desarrollo con un dispositivo TTL es necesario conectar las tierras entre ellas.<o:p></o:p></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><b style="mso-bidi-font-weight: normal;">Principales funciones<o:p></o:p></b></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;">Las principales funciones usadas en la comunicación por puerto serie vienen incluidas en la librería Serial() y son las siguientes:<o:p></o:p></div><div class="MsoListParagraphCxSpFirst" style="text-align: justify; text-indent: -18pt;"><div style="line-height: 150%;"></div><ul><li><b style="line-height: 150%;">Serial.begin(velocidad). </b><span class="Apple-style-span" style="line-height: 150%;">Establece la velocidad en bits por segundo (baudios) para la transmisión de datos en serie.</span></li>
<li><span class="Apple-style-span" style="line-height: 24px;">El </span><span class="Apple-style-span" style="line-height: 24px;">parámetro velocidad se puede configurar con el valor que se desee para comunicarse con un dispositivo externo (hasta un máximo de 115200 baudios), sin embargo si la comunicación por puerto serie va a ser con un ordenador, se deberá elegir una de las siguientes: 300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600 o 115200.</span></li>
<li><span class="Apple-style-span" style="line-height: 24px;"><b style="mso-bidi-font-weight: normal;">Serial.end(). </b></span>Desactiva la comunicación serie, permitiendo que los pines de recepción y transmisión puedan ser usados como pines de entrada / salida digitales. Si se desee reanudar la comunicación serie, se deberá invocar nuevamente Serial.begin().</li>
<li><span class="Apple-style-span" style="line-height: 24px;"><b style="mso-bidi-font-weight: normal;">Serial</b>.<b style="mso-bidi-font-weight: normal;">available().</b></span><span class="Apple-style-span" style="line-height: 24px;"> Devuelve, ecomo entero, el número de bytes (caracteres) disponibles para ser leídos por el puerto serie. Se refiere a datos ya recibidos y disponibles en el buffer de recepción del puerto, cuya capacidad es de 128 bytes. En el caso de Arduino Mega, existen además las funciones Serial1.available(), Serial2.available() y Serial3.available().</span></li>
<li><span class="Apple-style-span" style="line-height: 24px;"><b style="mso-bidi-font-weight: normal;">Serial.read(). </b></span><span class="Apple-style-span" style="line-height: 24px;">Lee los datos entrantes al puerto serie. Devuelve como entero el primer byte disponible recibido por el puerto serie, o -1 si no hay datos disponibles. Al igual que en el caso anterior, para la placa Arduino Mega existen también las funciones Serial1.read(), Serial2.read() y Serial3.read().</span></li>
<li><span class="Apple-style-span" style="line-height: 24px;"><b style="mso-bidi-font-weight: normal;">Serial.flush(). </b></span><span class="Apple-style-span" style="line-height: 24px;">Vacía el buffer de la entrada de datos serie. Esto quiere decir que si se llama a la función Serial.read() o Serial.available(), estas sólo devolverán los datos recibidos después de que se haya realizado esta llamada. No requiere parámetros ni devuelve nada. Para la placa Arduino Mega existen disponibles las llamadas Serial1.flush(), Serial2.flush() y Serial3.flush() además de la principal.</span></li>
<li><span class="Apple-style-span" style="line-height: 24px;"><b style="mso-bidi-font-weight: normal;">Serial.print(valor, formato). </b></span><span class="Apple-style-span" style="line-height: 24px;">Esta función imprime los datos al puerto serie como texto ASCII. El primer parámetro, valor, es el propio valor que se desea imprimir. Esto se podrá realizar de distintas formas:</span></li>
<ul><li><span class="Apple-style-span" style="line-height: 24px;">Los números son impresos mediante un juego de caracteres ASCII para cada dígito.</span></li>
<li><span class="Apple-style-span" style="line-height: 24px;">Los valores de tipo flotante (float) se imprimen en forma de dígitos ASCII con 2 decimales por defecto, es decir, si ejecutamos Serial.print(1.23456) se imprimirá “1.23”.</span></li>
<li><span class="Apple-style-span" style="line-height: 24px;">Los valores de tipo “byte” se enviarán como un único carácter.</span></li>
<li><span class="Apple-style-span" style="line-height: 24px;">Los caracteres y las cadenas se enviarán tal cual.</span></li>
</ul><li><span class="Apple-style-span" style="line-height: 24px;">Además, existe el segundo parámetro es opcional y permite especificar el formato que se desea usar. Así, este parámetro puede tomar el valor BYTE, BIN (valores binarios, en base 2), DEC (valores decimales, en base 10), HEX (valores hexadecimales, en base 16). Si lo que se está imprimiendo son números con coma flotante, este parámetro especificará el número de decimales a usar.</span></li>
<li><span class="Apple-style-span" style="line-height: 24px;"><b style="mso-bidi-font-weight: normal;">Serial.println(valor, formato). </b></span><span class="Apple-style-span" style="line-height: 24px;">Imprime los datos al puerto serie como texto ASCII seguido de un retorno de carro(ASCII 13 o ‘\r’) y un carácter de avance de línea (ASCII 10 o ‘\n’). Por lo demás, este comando tiene la misma forma y los mismos parámetros que Serial.print() descrito anteriormente.</span></li>
<li><span class="Apple-style-span" style="line-height: 24px;"><span style="font-family: Verdana;"><span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span></span><b style="mso-bidi-font-weight: normal;">Serial.write(). </b></span><span class="Apple-style-span" style="line-height: 24px;">Esta función escribe datos binarios en el puerto serie. Estos se enviarán como un byte o como una serie de bytes. Si lo que se desea es envíar los caracteres que representan los números, es mejor usar la función Serial.print() en su lugar. Puede tomar distintos parámetros:</span></li>
<ul><li><span class="Apple-style-span" style="line-height: 24px;">Serial.write(valor) enviará un solo byte.</span></li>
<li><span class="Apple-style-span" style="line-height: 24px;">Serial.write(str) enviará una cadena como una serie de bytes.</span></li>
<li><span class="Apple-style-span" style="line-height: 24px;">Serial.write(buf, len) enviará un array como una serie de bytes. El tamaño del array se indicará en el segundo parámetro.</span></li>
</ul></ul><span class="Apple-style-span" style="line-height: 150%;"><o:p></o:p></span><br />
<div style="line-height: 150%;"></div></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 72.0pt; mso-add-space: auto; mso-list: l0 level2 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 72.0pt; mso-add-space: auto; mso-list: l0 level2 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 72.0pt; mso-add-space: auto; mso-list: l0 level2 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 72.0pt; mso-add-space: auto; mso-list: l0 level2 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 72.0pt; mso-add-space: auto; mso-list: l0 level2 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; text-align: justify;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 72.0pt; mso-add-space: auto; mso-list: l0 level2 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 72.0pt; mso-add-space: auto; mso-list: l0 level2 lfo1; text-align: justify; text-indent: -18.0pt;"><o:p></o:p></div><div class="MsoListParagraphCxSpLast" style="line-height: 150%; margin-left: 72.0pt; mso-add-space: auto; mso-list: l0 level2 lfo1; text-align: justify; text-indent: -18.0pt;">--------------------------------------------------------------------------</div><div class="MsoListParagraphCxSpLast" style="line-height: 150%; margin-left: 72.0pt; mso-add-space: auto; mso-list: l0 level2 lfo1; text-align: justify; text-indent: -18.0pt;"><b>Referencias</b>: <span class="Apple-style-span" style="font-family: Times; font-size: small; line-height: normal;"><span class="MsoHyperlink"><span style="color: windowtext; font-family: Cambria; font-size: 12pt;">Arduino Serial library. </span></span></span><span class="Apple-style-span" style="font-family: Times; font-size: small; line-height: normal;"><span style="color: black; font-family: Cambria; font-size: 12pt;"><a href="http://arduino.cc/es/Reference/Serial">http://arduino.cc/es/Reference/Serial</a></span></span></div><style>
<!--
/* Font Definitions */
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
a:link, span.MsoHyperlink
{mso-style-unhide:no;
mso-style-parent:"";
color:blue;
text-decoration:underline;
text-underline:single;}
a:visited, span.MsoHyperlinkFollowed
{mso-style-noshow:yes;
mso-style-priority:99;
color:purple;
mso-themecolor:followedhyperlink;
text-decoration:underline;
text-underline:single;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
-->
</style> <br />
<div class="MsoListParagraphCxSpLast" style="line-height: 150%; margin-left: 72.0pt; mso-add-space: auto; mso-list: l0 level2 lfo1; text-align: justify; text-indent: -18.0pt;"><br />
</div><div class="MsoListParagraphCxSpLast" style="line-height: 150%; margin-left: 72.0pt; mso-add-space: auto; mso-list: l0 level2 lfo1; text-align: justify; text-indent: -18.0pt;"><br />
</div>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-38697316339668436252011-06-12T10:07:00.000-07:002011-06-12T10:07:06.752-07:00Sentencias NMEAPara poder entender el funcionamiento del receptor GPS que explicará a continuación, explicaremos primero en qué consisten las sentencias NMEA y cuáles son sus principales campos.<br />
<br />
Las siglas NMEA son las siglas en inglés de la Asociación de Marina y Electrónica Nacional, es decir, la “National Marine Electronic Asociation). Esta asociación americana, fue la primera en establecer un protocolo normalizado de comunicación entre equipos y dispositivos de navegación. A modo de reseña histórica, comentar que el primer protocolo en aparecer fue el NMEA 180 simple, que permitía a los barcos transmitir datos a un piloto automático del grado de desviación a babor o a estribor con respecto a una trayectoria predeterminada. Más tarde, aparecieron los protocolos NMEA 180 complejo y el NMEA 182, que mejoraban al primero incluyendo datos de geolocalización.<br />
El protocolo más usado actualmente, y el que usa nuestro GPS Venus, es el NMEA-183 cuyas principales secuencias se describen a continuación.<br />
<br />
<b>GGA - Global Positioning System Fix Data</b><br />
<b><br />
</b><br />
Este tipo de mensajes incluye información sobre el tiempo, la posición, y otros datos relativos al posicionamiento de un receptor GPS.<br />
La estructura de estos mensajes es la siguiente:<br />
<br />
<i>$GPGGA,hhmmss.sss,ddmm.mmmm,a,dddmm.mmmm,b,x,yy,z.z,x.x,M,,,,xxxx*hh</i><cr><lf><i><br />
</i> <br />
Veamos a continuación lo que significa cada campo:</lf></cr><br />
<ul><li>hhmmss.sss: Tiempo en formato UTC (Universal Coordinate Time).</li>
<li>ddmm.mmmm: Latitud. Se rellena con ceros por la izquierda.</li>
<li>a: Indica el hemisferio de la latitud (N o S según sea latitud Norte o Sur).</li>
<li>ddmm.mmmm: Longitud. Se rellena con ceros por la izquierda.</li>
<li>b: Indica el hemisferio de la longitud (E o W según la longitud sea Este u Oeste)</li>
<li>x: Indica la calidad del GPS</li>
<ul><li>0: no se ha podido obtener la posición</li>
<li>1: posición GPS válida. Modo SPS.</li>
<li>2: posición GPS váida. Modo GPS diferencial</li>
<li>3: posición GPS válida. Modo PPS.</li>
<li>4: Modo “Real Time Kinematic”.</li>
<li>5: Modo “Floating RTK”.</li>
<li>6: Modo de estimación</li>
<li>7: Modo de entrada de datos manual</li>
<li>8: Modo simulación</li>
</ul><li>yy: Número de satélites usados</li>
<li>z.z: Parámetro HOPD. Nos da la precisión horizontal</li>
<li>x.x: Altitud con respecto al nivel del mar</li>
<li>Finalmente, nos ofrece otros parámetros como el identificador de la estación GPS de referencia y un checksum para comprobar la correcta recepción de los datos.</li>
</ul><cr><lf><b> GLL – Latitude / Longitude</b><br />
Estos mensajes transmiten información sobre la latitud y la longitud de la posición actual, así como sobre el tiempo y el estado de la conexión. La estructura es la siguiente:<br />
<br />
<i> $GPGLL,ddmm.mmmm,a,dddmm.mmmm,b,hhmmss.sss,A,a*hh</i><cr><lf><i><br />
</i> <br />
Y veamos lo que significa cada campo:<br />
<ul><li>ddmm.mmmm: Latitud. Se rellena con ceros por la izquierda</li>
<li>a: Indica el hemisferio (N si es el hemisferio Norte, y S si es el Sur)</li>
<li>dddmm.mmmm: Longitud. Se rellena con ceros por la izquierda</li>
<li>b: Indica el hemisferio Este (E) u Oeste (W)</li>
<li>hhmmss.sss: Tiempo en formato UTC</li>
<li>A: Estado. Si muestra una ‘A’, los datós son válidos y si muestra una ‘V’ son inválidos.</li>
<li>a: Indicador del modo. Puede contener:</li>
<ul><li>N: Datos no válidos</li>
<li>A: Modo autónomo</li>
<li>D: Modo diferencial</li>
<li>E: Modo estimado</li>
<li>M: Entrada de datos de forma manual</li>
<li>S: Modo simulación</li>
</ul><li>Finalmente se incluye información de checksum</li>
</ul></lf></cr></lf></cr><cr><lf><cr><lf><b> GSA – GNSS DOP and Active Satellites</b><br />
</lf></cr></lf></cr><br />
<cr><lf><cr><lf>Indica el modo de operación del receptor GPS, los satélites usados para la navegación proporcionados por las sentencias GGA o GNS y los valores DOP. La estructura es la siguiente:<br />
<br />
<i> $GPGSA,A,a,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,x.x,x.x,x.x*hh</i><cr><lf><i><br />
</i> </lf></cr></lf></cr></lf></cr><cr><lf><cr><lf><cr><lf> Y la correspondencia de cada campo:<br />
</lf></cr></lf></cr></lf></cr><br />
<br />
<ul><li>A: Si contiene una ‘M’ estamos en modo manual, forzando el funcionamiento en 2D o en 3D, mientras que si contiene una ‘A’, se está en el modo automático, con selección 2D/3D automática</li>
<li>a: Si contiene un ‘1’ es que no ha sido posible obtener información sobre si se encuentra en modo 2D o 3D. El ‘2’ representa el modo 2D, mientras que el ‘3’ representa el modo 3D. </li>
<li>Los siguientes datos corresponden a los identificadores de los satélites (puede haber 12 satélites con identificadores comprendidos entre 01 y 32), seguidos de la precisión de posición, de la precisión horizontal y de la precisión vertical</li>
<li>El último campo corresponde al checksum</li>
</ul><cr><lf><cr><lf><cr><lf> <br />
<b> GSV – GNSS Satellites in View</b><br />
</lf></cr></lf></cr></lf></cr><div><cr><lf><cr><lf><cr><lf>Estas sentencias nos proporcionan información sobre el número de satélites que el GPS está “viendo” en ese momento, con sus respectivos identificadores, ángulos de azimuth, elevación y relación señal a ruido. Habrá un máximo de 4 satélites por sentencia. Su estructura es la siguiente:<br />
<i><br />
$GPGSV,N,s,yy,xx,xx,xxx,xx,…,xx,xx,xxx,xx *hh</i><cr><lf><i><br />
</i> <br />
Estos campos corresponden a:<br />
<br />
</lf></cr></lf></cr></lf></cr></lf></cr></div><div><ul><li>N: Indica cuántas sentencias de este tipo se van a transmitir (tomará por tanto valores de entre 1 y 3).</li>
<li>s: Número de secuencia</li>
<li>yy: Número de satélites que se están viendo en ese momento</li>
<li>Los datos siguientes son:</li>
<ul><li>Los identificadores de cada uno de los satélites</li>
<li>Su elevación</li>
<li>Su azimuth</li>
<li>Su relación señal a ruido, que valdrá cero si no se está logrando una correcta conexión.</li>
<li>Checksum</li>
</ul></ul><cr><lf><cr><lf><cr><lf><cr><lf><b> RMC – Recommended Minimum Specific GNSS Data</b><br />
</lf></cr></lf></cr></lf></cr></lf></cr></div><div><cr><lf><cr><lf><cr><lf><cr><lf>Nos proporcionan información sobre la hora, la fecha, el rumbo y la velocidad proporcionados por el receptor GNSS. Su estructura es la siguiente:<br />
<br />
<i> $GPRMC,hhmmss.sss,A,dddmm.mmmm,a,dddmm.mmmm,a,x.x,y.y,ddmmyy,,,a*hh</i><cr><lf><i><br />
</i> <br />
Veamos la explicación de los campos:<br />
<ul><li>hhmmss.sss: Hora en formato UTC</li>
<li>A: Estado. Si contiene una ‘A’ es que los datos son válidos, mientras que si contiene una ‘V’ es que se está produciendo algún problema</li>
<li>dddmm.mmmm: Son los datos de la latitud. Se rellena con ceros pos la izquierda.</li>
<li>a: Indicador de Norte (N) o Sur (S)</li>
<li>dddmm.mmmm: Datos de la longitud. Se rellena con ceros por la izquierda.</li>
<li>a: Indicador de Este (E) u Oeste (W)</li>
<li>x.x: Velocidad en nudos con respecto al suelo</li>
<li>y.y: Rumbo en grados con respecto a la horizontal</li>
<li>ddmmyy: Se transmite una actualización de la fecha en formato UTC</li>
<li>a: Indicador del modo. Puede contener:</li>
<ul><li>N: Datos no válidos</li>
<li>A: Modo autónomo</li>
<li>D: Modo diferencial</li>
<li>E: Modo de estimación</li>
<li>M: Modo de entrada de datos maual</li>
<li>S: Modo de simulación</li>
</ul><li>Finalmente se transmiere la información de checksum</li>
</ul><b> VTG – Course Over Ground and Ground Speed</b><br />
</lf></cr></lf></cr></lf></cr></lf></cr></lf></cr></div><div><cr><lf><cr><lf><cr><lf><cr><lf><cr><lf>Estas sentencias proporcionan información del rumbo y la velocidad con respecto al suelo. Su estructura es la siguiente:<br />
<i><br />
GPVTG,x.x,T,,M,x.x,N,x.x,K,a*hh</i><cr><lf><i><br />
</i> <br />
Y veamos cada campo:</lf></cr></lf></cr></lf></cr></lf></cr></lf></cr></lf></cr></div><div><ul><li>x.x: Rumbo en grados</li>
<li>T: Velocidad sobre el suelo en nudos</li>
<li>M: Velocidad sobre el sueño en kilómetros por hora</li>
<li>A: Indicador de modo. Puede contener:</li>
<ul><li>N: Datos no válidos</li>
<li>A: Modo autónomo</li>
<li>D: Modo diferencial</li>
<li>E: Modo de estimación</li>
<li>M: Modo de entrada de datos manual</li>
<li>S: Modo de simulación</li>
</ul><li>Finalmente se transfiere información de checksum.</li>
</ul><br />
<br />
<br />
<br />
</div>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-6230132115964056142011-06-12T09:51:00.000-07:002011-06-14T08:47:30.537-07:00Lector RFID ID-20 y su conexión con Arduino y el NXT<style>
<!--
/* Font Definitions */
@font-face
{font-family:"Courier New";
panose-1:2 7 3 9 2 2 5 2 4 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536859905 -1073711037 9 0 511 0;}
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:"MS ゴシック";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1791491579 18 0 131231 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
h3
{mso-style-qformat:yes;
mso-style-link:"Título 3 Car";
mso-style-next:Normal;
margin-top:10.0pt;
margin-right:0cm;
margin-bottom:0cm;
margin-left:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan lines-together;
page-break-after:avoid;
mso-outline-level:3;
font-size:13.0pt;
mso-bidi-font-size:12.0pt;
font-family:"Times New Roman";
mso-fareast-font-family:"MS ゴシック";
mso-fareast-theme-font:major-fareast;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:major-bidi;
mso-fareast-language:EN-US;}
p.MsoCaption, li.MsoCaption, div.MsoCaption
{mso-style-qformat:yes;
mso-style-next:Normal;
margin-top:0cm;
margin-right:0cm;
margin-bottom:10.0pt;
margin-left:0cm;
mso-pagination:widow-orphan;
font-size:9.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:#4F81BD;
mso-themecolor:accent1;
mso-fareast-language:EN-US;
font-weight:bold;}
p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
span.Ttulo3Car
{mso-style-name:"Título 3 Car";
mso-style-unhide:no;
mso-style-locked:yes;
mso-style-link:"Título 3";
mso-ansi-font-size:13.0pt;
font-family:"MS ゴシック";
mso-fareast-font-family:"MS ゴシック";
mso-fareast-theme-font:major-fareast;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:major-bidi;
mso-fareast-language:EN-US;
font-weight:bold;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
/* List Definitions */
@list l0
{mso-list-id:1448818088;
mso-list-type:hybrid;
mso-list-template-ids:2057584918 -847460270 201981955 201981957 201981953 201981955 201981957 201981953 201981955 201981957;}
@list l0:level1
{mso-level-start-at:2;
mso-level-number-format:bullet;
mso-level-text:-;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Verdana;
mso-fareast-font-family:"Times New Roman";
mso-bidi-font-family:"Times New Roman";}
@list l0:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level3
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level4
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level5
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level6
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level7
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level8
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level9
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->
</style> <br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="color: windowtext; font-family: 'Times New Roman';">El segundo sensor con el que se han realizado pruebas ha sido el lector de tarjetas RFID ID-20 de la empresa ID Innovations. Se trata de un pequeño módulo con antena incorporada, que detecta cuando se le acerca un tag RFID y devuelve a través del puerto serie su código de identificación. Las principales características de este dispositivo, que podemos ver en la figura de abajo, se listan a continuación:<o:p></o:p></span></div><div class="MsoListParagraphCxSpFirst" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><span style="color: windowtext; font-family: Verdana;">-<span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span></span><span style="color: windowtext; font-family: 'Times New Roman';">Alimentación de 5 V<o:p></o:p></span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><span style="color: windowtext; font-family: Verdana;">-<span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span></span><span style="color: windowtext; font-family: 'Times New Roman';">Frecuencia de lectura: 125 KHz<o:p></o:p></span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><span style="color: windowtext; font-family: Verdana;">-<span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span></span><span style="color: windowtext; font-family: 'Times New Roman';">Permite conexiones en serie a 9600 baudios y con puertos de tipo RS-232<o:p></o:p></span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><span style="color: windowtext; font-family: Verdana;">-<span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span></span><span style="color: windowtext; font-family: 'Times New Roman';">Es capaz de leer los tags RFID a una distancia de 200 mm aproximadamente<o:p></o:p></span></div><div class="MsoListParagraphCxSpLast" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><span style="color: windowtext; font-family: Verdana;">-<span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span></span><span style="color: windowtext; font-family: 'Times New Roman';">El tamaño del dispositivo es de 38x70x7 mm.</span></div><div align="center" class="MsoNormal" style="line-height: 150%; margin-left: 18.0pt; page-break-after: avoid; text-align: center;"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEga75Klxk7PAAZZG5hW3ExwpF-a_Kk8utRUM4lfl7DMK3ms4YrjteIb1kYHjWmHndZCGM7PLRSqBKEOaHtzjFQEJamRcgKPLi733kwGo27FW7DdeKpiGAR7IOH_B75HPbUuuM3K_0DG1mav/s1600/1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEga75Klxk7PAAZZG5hW3ExwpF-a_Kk8utRUM4lfl7DMK3ms4YrjteIb1kYHjWmHndZCGM7PLRSqBKEOaHtzjFQEJamRcgKPLi733kwGo27FW7DdeKpiGAR7IOH_B75HPbUuuM3K_0DG1mav/s1600/1.jpg" /></a></div><span style="font-family: 'Times New Roman';"><br clear="all" style="mso-special-character: line-break;" /> <o:p></o:p></span></div><div align="center" class="MsoCaption" style="text-align: center;"><span style="font-family: 'Times New Roman';">Figura </span><span style="font-family: 'Times New Roman';"> Lector RFID ID-20</span><span style="color: windowtext; font-family: 'Times New Roman';"><o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36.0pt;"><span style="font-family: 'Times New Roman';">Para facilitar la integración de este lector con Arduino, y para poder hacer pruebas pinchándolo directamente sobre una placa de prototipos, se ha usado también una base con conector USB como la que se ve en la figura siguiente:<o:p></o:p></span></div><div align="center" class="MsoNormal" style="line-height: 150%; page-break-after: avoid; text-align: center; text-indent: 36.0pt;"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTDW4fhD5KOhtPQmdY1xY0HVyFKxvH7sDefgKTv36CGDXtPk1Rn8Z8lOlp_mhbv-jqiHO-b1htZ9kUmRehifrLhDEcPwVDs9e_A0A_Nkl8reCOAJjxxeJLElTD7Ys15M43tkarRi3HHwqW/s1600/2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTDW4fhD5KOhtPQmdY1xY0HVyFKxvH7sDefgKTv36CGDXtPk1Rn8Z8lOlp_mhbv-jqiHO-b1htZ9kUmRehifrLhDEcPwVDs9e_A0A_Nkl8reCOAJjxxeJLElTD7Ys15M43tkarRi3HHwqW/s1600/2.jpg" /></a></div><span class="Apple-style-span" style="font-family: 'Times New Roman';"><br />
</span></div><div align="center" class="MsoCaption" style="text-align: center;"><span style="font-family: 'Times New Roman';">Figura</span><span style="font-family: 'Times New Roman';"> Lector RFID USB</span><span style="font-family: 'Times New Roman';"><o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36.0pt;"><span style="font-family: 'Times New Roman';">Como se aprecia en la figura anterior, esta placa tiene un zócalo que permite insertar el lector ID-20. Además de permitir la transferencia de datos mediante el puerto USB, esta placa sigue permitiendo la transmisión de datos vía serie con la misma configuración antes mencionada. Además, la placa consta de un pequeño zumbador para avisar de que ha leído un tag RFID, así como de un led que se encenderá cuando ésta se encuentre alimentada.<o:p></o:p></span></div><h3 style="line-height: 150%;">Conexiones entre el dispositivo y Arduino<o:p></o:p></h3><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36.0pt;"><span style="font-family: 'Times New Roman';">Las conexiones que se han realizado han sido las siguientes: <o:p></o:p></span></div><div class="MsoListParagraphCxSpFirst" style="line-height: 150%; mso-list: l0 level1 lfo1; text-align: justify; text-indent: -18.0pt;"><br />
<ul><li><span style="font-family: 'Times New Roman';"> El</span><span class="Apple-style-span" style="font-family: 'Times New Roman';"> dispositivo necesita para funcionar una tensión de alimentación de 5 V, por lo que en el caso de querer alimentarlo exclusivamente con la placa de Arduino, se deberá conectar el pin de 5 V del mismo con el pin VCC de la placa RFID USB.</span></li>
<li><span style="font-family: Verdana;"><span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span></span><span style="font-family: 'Times New Roman';">Los pines de tierra de la placa USB se conectarán a cualquiera de las tierras que ofrece Arduino.</span></li>
<li><span style="font-family: Verdana;"><span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span></span><span style="font-family: 'Times New Roman';">El pin TX de la placa USB es aquel por el que se enviarán los datos que posteriormente Arduino recibirá y procesará. Dicho pin deberá conectarse con el pin RX0 de Arduino, que en el caso de Arduino Mega 2560 es el pin 0.</span></li>
<li><span style="font-family: Verdana;"><span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span></span><span style="font-family: 'Times New Roman';">El resto de pines no es necesario conectarlos, aunque si se quisiera un mayor alcance de recepción de datos podría incorporarse una antena al pin AN1 o al AN2 de la placa.</span></li>
</ul></div><h3>Código cargado en Arduino<o:p></o:p></h3><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: 'Times New Roman';">La función que realiza el código que se muestra a continuación es, tras configurar la conexión por puerto serie a una velocidad de 9600 baudios, esperar a que el dispositivo le devuelva un identificador RFID válido. Esto ocurre cuando se acerca un tag válido al lector.<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: 'Times New Roman';">Para identificar que el valor recibido es correcto, se ha tenido en cuenta que los tags se reciben como una cadena de caracteres que siempre empieza con el valor “02” y termina con el valor “03”. Todo lo que se reciba entre estos dos valores forma parte del identificador.<o:p></o:p></span><br />
<span style="font-family: 'Times New Roman';"> <style>
<!--
/* Font Definitions */
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
-->
</style> </span><br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: 'Times New Roman';"><span style="font-family: 'Times New Roman';">Además, este código recibido se almacena en el array denominado “buffersalida” que será enviado al NXT. El procedimiento para prepararlo y enviarlo es similar al que ya se vio en el caso del IMU presentado en el apartado 5.1, sólo que en esta ocasión los datos se transmiten como bytes.<o:p></o:p></span></span></div><span style="font-family: 'Times New Roman';"> </span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: 'Times New Roman';">El código implementado es el siguiente:</span><br />
<span style="font-family: 'Times New Roman';"><br />
</span><br />
<span style="font-family: 'Times New Roman';"> <style>
<!--
/* Font Definitions */
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
-->
</style> </span><br />
<table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="border-collapse: collapse; border: none; mso-border-alt: solid windowtext .5pt; mso-padding-alt: 0cm 5.4pt 0cm 5.4pt; mso-yfti-tbllook: 1184;"><tbody>
<tr style="mso-yfti-firstrow: yes; mso-yfti-irow: 0; mso-yfti-lastrow: yes;"> <td style="background: #F2F2F2; border: solid windowtext 1.0pt; mso-background-themecolor: background1; mso-background-themeshade: 242; mso-border-alt: solid windowtext .5pt; padding: 0cm 5.4pt 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">#include <Wire.h> //Para gestionar las comunicaciones<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">//Definiciones y variables globales<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">uint8_t SensorVersion[9] = " V0.1 ";<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">uint8_t SensorName[9] = "RFIDReadr";<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">uint8_t SensorType[9] = "RFID ";<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">byte buffersalida[] = { 0, 0, 0, 0, 0, 0}; //Para enviar al RCX<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">byte buffrfid[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //Para el tag<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">//uint8_t buffrfid[13];<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">int val = 0; //Datos que se leeran del acelerometro o giroscopo<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">unsigned long timer=0; //timer<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">unsigned long delta_t; //delta o tiempo entre muestras <o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">byte rec;<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">void setup(){<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> <o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Serial.begin(9600);<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Wire.begin(1); //Nos unimos como esclavos con dir. 1<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Wire.onRequest(requestEvent); //Rutinas para cuando llegue algo<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Wire.onReceive(receiveEvent); <o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">}<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">void loop(){<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> char IDstring[13]; //Para almacenar el tag<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> int i;<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> <o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> if (Serial.available() > 0 ) {<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Serial.println("Tarjeta detectada");<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> if ( (val = Serial.read()) == 02 ) { // Se busca el inicio del codigo<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Serial.print("[SOT] ");<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> // Se lee hasta llegar al final<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> for ( i = 0; (val = Serial.read()) != 03 ; i++) {<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Serial.print(val, HEX);<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Serial.print(" ");<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> IDstring[i] = val;<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> buffrfid[i] = val;<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> }<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Serial.println("[EOT]");<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Serial.println();<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Serial.print(" IDString[");<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> IDstring[10] = 0x00; <o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Serial.print(IDstring);<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Serial.println("] ");<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Serial.println();<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">}<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> }<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> } <o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">void receiveEvent(int len){ //Devuelve el nº de bytes recibidos <o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> while (0 < Wire.available() ) {<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> rec = Wire.receive();<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> } //While<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">}<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">void requestEvent(){<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Serial.print(rec, BYTE);<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> if (rec == 0x00){ //Version del sensor<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Wire.send(SensorVersion, 8);<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> } else if (rec == 0x08){ //Nombre del sensor<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Wire.send(SensorName, 8);<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> } else if (rec == 0x10){ //Tipo del sensor<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Wire.send(SensorType, 8);<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> } else if (rec == 0x05) { // Lectura del tag<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Wire.send(buffrfid, 14);<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> } else {<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> buffersalida[0] = 0;<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> buffersalida[1] = 0;<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> Wire.send(buffersalida, 2);<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';"> }<o:p></o:p></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: 'Times New Roman';">} <o:p></o:p></span></div></td> </tr>
</tbody></table><span style="font-family: 'Times New Roman';"> </span><br />
<span style="font-family: 'Times New Roman';"><br />
</span><br />
<span style="font-family: 'Times New Roman';"><b>Código cargado en el NXT</b></span><br />
<span style="font-family: 'Times New Roman';"><b><br />
</b></span><br />
<span style="font-family: 'Times New Roman';"> <br />
<style>
<!--
/* Font Definitions */
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
-->
</style> </span><br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 14.2pt;"><span style="font-family: 'Times New Roman';"><span style="font-family: 'Times New Roman';">A continuación se muestra el código que se ha cargado en el NXT. Este código, similar al usado para recibir los datos del IMU que se conectaba a Arduino. Al igual que entonces, en primer lugar se procede a obtener los datos del sensor (versión, tipo e identificador), y a continuación se obtienen los tags que se vayan leyendo desde el lector. Para que la información de la lectura de los tags se muestre en hexadecimal, se hace la conversión de los bytes que vayan llegando usando las función <i>toHexString </i>propia de los tipos enteros. El código completo es el siguiente:<b><o:p></o:p></b></span></span></div><span style="font-family: 'Times New Roman';"> </span><br />
<table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="border-bottom-style: none; border-collapse: collapse; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-weight: bold;"><tbody>
<tr style="mso-yfti-firstrow: yes; mso-yfti-irow: 0; mso-yfti-lastrow: yes;"> <td style="background: #F2F2F2; border: solid windowtext 1.0pt; mso-background-themecolor: background1; mso-background-themeshade: 242; mso-border-alt: solid windowtext .5pt; padding: 0cm 5.4pt 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><b><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';">import</span></b><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> lejos.nxt.*; <o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><br />
</div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><b><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';">public</span></b><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> <b>class</b> ArduCom {<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><br />
</div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> <b>public</b> <b>static</b> <b>void</b> main(String[] args) <b>throws</b> Exception{ <o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> <b>byte</b> [] dato = <b>new</b> <b>byte</b>[15];<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> String Tipo = "";<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> String ID ="";<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> String Ver="";<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> String cad="";<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> <b>int</b> <u>err</u> = 0;<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> <o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> <b>for</b> (<b>int</b> i=0;i<dato.length;i++){<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> dato[i] = 0; <o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> }<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> <o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> I2CSensor Arduino = <b>new</b> I2CSensor(SensorPort.<i>S1</i>);<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> Arduino.setAddress(1); <o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> Ver = Arduino.getVersion();<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> System.<i>out</i>.println("Ver: "+Ver);<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> Tipo = Arduino.getSensorType();<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> System.<i>out</i>.println("Tipo: "+Tipo);<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> ID = Arduino.getProductID();<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> System.<i>out</i>.println("ID: "+ID);<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> Thread.<i>sleep</i>(1000);<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> <b>while</b> (!Button.<i>ESCAPE</i>.isPressed()) {<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> err = Arduino.getData(5, dato, 15);<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><br />
</div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> System.<i>out</i>.print("Tag: ");<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> <b>for</b>(<b>int</b> i=0; i<14;i++) {<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> <b>int</b> num = (<b>int</b>)dato[i];<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> cad = Integer.<i>toHexString</i>(num);<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> System.<i>out</i>.print(cad+" ");<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> }<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> Thread.<i>sleep</i>(1000);<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> System.<i>out</i>.println();<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> } //Fin <u>del</u> while<o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';"> } <o:p></o:p></span></div><div class="MsoNormal" style="mso-layout-grid-align: none; mso-pagination: none; text-autospace: none;"><span lang="ES" style="color: windowtext; font-family: 'Times New Roman';">}<o:p></o:p></span></div></td> </tr>
</tbody></table></div>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-15025439593310427482011-03-24T05:34:00.000-07:002011-03-25T06:24:06.176-07:00Primera comunicación NXT <--> Arduino <--> Sensor analógico<style>
<!--
/* Font Definitions */
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
-->
</style> <br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman";"> <span style="font-family: Times,"Times New Roman",serif; font-size: small;"> En esta entrada se va a describir cómo conectar sensores analógicos al NXT usando Arduino como intermediario. </span></span></div><div class="MsoNormal" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-size: small;">Aunque la conexión de sensores analógicos se puede hacer de manera directa a los puertos del NXT, cada sensor presenta unas resistencias de salida distintas, unos rangos de tensión y corriente distintos, y además, para poder conectar varios sensores a la misma entrada sería necesario un multiplexor y una circuitería que permitiera al robot elegir de qué sensor quiere leer. Todas estas funciones van a ser desempeñadas por Arduino, que será el encargado de leer los valores analógicos desde los sensores, hacer la conversión a digital, y mandar los datos al robot que éste necesite.</span></div><div style="font-family: Times,"Times New Roman",serif;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><b>Sensor analógico: Ardupilot 4 DOF</b></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><style>
<!--
/* Font Definitions */
@font-face
{font-family:"Courier New";
panose-1:2 7 3 9 2 2 5 2 4 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536859905 -1073711037 9 0 511 0;}
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
/* List Definitions */
@list l0
{mso-list-id:440034330;
mso-list-template-ids:821322494;}
@list l0:level1
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:36.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;
mso-ansi-font-size:10.0pt;
font-family:Symbol;}
@list l0:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:72.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;
mso-ansi-font-size:10.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level3
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:108.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;
mso-ansi-font-size:10.0pt;
font-family:Wingdings;}
@list l0:level4
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:144.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;
mso-ansi-font-size:10.0pt;
font-family:Wingdings;}
@list l0:level5
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:180.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;
mso-ansi-font-size:10.0pt;
font-family:Wingdings;}
@list l0:level6
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:216.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;
mso-ansi-font-size:10.0pt;
font-family:Wingdings;}
@list l0:level7
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:252.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;
mso-ansi-font-size:10.0pt;
font-family:Wingdings;}
@list l0:level8
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:288.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;
mso-ansi-font-size:10.0pt;
font-family:Wingdings;}
@list l0:level9
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:324.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;
mso-ansi-font-size:10.0pt;
font-family:Wingdings;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->
</style> </div><div class="MsoNormal" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: 18pt;"><span style="color: windowtext; font-size: small;">El Ardupilot 4 DOF es un IMU que proviene de un proyecto original de Chris Anderson y Jordi Muñoz para crear un AHRS (Attitude Heading Reference System) para control UAV y captura general de movimiento y orientación.</span></div><div class="MsoNormal" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: 18pt;"><span style="color: windowtext; font-size: small;">Ésta es la placa principal de sensores que se usa en la placa ArduPilot. Por si sola <b><span style="font-weight: normal;">proporciona 4 grados de libertad (4 DOF)</span> </b>y puede ser conectada directamente a sus pines analógicos o utilizado en cualquier otro proyecto que necesite de captura de movimiento sobre varios ejes.</span></div><div class="MsoNormal" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: 18pt;"><span style="color: windowtext; font-size: small;">El sensor viene equipado con un giroscopio LISY300AL de ±300°/s de un sólo eje y un acelerómetro ADXL335 de 3 ejes ±3g. Todo los componentes de filtrado están incorporados en la placa. No dispone de regulador de tensión, por lo que hay que aplicar una tensión de alimentación limpia de 3.3V.<br />
<br />
Las principales características de esta placa son:</span></div><ul style="font-family: Times,"Times New Roman",serif; text-align: justify;" type="disc"><li class="MsoNormal" style="color: windowtext; line-height: 150%;"><span style="font-size: small;">4 grados de libertad:</span></li>
<ul type="circle"><li class="MsoNormal" style="color: windowtext; line-height: 150%;"><span style="font-size: small;">ADXL335 - acelerómetro de 3 ejes, ±3g</span></li>
<li class="MsoNormal" style="color: windowtext; line-height: 150%;"><span style="font-size: small;">LISY300AL - giroscopio de un eje para velocidad angular, ±300°/s</span></li>
</ul><li class="MsoNormal" style="color: windowtext; line-height: 150%;"><span style="font-size: small;">Compatible con ArduPilot 6DOF daughter board</span></li>
<li class="MsoNormal" style="color: windowtext; line-height: 150%;"><span style="font-size: small;">Los valores analógicos de los seis ejes son accesibles</span></li>
<li class="MsoNormal" style="color: windowtext; line-height: 150%;"><span style="font-size: small;">Espaciado de pines: 0.1"</span></li>
<li class="MsoNormal" style="color: windowtext; line-height: 150%;"><span style="font-size: small;">Dimensiones: 2.3x1.5cm</span></li>
</ul><div class="MsoNormal" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: 18pt;"><span style="color: windowtext; font-size: small;">En las figura siguiente se puede ver tanto el tamaño de la placa, como las salidas que ésta nos ofrece:</span></div><div><div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div class="separator" style="clear: both; font-family: Times,"Times New Roman",serif; text-align: center;"><span style="font-size: small;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjevXJYLSKoCNXr6Ylq3nC7idnfqdEhsmE3-hFnTOm_5Hf0IsEkFOZV-xW2WWr1DfiRcx7uRzjmXDj9edcqeUoSGeNRQdgWoQdH94K62APYk_TazA0aSaEgGI_KtacRCOYDLUm2yIVa4Mcm/s1600/sensor-ardupilot-6-dof.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjevXJYLSKoCNXr6Ylq3nC7idnfqdEhsmE3-hFnTOm_5Hf0IsEkFOZV-xW2WWr1DfiRcx7uRzjmXDj9edcqeUoSGeNRQdgWoQdH94K62APYk_TazA0aSaEgGI_KtacRCOYDLUm2yIVa4Mcm/s320/sensor-ardupilot-6-dof.jpg" width="320" /></a></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div class="separator" style="clear: both; font-family: Times,"Times New Roman",serif; text-align: center;"><span style="font-size: small;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjatw5F4zzX2qzj5bbp_qtzXuYnPu2UDPhNVEzjau5xACrrZLMQEFinYW0E8evhZTyaXBV2bXaJiB9fSrFbgd0Od2c3iG6QxFZzc2kc46qzC-KkKVMekfdKXOkp1EL5aoI4ljBxFw80twcN/s1600/sensor-ardupilot-6-dof2.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjatw5F4zzX2qzj5bbp_qtzXuYnPu2UDPhNVEzjau5xACrrZLMQEFinYW0E8evhZTyaXBV2bXaJiB9fSrFbgd0Od2c3iG6QxFZzc2kc46qzC-KkKVMekfdKXOkp1EL5aoI4ljBxFw80twcN/s320/sensor-ardupilot-6-dof2.jpg" width="320" /></a></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div class="separator" style="clear: both; font-family: Times,"Times New Roman",serif; text-align: center;"><span style="font-size: small;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgYCcLvt0Z1UhQK0Vn40bJ3XSW9Gu6CKWWjSBSFJwdrmCpM2C4nl_zmLLCfmwfqG4iXI_fafFe0nAmsuCPASuow0Rz3aJcqlSKlhl6omWeSO7XzEavU1_FEcm7Xi-SPsJoADYclgicLsTkS/s1600/sensor-ardupilot-6-dof3.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgYCcLvt0Z1UhQK0Vn40bJ3XSW9Gu6CKWWjSBSFJwdrmCpM2C4nl_zmLLCfmwfqG4iXI_fafFe0nAmsuCPASuow0Rz3aJcqlSKlhl6omWeSO7XzEavU1_FEcm7Xi-SPsJoADYclgicLsTkS/s320/sensor-ardupilot-6-dof3.jpg" width="320" /></a></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><b>Conexiones entre Arduino Mega 2560 y el IMU</b></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><style>
<!--
/* Font Definitions */
@font-face
{font-family:"Courier New";
panose-1:2 7 3 9 2 2 5 2 4 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536859905 -1073711037 9 0 511 0;}
@font-face
{font-family:Times;
panose-1:2 0 5 0 0 0 0 0 0 0;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:3 0 0 0 1 0;}
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p
{mso-style-priority:99;
mso-margin-top-alt:auto;
margin-right:0cm;
mso-margin-bottom-alt:auto;
margin-left:0cm;
mso-pagination:widow-orphan;
font-size:10.0pt;
font-family:Times;
mso-fareast-font-family:"Times New Roman";
mso-bidi-font-family:"Times New Roman";}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
/* List Definitions */
@list l0
{mso-list-id:1448818088;
mso-list-type:hybrid;
mso-list-template-ids:2057584918 -847460270 201981955 201981957 201981953 201981955 201981957 201981953 201981955 201981957;}
@list l0:level1
{mso-level-start-at:2;
mso-level-number-format:bullet;
mso-level-text:-;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Verdana;
mso-fareast-font-family:"Times New Roman";
mso-bidi-font-family:"Times New Roman";}
@list l0:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level3
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level4
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level5
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level6
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level7
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level8
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level9
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->
</style> </div><div style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: 18pt;"><span style="font-size: small; line-height: 150%;">El primer paso es realizar la conexión entre la placa de Arduino que se ha utilizado (Arduino Mega 2560) y el sensor descrito anteriormente. Las conexiones que se han hecho han sido:</span></div><ul style="font-family: Times,"Times New Roman",serif; text-align: justify;"><li><span style="font-size: small; line-height: 150%;">Salidas y,z,x del acelerómetro y x, y z del giróscopo a las entradas A0-A5 analógicas de la placa (en ese orden, aunque eso da igual siempre y cuando lo tengamos en cuenta en el código que se use).</span></li>
<li><span style="font-size: small; line-height: 150%;"></span><span style="font-size: small; line-height: 150%;">La toma de alimentación de 3,3 V del sensor necesita una alimentación estable. Se conecta a la salida de 3,3 V de Arduino y al pin AREF. Esto último se hace para escalar correctamente el conversor A/D, ya que la referencia analógica por defecto para Arduino es de 5 V.</span></li>
<li><span style="font-size: small; line-height: 150%;"></span><span style="font-size: small; line-height: 150%;">Las tierras se conectan juntas</span></li>
</ul><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><b>Conexiones entre Arduino Mega 2560 y el NXT</b></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><b><br />
</b></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><style>
<!--
/* Font Definitions */
@font-face
{font-family:"Courier New";
panose-1:2 7 3 9 2 2 5 2 4 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536859905 -1073711037 9 0 511 0;}
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
/* List Definitions */
@list l0
{mso-list-id:1448818088;
mso-list-type:hybrid;
mso-list-template-ids:2057584918 -847460270 201981955 201981957 201981953 201981955 201981957 201981953 201981955 201981957;}
@list l0:level1
{mso-level-start-at:2;
mso-level-number-format:bullet;
mso-level-text:-;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Verdana;
mso-fareast-font-family:"Times New Roman";
mso-bidi-font-family:"Times New Roman";}
@list l0:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level3
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level4
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level5
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level6
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level7
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level8
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level9
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->
</style> </div><div class="MsoNormal" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: 18pt;"><span style="font-size: small;">En cuanto a las conexiones entre el sistema de desarrollo de Arduino y el NXT, éstas ya se comentaron en otra entrada del blog. Al igual que entonces, esta comunicación se va a realizar siguiendo el protocolo de comunicación I<sup>2</sup>C. Estas conexiones serían las siguientes:</span></div><ul style="font-family: Times,"Times New Roman",serif; text-align: justify;"><li><span style="font-size: small;">Pines 2 y 3 del NXT (colores rojo y negro) se conectan a las entradas de tierra de Arduino (GND).</span></li>
<li> <span style="font-size: small;">Pin 4 del NXT (color verde) que corresponde a la alimentación, se conecta a la entrada de 5 V de Arduino.</span></li>
<li><span style="font-size: small;"><span style="-moz-font-feature-settings: normal; -moz-font-language-override: normal; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-size: small;">Pin 5 del NXT (color amarillo) que corresponde a la línea de reloj del protocolo I<sup>2</sup>C se conecta al pin marcado como SCL en la placa de Arduino.</span></li>
<li><span style="font-size: small;">Pin 6 del NXT (color azul) que corresponde a la línea de datos del protocolo I<sup>2</sup>C se conecta al pin marcado como SDA en la placa de Arduino.</span></li>
</ul><div class="MsoListParagraphCxSpLast" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: -18pt;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"> <b>Código cargado en el NXT</b></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><b><br />
</b></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><style>
<!--
/* Font Definitions */
@font-face
{font-family:"Courier New";
panose-1:2 7 3 9 2 2 5 2 4 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536859905 -1073711037 9 0 511 0;}
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
/* List Definitions */
@list l0
{mso-list-id:1448818088;
mso-list-type:hybrid;
mso-list-template-ids:2057584918 -847460270 201981955 201981957 201981953 201981955 201981957 201981953 201981955 201981957;}
@list l0:level1
{mso-level-start-at:2;
mso-level-number-format:bullet;
mso-level-text:-;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Verdana;
mso-fareast-font-family:"Times New Roman";
mso-bidi-font-family:"Times New Roman";}
@list l0:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level3
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level4
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level5
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level6
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level7
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level8
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level9
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->
</style> </div><div class="MsoNormal" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: 18pt;"><span style="font-size: small;">En cuanto a las conexiones entre el sistema de desarrollo de Arduino y el NXT, éstas ya se comentaron el apartado 4.3 de esta memoria. Al igual que entonces, esta comunicación se va a realizar siguiendo el protocolo de comunicación I<sup>2</sup>C. Estas conexiones serían las siguientes:</span></div><div class="MsoListParagraphCxSpFirst" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: -18pt;"><span style="font-size: small;">-<span style="-moz-font-feature-settings: normal; -moz-font-language-override: normal; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-size: small;">Pines 2 y 3 del NXT (colores rojo y negro) se conectan a las entradas de tierra de Arduino (GND).</span></div><div class="MsoListParagraphCxSpMiddle" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: -18pt;"><span style="font-size: small;">-<span style="-moz-font-feature-settings: normal; -moz-font-language-override: normal; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-size: small;">Pin 4 del NXT (color verde) que corresponde a la alimentación, se conecta a la entrada de 5 V de Arduino.</span></div><div class="MsoListParagraphCxSpMiddle" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: -18pt;"><span style="font-size: small;">-<span style="-moz-font-feature-settings: normal; -moz-font-language-override: normal; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-size: small;">Pin 5 del NXT (color amarillo) que corresponde a la línea de reloj del protocolo I<sup>2</sup>C se conecta al pin marcado como SCL en la placa de Arduino.</span></div><div class="MsoListParagraphCxSpLast" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: -18pt;"><span style="font-size: small;">-<span style="-moz-font-feature-settings: normal; -moz-font-language-override: normal; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-size: small;">Pin 6 del NXT (color azul) que corresponde a la línea de datos del protocolo I<sup>2</sup>C se conecta al pin marcado como SDA en la placa de Arduino.</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="color: blue; font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;">import lejos.nxt.*; </span><br />
<span style="font-size: small;"><br />
</span><br />
<span style="font-size: small;"><br />
</span><br />
<span style="font-size: small;">public class ArduCom {</span><br />
<span style="font-size: small;"><br />
</span><br />
<span style="font-size: small;"><br />
</span><br />
<span style="font-size: small;"> public static void main(String[] args) throws Exception{ </span><br />
<span style="font-size: small;"> byte [] dato = new byte[3];</span><br />
<span style="font-size: small;"> String Tipo = "";</span><br />
<span style="font-size: small;"> String ID ="";</span><br />
<span style="font-size: small;"> String Ver="";</span><br />
<span style="font-size: small;"> int err = 0;</span><br />
<span style="font-size: small;"> </span><br />
<span style="font-size: small;"> for (int i=0;i<dato.length;i++){</span><br />
<span style="font-size: small;"> dato[i] = 0;</span><br />
<span style="font-size: small;"> }</span><br />
<span style="font-size: small;"> </span><br />
<span style="font-size: small;"> I2CSensor Arduino = new I2CSensor(SensorPort.S1);</span><br />
<span style="font-size: small;"> Arduino.setAddress(1); </span><br />
<span style="font-size: small;"> Ver = Arduino.getVersion();</span><br />
<span style="font-size: small;"> System.out.println("Ver: "+Ver);</span><br />
<span style="font-size: small;"> Tipo = Arduino.getSensorType();</span><br />
<span style="font-size: small;"> System.out.println("Tipo: "+Tipo);</span><br />
<span style="font-size: small;"> ID = Arduino.getProductID();</span><br />
<span style="font-size: small;"> System.out.println("ID: "+ID);</span><br />
<span style="font-size: small;"> Thread.sleep(1000);</span><br />
<span style="font-size: small;"> while (!Button.ESCAPE.isPressed()) {</span><br />
<span style="font-size: small;"> err = Arduino.getData(3, dato, 3);</span><br />
<span style="font-size: small;"> System.out.println("Acel: "+dato[0]+" "+dato[1]+" "+dato[2]);;</span><br />
<span style="font-size: small;"> err = Arduino.getData(4, dato, 3);</span><br />
<span style="font-size: small;"> System.out.println("Giros: "+dato[0]+" "+dato[1]+" "+dato[2]);</span><br />
<span style="font-size: small;"> } //Fin del while</span><br />
<span style="font-size: small;"> }</span><br />
<span style="font-size: small;">}</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><b><br />
Código cargado en Arduino</b></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><style>
<!--
/* Font Definitions */
@font-face
{font-family:"Courier New";
panose-1:2 7 3 9 2 2 5 2 4 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536859905 -1073711037 9 0 511 0;}
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-1593833729 1073750107 16 0 415 0;}
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast
{mso-style-priority:34;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-type:export-only;
margin-top:0cm;
margin-right:0cm;
margin-bottom:0cm;
margin-left:36.0pt;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
/* List Definitions */
@list l0
{mso-list-id:1448818088;
mso-list-type:hybrid;
mso-list-template-ids:2057584918 -847460270 201981955 201981957 201981953 201981955 201981957 201981953 201981955 201981957;}
@list l0:level1
{mso-level-start-at:2;
mso-level-number-format:bullet;
mso-level-text:-;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Verdana;
mso-fareast-font-family:"Times New Roman";
mso-bidi-font-family:"Times New Roman";}
@list l0:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level3
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level4
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level5
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level6
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
@list l0:level7
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Symbol;}
@list l0:level8
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:"Courier New";
mso-bidi-font-family:"Times New Roman";}
@list l0:level9
{mso-level-number-format:bullet;
mso-level-text:;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-18.0pt;
font-family:Wingdings;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->
</style> </div><div class="MsoNormal" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: 18pt;"><span style="font-size: small;">A continuación se va a presentar el código que se ha cargado en Arduino. Este código se ha dejado comentado para facilitar la comprensión del mismo. Las tareas que realiza son las siguientes:</span></div><div class="MsoListParagraphCxSpFirst" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: -18pt;"><span style="font-size: small;">-<span style="-moz-font-feature-settings: normal; -moz-font-language-override: normal; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-size: small;">En el apartado de configuración (setup) se configura:</span></div><div class="MsoListParagraphCxSpMiddle" style="font-family: Times,"Times New Roman",serif; line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-size: small;">o<span style="-moz-font-feature-settings: normal; -moz-font-language-override: normal; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-size: small;">Referencia externa de 3,3 V</span></div><div class="MsoListParagraphCxSpMiddle" style="font-family: Times,"Times New Roman",serif; line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-size: small;">o<span style="-moz-font-feature-settings: normal; -moz-font-language-override: normal; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-size: small;">Se marcan los pines analógicos como salidas</span></div><div class="MsoListParagraphCxSpMiddle" style="font-family: Times,"Times New Roman",serif; line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-size: small;">o<span style="-moz-font-feature-settings: normal; -moz-font-language-override: normal; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-size: small;">Nos unimos al bus I<sup>2</sup>C como esclavos usando la dirección 1. A través de él se realizará la comunicación con el NXT.</span></div><div class="MsoListParagraphCxSpMiddle" style="font-family: Times,"Times New Roman",serif; line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-size: small;">o<span style="-moz-font-feature-settings: normal; -moz-font-language-override: normal; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-size: small;">Se configura la velocidad de escritura por el puerto serie, lo que nos va a permitir ver a través de la herramienta de monitorización del propio entorno de desarrollo de Arduino los datos que vayamos leyendo y convirtiendo desde el sensor analógico.</span></div><div class="MsoListParagraphCxSpMiddle" style="font-family: Times,"Times New Roman",serif; line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-size: small;">o<span style="-moz-font-feature-settings: normal; -moz-font-language-override: normal; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-size: small;">Se configuran las rutinas que se ejecutarán cuando se reciba una petición de datos desde el NXT</span></div><div class="MsoListParagraphCxSpMiddle" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: -18pt;"><span style="font-size: small;">-<span style="-moz-font-feature-settings: normal; -moz-font-language-override: normal; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-size: small;">El bucle principal realiza la lectura de los pines analógicos comprendidos entre el 0 y el 5, que será donde estén conectados los pines del sensor. Se les resta el valor medio del sensor en reposo para que den un valor 0 estando en reposo. Estos datos se almacenan y se dejan listos para enviarlos al NXT cuando sea necesario.</span></div><div class="MsoListParagraphCxSpLast" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: -18pt;"><span style="font-size: small;">-<span style="-moz-font-feature-settings: normal; -moz-font-language-override: normal; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-size: small;">En las rutinas de interrupción se identifica el tipo de dato que está pidiendo el NXT (codificado en el campo registro) y se procede al envío de dichos datos.</span></div><div class="MsoNormal" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div class="MsoNormal" style="font-family: Times,"Times New Roman",serif; line-height: 150%; margin-left: 18pt; text-align: justify;"><span style="font-size: small;">El código usado es el siguiente:</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">#include <Wire.h> //Para gestionar las comunicaciones</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">//Definiciones y variables globales</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">uint8_t SensorVersion[9] = " V0.1 ";</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">uint8_t SensorName[9] = "Arduino ";</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">uint8_t SensorType[9] = "Casero ";</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">byte buffersalida[] = { 0, 0, 0, 0, 0, 0}; //Para enviar al RCX</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">byte buffgiros[] = { 0, 0, 0}; //Ejes x, y, z del giroscopo</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">byte buffacel[] = { 0, 0, 0}; // Ejes x, y, z del acelerometro</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">int val = 0; //Datos que se leeran del acelerometro o giroscopo</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">unsigned long timer=0; //timer</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">unsigned long delta_t; //delta o tiempo entre muestras </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">byte rec;</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">void setup(){</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> analogReference(EXTERNAL); //Usamos referencia externa de 3,3 V para calibrar el ADC</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Serial.begin(115200);</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> DDRC = B00000000; //Marcamos los puertos analogicos como salidas</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Serial.println("t[ms] \t az \t ay \t ax \t gx \t gy \t gz "); //Cabeceras</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Wire.begin(1); //Nos unimos como esclavos con dir. 1</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Wire.onRequest(requestEvent); //Rutinas para cuando llegue algo</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Wire.onReceive(receiveEvent); </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> timer=millis(); </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">}</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">void loop(){</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> delta_t = millis() - timer; // Calculamos el tiempo de adquisicion</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> timer=millis(); // Actualizamos el timer</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Serial.print(delta_t);</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Serial.print ("\t"); </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> for (long i=0; i<6; i++) //Vamos a recorrer los pines analogicos</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> { </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> val = analogRead(i); // Leemos el pin de entrada</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> if(i==0) { //Le quitamos el offset al valor leido</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> val = val - 601;</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> buffacel[2] = val; //Eje z del acelerometro</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> } else if (i==1) {</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> val = val - 506;</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> buffacel[1] = val; // Eje y del acelerometro</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> } else if (i==2) {</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> val = val - 504;</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> buffacel[0] = val; // Eje x del acelerometro</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> } else if (i==3) {</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> val = val - 504;</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> buffgiros[0] = val; //Eje x del giroscopo</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> } else if (i==4) {</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> val = val - 502; //Valor medio </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> buffgiros[1] = val; //Eje y del giroscopo</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> } else if (i==5) {</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> val = val - 483; //Valor medio</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> buffgiros[2] = val; //Eje z del giroscopo </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> }</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Serial.print(val); //Imrpimimos por puerto serie</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Serial.print ("\t");</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> } </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Serial.println("");</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> delay(16); //Bucle ejecutado a ~ 50Hz o 20ms</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">}</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">void receiveEvent(int len){ //Devuelve el nº de bytes recibidos </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> while (0 < Wire.available() ) {</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> rec = Wire.receive();</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> } //While</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">}</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">void requestEvent(){</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Serial.print(rec, BYTE);</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> if (rec == 0x00){ //Version del sensor</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Wire.send(SensorVersion, 8);</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> } else if (rec == 0x08){ //Nombre del sensor</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Wire.send(SensorName, 8);</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> } else if (rec == 0x10){ //Tipo del sensor</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Wire.send(SensorType, 8);</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> } else if (rec == 0x03) { // Lectura del acelerometro</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Wire.send(buffacel, 3);</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> } else if (rec = 0x04) { //Lectura del giroscopo</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Wire.send(buffgiros, 3);</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> } else {</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> buffersalida[0] = 0;</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> buffersalida[1] = 0;</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> Wire.send(buffersalida, 2);</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;"> }</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="color: blue; font-size: small;">} </span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><b>Conclusiones</b></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><style>
<!--
/* Font Definitions */
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1107305727 0 0 415 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
@font-face
{font-family:"ヒラギノ角ゴ Pro W3";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 2059927551 18 0 131085 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-fareast-font-family:"ヒラギノ角ゴ Pro W3";
mso-bidi-font-family:"Times New Roman";
color:black;
mso-fareast-language:EN-US;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
-->
</style> </div><div class="MsoNormal" style="font-family: Times,"Times New Roman",serif; line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-size: small;">Se ha realizado con éxito la comunicación entre un sensor analógico y el NXT usando como intermediario el Sistema de Desarrollo Arduino, que se comunica con el robot haciendo uso del protocolo I<sup>2</sup>C. Los datos que se reciben desde el sensor analógico son correctos, y sólo se aprecia una oscilación de números algo mayor en dos ejes del giróscopo. Esta oscilación debida al ruido de medida, puede estar relacionada con el hecho de que las pruebas se hayan realizado en una placa de prototipos estándar y con hilos de conexión normales. A continuación se muestra una fotografía tomada del sistema bajo pruebas.</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><b> </b></span></div><div class="separator" style="clear: both; font-family: Times,"Times New Roman",serif; text-align: center;"><span style="font-size: small;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgtq3ZaZl2b6bKPh4i23gaiii9e05jIo3Mm7sLSNDNdqI02340vvZCgf_P4REFuCTL88pBxRhX2FtLAYrj40z2ShdBWMb3hVXmDH_8YOrog3n2ZXd3jYINYyKrThGdqiTZJrlA9cVU3P7SV/s1600/cameraroll-1300967183.887894.jpeg" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgtq3ZaZl2b6bKPh4i23gaiii9e05jIo3Mm7sLSNDNdqI02340vvZCgf_P4REFuCTL88pBxRhX2FtLAYrj40z2ShdBWMb3hVXmDH_8YOrog3n2ZXd3jYINYyKrThGdqiTZJrlA9cVU3P7SV/s320/cameraroll-1300967183.887894.jpeg" width="239" /></a></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;">----------------------------------------------------------------------------------------------------------------</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><b>Referencias:</b></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;"><br />
</span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;">- La placa IMU usada: <a href="http://www.bricogeek.com/shop/181-sensor-ardupilot-6-dof.html">http://www.bricogeek.com/shop/181-sensor-ardupilot-6-dof.html</a> <b> </b></span></div><div style="font-family: Times,"Times New Roman",serif; text-align: justify;"><span style="font-size: small;">- Razor IMU and Arduino: <a href="http://voidbot.net/razor-6dof.html">http://voidbot.net/razor-6dof.html</a></span></div><br />
</div></div><b> </b>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-61641143381396536172011-03-08T04:33:00.000-08:002011-03-08T04:33:23.050-08:00Arduno y la comunicación I2C: Librería Wire()<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px 'Times New Roman'}
span.s1 {font: 8.0px 'Times New Roman'}
</style> <br />
<div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">En publicaciones anteriores del blog se comentaron las distintas herramientas de las que </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">disponía el NXT para establecer la comunicación mediante I<span class="s1">2</span>C con dispositivos esclavos, e hicimos </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">especial hincapié en el Sistema Operativo LejOs, que es con el que más estamos trabajando.</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">En el otro lado de la comunicación, y funcionando como esclavo, se va a encontrar nuestra </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">placa de Arduino. En este epígrafe se va a describir el funcionamiento de la librería Wire(), que es </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">aquella que nos va a permitir realizar esta comunicación, y se van a describir brevemente las </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">funciones más interesantes de las que ésta dispone.</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span></div><div class="p1"><b><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">Principales funciones</span></b><br />
<b><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span></b></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">Como se acaba de comentar, esta librería permite la comunicación de una placa Arduino con </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">dispositivos I<span class="s1">2</span>C y TWI. En la mayoría de las placas Arduino, la línea de datos (SDA) se </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">encuentra en el pin analógico 4, y la línea de reloj (SCL) se encuentra en el pin analógico 5. En el </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">caso de la placa que nosotros usamos, Arduino Mega 2560, estas líneas están en los pines digitales </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">20 y 21 respectivamente.</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">Las principales funciones que nos ofrece esta librería son las siguientes:</span><br />
<span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">- <b>Wire.begin() </b>y <b>Wire.begin(dirección). </b>Esta función inicializa la librería Wire y conecta </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">Arduino al bus. Si no se especifica la dirección, Arduino se conectará al bus como maestro, </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">mientras que si ésta se indica lo hará como esclavo y asumiendo la dirección que se la ha </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">proporcionado. En ambos casos, esta función no devuelve ningún valor.</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">- <b>Wire.requestFrom(dirección, cantidad). </b>Solicita bytes desde otros dispositivos. Los bytes </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">pueden ser recibidos con las funciones available() (que nos indica si hay datos disponibles </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">para ser leídos en el bus) y receive() (que realiza la lectura de los datos). Esta función no </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">devuelve nada.</span></div><div class="p1"><br />
<ul><li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">El parámetro “dirección” es la dirección de 7 bits del dispositivo al que le queremos </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">pedir los datos</span></li>
<li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">El parámetro “cantidad” es el número de bytes a pedir.</span></li>
</ul></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">- <b>Wire.beginTransmission(dirección). </b>Comienza una transmisión a un dispositivo I<span class="s1">2</span>C </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">esclavo con la dirección que se especifique en el parámetro “dirección”. Posteriormente, </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">prepara los bytes a transmitir con la función send() y los transmite llamando a la función </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">endTransmision(). Esta función no devuelve nada.</span></div><div class="p1"><br />
<ul><li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">El parámetro “dirección” es la dirección de 7 bits del dispositivo al que le queremos </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">pedir los datos.</span></li>
</ul></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">- <b>Wire.endTransmission(). </b>Finaliza una transmisión a un esclavo que fue empezada por </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">beginTransmission(), y realmente lo que hace es transmitir los bytes que fueron preparados </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">por send(). Esta función tampoco devuelve nada.</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">- <b>Wire.Send(valor)</b>, <b>Wire.Send(string) </b>o <b>Wire.Send(dato, cantidad). </b>Envía datos desde un </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">esclavo como respuesta a una petición de un maestro, o prepara los bytes para transmitir </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">desde un maestro a un esclavo (entre llamadas a beginTransmission() y endTransmission()).</span></div><div class="p1"><br />
<ul><li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">El parámetro “valor” es un byte que se desee enviar.</span></li>
<li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">El parámetro “string” es una cadena de tipo (char *) que se desee enviar.</span></li>
<li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">El parámetro “dato” es un vector de datos para enviar (byte *).</span></li>
<li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">El parámetro “cantidad” es el número de bytes que se desea transmitir</span></li>
</ul></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">- <b>Wire.available(). </b>Devuelve el número de bytes disponibles para recuperar con receive(). </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">Debería ser llamada por un maestro después de llamar a requestFrom() o por un esclavo </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">dentro de la función a ejecutar por onReceive(), que será lo que nosotros hagamos al recibir </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">datos del NXT. Esta función devuelve el número de bytes disponibles para leer.</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">- <b>Wire.receive(). </b>Recupera un byte que fue transmitido desde un dispositivo esclavo a un </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">maestro después de una llamada a requestFrom() o que fue transmitido desde un maestro a </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">un esclavo. Devuelve el byte recibido.</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">- <b>Wire.onReceive(handler). </b>Registra una función que será llamada cuando un dispositivo </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">esclavo reciba una transmisión desde un maestro. Esta función no devuelve nada.</span></div><div class="p1"><br />
<ul><li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">El parámetro “handler” corresponde a la función que será llamada cuando el esclavo </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">recibe datos. Esta función debería coger un único parámetro entero (el número de </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">bytes recibidos desde un maestro) y no devolver nada, por ejemplo: </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><i>void </i></span><i><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">myManejador(int numBytes).</span></i></li>
</ul></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">- <b>Wire.onRequest(handler). </b>Registra una función que será llamada por el dispositivo </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">esclavo cuando un maestro solicite datos. No devuelve nada.</span></div><div class="p1"><br />
<ul><li><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">El parámetro “handler” es la función que tiene que ser llamada.</span></li>
</ul></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">A modo de ejemplo se muestra a continuación el código de un maestro y de un esclavo que </span><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">hacen uso de esta librería. El esclavo envía datos, y el maestro los recibe y los imprime por puerto serie, con lo que se pueden monitorizar desde el PC.</span></div><div class="p1"><span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;"><br />
</span><br />
<span class="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">En primer lugar el código del maestro:</span><br />
<br />
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Courier; color: #919191}
p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Courier; color: #d67a1f}
p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Courier}
span.s1 {color: #000000}
span.s2 {color: #d67a1f}
</style> <br />
<div class="p1"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiz2S_6Nfy9GFwSY8WUkHjqjSuN9tCQCInMkELEgxhZqQbDLN8gU8hJlffvlnYPVcyTzGgXMRbFLm5arYF1qPyXXA8oWtaGAHBbnKcvbLZTxgLM1LxKxQ3dymGNhAc-sBjBov0tmXWI0XAJ/s1600/Captura+de+pantalla+2011-03-08+a+las+13.25.14.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="272" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiz2S_6Nfy9GFwSY8WUkHjqjSuN9tCQCInMkELEgxhZqQbDLN8gU8hJlffvlnYPVcyTzGgXMRbFLm5arYF1qPyXXA8oWtaGAHBbnKcvbLZTxgLM1LxKxQ3dymGNhAc-sBjBov0tmXWI0XAJ/s400/Captura+de+pantalla+2011-03-08+a+las+13.25.14.png" width="400" /></a></div><i><br />
</i></div><br />
<br />
Y a continuación el del esclavo:<br />
<br />
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Courier; color: #919191}
p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Courier; color: #d67a1f}
p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Courier}
span.s1 {color: #000000}
span.s2 {color: #d67a1f}
span.s3 {color: #1d7bd3}
</style> <br />
<div class="p1"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIacxoOoo-Ju1yhA7NAsHsYAkTZqtIDdjWO01lf10Oru3w-LV64MNCjm6aA9NTzzSohdjQTtdWlMmVZy_0KyoVlgkjmKtWKLTqV50DicxmwtzhMUz_JOUFVqURmyvoYb7bYB1BiHOUyfom/s1600/Captura+de+pantalla+2011-03-08+a+las+13.25.45.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="261" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIacxoOoo-Ju1yhA7NAsHsYAkTZqtIDdjWO01lf10Oru3w-LV64MNCjm6aA9NTzzSohdjQTtdWlMmVZy_0KyoVlgkjmKtWKLTqV50DicxmwtzhMUz_JOUFVqURmyvoYb7bYB1BiHOUyfom/s400/Captura+de+pantalla+2011-03-08+a+las+13.25.45.png" width="400" /></a></div><br />
</div><br />
<br />
--------------------------------------------------------------------<br />
<b>REFERENCIAS:</b><br />
- Ejemplo de comunicación I2C entre dos Arduinos: <a href="http://arduino.cc/en/Tutorial/MasterReader">http://arduino.cc/en/Tutorial/MasterReader</a><br />
- Arduino Wire: <a href="http://arduino.cc/es/Reference/Wire">http://arduino.cc/es/Reference/Wire</a><br />
- I2C bus. TWI bus: <a href="http://www.i2c-bus.org/twi-bus/">http://www.i2c-bus.org/twi-bus/</a></div>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-13859451582824675382011-03-07T10:19:00.000-08:002011-03-08T02:49:51.218-08:00Solución a los problemas entre Arduino Mega 2560 y el MindstormEn primer lugar, hacer referencia a una publicación que hice hace unos días, donde explicaba el problema y aún no le había encontrado solución: <a href="http://mindstormsyarduino.blogspot.com/2011/02/arduino-mega-2560-y-los-mindstorms.html">enlace</a><br />
<br />
En ella, básicamente comentaba los problemas que tenía para comunicar el NXT con la placa Arduino Mega 2560 mediante I2C. Voy a resumir el problema con datos y medidas para que todo quede bien claro, y finalmente pondré la solución a la que hemos llegado.<br />
<ul><li>En primer lugar, se hicieron pruebas de comunicación I2C entre Arduino Duemilanove y el NXT. La conexión entre ambos era la siguiente:<br />
<ul><li><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;">Pines 2 y 3 del NXT (Rojo y negro) (tierra) --> Arduino GND.</span></li>
<li><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"></span><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;">Pin 4 del NXT (alimentacion) (verde) --> Arduino 5V</span></li>
<li><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"></span><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;">Pin 5 del NXT (Amarillo) (SCL) --> Arduino A5</span></li>
<li><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"></span><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;">Pin 6 del NXT (Azul) (SDA) --> Arduino A4</span></li>
</ul>Con estas conexiones, y un programa sencillo que simplemente recogiera algunos datos del Arduino y los mostrara en la pantalla del NXT todo funcionó perfectamente. El programa usado también lo comenté en otra publicación y lo podéis encontrar <a href="http://mindstormsyarduino.blogspot.com/2011/02/primeras-pruebas.html">aquí.</a><br />
</li>
<li>El siguiente paso era hacer el mismo intercambio de datos usando una placa algo más potente y con más prestaciones: la Arduino Mega 2560. Las conexiones que se tienen que hacer para ellos son estas:</li>
<ul><li><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;">Pines 2 y 3 del NXT (Rojo y negro) (tierra) --> Arduino GND</span></li>
<li><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"></span><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;">Pin 4 del NXT (alimentacion) (verde) --> Arduino 5V</span></li>
<li><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"></span><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;">Pin 5 del NXT (Amarillo) (SCL) --> Arduino SCL</span></li>
<li><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"></span><span class="Apple-style-span" style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;">Pin 6 del NXT (Azul) (SDA) --> Arduino SDA</span></li>
</ul></ul>Bien, haciendo esto y lanzando exactamente el mismo programa que en el caso del Arduino Duemilanove tanto para el Mindstorm como para el Arduino... no pasó absolutamente nada. Es decir, no hubo intercambio de datos. ¿Por qué? Bueno, voy a ir explicando los pasos que he dado hasta dar con la solución...<br />
<ul></ul><div><b>Diferencias entre Arduino Duemilanove y Arduino Mega 2560</b></div><div>Si nos fijamos en los esquemáticos de ambos (disponibles en la página oficial de Arduino), hay una diferencia en el camino que recorren tanto la señal de datos (SDA) como la de reloj (SCL) del protocolo I2C desde el conector hasta el microcontrolador. Se trata de dos resistencias de pull-up, de un valor de 10K que sirven para mantener el valor lógico "uno" si la tensión en la línea no es suficiente. Estas resistencias son las que nos están originando el problema, como entenderemos enseguida. Estas resistencias las vemos en la siguiente captura (extraída del esquemático):</div><div><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEguW0KhRUGSvw9oxXM0MDZjq5FhiD7BKqPwUvXTxjIZYdT1R5wei0E3RoZNfdmp5b2WSEexjED8WHzPx0LYhen4CcPvDQqmSPynoh4RSDeBAaue0UgvzFq_hEWbcJIczYV3Gi8MN2p1hSb4/s1600/Captura+de+pantalla+2011-03-07+a+las+18.14.17.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEguW0KhRUGSvw9oxXM0MDZjq5FhiD7BKqPwUvXTxjIZYdT1R5wei0E3RoZNfdmp5b2WSEexjED8WHzPx0LYhen4CcPvDQqmSPynoh4RSDeBAaue0UgvzFq_hEWbcJIczYV3Gi8MN2p1hSb4/s1600/Captura+de+pantalla+2011-03-07+a+las+18.14.17.png" /></a></div><div><b>¿Por qué pueden dar problemas?</b></div><div>En principio, una resistencia de pull-up no es malo, sino todo lo contrario. Pero en este caso nos está perjudicando. Vamos a analizar el recorrido de las señales de reloj (SCL) y de datos (SDA) en el Mindstorm en el caso del puerto A (es idéntico para todos los puertos). </div><div><br />
</div><div>En la figura que tenemos aquí vemos como del procesador (AT91SAM7S256) salen las señales DIG1A0 y DIG1A1. Estas son las señales SCL y SDA respectivamente. </div><div><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCeGvqH1TbxfgeBPfSzeoSbpbLEhX27RapT5a9yQTwv32CI1b38N1wkXLrvIv2FkaoZ9_7BHCQfh5HbEsjQ-aXnJim4Xia7p9DCqKOqxo7nWGYiD9MugEpHdgseok9u2iVe4VGOseLxjBr/s1600/Captura+de+pantalla+2011-03-07+a+las+18.31.40.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="218" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCeGvqH1TbxfgeBPfSzeoSbpbLEhX27RapT5a9yQTwv32CI1b38N1wkXLrvIv2FkaoZ9_7BHCQfh5HbEsjQ-aXnJim4Xia7p9DCqKOqxo7nWGYiD9MugEpHdgseok9u2iVe4VGOseLxjBr/s320/Captura+de+pantalla+2011-03-07+a+las+18.31.40.png" width="320" /></a></div><div><br />
</div><div><br />
</div><div>Estas señales, van a parar al circuito siguiente:</div><div><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhAFvFUU2xbln3NCd7Q5hSADHSP9fQC7-gZ9jIN1w5J_Y76cjI58TII8bsWrCJ4it6ML4JfQqQZBv1-2UrM8YhR_UBJqhrx2MA84Dg_9hHHFlUL210NXQQKnUm3zfyxL_aYpCeapODyTaYd/s1600/Captura+de+pantalla+2011-03-07+a+las+18.32.21.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhAFvFUU2xbln3NCd7Q5hSADHSP9fQC7-gZ9jIN1w5J_Y76cjI58TII8bsWrCJ4it6ML4JfQqQZBv1-2UrM8YhR_UBJqhrx2MA84Dg_9hHHFlUL210NXQQKnUm3zfyxL_aYpCeapODyTaYd/s320/Captura+de+pantalla+2011-03-07+a+las+18.32.21.png" width="219" /></a></div><div><br />
</div><div>En él vemos el recorrido que hacen hasta obtener las señales DIGIAI0 y DIGIAI1 que son las que tendremos a la salida (podemos ver el conector en la figura inferior). Si nos fijamos, estas señales pasan por una resistencia en serie de 4,7 K y a continuación tienen conectadas unas resistencias de pull-up de 82 K que van alimentadas a 5V (ver nota 1). </div><div><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3oa_iZ-kS3JZ02himbJRlMIfrUpwNkGDyJMQMuz8kgZwUSUEHMg0WESXB0OqOgc5N349_gyT4YP6C3EuLpXoEJ_yAdTSKQCgkGxI-MJkCoFvprp7SLtf99M808QbEa9udDcIP_w_MtxXt/s1600/Captura+de+pantalla+2011-03-07+a+las+18.46.29.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3oa_iZ-kS3JZ02himbJRlMIfrUpwNkGDyJMQMuz8kgZwUSUEHMg0WESXB0OqOgc5N349_gyT4YP6C3EuLpXoEJ_yAdTSKQCgkGxI-MJkCoFvprp7SLtf99M808QbEa9udDcIP_w_MtxXt/s1600/Captura+de+pantalla+2011-03-07+a+las+18.46.29.png" /></a></div><div><b><br />
</b></div><div>Esta resistencia de pull-up de 82 K, al conectar nuestro Mindstorm con la placa Arduino Mega 2560 se asocia en paralelo con la de 10 K de dicha placa, formando una resistencia equivalente de 8,91 K (es decir, casi diez veces inferior a la original). </div><div>El procesador nos dará como nivel alto un valor de 3,3 V, y como nivel bajo 0 V. Si hacemos algunos cálculos (teniendo en cuenta el circuito equivalente) para calcular qué valores vamos a tener a la salida en cada caso, obtendremos lo siguiente:</div><div><br />
</div><div><br />
<ul><li>Circuito equivalente conectando el <b>NXT con Arduino Duemilanove</b>: se obtiene un valor a la salida de 3,40 V (nivel alto) y de 0,28 V (nivel bajo).</li>
<li>Circuito equivalente conectando el<b> NXT con Arduino Mega 2560</b> (y por tanto con el paralelo de las dos resistencias de pull-up): se obtiene un valor a la salida de unos 3,89 V (nivel alto) y 1,70 V (nivel bajo).</li>
</ul></div><div><br />
</div><div>Lo que parece, es que el valor de tensión a la salida para el nivel alto será detectado sin problemas, pero para el nivel bajo, en el caso del Arduino Mega tenemos 1,70 V. Es un valor demasiado alto, y probablemente pueda confundirse con el '1' lógico haciendo que la comunicación falle. Esto se debe a que la resistencia de 4,7 K que vemos en serie a la salida del Mindstorm, está alterando el valor de tensión que hay a la salida y hace que las resistencias de pull-up entren en acción cuando no deberían, es decir, cuando la línea está a nivel bajo.</div><div><b><br />
</b></div><div><b>Primeras medidas</b></div><div>Todas las medidas que se describen a continuación han sido realizadas con un osciloscopio digital de la marca Tektronix, modelo TDS 210, del departamento de Ingeniería de Sistemas y Automática de la Universidad de Málaga.</div><div><br />
</div><div>Lo primero que se hizo fue, para descartar que hubiera cualquier problema en los puertos I2C de la placa Arduino Mega 2560, interconectar dicha placa con la de Arduino Duemilanove y ponerlas a intercambiar datos. Hay muchos ejemplos de esto por internet, pero el que seguimos fue <a href="http://arduino.cc/en/Tutorial/MasterReader">este</a>. Al hacer esto, vimos que la comunicación era correcta, y que las señales de datos y de reloj mantenían un valor medio de señal próximo a los 5 v (de aproximadamente 4,90 V y cercano a 0 para el '0' lógico.</div><div><br />
</div><div>A continuación, para comprobar los cálculos teóricos que comentamos en el apartado anterior, se hicieron las medidas conectando en primer lugar el NXT con la placa Duemilanove, y a continuación con la Mega. Lo que se vio confirmó lo que pensábamos, ya que, aunque el valor medio de las señales era similar, en el caso de la conexión con Arduino Mega la señal tenía la mitad de amplitud (unos 2 V pico a pico) y su extremo inferior estaba cercana a los 2 V, mientras que con Duemilanove el pico inferior rozaba los 0 V y tenía una amplitud de 4 V pico a pico.</div><div><br />
</div><div>Por lo tanto, efectivamente el nivel bajo de la señal se está confundiendo con el nivel alto. </div><div><br />
</div><div><b>La solución</b></div><div>Tras todo este proceso, la única solución viable era la de eliminar las resistencias de la placa de Arduino Mega 2560. Para aquellos que tengan el modelo Arduino Mega (versión anterior) lo tendrán más fácil, ya que lo que tienen es simplemente dos resistencias separadas que se pueden desoldar y eliminar fácilmente. En nuestro caso, es algo más complejo ya que las resistencias están dentro de un encapsulado DIL, que contiene además la resistencia que mantiene el reset a nivel alto hasta que lo pulsemos. Si se eliminase este encapsulado (que vemos en la figura inferior con un 103 escrito), se estaría dejando el reset permanentemente a nivel bajo, y por lo tanto la placa no llegaría a encenderse. </div><div><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_Pon686Rgr-t7JD6QvcG2QyEN0CNTXh_M30BcP8MyyEMC5rRgo8w4uDU6pvo12nFHpMA1gBeNJW_8hJGj2Ewgy8YYbdlNU6PabhfQqo0afbKMr0GmG_I-bRGymwlouIA1yjElULNW4ynx/s1600/e97ugx.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="266" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_Pon686Rgr-t7JD6QvcG2QyEN0CNTXh_M30BcP8MyyEMC5rRgo8w4uDU6pvo12nFHpMA1gBeNJW_8hJGj2Ewgy8YYbdlNU6PabhfQqo0afbKMr0GmG_I-bRGymwlouIA1yjElULNW4ynx/s320/e97ugx.jpg" width="320" /></a></div><div><br />
</div><div>(Gracias por la captura a Chiva, del foro oficial de Arduino :) )</div><div><br />
</div><div>Aunque había otra alternativa, como desoldar el encapsulado, y colocar después una resistencia de 10k para el reset, optamos por "cortar" las líneas de datos que unían las pistas de SDA y SCL con las resistencias. Para ello, nos fijamos en el esquema de PCB de Arduino (también disponible en la página oficial) y elegimos el mejor sitio para el corte. En las dos figuras de abajo se han resaltado las líneas SDA y SCL, y se ha marcado en verde el sitio por el que se ha hecho el corte:</div><div><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqTHM2yAqdVGT73j7q7a8kSBu9UGNAUa9O5rjbIKsRoN03ipk1mI4dJXb_LoqAljE-5Me_3sfVu4erxHGYo3vvU7-UzmW-ACWpZgmPubeR5QgE5kgG4PPneo2L32SZwMXTfaH4pbJa5Ncy/s1600/Captura+de+pantalla+2011-03-07+a+las+19.12.16.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="291" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqTHM2yAqdVGT73j7q7a8kSBu9UGNAUa9O5rjbIKsRoN03ipk1mI4dJXb_LoqAljE-5Me_3sfVu4erxHGYo3vvU7-UzmW-ACWpZgmPubeR5QgE5kgG4PPneo2L32SZwMXTfaH4pbJa5Ncy/s320/Captura+de+pantalla+2011-03-07+a+las+19.12.16.png" width="320" /></a></div><div class="separator" style="clear: both; text-align: center;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimD_TEkUtOlDiLuJjKSl-EeFJvVJP1z_KxziPfWT1O3uf75gtJfzyA1Fe5xpqf7RG-Exekmw5AMJwa3-osUlHMfLL8KIXjTCztMc5wKSU-B3DvDjRsYW8ygyHeNytdQN64sBLImpc8gJW0/s1600/Captura+de+pantalla+2011-03-07+a+las+19.12.43.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimD_TEkUtOlDiLuJjKSl-EeFJvVJP1z_KxziPfWT1O3uf75gtJfzyA1Fe5xpqf7RG-Exekmw5AMJwa3-osUlHMfLL8KIXjTCztMc5wKSU-B3DvDjRsYW8ygyHeNytdQN64sBLImpc8gJW0/s320/Captura+de+pantalla+2011-03-07+a+las+19.12.43.png" width="304" /></a></div><div><br />
</div><div><br />
</div><div>Y tras hacer estos cortes (con cuidado, arañando con un cúter hasta comprobar con un multímetro que la vía por la que pasa la señal y la patilla de la resistencia ya no hacían contacto) se ha vuelto a probar la comunicación entre el NXT y el Arduino Mega 2560 y... todo funciona correctamente :)<br />
<br />
<b>Nota1: Sobre la tensión VCC_RS485</b><br />
<b><br />
</b><br />
En los cálculos se ha asumido que la tensión VCC_RS485 es de 5 V. Para ello, se ha recurrido una vez más al esquemático. El diagrama de bloques del sistema de alimentación se puede ver a continuación.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjg1ku-omEfVQ7dfvwmRqh-J71PnRCYVs54Ftu-IaHYHK5Je7r06tgSLOX5wq8eVxtAq20aYHyVwdoRf_6V3Up85u3klyjL8di5IUwf_s9a0hiX9cK7lnpCH0UfV2DvafpLJLVXRSG6N6aR/s1600/Captura+de+pantalla+2011-03-08+a+las+11.15.53.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="220" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjg1ku-omEfVQ7dfvwmRqh-J71PnRCYVs54Ftu-IaHYHK5Je7r06tgSLOX5wq8eVxtAq20aYHyVwdoRf_6V3Up85u3klyjL8di5IUwf_s9a0hiX9cK7lnpCH0UfV2DvafpLJLVXRSG6N6aR/s320/Captura+de+pantalla+2011-03-08+a+las+11.15.53.png" width="320" /></a></div><br />
<br />
Si nos fijamos, la señal VCC_RS485 tiene a su entrada un conmutador que alterna su valor entre 5 V y un circuito abierto. La señal que controla esto es POWER_EN que procede del ATMEGA48, y que corresponde al pin PB7. Se trata de una señal periódica generada por el oscilador interno del microcontrolador y que hace que el conmutador vaya abriéndose y cerrándose continuamente. </div><div><br />
</div><div><br />
</div><div><br />
</div><div><br />
</div><div><br />
</div><div><br />
</div><div><br />
</div>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-82684128864352528642011-02-23T09:13:00.000-08:002011-03-07T11:06:47.463-08:00Primeras pruebasLas primeras pruebas de comunicación entre el NXT y una placa Arduino Duemilanove se han realizado con éxito, usando la siguiente configuración:<br />
<div><br />
</div><div><div style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"><div>- Pines 2 y 3 del NXT (Rojo y negro) (tierra) --> Arduino GND</div><div>- Pin 4 del NXT (alimentacion) (verde) --> Arduino 5V</div><div>- Pin 5 del NXT (Amarillo) (SCL) --> Arduino A5</div><div>- Pin 6 del NXT (Azul) (SDA) --> Arduino A4</div></div><div style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"><br />
</div><div style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;">La primera prueba consiste simplemente en solicitar datos (Tipo de sensor, versión e identificador) desde el robot a Arduino, y todo ha ido sin problemas. Voy a poner a continuación el código de ambas partes.</div><div style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"><br />
</div><div style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"><b>CÓDIGO ESCRITO EN LEJOS PARA EL MINDSTORM</b></div><div style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"><br />
</div><div><div><span class="Apple-style-span" style="font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-style-span" style="color: #333333;">i</span><span class="Apple-style-span" style="color: blue;">mport lejos.nxt.*; </span></span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">import lejos.nxt.I2CPort;</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">import lejos.nxt.I2CSensor;</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><br />
</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">public class ArduCom {</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><br />
</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>public static void main(String[] args) throws Exception{ </span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>byte[] bufOut =new byte[10];</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>byte [] readData = new byte[10];</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>String Tipo = "";</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>String ID ="";</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>String Ver="";</span></span></div><div><span class="Apple-tab-span" style="line-height: 18px; white-space: pre;"><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"> </span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>for (int i=0;i<readData.length;i++){</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>readData[i] = 0;</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>bufOut[i] = 5;</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>}</span></span></div><div><span class="Apple-tab-span" style="line-height: 18px; white-space: pre;"><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"> </span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>I2CSensor Arduino = new I2CSensor(SensorPort.S1);</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>Arduino.setAddress(1); </span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>Thread.sleep(500);</span></span></div><div><span class="Apple-tab-span" style="line-height: 18px; white-space: pre;"><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"> </span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>Ver = Arduino.getVersion();</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>System.out.println("Ver: "+Ver);</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>Thread.sleep(100);</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>Tipo = Arduino.getSensorType();</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>System.out.println("Tipo: "+Tipo);</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>Thread.sleep(100);</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>ID = Arduino.getProductID();</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>System.out.println("ID: "+ID);</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>Thread.sleep(10000);</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><span class="Apple-tab-span" style="white-space: pre;"> </span>}</span></span></div><div><span class="Apple-tab-span" style="line-height: 18px; white-space: pre;"><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"> </span></span></div><div><span class="Apple-tab-span" style="line-height: 18px; white-space: pre;"><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"> </span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">}</span></span></div></div><div style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"><br />
</div><div style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"><br />
</div><div style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"><br />
</div><div style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"><b>CÓDIGO PARA ARDUINO</b></div></div><div style="color: #333333; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"><br />
</div><div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">#include <Wire.h> //Para gestionar las comunicaciones</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><br />
</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">//Definiciones y variables globales</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><br />
</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">uint8_t SensorVersion[9] = " V0.1 ";</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">uint8_t SensorName[9] = "Arduino ";</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">uint8_t SensorType[9] = "Casero ";</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><br />
</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">byte rec;</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><br />
</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">void setup(){</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> </span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> Serial.begin(9600);</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> Wire.begin(1); //Nos unimos como esclavos con dir. 1</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> Wire.onRequest(requestEvent); //Rutinas para cuando llegue algo</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> Wire.onReceive(receiveEvent); </span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">}</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><br />
</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><br />
</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">void loop(){</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> </span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">}</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><br />
</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">void receiveEvent(int len){ //Devuelve el nº de bytes recibidos </span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> while (0 < Wire.available() ) {</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> rec = Wire.receive();</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> } //While</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">}</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"><br />
</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">void requestEvent(){</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> if (rec == 0x00){ //Version del sensor</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> Wire.send(SensorVersion, 8);</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> } else if (rec == 0x08){ //Nombre del sensor</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> Wire.send(SensorName, 8);</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> } else if (rec == 0x10){ //Tipo del sensor</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> Wire.send(SensorType, 8);</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> } else {</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> Wire.send("Error de com"); </span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;"> }</span></span></div><div><span class="Apple-style-span" style="color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"><span class="Apple-style-span" style="line-height: 18px;">} </span></span></div></div>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-43601718735319076992011-02-23T09:05:00.000-08:002011-02-23T09:05:45.322-08:00Arduino Mega 2560 y los MindstormsComo ya sabeis, el primer paso es comunicar un Mindstorm NXT con una plaquita de Arduino. A la hora de hacer la elección de la placa para este proyecto, se tuvo en cuenta la capacidad, las prestaciones, etc. pero se omitió un detalle fundamental que voy a explicar a continuación. La placa elegida fue la Arduino Mega 2560.<div><br />
</div><div>En primer lugar, las conexiones que en principio hay que hacer entre el Mindstorm y Arduino son muy sencillas:</div><div><br />
</div><div><div>- Pines 2 y 3 del NXT (Rojo y negro) (tierra) --> Arduino GND</div><div>- Pin 4 del NXT (alimentacion) (verde) --> Arduino 5V</div><div>- Pin 5 del NXT (Amarillo) (SCL) --> Arduino SCL</div><div>- Pin 4 del NXT (Azul) (SDA) --> Arduino SDA</div></div><div><br />
</div><div>Y tanto la señal SDA como SCL están conectas a la línea de alimentación a través de unas <b>resistencias de Pull-up de 82 K</b>, así dichas líneas tendrán la tensión adecuada para que las detecte Arduino. Hasta aquí todo bien, salvo por un detalle... <b>no funciona.</b></div><div><br />
</div><div>Tras pasar varios días repasando el código (que ya pondré en otra entrada del blog), las conexiones, las resistencias, etc. descubrí el motivo por el que no funcionaba: la placa que estoy usando tiene ya integradas unas r<b>esistencias de 10 K </b>conectadas a las señales SDA y SCL. Estas resistencias hacen imposible poder conseguir el valor que necesito de resistencias de Pull-up.</div><div><br />
</div><div>Si la placa fuera una Arduino Mega (el modelo anterior) la solución es "sencilla", y consiste en eliminar las resistencias. Aquí tenéis una explicación de ello: <a href="http://mightor.wordpress.com/2009/08/04/connecting-the-nxt-to-an-arduinomega/">Enlace</a></div><div><br />
</div><div>¿Por qué en nuestro caso no es posible? Como veis en la imagen inferior, las resistencias que tiene nuestra placa están dentro de un encapsulado (el que pone 103) que, de acuerdo con el esquemático, engloba 4 resistencias. Una de ellas está conectada al pulsador de reset, lo que quiere decir que si eliminamos este encapsulado, nuestra placa no llegaría a encenderse (ya que el reset estaría siempre estaría a nivel bajo, y por tanto funcionando).</div><div><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_Pon686Rgr-t7JD6QvcG2QyEN0CNTXh_M30BcP8MyyEMC5rRgo8w4uDU6pvo12nFHpMA1gBeNJW_8hJGj2Ewgy8YYbdlNU6PabhfQqo0afbKMr0GmG_I-bRGymwlouIA1yjElULNW4ynx/s1600/e97ugx.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="266" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_Pon686Rgr-t7JD6QvcG2QyEN0CNTXh_M30BcP8MyyEMC5rRgo8w4uDU6pvo12nFHpMA1gBeNJW_8hJGj2Ewgy8YYbdlNU6PabhfQqo0afbKMr0GmG_I-bRGymwlouIA1yjElULNW4ynx/s320/e97ugx.jpg" width="320" /></a></div><div><br />
</div><div><br />
</div><div>De momento no he logrado encontrar solución a esto, así que cualquier sugerencia es bienvenida, pero me parece que poco se puede hacer salvo probar con otra modelo de Arduino.</div><div><br />
</div><div>Una alternativa que se ha barajado, ha sido la de usar SoftI2C, opción que ya comenté en alguna ocasión. Básicamente consiste en usar cualquier entrada analógica de Arduino para emular el protocolo I2C, y hacer toda la gestión por software. Pero esto tiene 2 problemas: las entradas analógicas también están conectadas a una resistencia interna, aunque algo más grande (20 K), y las librerías de softI2C sólo están creadas para que Arduino funcione como maestro en la comunicación, y nosotros lo necesitamos como esclavo del robot.</div>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-44267187923892438642011-01-26T10:05:00.000-08:002011-01-26T10:06:23.734-08:00Configurar Lejos en Eclipse en Mac OS XA continuación pongo un tutorial (el mejor que he encontrado) de cómo configurar Eclipse en OS X. Está hecho por los chicos de RoboByte, y el enlace está al final. Funciona a la perfección.<br />
<div><b><span class="Apple-style-span" style="font-size: medium;"><br />
Instalación de Entorno Eclipse</span></b></div><div><span class="Apple-style-span" style="font-size: small;">Para los que se instalen por primera vez la versión 3.5.1, avisar de que esta tiene problemas con la gestión de ventanas de Gnome (debido a recientes cambios en Gtk). Cuando no funcionen los botones utilizar el INTRO ó ALT+Tecla Botón.</span></div><div><ol><li>Instalamos <i>Eclipse</i> si todavía no lo tenemos<br />
Bajar la versión Classic desde <a href="http://www.eclipse.org/downloads/">Eclipse.org</a><br />
Lo descomprimir en un directorio cualquiera y lo ejecutamos<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivr-9xEjhLwOdsX0sbn4PCXveQMcLaGmxfOJO7rq0Jp_mEEspWVjflRH0OjwYxyFBLmsIMemiUtB5aKrawq7TDI3Qh0eFYJq9iVaEo_hIbi59aWip65gVucgPeo28FHn9jjba-UNKH_Ixh/s1600-h/Descarga+Eclipse.png"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5436710585689550450" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivr-9xEjhLwOdsX0sbn4PCXveQMcLaGmxfOJO7rq0Jp_mEEspWVjflRH0OjwYxyFBLmsIMemiUtB5aKrawq7TDI3Qh0eFYJq9iVaEo_hIbi59aWip65gVucgPeo28FHn9jjba-UNKH_Ixh/s320/Descarga+Eclipse.png" style="cursor: pointer; height: 194px; width: 320px;" /></a></li>
<li>Añadir el Plugin a Eclipse<br />
<i><blockquote>Help > Install New Software > Add...<br />
<span class="Apple-style-span" style="font-style: normal;">Name: <i>leJOS<br />
<span class="Apple-style-span" style="font-style: normal;">Location: <i>http://lejos.sourceforge.net/tools/eclipse/plugin/nxj/</i></span></i></span><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjwQ7yXjxlLU-Fmh03NoFsWRVI_LG3kXmrzimswBhz4HIlzccRXmL0nll0zvMDr-IJvoSE40nFVRP5tCh82L0xKB6SwMKnRIouLfn_-_jmwIzODjJSMx7R7oo01NbWIvCd9BI3OJZLPxB2K/s1600-h/A%C3%B1adir+Eclipse+Plugin.png"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5436710427497168178" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjwQ7yXjxlLU-Fmh03NoFsWRVI_LG3kXmrzimswBhz4HIlzccRXmL0nll0zvMDr-IJvoSE40nFVRP5tCh82L0xKB6SwMKnRIouLfn_-_jmwIzODjJSMx7R7oo01NbWIvCd9BI3OJZLPxB2K/s320/A%C3%B1adir+Eclipse+Plugin.png" style="cursor: pointer; height: 122px; width: 320px;" /></a></blockquote></i></li>
<li><i><span class="Apple-style-span" style="font-style: normal;"><i><span class="Apple-style-span" style="font-style: normal;"><i><span class="Apple-style-span" style="font-style: normal;">Lo instalamos<br />
Para la versión 3.5.1 es necesario desmarcar la opción "Group items by category"<br />
Establecer las preferencias:</span></i></span></i></span></i><span class="Apple-style-span" style="font-style: normal;"><span class="Apple-style-span" style="font-style: normal;"><span class="Apple-style-span" style="font-style: normal;"> Window > Preferences > leJOS NXJ</span></span></span><i><span class="Apple-style-span" style="font-style: normal;"><i><span class="Apple-style-span" style="font-style: normal;"><i><span class="Apple-style-span" style="font-style: normal;"><i><br />
<span class="Apple-style-span" style="font-style: normal;"><blockquote>NXJ_HOME: /opt/lejos<br />
Marcar "Conection Type > USB"<br />
Marcar "Run program after upload"<br />
Marcar "Verbose"<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEdd0IOzS4uJ_8HBIL3_fNn_rZaWmkPuNzk0GaZl4cebIxnBLtgQaJfE03TvJaigAOJDoKoPSei2r_hxDGcs7JuRbFlyy9b4IQVHc-FMDFAFQXgEEetJLgADCv12BWX3wRC0yUxumXe2MB/s1600-h/Instalacion+Eclipse+Plugins.png"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5436710929553541682" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEdd0IOzS4uJ_8HBIL3_fNn_rZaWmkPuNzk0GaZl4cebIxnBLtgQaJfE03TvJaigAOJDoKoPSei2r_hxDGcs7JuRbFlyy9b4IQVHc-FMDFAFQXgEEetJLgADCv12BWX3wRC0yUxumXe2MB/s320/Instalacion+Eclipse+Plugins.png" style="cursor: pointer; height: 282px; width: 320px;" /></a></blockquote></span></i></span></i></span></i></span></i></li>
</ol><span style="font-size: 100%;"><b><span class="Apple-style-span">Crear un Proyecto</span></b></span></div><div><ol><li><b><span class="Apple-style-span" style="font-weight: normal;">Para crear un proyecto para nuestro lego lo hacemos como uno normal de Java</span><span class="Apple-style-span" style="font-weight: normal;"><blockquote>File > New > Java Project<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2mCkLDRfxDKIeb_bti7xyTxHo7O4i7pXLC3gI3vx_HcdxUyf5g-9iaiImV1QcHyPnJnXISTYv20xHa3-5REqXNjq5fncq3Ju4AxhxhEexzt3cFkLW3mh-BkxeUTirEI-ifhD_z9o266n9/s1600-h/Eclipse+Nuevo+Proyecto.png"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5436712487196462130" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2mCkLDRfxDKIeb_bti7xyTxHo7O4i7pXLC3gI3vx_HcdxUyf5g-9iaiImV1QcHyPnJnXISTYv20xHa3-5REqXNjq5fncq3Ju4AxhxhEexzt3cFkLW3mh-BkxeUTirEI-ifhD_z9o266n9/s320/Eclipse+Nuevo+Proyecto.png" style="cursor: pointer; height: 188px; width: 320px;" /></a></blockquote></span></b></li>
<li>Convertimos el proyecto Java en leJOS<br />
<blockquote>Sobre el Proyecto, botón derecho: leJOS NXJ > Convert to leJOS NXT Project<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPLjG0vMju8DawDbVc5aAPH9SjkTsc34TGbKMW8Qog0_nLTDy-FAhjyJl8OvvyfW9PXI6mHGjJzq2yoWP5as2GSbq9ZrtuBeh8aBCLBAdhz4sbYBSC-CyLa3ofFNucw0C6omCWtHihr7xs/s1600-h/Eclipse+Convertir+Proyecto.png"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5436713256846585762" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPLjG0vMju8DawDbVc5aAPH9SjkTsc34TGbKMW8Qog0_nLTDy-FAhjyJl8OvvyfW9PXI6mHGjJzq2yoWP5as2GSbq9ZrtuBeh8aBCLBAdhz4sbYBSC-CyLa3ofFNucw0C6omCWtHihr7xs/s320/Eclipse+Convertir+Proyecto.png" style="cursor: pointer; height: 188px; width: 320px;" /></a></blockquote></li>
</ol></div><div><span class="Apple-style-span" style="font-size: 100%;"><b><span class="Apple-style-span">Añadir documentación Javadoc</span></b></span></div><div><span class="Apple-style-span" style="font-size: small;"><b><span class="Apple-style-span" style="font-weight: normal;"><div><ol><li>Seleccionamos la librería desde el Package Explorer<br />
References Libraries > classes.jar > (botón derecho) >Properties > Javadoc Location<br />
<blockquote>Javadoc URL: http://lejos.sourceforge.net/p_technologies/nxt/nxj/api/<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGbjroP8hyydkOtoxBzp-zyG_ylZT5d0ShzfgiHtvmbreqR9k33AzCvilxdziUeW5X1k3AQtJNm2MyjfMR1u9-FyDEgtMmJU70achl8xt_elI8ZxeOw3nFfhEmoW46_1aVvGaKJz1RNhMG/s1600-h/Eclipse+Javadoc+Proyecto.png"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5436713735790290338" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGbjroP8hyydkOtoxBzp-zyG_ylZT5d0ShzfgiHtvmbreqR9k33AzCvilxdziUeW5X1k3AQtJNm2MyjfMR1u9-FyDEgtMmJU70achl8xt_elI8ZxeOw3nFfhEmoW46_1aVvGaKJz1RNhMG/s320/Eclipse+Javadoc+Proyecto.png" style="cursor: pointer; height: 195px; width: 320px;" /></a></blockquote></li>
</ol></div></span></b></span></div><div><span style="font-size: 100%;"><b><span class="Apple-style-span">Compilar un Proyecto</span></b></span></div>Podemos compilar el proyecto manualmente cada vez que queramos probarlo, pero resultará a la larga más cómodo tener unos accesos directos ya puestos en Eclipse. Vamos a crear tres enlaces, para compilar, enlazar y subir al Lego.<br />
<ol><li> Nos dirigimos a: Run > External Tools > External Tools Configuration</li>
<li> Sobre: Program > New launch configuration</li>
<li>Creamos el enlace de compilacion con los siguientes parámetros<br />
<blockquote>Name: LeJOS Compile<br />
Location: ${env_var:NXJ_HOME}/bin/nxjc<br />
Directory: ${project_loc}/src/<br />
Arguments: ${java_type_name}.java<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUf9jI_IGPRgkmjg0waoauLTld9EvCe1BJ-OJVyu7y13XhfG3eQxvODtTUH2RQwfhnafQMeTW2oGWaStakDbCUviEEWy1xdmU9SI_tkn6wez6a_fhNtGbsExuaESIvKQkTa8yQyWce29C-/s1600-h/LeJOS+Compile.png"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5436708909975912850" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUf9jI_IGPRgkmjg0waoauLTld9EvCe1BJ-OJVyu7y13XhfG3eQxvODtTUH2RQwfhnafQMeTW2oGWaStakDbCUviEEWy1xdmU9SI_tkn6wez6a_fhNtGbsExuaESIvKQkTa8yQyWce29C-/s320/LeJOS+Compile.png" style="cursor: pointer; height: 262px; width: 320px;" /></a></blockquote></li>
<li> Creamos el enlace de enlazado<br />
<blockquote>Name: LeJOS Link<br />
Location: ${env_var:NXJ_HOME}/bin/nxjlink<br />
Directory: ${project_loc}/src/${java_type_name} -o ${java_type_name}.nxj<br />
Arguments: ${java_type_name} -o ${java_type_name}.nxj<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2qBwatusHIOGZq2LxD-atIuffgXKahenrRZXHAgddOfEQFlnflFweG4Wx3wi3raa-oJp2LAc-0Zd6S7Q6GrMPgctAVczoOKfdUUZm2LjV81lyULYEhKLgtSFXR8WyA6H_RDV3QY5ZtzGj/s1600-h/LeJOS+Link.png"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5436708789135593474" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2qBwatusHIOGZq2LxD-atIuffgXKahenrRZXHAgddOfEQFlnflFweG4Wx3wi3raa-oJp2LAc-0Zd6S7Q6GrMPgctAVczoOKfdUUZm2LjV81lyULYEhKLgtSFXR8WyA6H_RDV3QY5ZtzGj/s320/LeJOS+Link.png" style="cursor: pointer; height: 262px; width: 320px;" /></a></blockquote></li>
<li>Creamos el enlace para subir el programa al lego<br />
<blockquote>Name: LeJOS Upload<br />
Location: ${env_var:NXJ_HOME}/bin/nxjupload<br />
Working Directory: ${project_loc}/src/<br />
Arguments: ${java_type_name}.nxj<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgq9I6GhwlFgzFFQRNMryHMLfcq2TgPdVOJIuPmPeyf3HIs2YyrQsRb8aM9Al-0z0T0m7B4dOqJEXtIH19U593mtF9kHkur3D8t-OBG2Zo9yY8oqVlvMfl-nW_ySW8AMx_RQcsNpG_2Yawz/s1600-h/LeJOS+Upload.png"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5436708477358263170" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgq9I6GhwlFgzFFQRNMryHMLfcq2TgPdVOJIuPmPeyf3HIs2YyrQsRb8aM9Al-0z0T0m7B4dOqJEXtIH19U593mtF9kHkur3D8t-OBG2Zo9yY8oqVlvMfl-nW_ySW8AMx_RQcsNpG_2Yawz/s320/LeJOS+Upload.png" style="cursor: pointer; height: 262px; width: 320px;" /></a></blockquote></li>
<li>Creo obvio decir que para compilar y subir el programa habrá que seguir los pasos de forma ordenada: Compilar, Enlazar y Subir, xD</li>
</ol><div>Como último paso, hacemos un simple "Hello World" para comprobar que toda la configuración está correcta y que ya podemos ponernos manos a la obra.</div><div><b><br />
</b></div><div><b>----------------------------------------------------------------------------</b></div><div><b>REFERENCIAS:</b></div><div>Este tutorial ha sido sacado de <a href="http://robobyte.blogspot.com/2010/02/configurar-lejos-en-eclipse.html">aquí.</a><b><br />
</b></div>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-40633394524698550962011-01-26T10:00:00.000-08:002011-01-26T10:00:52.107-08:00Instalación de LejOS en Mac OSX Snow LeopardHola,<br />
<br />
No hay muchos tutoriales sobre esto y hasta que conseguí completar todos los pasos me llevé algún quebradero de cabeza. Intentaré que todo quede claro y lo más resumido posible, para que sólo tengais que seguir punto por punto lo que aquí pone.<br />
<br />
En primer lugar comentar que he usado Mac OS X 10.6, la última versión de Java (simplemente actualizando el sistema, ya que viene incluída por defecto en Mac) y la última versión de LejOS (a día de hoy la 0.85).<br />
<br />
Vamos al lío:<br />
<br />
<span class="postbody"> 1.Lo primero es instalar el 'Mac OS 10.5 (Leopard) Firmware Fix' de esta página: <a href="http://mindstorms.lego.com/support/updates/" target="_blank">http://mindstorms.lego.com/support/updates/</a>. Simplemente lo descargais y lo instalais como un .dmg más. </span><br />
<span class="postbody"><br />
2. Descargamos la versión de LeJOS que queramos usar. En mi caso, la última (versión 0.85) <a href="http://lejos.sourceforge.net/" target="_blank">http://lejos.sourceforge.net</a></span><br />
<span class="postbody"> <br />
3. Extraemos el fichero anterior donde queramos. Yo la he puesto en la librería. Como en Mac las rutas están mapeadas, la ruta sería: <br />
</span><br />
<table align="center" border="0" cellpadding="3" cellspacing="1"><tbody>
<tr> <td><span class="genmed"></span></td> </tr>
<tr> <td class="code">/Users/tunombredeusuario/Library/</td> </tr>
</tbody></table><span class="postbody"> <br />
4. Ponemos lo sisguiente en el terminal (el terminal está en Aplicaciones -> Utilidades):<br />
</span><table align="center" border="0" cellpadding="3" cellspacing="1"><tbody>
<tr> <td><span class="genmed"></span></td> </tr>
<tr> <td class="code">sudo pico ~/.bash_profile</td> </tr>
</tbody></table><span class="postbody"> <br />
Y en la ventana que nos sale introducimos lo siguiente: </span><table align="center" border="0" cellpadding="3" cellspacing="1"><tbody>
<tr> <td><span class="genmed"></span></td> </tr>
<tr> <td class="code">cd /Users/tunombredeusuario/Library/lejos_nxj <br />
LEJOS_HOME=`pwd` <br />
NXJ_HOME="$LEJOS_HOME" <br />
PATH="$LEJOS_HOME/bin:$PATH" <br />
export LEJOS_HOME NXJ_HOME <br />
export PATH</td> </tr>
</tbody></table><span class="postbody"> </span><br />
<span class="postbody">Es importante no dejar espacios entre operadores no nada que no salga aquí. Tampoco olvideís cambiar "</span>tunombredeusuario" por vuestro nombre de usuario :)<br />
<br />
Para guardar primero y salir después presionamos CTRL-O (y enter para salvar el archivo) y CTRL-X.<br />
<br />
---> Llegados aquí es conveniente reiniciar. Podemos seguir, pero los cambios no se aplicarán hasta que lo hayamos hecho.<br />
<table align="center" border="0" cellpadding="3" cellspacing="1"><tbody>
<tr> <td><br />
</td></tr>
<tr><td class="code"><br />
</td><td class="code"><br />
</td><td class="code"><br />
</td></tr>
</tbody></table><span class="postbody"><span style="font-weight: bold;"></span> 5. Establecemos la carpeta de lejos_nxj con los permisos necesarios para poder trabajar con ella. Para ello tecleamos desde el terminal:</span><table align="center" border="0" cellpadding="3" cellspacing="1"><tbody>
<tr><td><span class="genmed"><b></b></span></td> </tr>
<tr> <td class="code">chmod -R 755 ~/lejos_nxj/</td> </tr>
</tbody></table><span class="postbody"> <br />
<br />
6. Instalamos el driver fantom USB. Para ello tecleamos lo siguiente en el terminal:<br />
</span><table align="center" border="0" cellpadding="3" cellspacing="1"><tbody>
<tr> <td><span class="genmed"></span></td> </tr>
<tr> <td class="code">pico /Users/yourusername/Library/lejos_nxj/bin/nxj.properties</td><td class="code"> </td> </tr>
</tbody></table><br />
<span class="postbody">Y escribimos lo siguiente </span><span class="postbody">(de nuevo con cuidado de no dejar espacios): </span><span class="postbody"> </span><br />
<table align="center" border="0" cellpadding="3" cellspacing="1"><tbody>
<tr> <td><span class="genmed"><b><br />
</b></span></td> </tr>
<tr> <td class="code">NXTCommUSB=lejos.pc.comm.NXTCommFantom</td> </tr>
</tbody></table><span class="postbody"> <br />
7. Ahora vamos a las preferencias de JAVA (Aplicaciones -> Utilidades -> java -> Preferencias y cambiamos el orden de lo que nos sale: ponemos arriba los 32 bits y debajo los 64, ya que nuestro software usará la versión de 32 bits.</span><br />
<span class="postbody"> </span><br />
<div style="text-align: center;"><div style="text-align: center;"><span class="postbody"> <img border="0" src="http://img.skitch.com/20090904-emgd9uknqxdd2k3swuuast28j1.preview.jpg" /> </span></div><span class="postbody"></span></div><span class="postbody"><br />
</span><br />
<div style="text-align: center;"><div style="text-align: center;"><span class="postbody"> <img border="0" src="http://img.skitch.com/20090904-dkcggfgf8rtgnggu9urjug36nx.preview.jpg" /> </span></div><div style="text-align: center;"><span class="postbody"> </span></div><span class="postbody"></span></div><span class="postbody"> Finalmente, con el ladrillo conectado al ordenador y encendido tecleamos lo siguiente en el terminal para comprobar que todo ha ido bien:<br />
</span><br />
<table align="center" border="0" cellpadding="3" cellspacing="1"><tbody>
<tr> <td><br />
</td> </tr>
<tr> <td class="code">nxjbrowse -u</td> </tr>
</tbody></table><span class="postbody"> <br />
Otros comandos úties son, para compilar:<br />
</span><table align="center" border="0" cellpadding="3" cellspacing="1"><tbody>
<tr> <td><span class="genmed"></span></td> </tr>
<tr> <td class="code">nxjc myProject.java</td> </tr>
</tbody></table><span class="postbody"> <br />
Y para transferir al robot: </span><br />
<table align="center" border="0" cellpadding="3" cellspacing="1"><tbody>
<tr> <td><span class="genmed"></span></td> </tr>
<tr> <td class="code">nxj myProject</td><td class="code"> </td><td class="code"> </td><td class="code"> </td><td class="code"><br />
</td><td class="code"><br />
</td></tr>
</tbody></table><span class="gensmall"></span>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-12350589895776320022011-01-26T09:42:00.000-08:002011-01-26T10:07:29.440-08:00Como instalar LejOS en Windows XP usando EclipseAntes que nada comentaros que el siguiente tutorial no está redactado por mi. El sitio del que lo he sacado se encuentra al final de este post (como siempre en referencias) y todo el mérito es de los respectivos autores. Mi idea es elaborar un tutorial más actualizado, y si tengo tiempo lo subiré al blog en sustitución de este. Mientras tanto, espero que os sea de ayuda :)<br />
<br />
<i class="info">------------------------------- </i><br />
Aquí explicaremos como instalar y configurar todo el software necesario para desarrollar programas en java para el robot Lego Mindstorms NXT usando Lejos y software enbebido en el robot, es un metodo que permite colocar pequeños programas java adentro de la memoria del mismo y así proveer más independencia al mismo.<br />
Se incluyen también referencias a sitios de interés y dos libros muy buenos para trabajar con los NXT.<br />
Java es mucho más poderoso y flexible que el software provisto por Lego, NXT-G. Usaremos el editor Eclipse para escribir el código Java y bajarlo al NXT. Esta combinación permite escribir el software y convenientemente probarlo rápido en el NXT. Claro que hay muchos otros editores de Java, pero esta es una opción bastante viable. El tutorial es para plataforma Windows con la compilación LeJOS una alternativa muy buena para iniciarse en este campo, ya que no es dificil de instalar y las funciones son bastante intuitivas como se verá en el programa de ejemplo, seguiremos los siguientes 5 pasos:<br />
1. Instalar Java en la computadora<br />
2. Instalar el driver Lego NXT USB en la computadora.<br />
3. Instalar Lejos en la computadora y en el Robot NXT<br />
4. Instalar y configurar Eclipse en la computadora<br />
5. Escribir, bajar y correr un programa “HolaMundo”<br />
<span style="font-size: 11pt;"> </span><span id="more-11"></span><br />
<span style="font-size: 11pt;">Es importante seguir el orden de estos pasos uno a uno, además recomendamos estos excelentes libros, mayan adventure y extreme NXT, ambos con información básica de los robots como su construcción y empleo pasando luego a cualidades más avanzadas (se detallará más en otro post sobre los libros).</span><br />
En Mayan se diseña software para que salgan de un laberinto y en extreme se presentan múltiples ideas de proyectos con los NXT y cuestiones avanzadas como el quemador de pics y otros, con fotografías y guías paso a paso.<br />
<h3><a href="http://www.blogger.com/post-edit.g?blogID=754387214278989398&postID=1235058989577632002" name="installJava"></a>Libros</h3><a href="http://www.megaupload.com/?d=Z3B5WXJQ"><img alt="Mayan Adventure" class="alignnone size-thumbnail wp-image-57" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/51e0bfxx6bl.jpg?w=72&h=96" width="72" /></a><a href="http://www.megaupload.com/?d=0YNMTOAK"><img alt="Lego Extreme NXT" class="alignnone size-thumbnail wp-image-58" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/extrnxt.jpg?w=72&h=96" width="72" /></a><br />
<h3>1. Instalar Java en la computadora</h3><a href="http://www.java.com/en/download/manual.jsp">Descargar</a> e instalar Java SE (Stadard Edition) JRE (Java Runtime Environment). No es necesario instalar el JDK (Java DEveloper Kit). Luego se instalará Eclipse, que contiene todas las herramientas necesarias para escribir y compilar los programas. Luego de la instalación no es necesario definir ningún Path o Classpath para Java. Java se instala normalmente en C:\Program Files\Java.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/01jre_01.png"><img alt="" class="alignnone size-thumbnail wp-image-8" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/01jre_01.png?w=109&h=96" width="109" /></a><br />
Si ya se tiene Java hay que revisar que por lo menos sea la versión 5, de preferencia del JRE, el JDK también funciona. Luego se instalará Eclipse que requiere esta versión como mínimo.<br />
<h3><a href="http://www.blogger.com/post-edit.g?blogID=754387214278989398&postID=1235058989577632002" name="installUSB"></a>2.Instalar driver USB de Lego</h3>El NXT se puede conectar a la computadora por USB o por Bluetooth. La comunicación por USB es más confiable y rápida que la por Bluetooth. El Bluetooth depende de cada computadora en especifico. USB en cambio, esta más estandarizado. Primero se debe instalar el driver y hasta después, conectar el NXT con el cable USB. No se necesita instalar el software que viene en el CD del robot porque no se programará en NXT-G (El software de lego basado en Labview). Solo se necesita instalar el driver USB que esta disponible en el sitio oficial de Mindstorms. Si ya se ha instalado el software original de Mindstorms no es necesario desinstalarlo, solo revisar si el sitio de mindstorms tiene alguna actualización para el dirver USB.<br />
<a href="http://mindstorms.lego.com/Support/Updates/">Descargar</a> el Driver de Mindstorms NXT.<br />
<span style="color: blue;"> </span><a href="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_01download.png"><img alt="" class="alignnone size-thumbnail wp-image-20" height="95" src="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_01download.png?w=119&h=95" width="119" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_02download_here.png"><img alt="" class="alignnone size-thumbnail wp-image-21" height="95" src="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_02download_here.png?w=119&h=95" width="119" /></a><br />
Descomprimir el archivo y ejecutar setup.exe.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_03unzipped.png"><img alt="" class="alignnone size-thumbnail wp-image-22" height="77" src="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_03unzipped.png?w=128&h=77" width="128" /></a><br />
Recorrer el programa de instalación<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_04setup.png"><img alt="" class="alignnone size-thumbnail wp-image-23" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_04setup.png?w=124&h=96" width="124" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_05setup_success.png"><img alt="" class="alignnone size-thumbnail wp-image-24" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_05setup_success.png?w=124&h=96" width="124" /></a><br />
Es possible que windows solicite reiniciar el equipo luego de la instalación. Luego, se conecta el NXT por medio del USB. Comprobar la correcta instalación del driver comprobando si esta en el adminstrador de dispositivos. Para hacer esto, dar click derecho en “My Computer” y luego “Properties” pasar a Hardware. Dar Click en “Device manager”. Tiene que aparecer “Lego Devices=>Lego Mindstorms NXT”<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_06setup_check.png"><img alt="" class="alignnone size-thumbnail wp-image-25" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_06setup_check.png?w=82&h=96" width="82" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_07setup_check_ok.png"><img alt="" class="alignnone size-thumbnail wp-image-26" height="90" src="http://laberintonxt.files.wordpress.com/2008/05/11nxtdriver_07setup_check_ok.png?w=128&h=90" width="128" /></a><br />
<h3><a href="http://www.blogger.com/post-edit.g?blogID=754387214278989398&postID=1235058989577632002" name="installLejos"></a>3. Instalar Lejos en la computadora y en el Mindstorms NXT</h3><a href="http://lejos.sourceforge.net/p_technologies/nxt/nxj/downloads.php">Bajar</a> Lejos.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/02lejos_download_05.png"><img alt="" class="alignnone size-thumbnail wp-image-16" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/02lejos_download_05.png?w=109&h=96" width="109" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/02lejos_download_10.png"><img alt="" class="alignnone size-thumbnail wp-image-17" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/02lejos_download_10.png?w=109&h=96" width="109" /></a><br />
Crear un directorio llamado “ProgramFiles” en el disco duro. Esto para evitar problemas con el espacio asociado al usual “Program Files” que a veces no funciona correctamente con Java. Luego se instalará Eclipse también en “ProgramFiles”.<br />
Descomprimir Lejos. Esto nos dará una carpeta llamada “lejos_nxj”. Colocar esta carpeta en “ProgramFiles”.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/02lejos_download_14zip.png"><img alt="" class="alignnone size-thumbnail wp-image-18" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/02lejos_download_14zip.png?w=123&h=96" width="123" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/02lejos_download_15unzip.png"><img alt="" class="alignnone size-thumbnail wp-image-19" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/02lejos_download_15unzip.png?w=128&h=96" width="128" /></a><br />
Ahora hay que informar a Java de la existencia de la librería Lejos. Dar click derecho en “My Computer” y seleccionar “Propiedades”. <span lang="EN-US">Click en la pestaña “Advanced”. </span>Click en “Environment Variables” hasta abajo. Crear una nueva “System variable”dando click en “New” hasta abajo. No crear una “User variable” de arriba.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/02lejos_03systemproperties.png"><img alt="" class="alignnone size-thumbnail wp-image-9" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/02lejos_03systemproperties.png?w=82&h=96" width="82" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/02lejos_04envvariables.png"><img alt="" class="alignnone size-thumbnail wp-image-10" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/02lejos_04envvariables.png?w=85&h=96" width="85" /></a><br />
<span lang="EN-US">Por nombre poner a la nueva system variable:</span><br />
<div class="ccode"><span lang="EN-US">LEJOS_HOME</span></div><span lang="EN-US">Y dar el value:</span><br />
<div class="ccode"><span lang="EN-US">C:\ProgramFiles\lejos_nxj</span></div>En pocas palabras, Lejos necesita saber donde fue instalado. Notar que ahora ya usamos el nuevo directorio “ProgramFiles” que no tiene el carácter de espacio. Al finalizar, dar click en OK.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/02lejos_05lejos_home.png"><img alt="" class="alignnone size-thumbnail wp-image-11" height="54" src="http://laberintonxt.files.wordpress.com/2008/05/02lejos_05lejos_home.png?w=127&h=54" width="127" /></a><br />
Verificar que la variable del sistema aparece en la lista. Ahora, se necesita agregar la variable LEJOS_HOME a la variable del sistema “Path”. Seleccionar “Path”de la lista y dar click en “edit”. <span lang="EN-US">Agregar:</span><br />
<div class="ccode"><span lang="EN-US">;%LEJOS_HOME%\bin</span></div>Al final del valor. Los distintos valores estan separados por punto y coma y no se require punto y coma al final de la linea.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/02lejos_06envvariables_new.png"><img alt="" class="alignnone size-thumbnail wp-image-12" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/02lejos_06envvariables_new.png?w=85&h=96" width="85" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/02lejos_07envvariables_new.png"><img alt="" class="alignnone size-thumbnail wp-image-13" height="54" src="http://laberintonxt.files.wordpress.com/2008/05/02lejos_07envvariables_new.png?w=127&h=54" width="127" /></a><br />
Ahora hay que probar si se instaló correctamente Lejos usando una ventana de comandos DOS. Dar click en el menú inicio, luego “All Programs=>Accessories=>Command Prompt”. Escribir:<br />
<div class="ccode">lejosdl</div>El resultado debe ser como en esta imagen, si es así, todo esta bien.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/02lejos_08commandprompt.png"><img alt="" class="alignnone size-thumbnail wp-image-14" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/02lejos_08commandprompt.png?w=96&h=96" width="96" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/02lejos_09lejos_test.png"><img alt="" class="alignnone size-thumbnail wp-image-15" height="83" src="http://laberintonxt.files.wordpress.com/2008/05/02lejos_09lejos_test.png?w=128&h=83" width="128" /></a><br />
Ahora hay que reemplazar el firmware original que viene con el NXT por Lejos. Esto solo se hace una vez. Luego Lejos funcionará como el sistema operativo del NXT. Implementa una maquina virtual Java donde se pueden correr los programas Java. Asegurarse de que el NXT está conectado a ala computadora con un cable USB y que ha sido reconocido por el sistema operativo. Para asegurarse ir al Device Manager. Primero se necesita colocar al NXT en modalidad de subida del firmware. Usar un clip para presionar y sostener el botón oculto abajo del bloque. El NXT tocará un sonido suave y pulsante que indica que está listo.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl_nxt01.jpg"><img alt="" class="alignnone size-thumbnail wp-image-30" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl_nxt01.jpg?w=128&h=96" width="128" /></a><br />
<span lang="EN-US">Escribir:</span><br />
<div class="ccode"><span lang="EN-US">lejosfirmdl</span></div>En la linea de comandos DOS.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl.png"><img alt="" class="alignnone size-thumbnail wp-image-27" height="83" src="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl.png?w=128&h=83" width="128" /></a><br />
Lejos necesita Libusb para comunicarse con el NXT. Si no se ha instalado este software gratuito en la computadora, se iniciará el instalador del mismo. Libusb permite a los programas acceder a cualquier dispositivo USB de forma genérica. Hay que asegurarse de que no se ejecute la aplicación de prueba mencionada al final. En caso de que Lejos ya esté instalado en el NXT aún será necesario instalar LibUSB para ser capaz de bajar los programas. Se puede encontrar en “lejos_nxj\3rdparty\lib\libusb-win32-filter-bin-0.1.12.1.exe”. El nombre puede cambiar cuando una nueva versión de libusb esté disponible.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl_libusb.png"><img alt="" class="alignnone size-thumbnail wp-image-28" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl_libusb.png?w=123&h=96" width="123" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl_libusb_3.png"><img alt="" class="alignnone size-thumbnail wp-image-29" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl_libusb_3.png?w=123&h=96" width="123" /></a><br />
Una vez que Libusb está instalado el instalador de Lejos continuará hasta terminar exitosamente, viéndose de la siguiente manera:<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl_success.png"><img alt="" class="alignnone size-thumbnail wp-image-33" height="83" src="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl_success.png?w=128&h=83" width="128" /></a><br />
Ahora se reiniciará el NXT y luego mostrará el logo de Lejos antes de cambiar al menú principal.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl_nxt03.jpg"><img alt="" class="alignnone size-thumbnail wp-image-32" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl_nxt03.jpg?w=128&h=96" width="128" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl_nxt02.jpg"><img alt="" class="alignnone size-thumbnail wp-image-31" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/17lejosfirmdl_nxt02.jpg?w=128&h=96" width="128" /></a><br />
Ahora el NXT está listo para corer programas Java.<br />
<h3><a href="http://www.blogger.com/post-edit.g?blogID=754387214278989398&postID=1235058989577632002" name="installEclipse"></a>4. Instalar y configurar Eclipse en la computadora</h3><a href="http://www.eclipse.org/downloads/">Bajar</a> Eclipse IDE para desarrolladores Java. Eclips está escrito en Java y no contiene un instalador, viene en un ZIP sencillo que habrá que extraer en nuestro foler “ProgramFiles”. Se puede crear un acceso directo para conveniencia de “eclipse.exe” en el escritorio o donde sea necesario.<br />
<span style="color: blue;"> </span><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_01_install_02.png"><img alt="" class="alignnone size-thumbnail wp-image-34" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_01_install_02.png?w=128&h=96" width="128" /></a><br />
<span lang="EN-US"> </span><br />
Al iniciar Eclipse se solicitará escoger un espacio de trabajo. El espacio de trabajo contendrá todos los archives que se creen. De nuevo, se debería crear un directorio en una ubicación que no contenga espacios en blanco “ “. <span lang="EN-US">Usaremos un directorio “d:\programming\workspace”. Luego se da la pantalla de bienvenida de Eclipse.</span><br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_05.png"><img alt="" class="alignnone size-thumbnail wp-image-35" height="71" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_05.png?w=128&h=71" width="128" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_10_welcome.png"><img alt="" class="alignnone size-thumbnail wp-image-36" height="95" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_10_welcome.png?w=128&h=95" width="128" /></a><br />
Ahora crearemos un programa “Hola Mundo” y lo subiremos (o bajaremos) al NXT. <span lang="EN-US">Primero se necesita crear un nuevo proyecto Java. </span>Dar click en “File => New => Java Project”. Escribir un nombre para el proyecto, evitar siempre los caracteres en blanco. <span lang="EN-US">En este caso se llamará “LeJOS_NXJ”</span><br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject.png"><img alt="" class="alignnone size-thumbnail wp-image-37" height="95" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject.png?w=128&h=95" width="128" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject_01.png"><img alt="" class="alignnone size-thumbnail wp-image-38" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject_01.png?w=69&h=96" width="69" /></a><br />
A continuación, se requiere convertir este proyecto en un proyecto Lejos. Dar click derecho en el proyecto y seleccionar “properties”. Seleccionar “Java Build Path” en la izquierda y dar click en la pestaña “libraries”. Luego, dar click en “Add External JARs…” y encontrar el directorio “lib”en la carpeta “ProgramFiles\lejos_nxj”. Seleccionar “clases.jar” y presionar “Open”. Ahora la librería Lejos aparecerá en el listado.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject_04.png"><img alt="" class="alignnone size-thumbnail wp-image-39" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject_04.png?w=118&h=96" width="118" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject_08.png"><img alt="" class="alignnone size-thumbnail wp-image-40" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject_08.png?w=120&h=96" width="120" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject_12.png"><img alt="" class="alignnone size-thumbnail wp-image-41" height="95" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject_12.png?w=128&h=95" width="128" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject_14.png"><img alt="" class="alignnone size-thumbnail wp-image-42" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject_14.png?w=120&h=96" width="120" /></a><br />
En propiedades, nos movemos a la sección “Java Compiler” que está a la izquierda. Seleccionamos la opción “Enable prject specific settings”y escoger nivel 1.3 para el nivel de compatibilidad del compilador. Esta hará que el compilador optimice para una versión anterior de Java. Esta versión anterior es más compatible con el NXT ya que ha sido diseñada para sistemas enbebidos. Requiere mucho menos recursos que la última versión de Java. Dar click en “Apply” luego en “OK” para dejar las propiedades.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject_18.png"><img alt="" class="alignnone size-thumbnail wp-image-43" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_15_newjavaproject_18.png?w=106&h=96" width="106" /></a><br />
El siguiente paso es configurar Eclipse para bajar el software al NXT. Dar clic en <span lang="EN-US">“Run => External Tools => Open External Tools Dialog…”.</span><br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_05.png"><img alt="" class="alignnone size-thumbnail wp-image-44" height="90" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_05.png?w=128&h=90" width="128" /></a><br />
Seleccionar “program” en la izquierda y luego dar click en “New”. Nombrar la herramienta “lejos Download” arrba. En la pestaña principal, ingresar la ubicación del archivo “lejosd1.bat” que tendría que estar en la carpeta “lejos-nxj\bin\” que se puede ubicar dando click en “Browse File System”. Entrar a:<br />
<div class="ccode">${project_loc}\bin</div>En el “Working directory” e ingresar<br />
<div class="ccode"><span lang="EN-US">${java_type_name}</span></div>En la sección de argumentos.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_10.png"><img alt="" class="alignnone size-thumbnail wp-image-45" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_10.png?w=108&h=96" width="108" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_15.png"><img alt="" class="alignnone size-thumbnail wp-image-46" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_15.png?w=108&h=96" width="108" /></a><br />
Ahora crearemos un acceso directo para bajar el programa al NXT. Dar click en el icono “run” en la barra de herramientas y seleccionar “Organize Favorites…” Dar click en “Add…” en la ventana que aparece y luego seleccionar la opción de “lejos Download”, que es la herramienta externa que hemos configurado anteriormente. Presionar “OK”y luego “Ok” de nuevo.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_20.png"><img alt="" class="alignnone size-thumbnail wp-image-47" height="90" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_20.png?w=128&h=90" width="128" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_25.png"><img alt="" class="alignnone size-thumbnail wp-image-48" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_25.png?w=91&h=96" width="91" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_30.png"><img alt="" class="alignnone size-thumbnail wp-image-49" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_30.png?w=82&h=96" width="82" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_35.png"><img alt="" class="alignnone size-thumbnail wp-image-50" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_17_lejosdl_35.png?w=91&h=96" width="91" /></a><br />
<h3><a href="http://www.blogger.com/post-edit.g?blogID=754387214278989398&postID=1235058989577632002" name="programHelloWorld"></a>5. Escribir, bajar y ejecutar un programa “Hola mundo”</h3><span lang="EN-US"> </span><br />
Primero, creamos la clase principal para nuestro programa. <span lang="EN-US">Dar click en “New=>Class”. Nombrarla “HelloWorld” y seleccionar “public static void(String[] args)”. Luego recibira una clase casí vacia. </span>Eclipse es un editor de Java muy inteligente que intent compilar el programa a medida que se escribe. Similar a lo que ocurre en Word, subraya errores con una línea roja. En ocaciones esta compilación automática no funciona y se necesita forzar a que Eclipse compile. Esto se puede lograr simplemente guardando el archivo.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_20_newclass.png"><img alt="" class="alignnone size-thumbnail wp-image-51" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_20_newclass.png?w=118&h=96" width="118" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_20_newclass_05.png"><img alt="" class="alignnone size-thumbnail wp-image-52" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_20_newclass_05.png?w=80&h=96" width="80" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_20_newclass_10.png"><img alt="" class="alignnone size-thumbnail wp-image-53" height="96" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_20_newclass_10.png?w=118&h=96" width="118" /></a><br />
Ahora se ingresarán algunas lineas de codigo java. En la primera línea escribir:<br />
<div class="ccode"><span lang="EN-US">import lejos.nxt.LCD;</span></div>Esta linea permitirá que el programa use el display LCD del NXT. Luego, necesitamos definir que se mostrará y cuando. Agregar estas líneas al método principal:<br />
<div class="ccode"><span lang="EN-US">LCD.drawString(”Hola mundo!”, 2, 2);<br />
LCD.refresh();<br />
while(true) {}</span></div>Ahora se puede bajar el programa al NXT. En la siguiente pantalla se pueden ver estos pasos. Antes de empezar con el proceso de bajado hay que asegurarse de que el NXT este conectado a la computadora y de que el NXT ha sido reconocido por el sistema operativo, de nuevo, esto se puede comprobar en el administrador de dispositivos. Tambien hay que seleccionar la clase principal al centro antes de empezar a bajar, para que Eclipse sepa que clase es la que se quiere bajar. Usar el menú desplegable (4 en la pantalla) para seleccionar el favorito de bajada que antes creamos. Esto iniciará el proceso de bajado al NXT.<br />
<a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_20_newclass_20.png"><img alt="" class="alignnone size-thumbnail wp-image-54" height="90" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_20_newclass_20.png?w=128&h=90" width="128" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_20_newclass_25.png"><img alt="" class="alignnone size-thumbnail wp-image-55" height="90" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_20_newclass_25.png?w=128&h=90" width="128" /></a><a href="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_20_newclass_30.png"><img alt="" class="alignnone size-thumbnail wp-image-56" height="90" src="http://laberintonxt.files.wordpress.com/2008/05/30eclipse_20_newclass_30.png?w=128&h=90" width="128" /></a><br />
Luego de que la descarga ha sido completada se puede iniciar el program usando los botones en el NXT. Notar que el programa correrá para siempre. Para detenerlo se necesita resetear el NXT presionando los dos botones del centro por un tiempo más largo. Esto finalizará la conexión USB así que habrá que esperar un poco para reconectarse antes de bajar un nuevo programa. Claro que hay mejores maneras de terminar el programa, como escuchar por un botón o luego de algún tiempo, se puede reemplazar el while sin fin por esto:<br />
<div class="ccode"><span lang="EN-US">try {<br />
Thread.sleep(5000);<br />
} catch (InterruptedException e) {<br />
// TODO Auto-generated catch block<br />
}</span></div>Esto hará que el NXT duerma 5 segundos antes de que el programa termine. Ahora verá “Hola Mundo!” por cinco segundos y luego el programa termina. Para mas información de cómo programar en Java para el NXT se puede visitar el sitio <a href="http://lejos.sourceforge.net/">leJOS</a>.<br />
-------------------------------------------------------------------------------------------<br />
<b>REFERENCIAS:</b><br />
- Este tutorial está sacado de <a href="http://robotlego.wordpress.com/2008/06/15/tutorial-como-instalar-y-correr-java-con-un-robot-lego-mindstorms-nxt-usando-eclipse-metodo-alternativo/">aquí</a>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-15641093159493524452011-01-13T11:12:00.000-08:002011-01-13T11:12:06.544-08:00Emular I2C con otros pines en Arduino (softi2c)Desde hace algunos días, ando buscando una solución para el esquema del proyecto. El problema es el siguiente:<br />
<br />
- Por una parte, Arduino debe ser esclavo con respecto al Mindstorm, ya que éste será quien le solicite datos.<br />
- Por otra parte, Arduino debe ser maestro con respecto a los sensores, para que sea él quien inicie la comunicación y pedirles los datos cuando sea necesario.<br />
<br />
Como sólo puede haber un dispositivo maestro en el bus a la vez, y éste en principio será el Mindstorm, es dificil saber cómo solicitarle a los sensores los datos (suponiendo que estos usen I2C). Una posibilidad, es colocar los sensores en otros pines de nuestra placa de Arduino, que no sean los pines definidos para I2C. ¿Cómo? Es lo que se conoce como software I2C.<br />
<br />
He encontrado varios enlaces al respecto, y ando comparando soluciones para ver si esta es adecuada o no, pero de momento gana enteros. Los enlaces son los siguientes:<br />
<br />
- Un chico que ha creado una librería llamada "SoftI2CMaster": <a href="http://todbot.com/blog/2010/09/25/softi2cmaster-add-i2c-to-any-arduino-pins/">Aquí</a><br />
- Otro artículo y librerías de JeeLabs: <a href="http://jeelabs.org/2010/03/15/software-and-hardware-i2c/">Artículo</a> y <a href="http://jeelabs.net/projects/cafe/wiki/Libraries">Librerías</a><br />
<br />
Finalmente dejo un enlace del foro de Arduino donde planteé el tema y me están ayudando mucho :) Es interesante leer lo que han aportado los compañeros, porque son alternativas muy buenas: <a href="http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1294825899/0">Enlace al post del foro</a>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-62203783596559599632011-01-11T10:32:00.000-08:002011-01-11T10:40:38.068-08:00Fabricar conectores caseros para el NXT<div align="center"><a href="http://www.philohome.com/nxtplug/cable12.jpg"><span style="color: green; font-family: Arial; font-size: large;"><b><img border="2" height="300" src="http://www.philohome.com/nxtplug/plug.jpg" width="400" /></b></span></a></div><div align="left"><br />
</div><div align="left">El NXT usa un conector muy parecido al cable telefónico, pero con la "pestañita" de plástico del lado derecho en lugar del lado izquierdo. Hasta hace poco, este conector no se encontraba a la venta, por lo que era necesario fabricarlo (ahora se puede adquirir en la página de Mindsensors, cuyo enlace es <a href="http://www.mindsensors.com/index.php?module=pagemaster&PAGE_user_op=view_page&PAGE_id=67">este</a>). Vamos a explicar a continuación cómo fabricar este conector:<span style="color: green; font-family: Arial;"><b><br />
</b></span></div><table border="0"><tbody>
<tr><td><br />
</td><td width="947"><br />
</td> </tr>
<tr> <td><br />
</td><td><br />
</td><td><br />
</td><td><br />
</td><td><br />
</td><td><br />
</td><td><br />
</td> <td width="947"><br />
</td> </tr>
<tr> <td><br />
</td> <td width="947"><br />
</td> </tr>
</tbody></table>Para hacer lo siguiente, vamos a partir de los conectores RJ-12 del cable telefónico tradicional <br />
<table border="0"><tbody>
<tr> <td><a href="http://www.philohome.com/nxtplug/cable01.jpg"><img border="2" height="150" src="http://www.philohome.com/nxtplug/cable01-v.jpg" width="200" /></a></td> <td width="947">Inicialmente, nuestro conector se encuentra climpado al cable telefónico, como vemos en la figura de la izquierda. Tanto el conector como el cable debe tener 6 hilos disponibles, y para que coincida con los colores que usa LEGO es preferible que la combinación de colores sea (de izquierda a derecha): Azul - Amarillo - Verde - Rojo - Negro - Blanco. Si hemos climpado el cable manualmente, es recomendable antes de seguir, que verifiquemos si todo hace bien contacto.</td> </tr>
<tr> <td><a href="http://www.philohome.com/nxtplug/cable02.jpg"><img border="2" height="150" src="http://www.philohome.com/nxtplug/cable02-v.jpg" width="200" /></a></td> <td width="947">Si comparamos un cable RJ-12 a un conector del NXT vemos dos diferencias: <br />
<ul><ul type="disc"><li>La pestañita debe desplazarse hacia la derecha del conector. </li>
<li>La pestañita en el RJ-12 es más ancha que la del conector del NXT, por lo que tendremos que lijarla. Además, la pestañita del RJ-12 también es más larga, pero esto no nos importará demasiado, ya que no impedirá que entre en el hueco correspondiente.</li>
</ul></ul><br />
</td> </tr>
<tr> <td><a href="http://www.philohome.com/nxtplug/cable03.jpg"><img border="2" height="150" src="http://www.philohome.com/nxtplug/cable03-v.jpg" width="200" /></a></td> <td width="947">En primer lugar, se corta la pestañita siguiendo la línea roja que se ve en la figura de la izquierda.</td> </tr>
<tr> <td><a href="http://www.philohome.com/nxtplug/cable04.jpg"><img border="2" height="150" src="http://www.philohome.com/nxtplug/cable04-v.jpg" width="200" /></a></td> <td width="947">Esto se puede hacer por ejemplo con una hoja de acero montada sobre una lijadora, o de forma más casera. Obiamente cuanto más corte nuestra herramienta, más fácil y preciso será el resultado.</td> </tr>
<tr> <td><a href="http://www.philohome.com/nxtplug/cable05.jpg"><img border="2" height="150" src="http://www.philohome.com/nxtplug/cable05-v.jpg" width="200" /></a></td> <td width="947">En la figura se ve el conector después de quitarle la "pestañita" y esta colocada al lado del mismo.</td> </tr>
<tr> <td><a href="http://www.philohome.com/nxtplug/cable06.jpg"><img border="2" height="150" src="http://www.philohome.com/nxtplug/cable06-v.jpg" width="200" /></a></td> <td width="947">Lijamos los laterales de la pestaña de plástico que hemos cortado para que coincida en ancho con la del NXT.</td> </tr>
<tr> <td><a href="http://www.philohome.com/nxtplug/cable07.jpg"><img border="2" height="150" src="http://www.philohome.com/nxtplug/cable07-v.jpg" width="200" /></a></td> <td width="947">También podemos cortar ambos lados con la misma herramienta que antes, pero con esto es más fácil pasarnos y recortar demasiado la pieza.</td> </tr>
<tr> <td><a href="http://www.philohome.com/nxtplug/cable08.jpg"><img border="2" height="150" src="http://www.philohome.com/nxtplug/cable08-v.jpg" width="200" /></a></td> <td width="947">Iremos probando a meter la pieza en el conector. Debería entrar fácilmente si hemos hecho todo bien.</td> </tr>
<tr> <td><a href="http://www.philohome.com/nxtplug/cable09.jpg"><img border="2" height="150" src="http://www.philohome.com/nxtplug/cable09-v.jpg" width="200" /></a></td> <td width="947">Pegamos la pestaña en el lado derecho del conector con pegamento fuerte, y le ponemos cinta adhesiva (o parecido) encima para que no se despegue hasta que termine de secarse. Comprobamos que hemos pegado la pestaña en el sitio adecuado comparándola con la del conector del NXT.</td> </tr>
<tr> <td><a href="http://www.philohome.com/nxtplug/cable10.jpg"><img border="2" height="150" src="http://www.philohome.com/nxtplug/cable10-v.jpg" width="200" /></a></td> <td width="947">Colocamos el conector en una prensa y lo dejamos ahí hasta que seque bien. Eliminamos con un trozo de papel el pegamento sobrante que se haya salido por los lados tras hacer presión. Hay que tener en cuenta que los pegamentos de secado lento dan mejores resultados que los de secado rápido.</td> </tr>
<tr> <td><a href="http://www.philohome.com/nxtplug/cable11.jpg"><img border="2" height="150" src="http://www.philohome.com/nxtplug/cable11-v.jpg" width="200" /></a></td> <td width="947">Ponemos nuestra pieza (en su prensa) cerca de una fuente de calor durante 2 o 3 horas para que seque mejor. Ojo, no pongamos el foco de calor demasiado cerca, que correríamos el riesgo de quemar el conector.</td> </tr>
<tr> <td><a href="http://www.philohome.com/nxtplug/cable12.jpg"><img border="2" height="150" src="http://www.philohome.com/nxtplug/cable12-v.jpg" width="200" /></a></td> <td width="947">Aqui tenemos el conector fabricado junto con el original.</td></tr>
</tbody></table><br />
--------------------------------------------------------------------------------------------------------------<br />
<b>Referencias:</b><br />
<br />
Cables y conectores para el NXT ya hechos: <a href="http://www.mindsensors.com/index.php?module=pagemaster&PAGE_user_op=view_page&PAGE_id=67">Enlace</a> <br />
Artículo en el que me he basdo: <a href="http://www.philohome.com/nxtplug/nxtplug.htm">Enlace</a><br />
<table border="0"><tbody>
<tr><td><br />
</td><td width="947"><br />
</td></tr>
<tr><td><br />
</td><td width="947"><br />
</td></tr>
<tr><td><br />
</td><td width="947"><br />
</td></tr>
<tr><td><br />
</td><td width="947"><br />
</td></tr>
<tr><td><br />
</td><td width="947"><br />
</td></tr>
<tr><td><br />
</td><td width="947"><br />
</td></tr>
<tr><td><br />
</td><td width="947"><br />
</td></tr>
<tr><td><br />
</td><td width="947"><br />
</td></tr>
<tr><td><br />
</td><td width="947"><br />
</td></tr>
<tr><td><br />
</td><td width="947"><br />
</td></tr>
<tr><td><br />
</td><td width="947"><br />
</td></tr>
<tr><td><br />
</td><td width="947"><br />
</td></tr>
</tbody></table>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-24501361364509570002011-01-10T03:17:00.000-08:002011-01-10T03:17:36.961-08:00Primeros pasos en Arduino<style>
@font-face {
font-family: "Courier New";
}@font-face {
font-family: "Wingdings";
}@font-face {
font-family: "Verdana";
}@font-face {
font-family: "Cambria Math";
}@font-face {
font-family: "Cambria";
}@font-face {
font-family: "ヒラギノ角ゴ Pro W3";
}p.MsoNormal, li.MsoNormal, div.MsoNormal { margin: 0cm 0cm 0.0001pt; font-size: 12pt; font-family: Cambria; color: black; }p.MsoCaption, li.MsoCaption, div.MsoCaption { margin: 0cm 0cm 10pt; font-size: 9pt; font-family: Cambria; color: rgb(79, 129, 189); font-weight: bold; }pre { margin: 0cm 0cm 0.0001pt; font-size: 10pt; font-family: Courier; }p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph { margin: 0cm 0cm 0.0001pt 36pt; font-size: 12pt; font-family: Cambria; color: black; }p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst { margin: 0cm 0cm 0.0001pt 36pt; font-size: 12pt; font-family: Cambria; color: black; }p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle { margin: 0cm 0cm 0.0001pt 36pt; font-size: 12pt; font-family: Cambria; color: black; }p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast { margin: 0cm 0cm 0.0001pt 36pt; font-size: 12pt; font-family: Cambria; color: black; }span.HTMLconformatoprevioCar { font-family: Courier; }.MsoChpDefault { font-size: 10pt; }div.WordSection1 { page: WordSection1; }ol { margin-bottom: 0cm; }ul { margin-bottom: 0cm; }
</style> <br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="color: windowtext; font-family: "Times New Roman";">Como se comentó en el primer capítulo de esta memoria, Arduino es una plataforma de hardware abierta basada en los microcontroladores AVR de ATMEL. En el caso que nos ocupa, Arduino va a servir de interfaz entre los sensores que vayamos a usar, y el propio robot NXT de LEGO. Lo que se pretende en este apartado no es más que dar una visión general sobre cómo instalar y usar el entorno de programación de Arduino.</span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><b><span style="color: windowtext; font-family: "Times New Roman"; font-size: 14pt; line-height: 150%;">Instalación de Arduino en Windows</span></b></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: windowtext; font-family: "Times New Roman";"><span> </span></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: windowtext; font-family: "Times New Roman";"><span> </span>Lo primero que se debe hacer es descargar la última versión del Java Runtime Environment (J2RE) que se encuentra disponible en la página de Sun. Este paso es importante, ya que sin este entorno instalado nuestra interfaz de desarrollo para Arduino no funcionará.</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: windowtext; font-family: "Times New Roman";"><span> </span>El siguiente paso, es descargar la interfaz de desarrollo de Arduino, que se encontrará en la página oficial del sistema. La instalación es sencilla, ya que simplemente tendremos que realizar lo siguiente:</span></div><div class="MsoListParagraphCxSpFirst" style="line-height: 150%; text-align: justify; text-indent: -18pt;"><span style="color: windowtext; font-family: Verdana;"><span>-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><span style="color: windowtext; font-family: "Times New Roman";">Descomprimir el archivo .zip en el directorio en el que queremos que quede instalada la interfaz de desarrollo.</span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; text-align: justify; text-indent: -18pt;"><span style="color: windowtext; font-family: Verdana;"><span>-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><span style="color: windowtext; font-family: "Times New Roman";">Instalar los drivers USB.<span> </span>Si se ha instalado por ejemplo la interfaz en C:\, los drivers se encontrarán en la ruta C:\arduino-0012\drivers.<span> </span>Para instalarlos, se hace lo siguiente:</span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="color: windowtext; font-family: "Courier New";"><span>o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><span style="color: windowtext; font-family: "Times New Roman";">Conectar la placa Arduino al PC mediante el puerto USB. Si la placa trae un transformador adjunto, se conectará también para suministrar alimentación a la misma. Por lo general las placas USB toman la alimentación del propio puerto del ordenador.</span></div><div class="MsoListParagraphCxSpMiddle" style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="color: windowtext; font-family: "Courier New";"><span>o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><span style="color: windowtext; font-family: "Times New Roman";">Cuando se abra el asistente para hardware nuevo, seleccionaremos la opción de “No por el momento” a la pregunta de si deseamos que busque automáticamente los controladores, y a continuación elegiremos instalar dicho controlador desde una ubicación determinada. Es ahí donde seleccionaremos la carpeta de drivers antes mencionada.</span></div><div class="MsoListParagraphCxSpLast" style="line-height: 150%; text-align: justify; text-indent: -18pt;"><span style="color: windowtext; font-family: Verdana;"><span>-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><span style="color: windowtext; font-family: "Times New Roman";">Finalmente, sólo queda abrir la interfaz de Arduino, haciendo clic en el fichero Arduino.exe. Sólo habrá que seleccionar el puerto USB al que esté conectada la placa y elegir el modelo de tarjeta seleccionado.</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><b><span style="color: windowtext; font-family: "Times New Roman"; font-size: 14pt; line-height: 150%;">Instalación de Arduino en Mac OSX</span></b></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><span style="color: windowtext; font-family: "Times New Roman";"><span> </span>Vamos a ver ahora como proceder a la instalación de Arduino en sistemas basados en el sistema operativo de Apple: Mac OSX.</span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><span style="color: windowtext; font-family: "Times New Roman";"><span> </span>En primer lugar, al igual que con Windows, deberemos tener JAVA instalado y actualizado, y descargar desde la propia página de Arduino los drivers y la interfaz de desarrollo. </span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><span style="color: windowtext; font-family: "Times New Roman";"><span> </span>Una vez descargado lo anterior, montaremos el archivo dmg que va a contener tanto la interfaz como los controladores, tal y como vemos en la siguiente figura:</span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgn0_9zFUCdhkixLcZbwvIrGwhlmn_ae-NMeKETSurhSNqhV2vbriBbE1aVQ8eBP2k2uoXGA7-dz5hFG3bfu6T7gA0tLY1V89B6gJivVtzFyp56cb44BNmdfadwQdSv2yjFx8uKNFT8i3wE/s1600/1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="269" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgn0_9zFUCdhkixLcZbwvIrGwhlmn_ae-NMeKETSurhSNqhV2vbriBbE1aVQ8eBP2k2uoXGA7-dz5hFG3bfu6T7gA0tLY1V89B6gJivVtzFyp56cb44BNmdfadwQdSv2yjFx8uKNFT8i3wE/s320/1.png" width="320" /></a></div><div align="center" class="MsoCaption" style="line-height: 150%; text-align: center;"><span style="color: windowtext; font-family: "Times New Roman";"> </span>Contenido del paquete descargado<span style="color: windowtext; font-family: "Times New Roman";"></span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><span style="color: windowtext; font-family: "Times New Roman";"><span> </span>Al instalar el dirver FTDI (simplemente haciendo doble clic sobre él), veremos algo como esto:</span></div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1Z95i70xIX_NyDMOvjbiPyAFxeaX7vz0X0pkfMn_31_l3laa3xQTreGSqUJiuThnsrYL7lM1SKjcYZnqm54eFGBfmeyR3kEyLhS9agLtmYswJrLLKY_vWIp0sTtExUk1Qks0utR7nObyG/s1600/2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="229" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1Z95i70xIX_NyDMOvjbiPyAFxeaX7vz0X0pkfMn_31_l3laa3xQTreGSqUJiuThnsrYL7lM1SKjcYZnqm54eFGBfmeyR3kEyLhS9agLtmYswJrLLKY_vWIp0sTtExUk1Qks0utR7nObyG/s320/2.png" width="320" /></a></div><div align="center" class="MsoCaption" style="line-height: 150%; text-align: center;"><span></span>Instalación del controlador<span style="color: windowtext; font-family: "Times New Roman";"></span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><span style="color: windowtext; font-family: "Times New Roman";"><span> </span>Durante la instalación nos pedirán la contraseña de administrador, la introducimos, elegimos la ubicación de instalación y completamos el proceso. Es importante que cuando se complete el proceso se reinicie el ordenador, ya que éste necesita reconocer los nuevos puertos que acabamos de instalar.</span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><span style="color: windowtext; font-family: "Times New Roman";"><span> </span>Tras reiniciar, volvemos a abrir nuestro fichero dmg descargado, simplemente para instalar la interfaz de Arduino, que arrastraremos a la carpeta de aplicaciones. Esto se ve en la siguiente figura: </span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpUd1zUcapaqCWy1GM0BmAnE7prHekwovuCcP1LFYb_lZwJIIuIQmXmmZR_lZi9Ng3yW7FTYD79ziZgLOoSR0K52E7aq2awA8D6IN4FcG17o_p166bjwuu9d_jYAuJkcl0EcPocAJCYXTj/s1600/3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="123" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpUd1zUcapaqCWy1GM0BmAnE7prHekwovuCcP1LFYb_lZwJIIuIQmXmmZR_lZi9Ng3yW7FTYD79ziZgLOoSR0K52E7aq2awA8D6IN4FcG17o_p166bjwuu9d_jYAuJkcl0EcPocAJCYXTj/s320/3.png" width="320" /></a></div><div align="center" class="MsoCaption" style="line-height: 150%; text-align: center;">Copiando Arduino a la carpeta de aplicaciones<span style="color: windowtext; font-family: "Times New Roman";"></span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><span style="color: windowtext; font-family: "Times New Roman";"><span> </span>Finalmente, abrimos el IDE de Arduino y lo configuramos para que se comunique con nuestra placa. Para ello, nos dirigimos al menú TOOLS/BOARD y seleccionamos la placa que vayamos a usar. A continuación vamos al menú TOOLS/PORT y seleccionamos dónde se encuentra nuestra placa. Todo esto se ve en las dos siguientes figuras:</span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjTcUOThO4RzirmsifQHYicjW1JTNPIpbHvQqkKt2jlrKK3YSMJrnJJzDc7R_jNMtDpmgSdnTH63yYw2P3NJvhpDciR4L0payOhJYuSVOEY4bxrRLzzCzOY1hBtNDhOdKrLo9SoRKSOU5FW/s1600/4.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="125" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjTcUOThO4RzirmsifQHYicjW1JTNPIpbHvQqkKt2jlrKK3YSMJrnJJzDc7R_jNMtDpmgSdnTH63yYw2P3NJvhpDciR4L0payOhJYuSVOEY4bxrRLzzCzOY1hBtNDhOdKrLo9SoRKSOU5FW/s320/4.png" width="320" /></a></div><div align="center" class="MsoCaption" style="line-height: 150%; text-align: center;">Selección del tipo de placa usada<span style="color: windowtext; font-family: "Times New Roman";"></span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfaOheK18aXbwTDI5fyi6kAWG9Zm5BwvyQ-jYDPsFpbo4fBaWCDf_GVzpXh8OPVE2SSIv3MX7ib_ThzFKJRi1yOwnFSrAENmCT5ueCIJ8zj7i7uPjCVmAStqp4c0raFg8C8Jo7sGgDIUa4/s1600/5.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfaOheK18aXbwTDI5fyi6kAWG9Zm5BwvyQ-jYDPsFpbo4fBaWCDf_GVzpXh8OPVE2SSIv3MX7ib_ThzFKJRi1yOwnFSrAENmCT5ueCIJ8zj7i7uPjCVmAStqp4c0raFg8C8Jo7sGgDIUa4/s320/5.png" width="312" /></a></div><div align="center" class="MsoCaption" style="line-height: 150%; text-align: center;">Selección del puerto al que está conectada la placa<span style="color: windowtext; font-family: "Times New Roman"; font-size: 16pt; font-weight: normal; line-height: 150%;"></span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><b><span style="color: windowtext; font-family: "Times New Roman"; font-size: 14pt; line-height: 150%;">Carga de un programa de ejemplo en Arduino</span></b></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify;"><span style="color: windowtext; font-family: "Times New Roman";"><span> </span></span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: 36pt;"><span style="color: windowtext; font-family: "Times New Roman";">El programa que se va a cargar de ejemplo es “Blink Led”, algo parecido al típico “Hola Mundo” presente en todos los lenguajes de rogramación. Lo que va a hacer este programa es que parpadee el led 13 de la placa (que ya viene integrado en ella). Para cargar este ejemplo nos dirigimos a Files </span><span style="color: windowtext; font-family: Wingdings;"><span>à</span></span><span style="color: windowtext; font-family: "Times New Roman";"> Examples </span><span style="color: windowtext; font-family: Wingdings;"><span>à</span></span><span style="color: windowtext; font-family: "Times New Roman";"> Digital </span><span style="color: windowtext; font-family: Wingdings;"><span>à</span></span><span style="color: windowtext; font-family: "Times New Roman";"> Blink. Nos aparecerá el código cargado de esta forma:</span></div><div align="center" class="MsoNormal" style="line-height: 150%; margin-left: 36pt; page-break-after: avoid; text-align: center; text-indent: 36pt;"><span lang="ES" style="color: windowtext; font-family: "Times New Roman";"><br />
</span></div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1S5dHctCdtJOxhBUOU6-Bh4JdosJ4-3-Zq54OLLsq5TXK9M-7S6WLTND5mXI5fifVSbXC2SKslL_Tw4DvxmikbiQ2OpiWRZ5YZ9LodhQDm6gH0JGVM67ZhZAcogbaSXYg6DKaQoJ4Lq7o/s1600/6.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1S5dHctCdtJOxhBUOU6-Bh4JdosJ4-3-Zq54OLLsq5TXK9M-7S6WLTND5mXI5fifVSbXC2SKslL_Tw4DvxmikbiQ2OpiWRZ5YZ9LodhQDm6gH0JGVM67ZhZAcogbaSXYg6DKaQoJ4Lq7o/s320/6.png" width="280" /></a></div><div align="center" class="MsoCaption" style="line-height: 150%; text-align: center;">Programa de ejemplo Blink listo para cargarse en la placa<span style="color: windowtext; font-family: "Times New Roman";"></span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: 36pt;"><br />
</div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: 36pt;"><span style="color: windowtext; font-family: "Times New Roman";">Para comprobar que el código es correcto le daremos al símbolo de “Play”, si hay algún error este será el momento en el que se nos notificará y habrá que corregirlo antes de proseguir. Si todo va bien, al darle a Upload el código se verificará y se cargará en la placa que hemos configurado anteriormente.</span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: 36pt;"><span style="color: windowtext; font-family: "Times New Roman";">Si todo el proceso ha sido correcto, se nos mostrará un mensaje como el de la siguiente figura, y podremos ver cómo el led 13 de la placa parpadea con un intervalo de 1 segundo.</span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: 36pt;"><span style="color: windowtext; font-family: "Times New Roman";">A continuación se muestra el código usado en este ejemplo:</span></div><div class="MsoNormal" style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: 36pt;"><br />
</div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none; margin-left: 36pt;"><tbody>
<tr> <td style="border: 1pt solid windowtext; padding: 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>1.<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><i>/**</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>2.<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><i> * Archivo: HelloWorldDelay.c</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>3.<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><i> * Descripción: Hola mundo con delay (led)</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>4.<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><i> * Autores: Boops y Gizer20</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>5.<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><i> *<span> </span>Asociación de Robótica y Domótica de España (A.R.D.E.)</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>6.<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><i> *<span> </span>http:\\www.webdearde.com</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>7.<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><i> * Revisiones:</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>8.<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><i> * +RRR+ AAAA/MM/DD Nombre<span> </span>Descripción</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>9.<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><i> * ------------------------------------------</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>10.</span></span><i> * +001+ 2009/02/23 Ranganok<span> </span>Modificada cabecera</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>11.</span></span><i> */</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>12.</span></span> </pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>13.</span></span>int Led = 13; <i>// Pin de la placa arduino donde se conecta el led.</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>14.</span></span>void setup() <i>// Función para inicializar los pines de la placa</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>15.</span></span>{</pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>16.</span></span><span> </span>pinMode(Led, OUTPUT); <i>// Asignamos la variable Led ,que <span> </span></i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>17.</span></span><i><span> </span>//corresponde al pin 13,como salida<span> </span></i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>18.</span></span>}</pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>19.</span></span> </pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>20.</span></span>void loop()<span> </span><i>//Iniciamos lo que es propiamente el programa</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>21.</span></span>{</pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>22.</span></span><span> </span>digitalWrite(Led, HIGH); <i>// Ponemos a 1 el pin 13 para encender </i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>23.</span></span><i><span> </span><span> </span>//el led</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>24.</span></span><span> </span>delay(500); <span> </span><i>// esperamos medio segundo</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>25.</span></span><span> </span>digitalWrite(Led, LOW); <i>// Ponemos a 0 el pin 13 para apagar el </i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>26.</span></span><i><span> </span>//led</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>27.</span></span><span> </span>delay(500); <i>// esperamos medio segundo</i></pre><pre style="line-height: 14.4pt; margin-left: 36pt; text-indent: -18pt; vertical-align: top;"><span><span>28.</span></span>}</pre></td> </tr>
</tbody></table><br />
<div class="MsoNormal" style="margin-left: 36pt;">------------------------------------------------------------------------------------------------------ <b>Referencias:</b><span style="color: windowtext; font-family: "Times New Roman";"> </span></div><ul><li><span style="color: windowtext; font-family: "Times New Roman";">Página principal de Arduino. </span><a href="http://www.arduino.cc/es/">www.<b>arduino</b>.cc/es</a><cite><span style="font-family: Cambria;"></span></cite></li>
<li><span class="MsoHyperlink"><span style="color: windowtext;">Página para descargar el entorno de JAVA <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html">http://www.oracle.com/technetwork/java/javase/downloads/index.html</a></span></span></li>
<li><span class="MsoHyperlink"><span style="color: windowtext;">Tutorial: comenzando con Arduino. <a href="http://wiki.webdearde.com/index.php?title=Tutorial:_Comenzando_con_Arduino">http://wiki.webdearde.com/index.php?title=Tutorial:_Comenzando_con_Arduino</a></span></span></li>
<li><span class="MsoHyperlink"><span style="color: windowtext;">Guía para instalar Arduino en OSX. <a href="http://www.nuevomaterial.com/2010/04/guia-para-instalar-arduino-en-osx/">http://www.nuevomaterial.com/2010/04/guia-para-instalar-arduino-en-osx/</a></span></span></li>
</ul><style>
@font-face {
font-family: "Cambria";
}@font-face {
font-family: "ヒラギノ角ゴ Pro W3";
}p.MsoNormal, li.MsoNormal, div.MsoNormal { margin: 0cm 0cm 0.0001pt; font-size: 12pt; font-family: Cambria; color: black; }a:link, span.MsoHyperlink { color: blue; text-decoration: underline; }a:visited, span.MsoHyperlinkFollowed { color: purple; text-decoration: underline; }.MsoChpDefault { font-size: 10pt; }div.WordSection1 { page: WordSection1; }
</style>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-78442126628991734192011-01-10T01:36:00.000-08:002011-01-10T01:36:18.367-08:00Manejo del protocolo I2C usando Labview<style>
@font-face {
font-family: "Courier New";
}@font-face {
font-family: "Times";
}@font-face {
font-family: "Wingdings";
}@font-face {
font-family: "Verdana";
}@font-face {
font-family: "Cambria Math";
}@font-face {
font-family: "Cambria";
}@font-face {
font-family: "ヒラギノ角ゴ Pro W3";
}p.MsoNormal, li.MsoNormal, div.MsoNormal { margin: 0cm 0cm 0.0001pt; font-size: 12pt; font-family: Cambria; color: black; }h2 { margin-right: 0cm; margin-left: 0cm; font-size: 18pt; font-family: Times; font-weight: bold; }p.MsoCaption, li.MsoCaption, div.MsoCaption { margin: 0cm 0cm 10pt; font-size: 9pt; font-family: Cambria; color: rgb(79, 129, 189); font-weight: bold; }p { margin-right: 0cm; margin-left: 0cm; font-size: 10pt; font-family: Times; }span.Ttulo2Car { font-family: Times; font-weight: bold; }.MsoChpDefault { font-size: 10pt; }div.WordSection1 { page: WordSection1; }ol { margin-bottom: 0cm; }ul { margin-bottom: 0cm; }
</style> <br />
<div style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> Labview es un entorno de programación gráfica usado por millones de ingenieros y científicos para el desarrollo de sistemas de control, medidas, pruebas mediante el uso de intuitivos iconos gráficos conectados por hilos, que recuerdan a los diagramas de flujo. Labview permite la integración con numerosos dispositivos Hardware (entre ellos el NXT) y proporciona librerías que permiten el análisis avanzado y la visualización de los datos. La plataforma Labview es escalable, y trabaja en distintos sistemas operativos.</span></div><div style="line-height: 150%; text-align: justify;"><br />
</div><div style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%;"><b><span style="font-family: "Times New Roman";">Bloques básicos</span></b></div><div style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Para implementar el protocolo I2C en Labview, los primeros bloques que debemos definir son los que sirven para controlar las entradas/salidas digitales del hardware que conectemos. Estos bloques son 3, y como se puede ver a continuación corresponden a las salidas digitales, a las entradas digitales y a la habilitación de dichas entradas/salidas:</span></div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDMkBA39IZYzX80lZud-sXczqd5swAZJoj7MGotdo0eTJV1s05pUvNhd9dXoPMZJjfvS1opsMA9xSKkmsYiYcoV22SwjsBMWC0XQKwNSk-3UTGNVjqP0ueUg0ZLvl8M0haFx4MC70R5ZzT/s1600/11.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="60" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDMkBA39IZYzX80lZud-sXczqd5swAZJoj7MGotdo0eTJV1s05pUvNhd9dXoPMZJjfvS1opsMA9xSKkmsYiYcoV22SwjsBMWC0XQKwNSk-3UTGNVjqP0ueUg0ZLvl8M0haFx4MC70R5ZzT/s320/11.png" width="320" /></a></div><div align="center" class="MsoCaption" style="text-align: center;"><span></span>Bloques para controlar las E/S digitales en Labview<span style="color: windowtext; font-family: Times; font-size: 10pt;"></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman";">El protocolo se empieza generando una condición de arranque. Como ya se explicó anteriormente. Para ello, es necesario mantener la línea de reloj en estado lógico alto, mientras se genera una transición de nivel alto a nivel bajo en el bus de datos. Tras esta condición inicial, todos los dispositivos van a observar el bus esperando ver su dirección, que será de 7 o de 10 bits. Después de que cada bit (dirección, lectura/escritura o dato) se envíe por el bus, se produce un ciclo de reloj y se espera confirmación por parte del dispositivo esclavo.</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman";">Lo primero que se hace es empezar con la transacción más básica, es decir, escribir un dato en un dispositivo. Con el bloque de salida digital, se configura una línea digital como salida, y se pone dicha línea al nivel lógico deseado (alto o bajo). Como se ve en la siguiente figura, tras poner el bit deseado se completa un ciclo de reloj completo:</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTQmKxHfjiejQ6rbthyphenhyphenzACkxHDR_GDTTq2_T01CKTVMZ4pPB0zyZFv82GYKx12PqT37xHFQ5uIlecqxZVEmz5ZQl1or32kzPJcYOqZdHpusPbwAf5axRN1gxnBc4K1wLA0eZzLOuSBFrPo/s1600/12.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="205" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTQmKxHfjiejQ6rbthyphenhyphenzACkxHDR_GDTTq2_T01CKTVMZ4pPB0zyZFv82GYKx12PqT37xHFQ5uIlecqxZVEmz5ZQl1or32kzPJcYOqZdHpusPbwAf5axRN1gxnBc4K1wLA0eZzLOuSBFrPo/s320/12.png" width="320" /></a></div><div align="center" class="MsoCaption" style="text-align: center;">Tranferencia de un bit en<span> </span>Labview</div><div style="line-height: 150%; margin-bottom: 12pt; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">La función <i>wait </i>que se ve en la figura anterior, va a determinar cuánto tiempo la señal de reloj se mantiene a nivel bajo y alto. La temporización del bus cambia según la señal de reloj sea ascendente o descendente, y dicha temporización puede ser de tres formas: estándar, rápida o muy rápida. Normalmente operaremos en cualquiera de los 2 primeros modos.</span></div><div style="line-height: 150%; margin-bottom: 12pt; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Podemos definir la función siguiente, que se encarga de la transmisión de un dato. Esta función se puede guardar como un fichero .vi para que así podamos reutilizarla siempre que nos sea necesario:</span><span style="font-size: 12pt; line-height: 150%;"></span></div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi14NG09HU-VbhlrTQXilE5sf0fzwdLW8UenH8zL70rsBQSFKYIujRna9hIwCSlLTPbSs2ST1uAmQA9yPobtxH86sP7kOxHSP81236ETktifOyLm1aRTd4C8STqb7bbgq9N3RF1HftNmQ74/s1600/13.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="233" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi14NG09HU-VbhlrTQXilE5sf0fzwdLW8UenH8zL70rsBQSFKYIujRna9hIwCSlLTPbSs2ST1uAmQA9yPobtxH86sP7kOxHSP81236ETktifOyLm1aRTd4C8STqb7bbgq9N3RF1HftNmQ74/s320/13.png" width="320" /></a></div><div align="center" class="MsoCaption" style="text-align: center;">Transferencia de un dato en Labview</div><div class="MsoNormal" style="line-height: 150%;"><br />
</div><div style="line-height: 150%; margin-bottom: 12pt; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Después de que cada byte se haya transmitido a través de la salida digital, se debe recibir una confirmación por parte del dispositivo direccionado. Durante este bit de confirmación, la línea de datos para a estar a nivel bajo mientras dure el nivel alto de la señal de reloj. Este bit de confirmación se va a recibir siempre tras enviar un dato, hasta que se envíe una condición de parada.</span></div><div style="line-height: 150%; margin-bottom: 12pt; text-align: justify; text-indent: 36pt;"><span style="font-size: 12pt; line-height: 150%;">En la figura siguiente, el dispositivo confirma la recepción del dato. Veamos cada una de las partes de esta figura:</span></div><div style="line-height: 150%; margin: 5pt 0cm 12pt 36pt; text-align: justify; text-indent: -18pt;"><span style="font-family: Verdana; font-size: 12pt; line-height: 150%;"><span>-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><span style="font-size: 12pt; line-height: 150%;">En el primer bloque de la secuencia, se establece la línea digital como entrada para que el maestro pueda recibir las confirmaciones de los dispositivos.</span></div><div style="line-height: 150%; margin: 5pt 0cm 12pt 36pt; text-align: justify; text-indent: -18pt;"><span style="font-family: Verdana; font-size: 12pt; line-height: 150%;"><span>-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><span style="font-size: 12pt; line-height: 150%;">A continuación, se produce un ciclo completo de la señal de reloj.</span></div><div style="line-height: 150%; margin: 5pt 0cm 12pt 36pt; text-align: justify; text-indent: -18pt;"><span style="font-family: Verdana; font-size: 12pt; line-height: 150%;"><span>-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span></span><span style="font-size: 12pt; line-height: 150%;">Finalmente, se vuelve a configurar la línea como salida para que el maestro pueda seguir enviando datos al dispositivo.</span></div><div style="line-height: 150%; margin: 5pt 0cm 12pt 18pt; text-align: justify; text-indent: 18pt;"><span style="font-size: 12pt; line-height: 150%;">En I<sup>2</sup>C, un dispositivo puede mantener la línea de datos a nivel bajo tanto tiempo como necesite. Dependiendo de los dispositivos y de lo que nos diga el fabricante, se pueden establecer tiempos de espera máximos para evitar que se quede colgado el programa.</span></div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg3Zdt9gyCiII9g3VU_c8vnu7cPsBnJ-eYWpsD82Yd0dv4phuTo71PZDtu8cyPIFcvZHFu5qMOPC9F3kzw3u45HwbMOObFA9MWlO1isF25a7SwNT5dTQ0YF7VTk0ANxyr5O-zpDRKAu-4J2/s1600/14.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="214" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg3Zdt9gyCiII9g3VU_c8vnu7cPsBnJ-eYWpsD82Yd0dv4phuTo71PZDtu8cyPIFcvZHFu5qMOPC9F3kzw3u45HwbMOObFA9MWlO1isF25a7SwNT5dTQ0YF7VTk0ANxyr5O-zpDRKAu-4J2/s320/14.png" width="320" /></a></div><div align="center" class="MsoCaption" style="text-align: center;">ACK de un bit en Labview<span style="font-family: "Times New Roman"; font-size: 16pt;"></span></div><div class="MsoNormal" style="line-height: 150%;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman";">Combinando el maestro para recibir los datos, con las confirmaciones de los dispositivos, se obtiene un esquema similar al que se ve a continuación, en el que el bucle “WHILE” se ejecuta mientras haya datos que escribir en el dispositivo, y la señal de datos no se mantenga a nivel bajo durante más de un ciclo. Se ha usado el función de entrada digital para leer el estado de la línea digital (nivel alto o bajo).</span><span style="font-family: "Times New Roman"; font-size: 16pt; line-height: 150%;"></span></div><div class="MsoNormal" style="line-height: 150%;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiuDTqU9eOqm_jH-HGT95ZXy8RPvAPU948QFtAVOFL1xI-tRLibVhWMpOX4weDLfyLUr8iV1bFaPszoN8A0Yll4omd72Fwwjob0f27qVaKW4KYLJaSA4OiClr0mB3jazpHEtimELGqyTnIA/s1600/15.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="211" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiuDTqU9eOqm_jH-HGT95ZXy8RPvAPU948QFtAVOFL1xI-tRLibVhWMpOX4weDLfyLUr8iV1bFaPszoN8A0Yll4omd72Fwwjob0f27qVaKW4KYLJaSA4OiClr0mB3jazpHEtimELGqyTnIA/s320/15.png" width="320" /></a></div><div align="center" class="MsoCaption" style="text-align: center;">Función I2CWrite de Labview<span style="font-family: "Times New Roman"; font-size: 16pt;"></span></div><b><span style="font-family: "Times New Roman"; font-size: 12pt;">Lecturas</span></b><br />
<div style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">El protocolo I<sup>2</sup>C no se limita a escribir datos en un dispositivo, sino que los dispositivos también pueden mandar datos al maestro, En este caso, el dispositivo maestro actúa como un receptor maestro. El sentido por defecto para los datos es salir del maestro en dirección al esclavo. Para permitir que los datos fluyan también en esta dirección es necesario configurar la línea que antes configuramos como salida a entrada. A continuación se muestra una posible forma de implementar esto:</span></div><div style="line-height: 150%; text-align: justify; text-indent: 36pt;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-L89f5Bbbpz6_X-5e4egj1A4QXYrrm_O9JxBcruD8puyU8U5te6OHsHw13fePyMWqV4Cz_jNPBzcuziN-AJ8IHBdAeRkBkPQRZr6-WTQYKOKClQ3iLFmj-6fQONW_a9yysTsNmetghP41/s1600/16.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="191" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-L89f5Bbbpz6_X-5e4egj1A4QXYrrm_O9JxBcruD8puyU8U5te6OHsHw13fePyMWqV4Cz_jNPBzcuziN-AJ8IHBdAeRkBkPQRZr6-WTQYKOKClQ3iLFmj-6fQONW_a9yysTsNmetghP41/s320/16.png" width="320" /></a></div><div align="center" class="MsoCaption" style="text-align: center;">Lectura de un bit en Labview<span style="font-family: "Times New Roman"; font-size: 16pt; font-weight: normal;"></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman";">Usando un bucle FOR, el maestro va leyendo de byte en bye. Como el protocolo I<sup>2</sup>C lee primero el bit más significativo, se usa un array de 1 dimensión invertido para darle la vuelta al array que se ha leído. Esto se ve en la figura siguiente: </span><span style="font-size: 16pt; line-height: 150%;"></span></div><div class="MsoNormal" style="line-height: 150%;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjTxKVIzFg_UNA-aGtAeiJLjm65Byq6YuCCfojFs2tEcDnm9ZmlIn9PMHFwX8H7deBT1ouAGiRH9tgrCfZPKWq4v136RLb0brKDrKAM3O6bQykcltPuCA1VAl_aqvzPdbONRlmiyX7-jGIj/s1600/17.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="173" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjTxKVIzFg_UNA-aGtAeiJLjm65Byq6YuCCfojFs2tEcDnm9ZmlIn9PMHFwX8H7deBT1ouAGiRH9tgrCfZPKWq4v136RLb0brKDrKAM3O6bQykcltPuCA1VAl_aqvzPdbONRlmiyX7-jGIj/s320/17.png" width="320" /></a></div><div align="center" class="MsoCaption" style="text-align: center;">Lecutra de un byte<span style="font-size: 16pt;"></span></div><div class="MsoNormal" style="line-height: 150%;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman";">La función completa de lectura se muestra a continuación, y es similar a la de escritura que vimos anteriormente. </span></div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhT3riRRjDpAbe4ZVUZ_kfa74HSdrVLz99vuWzwdW5kmf4aTySL3TVzPyIXl182F1fg4RjXVfFhEdT4TmVScLHSHEcKYh_RpBI1WDcGNpsO9sJT96yIlahtSOiia0h-jCUJJxGpou4M0rUE/s1600/18.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="211" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhT3riRRjDpAbe4ZVUZ_kfa74HSdrVLz99vuWzwdW5kmf4aTySL3TVzPyIXl182F1fg4RjXVfFhEdT4TmVScLHSHEcKYh_RpBI1WDcGNpsO9sJT96yIlahtSOiia0h-jCUJJxGpou4M0rUE/s320/18.png" width="320" /></a></div><div align="center" class="MsoCaption" style="text-align: center;">Función completa I2CRead<span style="font-family: "Times New Roman"; font-size: 16pt; font-weight: normal;"></span></div><h2><span style="font-size: 12pt;">Direccionar dispositivos</span></h2><div style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"><span> </span>En el protocolo I<sup>2</sup>C se puede direccionar un dispositivo de dos formas diferentes, con una dirección de 7 bits y con una de 10 bits. En el primer caso, tal y como se explicó en el apartado correspondiente a la descripción del protocolo, el octavo bit se usa para indicar si el maestro va a leer o escribir del dispositivo esclavo. La figura siguiente contiene la forma de invertir las direcciones de 7 bits del bit menos significativo al más significativo, ya que como acabamos de mencionar, el protocolo escribe primero el bit de mayor peso (MSB). En último lugar se añade a la dirección el bit de lectura/escritura.</span></div><div style="line-height: 150%; text-align: justify;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiBO5FGfh3ijPBT3PyluuCa8I9_3Ja8xVL16KvUxikp-0etw-pYiv40l3HZekIOUZmWHKv8zsBlRJvOeF3JTd7DZ9ULDSByOIc4HJOAA0dw8vLIKbhgcCNUdGOLjaSv_I6s0Hyw6JHYpY_o/s1600/19.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="206" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiBO5FGfh3ijPBT3PyluuCa8I9_3Ja8xVL16KvUxikp-0etw-pYiv40l3HZekIOUZmWHKv8zsBlRJvOeF3JTd7DZ9ULDSByOIc4HJOAA0dw8vLIKbhgcCNUdGOLjaSv_I6s0Hyw6JHYpY_o/s320/19.png" width="320" /></a></div><div align="center" class="MsoCaption" style="text-align: center;">Direcciones de 7 bits<span style="font-family: "Times New Roman"; font-size: 16pt; font-weight: normal;"></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman";">El caso de 10 bits no lo vamos a usar en principio para nuestros fines, pero se muestra en la siguiente figura cómo se direccionaría.</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_8zWmdwORsBgQbmAbI5HfQLsysaZzLw2HfnvoXNQG-7JrU6Po7V9Z-_-MbdIIlVtRa8ob5nVIrzIFBxdEIhpZ2FH8Lzn_fKf7LgQLJsoJwQBIh4dPuEI1w332BIEdjgOb1FUXdEZVN9TJ/s1600/20.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="150" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_8zWmdwORsBgQbmAbI5HfQLsysaZzLw2HfnvoXNQG-7JrU6Po7V9Z-_-MbdIIlVtRa8ob5nVIrzIFBxdEIhpZ2FH8Lzn_fKf7LgQLJsoJwQBIh4dPuEI1w332BIEdjgOb1FUXdEZVN9TJ/s320/20.png" width="320" /></a></div><div align="center" class="MsoCaption" style="text-align: center;">Direcciones de 10 bits<span style="font-family: "Times New Roman";"></span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman";">Todo lo anterior se puede ver recogido en la siguiente figura:</span></div><div class="MsoNormal" style="line-height: 150%; text-indent: 36pt;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-OLOYrBaM74Uq9AtV7haAl-opfZQXhZxfzAvV5gBZxEyjT6K4FSXeHmUdhSEWInj2IUEmOEblFUnIAaQSVho1NpjadhvV_PUhc8HaZpsc2dhtljxpSrwMcGoQE0MDWiukCAhj9_yD49Jr/s1600/21.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="184" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-OLOYrBaM74Uq9AtV7haAl-opfZQXhZxfzAvV5gBZxEyjT6K4FSXeHmUdhSEWInj2IUEmOEblFUnIAaQSVho1NpjadhvV_PUhc8HaZpsc2dhtljxpSrwMcGoQE0MDWiukCAhj9_yD49Jr/s320/21.png" width="320" /></a></div><div align="center" class="MsoCaption" style="text-align: center;">Esquema completo</div><br />
--------------------------------------------------------------------------------------------------------------------------------------------<br />
<b>Referencias:</b><br />
<style>
@font-face {
font-family: "Cambria Math";
}@font-face {
font-family: "Cambria";
}@font-face {
font-family: "ヒラギノ角ゴ Pro W3";
}p.MsoNormal, li.MsoNormal, div.MsoNormal { margin: 0cm 0cm 0.0001pt; font-size: 12pt; font-family: Cambria; color: black; }a:link, span.MsoHyperlink { color: blue; text-decoration: underline; }a:visited, span.MsoHyperlinkFollowed { color: purple; text-decoration: underline; }.MsoChpDefault { font-size: 10pt; }div.WordSection1 { page: WordSection1; }
</style> <br />
<ul><li><span class="MsoHyperlink"><span style="color: windowtext; font-family: Cambria; font-size: 12pt;">Implementing I2C Communication Protocol in Labview FPGA: <a href="http://zone.ni.com/devzone/cda/tut/p/id/3479#toc0">http://zone.ni.com/devzone/cda/tut/p/id/3479#toc0</a></span></span> <b> </b></li>
</ul>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com1tag:blogger.com,1999:blog-754387214278989398.post-43974729985237592302011-01-10T01:18:00.000-08:002011-01-10T01:20:15.267-08:00Manejo del protocolo I2C usando ROBOTC<style>
@font-face {
font-family: "Courier New";
}@font-face {
font-family: "Times";
}@font-face {
font-family: "Wingdings";
}@font-face {
font-family: "Verdana";
}@font-face {
font-family: "Cambria Math";
}@font-face {
font-family: "Cambria";
}@font-face {
font-family: "ヒラギノ角ゴ Pro W3";
}p.MsoNormal, li.MsoNormal, div.MsoNormal { margin: 0cm 0cm 0.0001pt; font-size: 12pt; font-family: Cambria; color: black; }p.MsoCaption, li.MsoCaption, div.MsoCaption { margin: 0cm 0cm 10pt; font-size: 9pt; font-family: Cambria; color: rgb(79, 129, 189); font-weight: bold; }p { margin-right: 0cm; margin-left: 0cm; font-size: 10pt; font-family: Times; }pre { margin: 0cm 0cm 0.0001pt; font-size: 10pt; font-family: Courier; }span.HTMLconformatoprevioCar { font-family: Courier; }.MsoChpDefault { font-size: 10pt; }div.WordSection1 { page: WordSection1; }ol { margin-bottom: 0cm; }ul { margin-bottom: 0cm; }
</style> <br />
<div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> ROBOTC es un lenguaje de programación para robótica basado en el popular lenguaje C. Fue desarrollado en la unidad de robótica de la Universidad de Carnegie Mellon [21] y la documentación y el entorno de desarrollo se pueden obtener tanto desde la página oficial de lego como desde la página del proyecto de ROBOTC </span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> Se trata de software libre, desarrollado por la comunidad, compatible con distintas plataformas y que suele venir acompañado del ensamblador NBC. Soporta bluetooh y puerto serie, por lo que también nos permitirá acceder al protocolo I<sup>2</sup>C de manera sencilla. Para cargarse en el robot hace uso del firmware estándar, y se generan programas ligeros y de rápida ejecución.</span></div><div class="MsoNormal" style="line-height: 150%; text-indent: 36pt;"><span style="font-family: "Times New Roman";">En cuanto a la forma de programar, aunque textual este lenguaje tiene una característica similar a la de “arrastrar y soltar” que se encuentra en los métodos gráficos de programación para el RCX, sólo que en este caso lo que se “suelta” no es una caja, sino un trozo de código. En la figura que tenemos a continuación, se ve el espacio de trabajo del programa: la parte izquierda de la pantalla contiene el diccionario de ROBOTC con todas las posibilidades del lenguaje. Además, este diccionario se puede organizar tanto para usuarios noveles, ocultando las funciones más complejas, como para usuarios más avanzados.</span></div><div class="MsoNormal" style="line-height: 150%; text-indent: 36pt;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgcxS3UAIogLKZGRZdBr_oI_El4lJohMHhMSDuAQzT8q-DpuQXXAJW38tZTgYCDfZStZzVBO2KOYnVSxZ9XXA3uzTtiaJ7OATyPFB7gnmoTZ0vx9ubHMMTsB1TdqS5vO8lWf8aDJ3pmzIC7/s1600/1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="211" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgcxS3UAIogLKZGRZdBr_oI_El4lJohMHhMSDuAQzT8q-DpuQXXAJW38tZTgYCDfZStZzVBO2KOYnVSxZ9XXA3uzTtiaJ7OATyPFB7gnmoTZ0vx9ubHMMTsB1TdqS5vO8lWf8aDJ3pmzIC7/s320/1.png" width="320" /></a></div><div class="MsoNormal" style="line-height: 150%; text-indent: 36pt;"><br />
</div><div align="center" class="MsoNormal" style="line-height: 150%; page-break-after: avoid; text-align: center;"><span lang="ES" style="font-family: "Times New Roman";"></span></div><div align="center" class="MsoCaption" style="text-align: center;">Entorno de trabajo de ROBOTC<span style="font-family: "Times New Roman";"></span></div><div class="MsoNormal" style="line-height: 150%;"><br />
</div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> ROBOTC tiene un depurador en tiempo real bastante potente que consigue reducir el tiempo que se debe emplear para depurar un programa. Además, la gran cantidad de manuales y de vídeos explicativos proporcionadas por el propio desarrollador, hacen de este lenguaje una excelente alternativa para programar el NXT.</span></div><div class="MsoNormal" style="line-height: 150%;"><br />
</div><div class="MsoNormal" style="line-height: 150%;"><b><span style="font-family: "Times New Roman";">Descripción del funcionamiento</span></b></div><div class="MsoNormal" style="line-height: 150%;"><span style="color: black; font-family: "Times New Roman";"> A continuación se va a explicar cómo acceder al protocolo I2C mediante ROBOTC. Veamos un ejemplo de comunicación paso a paso:</span></div><div style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: -18pt;"><span style="font-family: Verdana; font-size: 12pt; line-height: 150%;">-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Para comunicarse con un dispositivo I<sup>2</sup>C desde RobotC hay que empezar configurando el puerto a utilizar como sensorI2CCustom9V. En este caso utiliza el puerto S1 y le da el nombre PROTO_PORT:</span></div><div style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-family: "Courier New"; font-size: 12pt; line-height: 150%;">o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">#pragma config(Sensor, S1, PROTO_PORT, sensorI2CCustom9V)</span></div><div style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: -18pt;"><span style="font-family: Verdana; font-size: 12pt; line-height: 150%;">-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Hay que definir las variables que almacenarán los datos de salida y los de entrada. Estas variables serán matrices de bytes, cmdbuff[] y respbuff[]:</span></div><div style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-family: "Courier New"; font-size: 12pt; line-height: 150%;">o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">byte cmdbuff[4];</span></div><div style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-family: "Courier New"; font-size: 12pt; line-height: 150%;">o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">byte respbuff[2];</span></div><div style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: -18pt;"><span style="font-family: Verdana; font-size: 12pt; line-height: 150%;">-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Veamos qué contendrá cada elemento de la matriz:</span></div><div style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-family: "Courier New"; font-size: 12pt; line-height: 150%;">o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[0]: número de bytes que conforman el comando I2C a enviar</span></div><div style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-family: "Courier New"; font-size: 12pt; line-height: 150%;">o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[1]: la dirección del dispositivo I2C esclavo en el que se desea escribir o leer</span></div><div style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-family: "Courier New"; font-size: 12pt; line-height: 150%;">o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[2]: la dirección de la posición de memoria en la que ha de escribirse o que hay que leer. Esta información se encuentra en la información técnica del dispositivo.</span></div><div style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-family: "Courier New"; font-size: 12pt; line-height: 150%;">o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[3]: cuando la operación es de escritura contiene los datos a enviar </span></div><div style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-family: "Courier New"; font-size: 12pt; line-height: 150%;">o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">respbuff[2]: es la matriz utilizada para almacenar las lecturas que se realizan en algún dispositivo I<sup>2</sup>C. Está compuesta de dos bytes que contendrán las lecturas. </span></div><div style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: -18pt;"><span style="font-family: Verdana; font-size: 12pt; line-height: 150%;">-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Tal y como he señalado antes, para iniciar las comunicaciones hay que enviar una secuencia de inicio para poner en escucha el dispositivo esclavo deseado. Para enviar mensajes RobotC dispone del siguiente procedimiento:</span></div><div style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-family: "Courier New"; font-size: 12pt; line-height: 150%;">o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><b><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">sendI2CMsg(nPort, sendMsg, nReplySize), </span></b><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">donde los parámetros son los siguientes:<b></b></span></div><ul style="margin-left: 80px;"><li><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">nPort nombre del puerto I2C utilizado, en el ejemplo PROTO_PORT</span></li>
<li><span style="font-family: Wingdings; font-size: 12pt; line-height: 150%;"><span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"></span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">sendMsg el mensaje a enviar, en nuestro caso cmdbuff[0]</span></li>
<li><span style="font-family: Wingdings; font-size: 12pt; line-height: 150%;"><span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"></span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">nReplySize tamaño en bytes de la respuesta. Si se trata sólo de escritura su valor será 0.</span></li>
</ul><div style="line-height: 150%; margin-left: 36pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">La secuencia de inicio será un mensaje que contiene la dirección del dispositivo esclavo, el procedimiento sendI2CMsg se encarga de dar el formato necesario así que no tendremos mas que dar a los dos primeros elementos de la matriz cmdbuff[i] sus valores y enviarla.<b></b></span></div><div style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-family: "Courier New"; font-size: 12pt; line-height: 150%;">o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[0] = 1; //se va a enviar únicamente un byte</span></div><div style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-family: "Courier New"; font-size: 12pt; line-height: 150%;">o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[1] = 0x02; // la dirección del dispositivo, en este caso “2”</span></div><div style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-family: "Courier New"; font-size: 12pt; line-height: 150%;">o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">sendI2CMsg(PROTO_PORT, cmdbuff[0], 0); //Envío de la secuencia de inicio</span></div><div style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: -18pt;"><span style="font-family: Verdana; font-size: 12pt; line-height: 150%;">-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Una vez iniciada la comunicación ya se pueden enviar o recibir mensajes. De todos modos, todavía queda por hacer algo si vamos a utilizar las entradas/salidas digitales. Hay que decirle cuáles vamos a utilizar como entradas y cuáles como salidas. Para ello el dispositivo dispone de una posición de memoria (posición 0x4E) en la que se registra dicha configuración, en ella deberemos de escribir los valores deseados. Imaginemos que deseamos configurar los puertos digitales del sensor a conectar de la siguiente manera:</span></div><div align="center"><table border="1" cellpadding="0" cellspacing="1" class="MsoNormalTable" style="width: 400px;"><tbody>
<tr> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Puerto</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> B5</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> B4</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> B3</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> B2</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> B1</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> B0</span></div></td> </tr>
<tr> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Modo</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Salida</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Entrada</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Entrada</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Salida</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Salida</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Entrada</span></div></td> </tr>
<tr> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Valor binario</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> 1</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> 0</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> 0</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> 1</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> 1</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> 0</span></div></td> </tr>
<tr> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Valor Decimal</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> 32</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> (16)</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> (8)</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> 4</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";">2</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> (1)</span></div></td> </tr>
</tbody></table></div><div style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Si el puerto está configurado como Salida (escritura) el valor asignado será 1 y si es como Entrada (lectura) el valor será 0. Tenemos una cadena de 6 bits (100110), en un orden determinado, que habremos de escribir en la posición 0x4E. Este valor lo habremos de convertir en su valor decimal (38 = 32 + 4 + 2) o hexadecimal (0x26), para no liarse lo más cómodo para la conversión es la calculadora de Windows u otra similar. El código será el siguiente:</span></div><table border="1" cellpadding="0" cellspacing="0" class="MsoNormalTable" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none; width: 100%;"><tbody>
<tr style="height: 224.65pt;"> <td style="border: 1pt solid windowtext; height: 224.65pt; padding: 0cm 3.5pt; width: 100%;" valign="top" width="100%"><pre style="line-height: 150%; margin-left: 4.7pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> </span></pre><pre style="line-height: 150%; margin-left: 4.7pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> </span></pre><pre style="line-height: 150%; margin-left: 4.7pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> ... </span></pre><div style="line-height: 150%; margin-left: 4.7pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[0] = 3; // Número de bytes del comando I2C</span></div><div style="line-height: 150%; margin-left: 4.7pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[1] = 0x02; // dirección I2C del esclavo</span></div><div style="line-height: 150%; margin-left: 4.7pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[2] = 0x4E; // posición de memoria en la que han de escribirse los datoscmdbuff[3] = 0x26; //datos a escribir: 100110 = 0x26</span></div><div style="line-height: 150%; margin-left: 4.7pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">sendI2CMsg(PROTO_PORT, cmdbuff[0], 0); // Envío de la orden al esclavo</span></div><pre style="line-height: 150%; margin-left: 4.7pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">... </span></pre></td> </tr>
</tbody></table><div style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: -18pt;"><span style="font-family: Verdana; font-size: 12pt; line-height: 150%;">-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Ahora ya es el momento de aprovechar los recursos que nos ofrece el dispositivo I2C que tengamos conectado. En cualquier operación de escritura se realiza del modo que se acaba de explicar, lo único que variará es la posición de memoria en la que han de escribirse los datos y el valor de los datos a escribir. </span></div><div style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: -18pt;"><span style="font-family: Verdana; font-size: 12pt; line-height: 150%;">-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Hemos configurado en el paso anterior los puertos digitales B1, B2 y B5 como salidas. Imaginemos que tenemos conectados a ellas tres LEDs rojo (B1), amarillo (B2) y verde (B5) a modo de semáforo y que deseamos encender los LEDs amarillo y verde. Para ello deberemos dar a esas salidas el valor lógico 1 (el 0 sería para apagar). </span></div><div style="line-height: 150%; margin-left: 36pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Podemos ver los valores en la tabla, los bits de las salidas no van a ser significativos así que los he dejado en cero.</span></div><div align="center"><table border="1" cellpadding="0" cellspacing="1" class="MsoNormalTable" style="width: 400px;"><tbody>
<tr> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Puerto</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> B5</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> B4</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> B3</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> B2</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> B1</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> B0</span></div></td> </tr>
<tr> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> LED</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Verde</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Amarillo</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Rojo </span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div></td> </tr>
<tr> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Valor binario</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> 1</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> 1</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> 0</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div></td> </tr>
<tr> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> Valor Decimal</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> 32</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> (16)</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> (8)</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> 4</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";">(2)</span></div></td> <td style="padding: 1pt;"><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="color: black; font-family: "Times New Roman";"> (1)</span></div></td> </tr>
</tbody></table></div><div style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">El valor a escribir será 100100 en binario, 36 (= 32 + 4) en decimal y 0x24 en hexadecimal, así que el código será el siguiente:</span></div><table border="1" cellpadding="0" cellspacing="0" class="MsoNormalTable" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none; width: 100%;"><tbody>
<tr style="height: 230.65pt;"> <td style="border: 1pt solid windowtext; height: 230.65pt; padding: 0cm 3.5pt; width: 100%;" valign="top" width="100%"><div style="line-height: 150%; margin-left: 9.35pt; text-align: justify;"><br />
</div><div style="line-height: 150%; margin-left: 9.35pt; text-align: justify;"><br />
</div><div style="line-height: 150%; margin-left: 9.35pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">…</span></div><div style="line-height: 150%; margin-left: 9.35pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[0] = 3; // Número de bytes del comando I2C</span></div><div style="line-height: 150%; margin-left: 9.35pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[1] = 0x02; // dirección I2C del esclavo</span></div><div style="line-height: 150%; margin-left: 9.35pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[2] = 0x4D; // posición de memoria en la que han de escribirse los datos. 0x4D es la dirección para salidas digitales.</span></div><div style="line-height: 150%; margin-left: 9.35pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[3] = 0x24; //datos a escribir: 100100 = 0x24</span></div><div style="line-height: 150%; margin-left: 9.35pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">sendI2CMsg(PROTO_PORT, cmdbuff[0], 0); // Envío de la orden al esclavo</span></div><pre style="line-height: 150%; margin-left: 9.35pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">... </span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"></span></pre></td> </tr>
</tbody></table><div style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: -18pt;"><span style="font-family: Verdana; font-size: 12pt; line-height: 150%;">-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Vamos a ver cómo se realiza una lectura de datos. En realidad una lectura de datos consta de dos operaciones: la primera es de escritura, la solicitud de datos al esclavo y la segunda de lectura de los datos recibidos. Vamos a ver primero el código de solicitud de datos:</span></div><div style="line-height: 150%; text-align: justify;"><br />
</div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none;"><tbody>
<tr> <td style="border: 1pt solid windowtext; padding: 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><div style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> …</span></div><div style="line-height: 150%; margin-left: 6.7pt;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[0] = 2; // Número de bytes del comando I2C</span></div><div style="line-height: 150%; margin-left: 6.7pt;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[1] = 0x02; // dirección I2C del esclavo</span></div><div style="line-height: 150%; margin-left: 6.7pt;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">cmdbuff[2] = 0x42; // dirección correspondiente a la entrada a leer. En este ejemplo se trata de la entrada analógica A0</span></div><div style="line-height: 150%; margin-left: 6.7pt;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">sendI2CMsg(PROTO_PORT, cmdbuff[0], 2); // Envío del comando al esclavo</span></div></td> </tr>
</tbody></table><div style="line-height: 150%; text-align: justify;"><br />
</div><div style="line-height: 150%; margin-left: 7.35pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> En este caso hay una diferencia en el procedimiento sendI2CMsg, el tercer parámetro es un 2 lo que indica que quiere leer dos bytes.</span></div><div style="line-height: 150%; margin-left: 7.35pt; text-align: justify;"><br />
</div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none;"><tbody>
<tr> <td style="border: 1pt solid windowtext; padding: 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><div style="line-height: 150%; margin-left: 7.35pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">... </span></div><div style="line-height: 150%; margin-left: 7.35pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">wait1Msec(10); // da tiempo para que responda</span></div><div style="line-height: 150%; margin-left: 7.35pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">readI2CReply(PROTO_PORT, respbuff[0], 2); // <span style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%;">almacena</span> la respuesta en la matriz respbuff[i].</span></div><div class="MsoNormal">…</div></td> </tr>
</tbody></table><div style="line-height: 150%; text-align: justify;"><br />
</div><div style="line-height: 150%; margin-left: 36pt; text-align: justify; text-indent: -18pt;"><span style="font-family: Verdana; font-size: 12pt; line-height: 150%;">-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Algunas entradas analógicas de ciertos sensores devuelven un valor entre 0 y 1023 (un valor de 10 bits) que almacenan en grupos de dos bytes: los 8 bits del primer byte recibido (respbuff[0]) contienen los 8 bits más significativos de la lectura mientras que los dos bits menos significativos del segundo byte (respbuff[1]) almacenan los dos bits menos significativos de la lectura del canal de entrada. Así que una vez recibidos hay que combinarlos para obtener el valor de lectura. Los valores recibidos son ubytes (byte sin signo de 0 a 255), no bytes (-128...127) lo que genera un problema en RobotC ya que no dispone de dicho tipo de variable. Si no se tiene esto en cuenta los valores no serán lo esperado (esto no ocurre en NXC). Para convertir los dos bytes en un solo valor la operación será la siguiente (no es código):</span></div><div style="line-height: 150%; margin-left: 72pt; text-align: justify; text-indent: -18pt;"><span style="font-family: "Courier New"; font-size: 12pt; line-height: 150%;">o<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Lectura = respbuff[0]*4 + respbuff[1] </span></div><div style="line-height: 150%; margin-left: 36pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Si lo que deseamos es hacer una lectura de las entradas digitales, el proceso es muy similar, la diferencia es que sólo se recibirá un byte que contendrá las lecturas de todas ellas, una vez recibidas habrá que relacionar cada bit con la entrada correspondiente.</span></div><div style="line-height: 150%; margin-left: 36pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-----------------------------------------------------------------------------------------------------------</span></div><div style="line-height: 150%; margin-left: 36pt; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> <b>Referencias:</b></span></div><div style="line-height: 150%; margin-left: 36pt; text-align: justify;"><style>
@font-face {
font-family: "Cambria Math";
}@font-face {
font-family: "Cambria";
}@font-face {
font-family: "ヒラギノ角ゴ Pro W3";
}p.MsoNormal, li.MsoNormal, div.MsoNormal { margin: 0cm 0cm 0.0001pt; font-size: 12pt; font-family: Cambria; color: black; }a:link, span.MsoHyperlink { color: blue; text-decoration: underline; }a:visited, span.MsoHyperlinkFollowed { color: purple; text-decoration: underline; }.MsoChpDefault { font-size: 10pt; }div.WordSection1 { page: WordSection1; }
</style> </div><ul><li>Universidad de Carnegie Mellon. <a href="http://www.cmu.edu/index.shtml">http://www.cmu.edu/index.shtml</a></li>
<li>Programming Solutions for the LEGO Mindstorms NXT. <a href="http://www.botmag.com/articles/10-31-07_NXT.shtml">http://www.botmag.com/articles/10-31-07_NXT.shtml</a></li>
<li>ROBOTC. <a href="http://www.robotc.net/">http://www.robotc.net</a></li>
<li>I2C con ROBOTC e Hitechnic Experimenter Kit. <a href="http://lrobotikas.net/eu/modeloak/nxt/91-i2c-con-robotc-e-hitechnic-experimenter-kit">http://lrobotikas.net/eu/modeloak/nxt/91-i2c-con-robotc-e-hitechnic-experimenter-kit</a></li>
</ul><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> </span>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-43374075159307423032011-01-10T01:09:00.000-08:002011-01-10T01:10:45.239-08:00Manejo del protocolo RS-485 mediante PbLua<style>
@font-face {
font-family: "MS ゴシック";
}@font-face {
font-family: "Cambria Math";
}@font-face {
font-family: "Cambria";
}@font-face {
font-family: "ヒラギノ角ゴ Pro W3";
}p.MsoNormal, li.MsoNormal, div.MsoNormal { margin: 0cm 0cm 0.0001pt; font-size: 12pt; font-family: Cambria; color: black; }h5 { margin: 10pt 0cm 0.0001pt; page-break-after: avoid; font-size: 12pt; font-family: Calibri; color: rgb(36, 63, 96); font-weight: normal; }tt { font-family: Courier; }span.Ttulo5Car { font-family: Calibri; color: rgb(36, 63, 96); }.MsoChpDefault { font-size: 10pt; }div.WordSection1 { page: WordSection1; }
</style> <br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="color: black; font-family: "Times New Roman";">Veamos cómo trabajar usando este protocolo con el lenguaje pbLua. En primer lugar tenemos la función siguiente:</span></div><h5 align="center" style="line-height: 150%; text-align: center; text-indent: 36pt;"><tt><b><span style="color: black; font-family: "Times New Roman"; font-size: 10pt; line-height: 150%;">rate = nxt.RS485Enable( rate )</span></b></tt></h5><h5 align="center" style="line-height: 150%; text-align: center; text-indent: 36pt;"><tt><b><span style="color: black; font-family: "Times New Roman"; font-size: 10pt; line-height: 150%;"> </span></b></tt><b><span style="color: black; font-family: "Times New Roman";"></span></b></h5><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="color: black; font-family: "Times New Roman";">Esta función inicializa la interfaz para la comunicación. Un valor de cero, apaga la interfaz, mientras que cualquier otro valor la deja preparada para la comunicación. El puerto se va a configurar con una velocidad mayor o igual que la indicada en campo “rate”, y con 8 bits de datos, sin paridad y con un bit de parada. Por ejemplo, si especificamos una tasa de 1000, el puerto se configurará con 1200, que es el valor superior más cercano existente que está disponible.</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="color: black; font-family: "Times New Roman";">Otra función itneresante es la siguiente:</span></div><h5 align="center" style="line-height: 150%; text-align: center; text-indent: 36pt;"><tt><b><span style="color: black; font-family: "Times New Roman"; font-size: 10pt; line-height: 150%;">nxt.RS485SendData( string )</span></b></tt><b><span style="color: black; font-family: "Times New Roman";"></span></b></h5><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="color: black; font-family: "Times New Roman";">Envía los bytes de la cadena al puerto de alta velocidad. Se envía un máximo de 128 bytes cada vez. Hay que tener en cuenta que no existe ninguna manera de saber si la interfaz está preparada para recibir más datos. El firmware original de LEGO llama a esta función una vez cada milisegundo, y el puerto envía aproximadamente 100 caracteres por milisegundo, con lo que no es muy probable que se produzca un desbordamiento.</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="color: black; font-family: "Times New Roman";">Finalmente, otra función que nos va a resultar útil es la que se muestra a continuación:</span></div><h5 align="center" style="line-height: 150%; text-align: center; text-indent: 36pt;"><tt><b><span style="color: black; font-family: "Times New Roman"; font-size: 10pt; line-height: 150%;">string = nxt.RS485RecvData( )</span></b></tt></h5><h5 align="center" style="line-height: 150%; text-align: center; text-indent: 36pt;"><tt><b><span style="color: black; font-family: "Times New Roman"; font-size: 10pt; line-height: 150%;"> </span></b></tt><b><span style="color: black; font-family: "Times New Roman";"></span></b></h5><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="color: black; font-family: "Times New Roman";">Nos devuelve los caracteres disponibles en el buffer de recepción del puerto.</span> </div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;">-------------------------------------------------------------------------------------------------------------</div><br />
<div class="MsoNormal" style="margin-left: 36pt;"><b>Referencias:</b> </div><ul><li>API de pbLua. <a href="http://www.hempeldesigngroup.com/lego/pblua/nxtfunctiondefs/#I2CAPI">http://www.hempeldesigngroup.com/lego/pblua/nxtfunctiondefs/#I2CAPI</a></li>
</ul><br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="color: black; font-family: "Times New Roman";"> </span></div>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-12582573423241926222011-01-10T00:53:00.000-08:002011-01-10T01:07:39.482-08:00Manejo del protocolo I2C con el lenguaje PbLua<style>
@font-face {
font-family: "Courier New";
}@font-face {
font-family: "Wingdings";
}@font-face {
font-family: "Cambria Math";
}@font-face {
font-family: "Cambria";
}@font-face {
font-family: "ヒラギノ角ゴ Pro W3";
}p.MsoNormal, li.MsoNormal, div.MsoNormal { margin: 0cm 0cm 0.0001pt; font-size: 12pt; font-family: Cambria; color: black; }pre { margin: 0cm 0cm 0.0001pt; font-size: 10pt; font-family: Courier; }span.HTMLconformatoprevioCar { font-family: Courier; }.MsoChpDefault { font-size: 10pt; }div.WordSection1 { page: WordSection1; }ol { margin-bottom: 0cm; }ul { margin-bottom: 0cm; }
</style> <br />
<div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman";">Las cuatro funciones básicas que se encuentran en la API de pbLua son las siguientes [25]:</span></div><ul type="disc"><li class="MsoNormal" style="color: windowtext; line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman";">nxt.I2CInitPins() </span></li>
<li class="MsoNormal" style="color: windowtext; line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman";">nxt.I2CGetStatus() </span></li>
<li class="MsoNormal" style="color: windowtext; line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman";">nxt.I2CSendData() </span></li>
<li class="MsoNormal" style="color: windowtext; line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman";">nxt.I2CRecvData() <br />
</span></li>
</ul><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><b><span style="font-family: "Times New Roman";">Configurando el puerto I2C<br />
</span></b></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman";"> Lo primero que se necesita conocer es el puerto al que está conectado el sensor. Como ya vimos, los puertos están numerados del 1 al 4 y será un valor que se use en todas las llamadas que usemos. Un posible código para preparar el puerto para la comunicación sería el siguiente:</span></div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none;"><tbody>
<tr> <td style="border: 1pt solid windowtext; padding: 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- Initialize port 4 for I2C communication </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">nxt.I2CInitPins(4) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- Use a variable to hold the port number </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">port = 4 nxt.I2CInitPins(port) </span></pre></td> </tr>
</tbody></table><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><b><span style="font-family: "Times New Roman";">Envío y recepción de datos<br />
</span></b></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman";"> Como vimos, la comunicación va a tener dos partes: una primera en la que se envía un dato al dispositivo, y una segunda en la que éste puede contestar al maestro, La función nxt.I2CSendData() se encarga de manejar esta comunicación. En el siguiente ejemplo de código se puede ver cómo se configura un puerto para usar el protocolo I<sup>2</sup>C y cómo a continuación establece las tres cadenas de texto necesarias para obtener la información básica del dispositivo:</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none;"><tbody>
<tr> <td style="border: 1pt solid windowtext; padding: 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- setupI2C() - sets up the specified port to handle an I2C sensor </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">function setupI2C(port) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">nxt.InputSetType(port,2) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">nxt.InputSetDir(port,1,1) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">nxt.InputSetState(port,1,1) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">nxt.I2CInitPins(port) end </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- Now put the standard I2C messages into the nxt table </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">nxt.I2Cversion = string.char( 0x02, 0x00 ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">nxt.I2Cproduct = string.char( 0x02, 0x08 ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">nxt.I2Ctype = string.char( 0x02, 0x10 ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">nxt.I2Ccontinuous = string.char( 0x02, 0x41, 0x02 ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">nxt.I2Cdata = string.char( 0x02, 0x42 ) </span></pre></td> </tr>
</tbody></table><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman";">La función string.char() forma parte de la librería básica de cadenas de Lua, y su función es la de ensamblar cadenas a partir de bytes individuales. </span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman";">El envío de cadenas I<sup>2</sup>C al sensor se puede realizar de esta forma:</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><br />
</div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none;"><tbody>
<tr> <td style="border: 1pt solid windowtext; padding: 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- Use the ultrasound sensor in port 4, make sure the </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- previous sample has been loaded setupI2C(4) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- Now send the product string, up to 8 bytes can be sent by the sensor </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">nxt.I2CSendData( 4, nxt.I2Cproduct, 8 ) </span></pre><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div></td> </tr>
</tbody></table><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman";">Y la lectura es igualmente sencilla:</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><br />
</div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none;"><tbody>
<tr> <td style="border: 1pt solid windowtext; padding: 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- Reading the data is simple. Make sure the previous example has been </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- loaded. The = notation is a short form for "print" </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">=nxt.I2CRecvData(4) </span></pre></td> </tr>
</tbody></table><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><b><span style="font-family: "Times New Roman";">Comprobar el estado I<sup>2</sup>C</span></b></div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman";">Envíar y recibir datos en este lenguaje es sencillo, pero para que todo funcione correctamente debemos, como siempre, tener en cuenta los tiempos y velar porque todo se haya producido correctamente.</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman";">La función I2CGetStatus() nos ayuda a conocer cuál es el estado del puerto I<sup>2</sup>C. Devuelve tres valores: el estado global del puerto I2C, el segundo es la fase en la que se encuentra la transmisión, y el tercero es el estado en el que se encuentra la recepción. Cuando una transacción I<sup>2</sup>C se ha completado (o ha agotado su tiempo) el primer valor devuelto por esta función debe ser cero, así que la función que hace que se espere a que la transacción se complete es la siguiente:</span></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><br />
</div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none;"><tbody>
<tr> <td style="border: 1pt solid windowtext; padding: 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- waitI2C() - sits in a tight loop until the I2C system goes idle </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">function waitI2C( port ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> while( 0 ~= nxt.I2CGetStatus( port ) ) do </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> end </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">end </span></pre></td> </tr>
</tbody></table><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none;"><tbody>
<tr> <td style="border: 1pt solid windowtext; padding: 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- Put it all together in a function that prints out a report of which </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- sensor is connected to a port </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">function checkI2C(port) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> setupI2C(port) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> nxt.I2CSendData( port, nxt.I2Cversion, 8 ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> waitI2C( port ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> print( "Version -> " .. nxt.I2CRecvData( port, 8 ) ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> nxt.I2CSendData( port, nxt.I2Cproduct, 8 ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> waitI2C( port ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> print( "Product ID -> " .. nxt.I2CRecvData( port, 8 ) ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> nxt.I2CSendData( port, nxt.I2Ctype, 8 ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> waitI2C( port ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> print( "SensorType -> " .. nxt.I2CRecvData( port, 8 ) ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">end </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- And now run the function to see if it recognizes the sensor checkI2C(4) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- Results are below, do not paste the following text to the console! </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Version -> V1.0 </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">Product ID -> LEGO </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">SensorType -> Sonar </span></pre><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div></td> </tr>
</tbody></table><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-align: justify;"><b><span style="font-family: "Times New Roman";">Lectura de datos de forma continua</span></b></div><div class="MsoNormal" style="line-height: 150%; text-align: justify; text-indent: 36pt;"><span style="font-family: "Times New Roman";">Para concluir esta explicación de cómo acceder al puerto I<sup>2</sup>C usando Lua, vamos a ver un ejemplo de cómo leer un dato del puerto I<sup>2</sup>C de manera continua mientras se mantenga pulsado el botón naranja del NXT. El código es el siguiente:</span></div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none;"><tbody>
<tr> <td style="border: 1pt solid windowtext; padding: 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">function I2CRead(port)</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> -- Set up the port and report on the sensor type</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> checkI2C(port)</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> -- Put it into continuous sample mode</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> nxt.I2CSendData( port, nxt.I2Ccontinuous, 0 </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> waitI2C( port ) </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> -- Read and print the results until the orange button is pressed</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> repeat</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> -- Read 8 bytes of data from the sensor</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> nxt.I2CSendData( port, nxt.I2Cdata, 8 )</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> waitI2C( port )</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> s = nxt.I2CRecvData( port, 8 )</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> -- Break the resulting string into 8 bytes and print the results</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> c1,c2,c3,c4,c5,c6,c7,c8 = string.byte(s,1,8)</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> print( string.format( "Result: %3i %3i %3i %3i %3i %3i %3i %3i", </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> c1, c2, c3, c4, c5, c6, c7, c8 ) )</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;"> until( 8 == nxt.ButtonRead() )</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">end </span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">-- And using the function - press the orange button on the NXT to stop it</span></pre><pre style="line-height: 150%; text-align: justify;"><span style="font-family: "Times New Roman"; font-size: 12pt; line-height: 150%;">I2CRead(4)</span></pre></td> </tr>
</tbody></table><br />
----------------------------------------------------------------------------------------------------------------------------<br />
<div class="MsoNormal" style="margin-left: 36pt;"><b>Referencias:</b> </div><ul><li>API de pbLua. <a href="http://www.hempeldesigngroup.com/lego/pblua/nxtfunctiondefs/#I2CAPI">http://www.hempeldesigngroup.com/lego/pblua/nxtfunctiondefs/#I2CAPI</a></li>
</ul><style>
@font-face {
font-family: "Cambria Math";
}@font-face {
font-family: "Cambria";
}@font-face {
font-family: "ヒラギノ角ゴ Pro W3";
}p.MsoNormal, li.MsoNormal, div.MsoNormal { margin: 0cm 0cm 0.0001pt; font-size: 12pt; font-family: Cambria; color: black; }a:link, span.MsoHyperlink { color: blue; text-decoration: underline; }a:visited, span.MsoHyperlinkFollowed { color: purple; text-decoration: underline; }.MsoChpDefault { font-size: 10pt; }div.WordSection1 { page: WordSection1; }
</style> <b><br />
</b>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-26145055934786089732011-01-10T00:45:00.000-08:002011-01-10T00:47:37.222-08:00Ejemplo 1: Manejar I2C desde LejOS<style>
@font-face {
font-family: "Courier New";
}@font-face {
font-family: "Wingdings";
}@font-face {
font-family: "Verdana";
}@font-face {
font-family: "Verdana";
}@font-face {
font-family: "Cambria";
}@font-face {
font-family: "ヒラギノ角ゴ Pro W3";
}p.MsoNormal, li.MsoNormal, div.MsoNormal { margin: 0cm 0cm 0.0001pt; font-size: 12pt; font-family: Cambria; color: black; }p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph { margin: 0cm 0cm 0.0001pt 36pt; font-size: 12pt; font-family: Cambria; color: black; }p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst { margin: 0cm 0cm 0.0001pt 36pt; font-size: 12pt; font-family: Cambria; color: black; }p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle { margin: 0cm 0cm 0.0001pt 36pt; font-size: 12pt; font-family: Cambria; color: black; }p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast { margin: 0cm 0cm 0.0001pt 36pt; font-size: 12pt; font-family: Cambria; color: black; }.MsoChpDefault { font-size: 10pt; }div.WordSection1 { page: WordSection1; }ol { margin-bottom: 0cm; }ul { margin-bottom: 0cm; }
</style> <br />
<div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";">A continuación se va a presentar un ejemplo de cómo manejar desde LejOS un dispositivo que usa el protocolo I<sup>2</sup>C. Se trata del NXTServo de Mindsensors, que ha sido desarrollado para manejar varios servos RC. </span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> En primer lugar, para poder leer la batería conectada a este dispositivo, es necesario conocer los siguientes parámetros:</span></div><div class="MsoListParagraphCxSpFirst" style="line-height: 150%; text-indent: -18pt;"><span style="font-family: Verdana;">-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman";">Dirección I<sup>2</sup>C del NXTServo: 0xb0</span></div><div class="MsoListParagraphCxSpLast" style="line-height: 150%; text-indent: -18pt;"><span style="font-family: Verdana;">-<span style="font-family: "Times New Roman"; font-size-adjust: none; font-size: 7pt; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"> </span></span><span style="font-family: "Times New Roman";">Registro I<sup>2</sup>C del NXTServo que nos permite leer el nivel de batería: 0x41</span></div><div class="MsoNormal" style="line-height: 150%;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-indent: 18pt;"><span style="font-family: "Times New Roman";">Un ejemplo de código que efectuaría la lectura del nivel de batería de nuestro dispositivo sería el siguiente:</span></div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none;"><tbody>
<tr> <td style="border: 1pt solid windowtext; padding: 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";">Public class NXTServoTest {</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> Public static void main(String[] args) {</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> DebugMessages dm = new DebugMessages();</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> dm.setLCDLines(6);</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> dm.echo(“Probando NXT Servo);</span></div><div class="MsoNormal" style="line-height: 150%;"><br />
</div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> MSC msc = new MSC(SensorPort.S1);</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> msc.addServo81,”Mindsensors RC Servo 9Gr”);</span></div><div class="MsoNormal" style="line-height: 150%;"><br />
</div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> while(¡Buton.ESCAPE.isPressed()){</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> dm.echo(msc.getBattery());</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> }</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> dm.echo(“Test finalizado”);</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> }</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";">}</span></div></td> </tr>
</tbody></table><div class="MsoNormal" style="line-height: 150%; text-indent: 18pt;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-indent: 18pt;"><span style="font-family: "Times New Roman";">La clase MSC (Mindsensors Servo Controller) es capaz de manejar hasta 8 servos RC. Vamos a ver, para entender un poco mejor todo esto, dos métodos internos de la clase MSC.</span></div><div class="MsoNormal" style="line-height: 150%; text-indent: 18pt;"><span style="font-family: "Times New Roman";">El primero de ellos es el constructor. Si nos fijamos en él, veremos que todas las operaciones de I<sup>2</sup>C usan la dirección 0xb0:</span></div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none;"><tbody>
<tr> <td style="border: 1pt solid windowtext; padding: 0cm 5.4pt; width: 488.6pt;" valign="top" width="489"><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";">public static final byte NXTSERVO_ADDRESS = (byte)0xb0;</span></div><div class="MsoNormal" style="line-height: 150%;"><br />
</div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";">public MSC (SensorPort port) {</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> super(port);</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> port.setType(TYPE_LOWSPEED_9V);</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> this.setAddress(MSC.NXTSERVO_ADDRESS);</span></div><div class="MsoNormal" style="line-height: 150%;"><br />
</div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> this.portConnected = port;</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";"> arrServo = new ArrayList();</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman";">}</span></div></td> </tr>
</tbody></table><div class="MsoNormal" style="line-height: 150%; text-indent: 18pt;"><br />
</div><div class="MsoNormal" style="line-height: 150%; text-indent: 18pt;"><span style="font-family: "Times New Roman";">El segundo método es el que nos devuelve el estado de la batería. En este caso se lee el registro 0x41 que, como se dijo anteriormente, almacena dicho nivel. Cada acción que se realice en I<sup>2</sup>C tiene una repsuesta: si esta respuesta es cero, es que todo ha ido bien, pero en caso contrario es que algo ha fallado. Normalmente cuando se lee un valor de un registro es necesario usar un buffer para almacenar los datos leídos, en nuestro caso se denomina “bufReadResponse”. Tenemos el código a continuación: </span></div><table border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(230, 230, 230) none repeat scroll 0% 0%; border-collapse: collapse; border: medium none; margin-left: 5.4pt;"><tbody>
<tr style="height: 42.05pt;"> <td style="border: 1pt solid windowtext; height: 42.05pt; padding: 0cm 5.4pt; width: 477pt;" valign="top" width="477"><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman"; font-size: 13pt; line-height: 150%;">Public int getBattery() {</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman"; font-size: 13pt; line-height: 150%;"> int I2C_repsonse;</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman"; font-size: 13pt; line-height: 150%;"> byte [] bufReadResponse;</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman"; font-size: 13pt; line-height: 150%;"> bufReadResponse = new bye[8];</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman"; font-size: 13pt; line-height: 150%;"> byte kSc8_Vbatt = 0x41; // El registro I2C para leer la batería</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman"; font-size: 13pt; line-height: 150%;"> return(37*(0x00FF & bufReadResponse[0])); //El 37 proviene de el voltaje que</span></div><div class="MsoNormal" style="line-height: 150%;"><span style="font-family: "Times New Roman"; font-size: 13pt; line-height: 150%;"> //nos da el NXT = 4700 mv / 128</span></div></td> </tr>
</tbody></table><div class="MsoNormal" style="line-height: 150%;"><br />
</div>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-84190537123914015762010-11-30T02:48:00.000-08:002010-11-30T02:48:45.880-08:00¿Cómo maneja LejOS los protocolos I2C y RS-485? LejOS permite la ejecución de código escrito en el lenguaje de programación JAVA en el interior del RCX. Incluye un API (Interfaz de Programación de Aplicaciones) que permite tener acceso a los distintos medios de comunicación propios de JAVA, además de a una parte del API estándar del propio lenguaje. LejOS no consta de todas la características de JAVA, pero puede fácilmente evolucionar hacia ellas en un futuro, siempre que la memoria del RCX, por ahora la principal limitación, lo permita<br />
<br />
<b>Protocolo I2C mediante LejOS</b><br />
<br />
Como se ha visto anteriormente, el robot puede comunicarse con los sensores que se le conecten haciendo uso del protocolo I2C. LejOS es capaz de gestionar esta comunicación haciendo uso de una clase denominada I2CSensor, cuyas principales funciones se van a describir a continuación.<br />
<br />
La clase I2CSensor, se encuentra contenida en el paquete Java.Lang.Object de JAVA. En primer lugar se van a ver los tres métodos más usados para nuestros propósitos. Cabe destacar que en todos los casos, si el método devuelve 0 la operación habrá sido un éxito, mientras que si devuelve otra cosa habrá que tratar el error producido.<br />
<ul><li><b>void setAddress(int addr).</b> Establece la dirección del puerto. Es importante destacar que el rango de direcciones que cubre va de 0x01 a 0x7F, y no de 0x02 a 0x7E como se incluye en las especificaciones de algunos dispositivos que funcionan bajo este protocolo.</li>
<li><b>Int sendData(int register, byte value) o Int sendData (int register, byte [ ] buf, int len)</b>. Esta instrucción nos va a permitir escribir lo que queramos en el registro del dispositivo seleccionado. En el primer caso, se va a escribir un único byte en el registro I2C deseado, en el segundo caso, se puede especificar la longitud del dato a mandar.</li>
<li><b>Int getData (int register, byte [ ] buf, int len).</b> Es la operación contraria a la anterior. Nos va a permitir obtener el dato que el sensor haya puesto en el registro que indiquemos.</li>
</ul><br />
Otros métodos que también nos van a ser de utilidad son los siguientes:<br />
<br />
<ul><li><b>I2CPort GetPort ( ).</b> Es un método que pertenece a la clase I2CPort, contenida dentro del paquete lejos.nxt.BasicSensorPort y más concretamente al paquete lejos.nxt.BasicSensorPort. Nos va a permitir obtener el número de puerto al que está conectado el sensor.</li>
<li><b>String getProductID ( ).</b> Esta función devuelve el identificador de producto del sensor que se esté usando.</li>
<li><b>String getSensorType ( ).</b> Nos va a devolver el tipo de sensor en una cadena, es decir, si es un sensor de temperatura, un sensor de luz, etc.</li>
<li><b>String getVersion ( )</b>. Esta función devolverá, contenida en una cadena, la versión del sensor.</li>
</ul><br />
<b>Protocolo RS-485 mediante LejOS</b><br />
<br />
La clase de LejOS que nos va a permitir tener acceso al protocolo RS-485 es la lejos-nxt.comm.RS485, contenida también dentro del paquete java.lang.objetc, y más conretamente dentro de lejos.nxt.comm.NXTCommDevice. Esta clase proporciona un acceso a bajo nivel a las capas más bajas del hardware que use el protocolo RS-485 y que esté conectado al puerto 4 del NXT. Así mismo, también soporta una conexión de más alto nivel basada en una red de tipo BitBus. Báicamente, la red proporciona una implementación simple de tipo maestro/esclavo usando transmisión de paquetes SDLC (Synchronous Data Link Control) con un control de errores mediante redundancia cíclica CRC-16-CITT. En esta implementación se usa una tasa de transferencia de 921.600 baudios y se usan bytes de lleno en lugar de bits de relleno, como se suele hacer (ya que no hay soporte hardware). El protocolo nos permite realizar hasta siete conexiones.<br />
<br />
Si bien la implementación original usaba JAVA para el manejo de tramas, se comprobó que se estaba añadiendo una gran tara innecesaria al proceso. Por este motivo, las rutinas de más bajo nivel de implementaron en C y se incluyeron en el firmware como métodos nativos. Así, se consiguió una mejora de un factor de 10 aproximadamente.<br />
<br />
A continuación se van a describir los métodos más importantes para el manejo de este protocolo:<br />
<ul><li><b>Static RS485connection connect (String target).</b> Va a establecer la conexión con un dispositivo remoto mediante el nombre o la dirección, que irán contenida en el parámetro target.</li>
<li><b>Static RS485connection connect (String target, int mode).</b> Es idéntica a la anterior, salvo que nos permite definir el método de entrada/salida que queremos usar.</li>
<li><b>Static void hsDisable ( ).</b> Desactiva el puerto hardware del protocolo RS-485</li>
<li><b>Static void hcEnable ( ).</b> Activa el puerto harware del protocolo RS-485</li>
<li><b>Static int hsRead (byte [ ] buf, int offset, int len). </b>Realiza una lectura de bajo nivel del puerto 4 del Mindstorm. Devuelve el número de bytes leídos.</li>
<li><b>Static int hsWrite (byte [ ] buf, int offset, int len). </b>Realiza una escritura de bajo nivel en el puerto 4 del NXT. Devuelve el número de bytes escritos.</li>
<li><b>Static RS485connection waitForConnection (int timeout, int mode). </b>Espera una conexión de otro NXT. Devuelve el objeto conector.</li>
</ul>--------------------------------------------------------------------------------------------------------------------------<br />
<b>Referencias:</b><br />
<ul><li>Sistemas de bus RS-485. http://www.wut.de/e-6wwww-11-apes-000.php</li>
<li>Charbel Stockmans Daou (2008). Desarrollo y Evaluación de Aplicaciones Robóticas con Lego Mindstorms. Universidad de Málaga</li>
<li>Class I2CSensor (lejos NXJ API Documentation). http://lejos.sourceforge.net/nxt/nxj/api/lejos/nxt/I2CSensor.html#SENSOR_TYPE</li>
<li>Class RS485 (lejos NXJ API Documentaion). http://lejos.sourceforge.net/nxt/nxj/api/index.html<b> </b></li>
</ul>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-82322520788863666572010-11-30T02:30:00.000-08:002010-11-30T02:34:47.448-08:00Protocolos usados por los Mindstorms en la comunicación (II): RS-485 El protocolo RS-485, también conocido como EIA-485 es un estándar de comunicaciones en bus de la capa física del modelo OSI.<br />
<br />
Este protocolo se define como un sistema para transmisión multipunto, ideal para transmisión a altas velocidades y a largas distancias (35 Mbps hasta 10 metros y 100 Kbps en 1200 metros) incluso en medios de transmisión ruidosos, ya que reduce los ruidos que aparecen a lo largo de las líneas de transmisión.<br />
<br />
Como medio de transmisión se suele utilizar un par de hilos entrelazados que admite hasta 32 estaciones en un solo hilo con comunicación half-duplex. Se soportan 32 transmisores y 32 receptores. Una de las grandes ventajas de este protocolo es que, al tratarse de un estándar abierto, permite muchas y muy diferentes configuraciones y utilizaciones. En la figura siguiente se puede apreciar un esquema del bus de comunicaciones:<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTAG1uxF9ewByTfXllqpVuU860HQPKlS94BwZTCpxQGbYOksxPiCFWDJn0W_NxfyTaDlrc_i78F-miR_Gl9-U4q4u_kEjUQjBoLkfhdvS2-V8822XWjdQ_bZUWlQGKmH4H9ZyYMaNlKqSV/s1600/5.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="118" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTAG1uxF9ewByTfXllqpVuU860HQPKlS94BwZTCpxQGbYOksxPiCFWDJn0W_NxfyTaDlrc_i78F-miR_Gl9-U4q4u_kEjUQjBoLkfhdvS2-V8822XWjdQ_bZUWlQGKmH4H9ZyYMaNlKqSV/s320/5.png" width="320" /></a></div> <br />
En algunos casos, como en el bus de medición DIN, se puede encontrar un bs de 4 hilos como el que se muestra en la figura inferior. En este caso se cablea la salida de datos del maestro a la entrada de datos de todos los servidores. Las salidas de datos de los servidores están concebidas conjuntamente a la entrada de datos del maestro.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg7fgpunkpwn6qZQgWV-70oRf9uEPYVLq4-9GqgkWcc4Xo9W2mTIb4PV7wcsltWAGJQmgm9fKPHyWG5CUWZjvt3dPBqsy92Il8kkjt_xPAK6K-MHO2WVnhKT9kQMa04Wi1m176_-MFqNK5D/s1600/6.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="130" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg7fgpunkpwn6qZQgWV-70oRf9uEPYVLq4-9GqgkWcc4Xo9W2mTIb4PV7wcsltWAGJQmgm9fKPHyWG5CUWZjvt3dPBqsy92Il8kkjt_xPAK6K-MHO2WVnhKT9kQMa04Wi1m176_-MFqNK5D/s320/6.png" width="320" /></a></div><br />
Dado que varios transmisores transmisores trabajan en una línea común, tiene que garantizarse con un protocolo que en todo momento sólo haya activo un transmisor de datos. El resto de transmisores en ese momento deben estar en un estado de alta impedancia para no interferir en la emisión de datos.<br />
<br />
Las principales aplicaciones de este protocolo son:<br />
<ul><li>SCSI-2 (Small Computer System Interface) y SCSI-3 usan esta especificación para ejecutar la capa física. </li>
<li>Este protocolo se suele usar con frecuencia en las UARTs para comunicaciones de datos de poca velocidad en las cabinas de los aviones. Un ejemplo de ello es su uso en algunas unidades de control de pasajeros. El motivo es que se requiere un cableado mínimo y éste puede ser compartido entre varios asientos, con lo que el sistema resulta simple y de poco peso.</li>
<li>Se suele usar también en sistemas grandes de sonido, tales como conciertos, teatros, etc. En los que se controla el sonido desde un ordenador y se envía el sonido a distintos elementos repartidos por la sala.</li>
<li>Otro ejemplo de uso de este protocolo es en domótica. Al permitir largas distancias y un cableado simple es idóneo para automatizar distintas partes de un edificio o de una vivienda.</li>
</ul><br />
<b>Método físico de transmisión</b><br />
<br />
Los datos en serie se van a transmitir sin estar referidos a masa, es decir, se envían como la diferencia de tensión entre las líneas correspondientes. Para cada señal a transmitir existe un par de conductores que se compone de una línea de señales invertida y de otra sin invertir.<br />
<br />
La línea invertida suele denominarse “A” y la no invertida “B”, lo que como vimos anteriormente en el caso del Mindstorm corresponde a los pines 5 y 6 respectivamente. El receptor sólo va a evaluar la diferencia de tensión existente entre ambas líneas, de modo que las interferencias comunes a las dos líneas no afectan a la medida.<br />
<br />
Los transmisores ponen a disposición bajo carga un nivel de tensión de ±2V entre las salidas. Los módulos de los receptores reconocen el nivel de ± 200 mV como señal válida.<br />
<br />
La asignación del nivel de tensión diferencial para el estado lógico se define como:<br />
<br />
<ul><li>A – B < -0,3 V = MARK = OFF = Nivel lógico ‘1’</li>
<li>A – B > +0,3 V = SPACE = ON = Nivel lógico ‘0’</li>
</ul>------------------------------------------------------------------------------------------------------------------------<br />
<b>Referencias</b><br />
<ul><li>El protocolo RS-485. http://es.wikipedia.org/wiki/RS-485</li>
<li>El modelo de referencia OSI. http://www.eveliux.com/mx/modelo-de-referencia-osi.php</li>
<li>Small Computer System Interface. http://es.wikipedia.org/wiki/SCSI</li>
<li>Sistemas de bus RS-485. http://www.wut.de/e-6wwww-11-apes-000.php<b> </b></li>
</ul>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0tag:blogger.com,1999:blog-754387214278989398.post-23351539263463062982010-11-30T02:26:00.000-08:002010-11-30T02:33:01.084-08:00Protocolos usados por los Mindstorms en la comunicación (I): I2C <br />
<b>Introducción</b><br />
<br />
Bajo estas siglas encontramos uno de los estándares de comunicaciones serie más conocidos en la industria electrónica. I2C es el acrónimo en inglés de Inter-Integrated Circuit, es decir, circuito Inter-Integrado. Atendiendo a esta descripción es fácil imaginar que el objetivo de este bus no será otro que el de interconectar distintos elementos para que pasen a formar parte de un todo. Vamos a describir las principales características de este bus, y lo relacionaremos con los robots de LEGO viendo de qué manera se hace uso del mismo. <br />
<br />
El bus I2C, un estándar que facilita la comunicación entre microcontroladores, memorias y otros dispositivos con cierto nivel de "inteligencia", sólo requiere de dos líneas de señal y un común o masa. Fue diseñado a este efecto por Philips y permite el intercambio de información entre muchos dispositivos a una velocidad aceptable, de unos 100 Kbits por segundo, aunque hay casos especiales en los que el reloj llega hasta los 3,4 MHz.<br />
<br />
La metodología de comunicación de datos del bus I2C es en serie y sincrónica. Una de las señales del bus marca el tiempo (pulsos de reloj) y la otra se utiliza para intercambiar datos.<br />
<br />
<b>Descripción de las señales</b><br />
<br />
Dado que es un bus serie, el número de hilos necesarios suele ser ya pequeño de por sí, pero en este caso se ve reducido a sólo 3, de los cuales uno es el cable de masa. El cable de masa puede omitirse en todos aquellos casos en los que hablemos de un único circuito impreso, ya que habitualmente existe una única zona de masa común a todos los componentes. Es una de las principales características de este tipo de bus: menor número de señales implica menor probabilidad de interferencias y una mayor sencillez de cableado en entornos donde el espacio es un factor crítico.<br />
<br />
Los cables usados son los siguientes:<br />
<br />
<ul><li><b>SCL (System Clock)</b> es la línea de los pulsos de reloj que sincronizan el sistema.</li>
<li><b>SDA (System Data)</b> es la línea por la que se mueven los datos entre los dispositivos.</li>
<li><b>GND (Masa)</b> común de la interconección entre todos los dispositivos "enganchados" al bus.</li>
</ul><br />
Las líneas SDA y SCL son del tipo drenador abierto, es decir, un estado similar al de colector abierto, pero asociadas a un transistor de efecto de campo (o FET). Se deben polarizar en estado alto (conectando a la alimentación por medio de resistores "pull-up") lo que define una estructura de bus que permite conectar en paralelo múltiples entradas y salidas. Esto se puede ver en la siguiente figura:<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5JnFR5pnkYXMmt3MrhdLXBznQ3VjRiEZy9QB1Y5rbB-FEo9B7GOJIg-Wn9fAHESw5RE9OrfMXaplWT-WcblWXWFQs4gE4oFn9RHg2FlB5r6cmdO11AmFYmIaoM-08aMiH7IBgWalbd6K9/s1600/1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="94" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5JnFR5pnkYXMmt3MrhdLXBznQ3VjRiEZy9QB1Y5rbB-FEo9B7GOJIg-Wn9fAHESw5RE9OrfMXaplWT-WcblWXWFQs4gE4oFn9RHg2FlB5r6cmdO11AmFYmIaoM-08aMiH7IBgWalbd6K9/s320/1.png" width="320" /></a></div><br />
<br />
En el diagrama anterior se pueden ver como las dos líneas del bus están en un nivel lógico alto cuando están inactivas. En principio, el número de dispositivos que se puede conectar al bus no tiene límites, aunque hay que observar que la capacidad máxima sumada de todos los dispositivos no supere los 400 pF. El valor de los resistores de polarización no es muy crítico, y puede ir desde 1K8 (1.800 ohms) a 47K (47.000 ohms). Un valor menor de resistencia incrementa el consumo de los integrados pero disminuye la sensibilidad al ruido y mejora el tiempo de los flancos de subida y bajada de las señales. Los valores más comunes en uso son entre 1K8 y 10K.<br />
<br />
<b>Protocolo de comunicación del bus I2C</b><br />
<br />
Un único bus de comunicación I2C puede soportar hasta 128 dispositivos conectados a él directamente. Para poder identificar a los dispositivos, y poder establecer así la comunicación, todos los dispositivos cuentan con una dirección única de 7 bits (de ahí las 128 combinaciones resultantes). Los dispositivos pueden funcionar tanto en modo esclavo como en modo maestro. En cada momento, sólo puede haber un dispositivo en modo maestro en el bus, sin embargo, este dispositivo puede ir cambiando siempre que sus características lo permitan. El maestro es el único autorizado para iniciar el envío de datos, y es también el encargado de generar la señal de reloj. La secuencia de inicio se puede ver en la siguiente figura:<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg7equQktdJsCUtHZHLHDRrap6P_8RqjlR6sYZa9EdKtpc2QoYPzesVAiQPrm5Ir0IyMAW26XJss4Coy3Jv-X2JiZltbTXcVhzKOsvIw_j4Y05gKBTRbKjVceySyFBUlYTrR8rsiCHz_zQd/s1600/2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg7equQktdJsCUtHZHLHDRrap6P_8RqjlR6sYZa9EdKtpc2QoYPzesVAiQPrm5Ir0IyMAW26XJss4Coy3Jv-X2JiZltbTXcVhzKOsvIw_j4Y05gKBTRbKjVceySyFBUlYTrR8rsiCHz_zQd/s1600/2.png" /></a></div><ul><li>La condición inicial, de bus libre se produce cuando ambas señales están en estado lógico alto. En este estado cualquier dispositivo maestro puede ocuparlo, estableciendo la condición de inicio (start). Esta condición se presenta cuando un dispositivo maestro pone en estado bajo la línea de datos (SDA), pero dejando en alto la línea de reloj (SCL).</li>
<li>El primer byte que se transmite tras la condición de inicio contiene siete bits que componen la dirección del dispositivo que se desea seleccionar, y un octavo bit que corresponde a la operación que se quiere realizar con él (lectura o escritura).</li>
<li>Si el dispositivo cuya dirección corresponde a la que se indica en los siete bits (A0-A6) está presente en el bus, éste contesta con un bit en bajo, ubicado inmediatamente luego del octavo bit que ha enviado el dispositivo maestro. Este bit de reconocimiento (ACK) en bajo le indica al dispositivo maestro que el esclavo reconoce la solicitud y está en condiciones de comunicarse. Aquí la comunicación se establece en firme y comienza el intercambio de información entre los dispositivos. </li>
</ul><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh04J-iHLNOFDQ78wEUnbymSrWsT4rbysQH4IFn2sox7vpjJ-kf2dhqqIuLDt8rKItBWbc4Wm6n8Q4RSgrQIXuhaltOnNgYSmi8BFPsDl0cozNknbyTyn9ytkRcOmGiaJdPqgSDZwtOvsDM/s1600/3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="50" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh04J-iHLNOFDQ78wEUnbymSrWsT4rbysQH4IFn2sox7vpjJ-kf2dhqqIuLDt8rKItBWbc4Wm6n8Q4RSgrQIXuhaltOnNgYSmi8BFPsDl0cozNknbyTyn9ytkRcOmGiaJdPqgSDZwtOvsDM/s320/3.png" width="320" /></a></div><ul><li>Si el bit de lectura/escritura (R/W) se ha puesto en esta comunicación a nivel lógico bajo (escritura), el dispositivo maestro envía datos al dispositivo esclavo. Esto se mantiene mientras continúe recibiendo señales de reconocimiento, y el contacto concluye cuando se hayan transmitido todos los datos.</li>
<li>En el caso contrario, cuando el bit de lectura/escritura estaba a nivel lógico alto (lectura), el dispositivo maestro genera pulsos de reloj para que el dispositivo esclavo pueda enviar los datos. Luego de cada byte recibido el dispositivo maestro (quien está recibiendo los datos) genera un pulso de reconocimiento.</li>
<li>El dispositivo maestro puede dejar libre el bus generando una condición de parada (o detención; stop en inglés). Esta secuencia se puede ver en la figura siguiente: </li>
</ul><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEheYJKxgDh-lK8NAbPZ6TuTc0gy-jB1TMM9DrIfXzZd6s4RvV_TTpbRhqyQ5W0T7UYx4Jj-4EGRF-aQv4-yGy5G8_5KYOJjrPaqnDAkOvy243h1IKW5TZ34lqAUg-JtwJzOqriEiQVBB_J0/s1600/4.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEheYJKxgDh-lK8NAbPZ6TuTc0gy-jB1TMM9DrIfXzZd6s4RvV_TTpbRhqyQ5W0T7UYx4Jj-4EGRF-aQv4-yGy5G8_5KYOJjrPaqnDAkOvy243h1IKW5TZ34lqAUg-JtwJzOqriEiQVBB_J0/s1600/4.png" /></a></div><ul><li>Si se desea seguir transmitiendo, el dispositivo maestro puede generar otra condición de inicio en lugar de una condición de parada. Esta nueva condición de inicio se denomina "inicio reiterado" y se puede emplear para direccionar un dispositivo esclavo diferente o para alterar el estado del bit de lectura/escritura.</li>
</ul><br />
<b>Direccionamiento de dispositivos en el bus I2C</b><br />
<br />
Lo más común en los dispositivos para el bus I2C es que utilicen direcciones de 7 bits, aunque existen dispositivos de 10 bits. Este último caso es raro.<br />
<br />
Una dirección de 7 bits implica que se pueden poner hasta 128 dispositivos sobre un bus I2C, ya que un número de 7 bits puede ir desde 0 a 127. Cuando se envían las direcciones de 7 bit, de cualquier modo la transmisión es de 8 bits. El bit extra se utiliza para informarle al dispositivo esclavo si el dispositivo maestro va a escribir o va a leer datos desde él. Si el bit de lectura/escritura (R/W) es cero, el dispositivo maestro está escribiendo en el esclavo. Si el bit es 1 el maestro está leyendo desde el esclavo. La dirección de 7 bit se coloca en los 7 bits más significativos del byte y el bit de lectura/escritura es el bit menos significativo.<br />
<br />
El hecho de colocar la dirección de 7 bits en los 7 bits más significativos del byte produce confusiones entre quienes comienzan a trabajar con este bus. Si, por ejemplo, se desea escribir en la dirección 21 (hexadecimal), en realidad se debe enviar un 42, que es un 21 desplazado un bit hacia arriba. También se pueden tomar las direcciones del bus I2C como direcciones de 8 bit, en las que las pares son de sólo escritura y las impares son de sólo lectura. <br />
<br />
<b>Resumen de lectura/Escritura de un dispositivo esclavo</b><br />
<br />
Para escribir en un dispositivo esclavo, se debe seguir la siguiente secuencia:<br />
<br />
1. Enviar una secuencia de inicio<br />
2. Enviar la dirección de dispositivo con el bit de lectura/escritura en bajo<br />
3. Enviar el número de registro interno en el que se desea escribir<br />
4. Enviar el byte de dato<br />
5. [Opcionalmente, enviar más bytes de dato]<br />
6. Enviar la secuencia de parada<br />
Y para leer de un dispositivo esclavo la secuencia es la siguiente:<br />
1. Enviar una secuencia de inicio<br />
2. Enviar 0xC0 (La dirección de dispositivo del CMPS03 con el bit de lectura/escritura en bajo)<br />
3. Enviar 0x01 (dirección interna del registro de ángulo en valor 0-255)<br />
4. Enviar una secuencia de inicio (inicio reiterado)<br />
5. Enviar 0xC1 (La dirección de dispositivo del CMPS03 con el bit de lectura/escritura en alto)<br />
6. Leer un byte de dato desde el CMPS03<br />
7. Enviar la secuencia de parada<br />
<br />
<b>Si el esclavo necesita más tiempo</b><br />
<br />
Esto es todo cuando se trata de comunicaciones simples, pero debemos considerar una posible complicación: Cuando el dispositivo maestro está leyendo desde el esclavo, quien pone los datos en la línea SDA del bus es el dispositivo esclavo, y el maestro es el que controla el pulso de reloj. ¿Qué pasa si el esclavo no está listo para enviar un dato? Con dispositivos como una EEPROMs esto no sería problema, pero si el dispositivo esclavo es un microprocesador, que tiene otras tareas que realizar, pueden surgir inconvenientes.<br />
<br />
Para atender la transacción, el microprocesador debe pasar a una rutina de interrupción, guardar sus registros de trabajo, determinar qué dirección desea leer el dispositivo maestro, obtener el dato y ponerlo en su registro de transmisión. Esto puede llevar varios microsegundos, lo que implica que el dispositivo maestro podría estar enviando pulsos de reloj ciegamente por la línea SCL sin que el dispositivo esclavo pueda responderle. El protocolo I2C ofrece una solución para esto: el esclavo puede mantener la línea SCL en bajo. A esto se le llama estiramiento del reloj. Cuando el esclavo recibe el comando de lectura lo primero que hace es poner la línea de reloj en bajo. Entonces sí, obtiene el dato solicitado, lo pone en el registro de transmisión, y sólo entonces libera la línea de reloj, que pasará de inmediato a nivel alto debido al nivel que aporta el resistor de polarización.<br />
<br />
Desde el punto de vista del dispositivo maestro, éste tratará de enviar el primer pulso de reloj para la lectura de datos liberando la línea SCL para que pase a alto, pero antes de continuar comprobará que ésta realmente haya ido al nivel lógico 1. Si la línea SCL permanece en bajo, el dispositivo maestro interpreta que el esclavo la mantiene así y espera a que SCL vaya a alto antes de continuar. Por suerte, la mayoría de los puertos I2C de los microprocesadores manejan esto de manera automática.<br />
<br />
----------------------------------------------------------------------------------------------------------------------<br />
<br />
<b>Referencias:</b><br />
<ul><li>Carles Llacer (2009). El bus I2C y LEGO Mindstorms NXT.</li>
<li>El bus I2C. http://robots-argentina.com.ar/Comunicacion_busI2C.htm<b> </b></li>
</ul>Azerhttp://www.blogger.com/profile/09882684343828204146noreply@blogger.com0