You are on page 1of 498
ARDUINO Curso practico de formacién Los esquemas eléctricos han sido realizados con CircuitLab: http://www.circuitlab.com Los graficos de circuitos han sido realizados con Fritzing: http://www.fritzing. org los retoques han sido realizados con Inkscape y Gimp: htto://inkscape.org, httg://gimp.org las imagenes han sido obtenidas por medics propios o bien descargadas de la Wikipedia 6 Ladyada.net (con licencia CC-Share-Alike}: http://es.wikipedia.org http://www.ladyada.net ARDUINO. Curso practico de formacién Oscar Torrente Arter ISBN: 978-84-940725-0-5 EAN: 9788494072505 Bic: J; Uy Copyright © 2013 RC Libros © RC Libros es un selloy marca comercial registrados Arduino. Curso prictico de formacién Resecvados todos los derechos. Ninguna parte de este libro incluida la cubierta puede cer reproducida, su cantenide ezté protegido por la Ley vigente que establece penas de prisién y/o multas a cuienes intencionadamente reprodujeren © plagiaren, en todo o en parte, una obra literaria, artstica 0 cientifca, ‘9 su transformacién, interpretacién 9 ejecucién en cualquier tipo de soporte existente 0 de préxima invencién, sin autorizacién previa y por escrito de los titulares de los derechos del copyright. La infraccién de los derechos citados puede constituir delito contra la propiedad intoloctual, (Art. 270 y siguientes del Cédigo Penal). Dirijase a CEDRO (Centro Espafiol de Derechos Reprogrificos) sinecesita fotocopiar 0 escanear algiin fragmento de esta obra através de la web www.conlicencia.com; © por teléfone a: 91 702 1970 /93 272.04 47) finguncaca era esponeables de ls read del wo du corten, nde cualquier walaesn da patents © derechos de cers pate, lobiatva dela ova es proporionaral eto conacimentoupreciony ae abt e tema tatadeperosu venta nosepore ninguna fora de asitenc legal admnstatva nde ing cr ipo, se ‘ado en scanteno exten sno rapa, prtenecen asus respects propi=to8 RC Libros Calle Mar Mediterraneo, 2. Nave 6 28830 SAN FERNANDO DE HENARES, Madrid Teléfono: #3491 677 57 22 Fax: +3491 67757 22 Correo electrénice: info@rclibros.es Internet: wwvirclioros.es Disefio de coleccién, cubierta y pre-impresién: Grupo RC Impresion y encuadernacién: Depésito Legal: Impreso en Espans 17 1615 1413 (1234567891011 12) (NDICE INTRODUCCION.. CAPITULO 1. ELECTRONICA BASICA... CONCEPTOS TEORICOS SOBRE ELECTRICIDAD... éQué es laelectricidad? éQué es el voltaje? éQué es la intensidad de corriente? ... aQué es la corriente continua (DC) y la corriente alterna (AC\? éQué es la resistencia eléctrica? éQué es la Ley de Ohm?.... éQué es la potencia?... éQué son las sefiales digitales y las sefiales analégicas éQué son las sefiales periédicas y las sefiales aperiédicas? CIRCUITOS ELECTRICOS BASICOS Representacién grafica de circuitos Conexiones en serie y en paralelo El divisor de tensién Las resistencias “pull-up” y “pull-down” FUENTES DE ALIMENTACION ELECTRICA Tipos de pilas/baterias Caracteristicas de las pilas/pateries .. Conexiones de varias pilas/vaterias.. Compra de pilas/baterias.. Compra de cargadores... Caracteristicas de los adaptadores AC/DC... ARDUINO. CURSO PRACTICO DE FORMACION COMPONENTES ELECTRICOS .. Resistencias.. Potenciémetros Otras resistencias de valor variable Diodos y LEDs... Condensadores Transistores Pulsadores.... Reguladores de tension Placas de prototipado USO DE UNA PLACA DE PROTOTIPADO USO DE UN MULTIMETRO DIGITAL .. CAPITULO 2. HARDWARE ARDUINO QUE ES UN SISTEMA ELECTRONICC?. QUE ES UN MICROCONTROLADOR?, éQUE ES ARDUINO? .... ACUALES EL ORIGEN DE ARDUINO?. QUE QUIERE DECIR QUE ARDUINO SEA “SOFTWARE LIBRE”? {QUE QUIERE DECIR QUE ARDUINO SEA “HARDWARE LIBRE”? éPOR QUE ELEGIR ARDUINO? CARACTERISTICAS DEL MICRO DE LA PLACA ARDUINO UNO. El encapsulado del microcontrolador ... El modelo del microcontrolader .... las memorias del microcontrolador .. Los registros del microcontrolador .. Los protocolos de comunicacién I'C/TWIy SPI .. El gestor de arranque del microcontrolador QUE OTRAS CARACTERISTICAS TIENE LA PLACA ARDUINO UNO?, La alimentacién El chip ATmega16U2... Las entradas y salidas digitales . Las entradas analogicas ... Las salidas analdgicas (PWM) Otros usos de los pines-hembra de la placa El conector ICSP ...... El reloj... sas El boton de “reset” Obtener el disefio esquemitico y de referencia QUE OTRAS PLACAS ARDUINO OFICIALES EXISTEN vill © RC Libros inpice Arduino Mega 2580 .... Arduino Mega ADK. Arduino Ethernet .. Los adaptadores USB-Serie.. PoE (“Power Over Ethernet”) Arduino Fio Arduino Pro Arduino Lilypad .. Arduino Nano. Arduino Mini. Arduino Pro Mini... Arduino Leonardo El “auto-reset” de la placa Leonardo Arduino Micro... Arduino Due... {QUE “SHIELDS” ARDUINO OFICIALES EXISTEN? Arduino Ethernet Shield Arduino Wireless SD Shiel Arduino Wireless Proto Shield Arduino WiFi Shield .. Arduino Motor Shield Tinkerkit (y otros) Arduino Proto Shield... QUE SHIELDS NO OFICIALES EXISTEN CAPITULO 3. SOFTWARE ARDUINO. QUE ES UN IDE? INSTALACION DEL IDE ARDUINO. Ubuntu. Fedora... Cualquier sistema Linux Las dependencias .. Los permisos de usuario Sobre el reconocimiento y uso de dispositivos USB-ACM en Linux Cualquier sistema Linux (a partir del cédigo fuente) Windows........ Mac OS X... sa PRIMER CONTACTO CON EL IDE. El “Serial Monitor” y otros terminales serie .. CONFIGURACION Y COMPROBACION DEL CORRECTO FUNCIONAMIENTO DELIDE .. © RC Libros IK ARDUINO. CURSO PRACTICO DE FORMACION MAS ALLA DEL LENGUAJE ARDUINO: EL LENGUAJE C/C++ .. IDES ALI ERNATIVGS AC ORCINR ssc acon auc acrea nad Asignacién de valores a una variable .. ee eects Ambito de una variable 159 Tipos posibles de una variabl 160 Cambio de tipo de datos (numéricos)... 168 Instrucciones para enviar datos desde la placa al exterior. Instrucciones para recibir datos desde el exterior Los objetos serie de otras placas Arduino... asa UNSTRUCCIONES DE GESTION DEL TIEMPO o..ssscesssssesssesentssssnnenecennnsssesnnsee 184 INSTRUCCIONES MATEMATICAS, TRIGONOMETRICAS Y DE PSEUDOALEATORIEDAD .0cccccssseeceenneceensececsnssteneseneenssensesenennnsseeceneee 186 INSTRUCCIONES DE GESTION DE CADENAS. Od CREACION DE INSTRUCCIONES (FUNCIONES) PROPIAS .. 197 BLOQUES CONDICIONALES.. 200 Los bloques “if” y “iffelse”’. .200 El bloque “switch”... .206 BLOQUES REPETITIVOS (BUCLES).. 207 El bloque “while” .207 El bloque “do’ .210 El bloque “for” .210 Las instrucciones “break” y “continue” .. 214 CAPITULO 5. LIBRERIAS ARDUINO LAS LIBRERIAS OFICIALES .... Libreria LiquidCrystal Libreria EEPROM. 217 217 217 217 x © RC Libros inoice Libreria SD. 1218 Libreria Ethernet. 218 Libreria Firmata.. 219 Libreria SPI. 219 Libreria Wire 220 Libreria SoftwareSerial see 220 Librerias Servo y Stepper 221 Librerias Keyboard y Mouse (solo para Arduino Leonardo y Due) 221 Librerias Audio, Scheduler y USBHost (solo para Arduino Due) 221 USO DE PANTALLAS. 222 Las pantallas de cristal liquido (LCDs). 222 La libreria LiquidCrystal.. 225 Médulos LCD de tipo I°C, Serie o SPI 230 Shields que incorporan LCDs... 234 Shields y médulos que incorporan GLCD... 236 Shields que incorporan pantallas OLED de 4DSystems .. 239 Médulos OLED de Adafruit 241 Shields y médulos que incorporan pantallas TFT 244 Shields y médulos que incorporan pantallas TFT tactiles 246 Shields que incorporan displays “7-segmentos”......... 249 Matrices de LEDs. 253 USO DE LA MEMORIA EEPROM . 256 USO DE TARJETAS SD... 257 Caracteristicas de las tarjetas SD . 257 La libreria SD 259 Shields que incorporan z6calos microSD. 269 Modulos que incorporan z6calos microSD... 270 USO DE PUFRTOS SERIF SOFTWARE 0 sscsscssssassscaninnnsssnnnssssnrannssssnsssssssann 270 USO DE MOTORES... 273 Conceptos bésicos sobre motores 273 Tipos de motores... 275 Los motores DC. 275 Los servomotore: 22 Los motores paso a paso. 280 La libreria Servo.... 283 La libreria Stepper... 2288 CORPETIUUCSGZENNTRERDAS VNR pie USO DE LAS ENTRADAS Y SALIDAS DIGITALFS oR Ejemplos con salidas digitales.. © RC Libros xl ARDUINO. CURSO PRACTICO DE FORMACION noe 0S, 318 320 322 Ejemplos con entradas digitales (pulsadores). Keypads...... USO DE LAS ENTRADAS Y SALIDAS ANALOGICAS .. Ejemplos con salidas analégicas. Ejemplos con entradas analégicas (potenciémetros .328 Ejemplo de uso de joysticks como entradas analégicas 336 Ejemplo de uso de pulsadores como entradas analégicas 338 Sensores capacitivos. 342 Cambiar el voltaje de referencia de las lecturas analdgica: 347 CONTROL DE MOTORES DC... 349 El chip (293... 355 Médulos de control para motores DC 357 La placa TB6612FNG Otros médulos... Shields de control para motores DC (y paso a paso) El “Adafruit Motor Shield” Otros shields... 357 359 360 360 361 EMISION DE SONIDO.. 365 Uso de zumbadores ... 365, Las funciones tone() y noTone().... 1.368 Uso de altavoces..... 373 375 378 378 Amplificacién simple del sonido Sonidos pregrabados ... La libreria “SimpleSDAudio” El “Wave Shield” de Adafruit 380 Shields que reproducen MP3 : 381 Maédulos de audio. 38: Reproductores de voz... 387 CAPITULO 7. SENSORES.... SENSORES DE LUZ VISIBLE. 391 392 Fotorresistores 392 El sensor digital TSL2561.. 405 El sensor analégico TEMT6000 .. 405 SENSOPECDE Ll i2 INFRARRQIR csc cccnc ania nn nO Fotodiodos y fototransistores ... 21.406 Control remoto «0. rasa grease EL SENSORES DETEMPERSTURA Gf ccsctiid alain Termistare: a2 El chip analdgico TMP36 . 1428 XII © RC Libros inoice El chip digital 0S18820 y el protocolo 1-Wire...... 432 La plaquita breakout TMP421 . 434 SENSORES DE HUMEDAD cc teecieernenrinnnrnrresanreicrsrsnnsrnrrsrreesanrssararsnrsance SSS El sensor DHT22/RHTO3..... 435 Los sensores SHT1S y SHT21 439 SENSORES DE DISTANCIA... 440 El sensor Ping])) 440 El sensor SRFOS.. 443 El sensor HC-SRO4 446 El sensor LV-EZO 446 Los sensores GP2Vxxx.. El sensor IS471F... Los sensores QRD1114 y QRE1113... EL SENSOR EPIR ensores de fuerza ensores de flexion Sensores de golpes SENSORES DE SONIDO. Plaquitas breakout Circuitos pre-amplificadores. Reconocimiento de voz CAPITULO 8. COMUNICACION EN RED CONCEPTOS BASICOS SOBRE REDES Direccién IP ... Mascara de red... Direcciones IP privadas. Direccion MAC Servidores DNS... Puerta de enlace predeterminada... USO DE LA PLACA/SHIELD ARDUINO ETHERNET Configuracién inicial de los parametros de red Uso de Arduino como servidor.. Eluso de ips piblicas para acceder’a Arduino Uso de Arduino como cliente . Caso practico: servidor web_integrado en la placa/shield Arduino Caso practico: servidor web con tarjeta SD... © RC Libros xill ARDUINO. CURSO PRACTICO DE FORMACION Caso practico: formulario web de control de actuadores..... Caso practico: envio de mensajes a Twitter.com Caso practico: envio de datos a Cosm.com Caso practico: obtencién de datos provenientes de Cosm.com Caso practico: envio de datos a Google Spreadsheets Caso practico: envio de notificaciones a Pushingbox.com Shields alternativos a Arduino Ethernet. Comunicacién por red usando una placa Arduino UNO estandat COMUNICACION A TRAVES DE WI-FI. éQué es Wi-Fi? Uso del Arduino WiFi Shield y de la libreria oficial WiFi .. Otros shields y médulos que afiaden conectividad Wi-Fi COMUNICACION A TRAVES DE BLUETOOTH. éQué es Bluetooth?... Sz Modulos que aftaden conectividad Bluetooth Shields que afiaden conectividad Bluetooth APENDICE A, DISTRIBUIDORES DE ARDUINO Y MATERIAL ELECTRONICO .. Kits... APENDICE B. CODIGOS IMPRIMIBLES DE LA TABLA ASCI.. APENDICE C. RECURSOS PARA SEGUIR APRENDIENDO. 561 Plataforma Arduino Electronica general Proyectos... SIN BIICE AN BL TAG. neaspsrcecoesersrsererreresprpremnrenmemeentecgnareonnererrereenemneteenrerieerencte SOD xIV © RC Libros aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. CAPITULO 3: SOFTWARE ARDUINO sencillo es desconectarla y reabrir el menu: la entrada que haya desaparecido seré la que buscamos; conectando otra vez la placa podremos seleccionarla sin problemas. temas MacOS X: aparecen los ficheros de dispositive (normalmente /dev/tty.usbmodem###). Es posible que en el momento de conectar una placa UNO o Mega se muestre una ventana emergente informando de que se ha detectado un nuevo dispositive de red. Si ocurre esto, basta con clicar en “Network preferences...” y cuando aparezca la nueva ventana, simplemente clicar en “Apply”. La placa se mostraré como “Not configured”, pero funcionaré correctamente por lo que ya se puede salir de las preferencias del sistema. Ambas configuraciones (placa y puerto) solamente serén necesarias especificarlas una sola vez mientras no las modifiquemos (es decir, mientras no usemos otro tipo de placa, por ejemplo). Ahora solo nos falta comprobar que todo funcione correctamente, ejecutando algtin sketch de prueba. Como todavia no sabemos escribir ninguno por nuestra cuenta, utilizaremos un sketch de los que vienen como ejemplo Concretamente, el sketch llamado “Blink”. Para abrirlo, debemos ir al ment “File”- >” Examples”->"01.Basics’->"Blink”. Ahora no nos interesa estudiar el cédigo que aparece: simplemente hemos de pulser en el botén “Verify” y seguidamente en el botén “Upload”. Siempre deberemos seguir esta pauta con todos los sketches: una vez queramos probar cémo funcionan, debemos pulsar primero en “Verify” (para compilar y verificar el cédigo) y seguidamente en “Upload” (para cargarlo en el microcontrolador). Justo después de haber pulsado este Ultimo botén, ocurre que. 1. Primero parpadearé muy rapidamente el LED etiquetado como “L”, indicando que la place se ha reseteado y, por lo tanto, que se esté ejecutando el bootloader 2. Seguidamente los LEDs de la placa etiquetados como “RX” y “TX” parpadearan rapidamente varias veces, indicando que el sketch esté llegando a la placa y, por tanto, que esta siendo recibido por el bootloader y cargado en la memoria Flash del microcontrolador. En el IDE deberemos observar mensajes informando del estado del proceso, y de su finalizacién exitosa. 3. Finalmente, una vez acabada la carga, lo que deberia ocurrir es que el LED etiquetado como “L” empezara 2 parpadear de forma periédice, ya para © RC Libros 147 ARDUINO. CURSO PRACTICO DE FORMACION siempre. Si ocurre eso, ifelicidades!: nuestra placa funciona perfectamente y nuestro computador la puede programar sin problemas. MAS ALLA DEL LENGUAJE ARDUINO: EL LENGUAJE C/C++ A lo largo de los parrafos anteriores hemos repetido varias veces la palabra “compilacién’, pero no hemos exolicado su significado hasta ahora. “Compilar” significa convertir un cédigo escrito en el IDE (utilizando el lenguaje Arduino, y por tanto, entendible facilmente por los seres humanos} en el programa realmente ejecutable por el microcontrolador, que no es mas que un inmenso conjunto de bits (es decir, 1s y Os} tan solo entendible por él. Es decir, nosotros escribimos en el IDE las instrucciones usando el sencillo lenguaje de programacién Arduino y posteriormente, mediante la compilacién, transformamos ese sketch en instrucciones “digeribles” para el microcontrolador (en lo que viene a llamarse “codigo maquina” o “codigo binario”). Este cédigo maquina en esencia no es mas que un conjunto de Impulsos eléctricos (1s pase corriente— y Os -no pasa corriente-), que es lo Unico que realmente saben procesar los circuitos electrénicos. Asi pues, un cédigo maquina (ficticio) resultante de le compilacién de un sketch Arduino cualquiera podria ser similar a esto: 10010111010101011011... Es evidente que es imposible escribir un programa directamente en cédigo maquina: por eso existen los compiladores. Pero, ademas, estas herramientas ofrecen otra ventaja: hay que saber que el codigo maquina valido para un microcontrolador no lo es para otro, debido a su diferente construccién electronica interna. Por lo tanto, un mismo programa se tendria que codificar en diferentes c6digos maquina para diferentes modelos de microcontrolador. Sin embargo, si disponemos de compiladores especificos para cada uno de estos modelos, a partir de un mismo cédigo fuente podemos obtener diferentes codigos maquina utilizando en cada caso el compilador respectivo. Esto es una gran ventala, porque nos permite no reescribir codigo ya funcional ni cometer errores en nuestros desarrollos, ademas de aportar una gran flexibilidad y escalabilidad a nuestros sketches. Ya que las placas Arduino incorporan microcontroladores de arquitectura AVR (excepto la Due, que es ARM, pero no lo tendremos en cuenta), es Idgico pensar que el compilador incluido en el entorno de programacion oficial de Arduino es uno especifico para generar cédigo binario compatible con este tipo de chips. Y asies. Sin embargo, dicha herramienta (llamada “gcc-avr”) no compila cédigo escrito en lenguaje Arduino a cédigo binario AVR (concretamente, en formato “.hex”), sino que compila cédigo escrito en lenguaje C/C++ a cédigo binario AVR. éPor qué? 148 © RC Libros CAPITULO 3: SOFTWARE ARDUINO Porque realmente, el lenguaje Arduino no es un lenguaje en sentido estricto: es simplemente un conjunto de instrucciones C y C++ “camufladas”, disefiadas para simplificar el desarrollo de programas para microcontroladores AVR. Es decir, cuando estamos escribiendo nuestro sketch en “lenguaje Arduino”, sin saberlo en realidad estamos programando en una versién simplificada del lenguaje C/C++. Si se desea conocer en detalle todo el proceso interno de transformacién del sketch originalmente escrito en lenguaje Arduino a su versién en lenguaje C++ y su posterior compilacién por “gcc-avr", en http://code.google.com/p/arduino/wiki/BuildProcess se puede consultar la informacién necesaria. Ellenguaje Cy su “pariente” C++ son dos de los lenguajes m4s importantes y extendidos del mundo por varias razones: porque son lenguajes muy potentes y a la vez ligeros y flexibles, porque poseen un ecosistema amplisimo de librerias que los dotan de funcionalidad que otros lenguajes no ofrecen, porque los programas escritos y compilados en estos lenguajes son tremendamente eficientes y rapidos, y porque existen compiladores para practicamente cualquier tipo de hardware (con lo que hoy en dia podemos ver multitud de software escrito con estos lenguajes ejecutandose en una gran variedad de mdquinas). No obstante, tal vez para una persona que se inicia en el mundo de la programacién, los lenguajes C/C++ no son demasiado amigables. En otras palabras: son lenguajes relativamente dificiles de aprender y dominar. Por eso existe el lenguaje Arduino: para que una persona sin apenas conocimientos de desarrollo de aplicaciones pueda escribir rapidamente un sketch Arduino funcional sin tener que aprender todo un lenguaje de programacién completo pero complejo como es C 0 C++. Es decir: el lenguaje Arduino hace de “mascara” del lenguaje C/C++, ocultando gran centidad de detalles superfluos para el entusiasta de los proyectos electronicos y facilitando asi el uso de la plataforma Arduino en conjunto. El “precio” a pagar por ganar esta facilidad en la programacién de sketches es que tan solo tenemos un subconjunto de toda la funcionalidad que puede llegar a ofrecer el lenguaje C/C++. Afortunadamente, para la mayoria de proyectos no es necesario ir mas alld de lo que ya nos ofrece el lenguaje Arduino y su IDE oficial, y por supuesto, todos los ejemplos de este libro estén programados utilizando solo las funcionalidades que ofrece el lenguaie Arduino en exclusiva. IDEs ALTERNATIVOS AL OFICIAL Hey gente por todo el mundo ala que el IDE oficial de Arduino no le acaba de convencer, por varios motivos: la falta de funcionalidades avanzadas (como el © RC Libros 149 ARDUINO. CURSO PRACTICO DE FORMACION autocompletado de sentencias, por ejemplo) o la dependencia del lenguaje Java {hecho que implica tener instalado en nuestro computador mas paquetes de los realmente necesarios para poder compilar y cargar nuestros sketches) son algunos. Otra razén es que muchos programaderes ya estén familiarizados con un IDE concreto y quieren seguir utilizandolo para sus desarrollos con Arduino. La consecuencia de esto es que actualmente existe una variedad de IDEs “alternativos” que aportan més caracteristicas que el IDE original o simplemente que cambian la manera de trabajar. A continuacién, se nombran algunos de estos IDEs (ino es una lista exhaustiva!) por si el lector quiere buscar en ellos alguna caracteristica que el IDE oficial no tiene: CodeBlocks (http://www.codeblocks.org): es un IDE libre y multiplataforma para el desarrollo de aplicaciones escritas en lenguaje C y C++. No obstante, se pueden escribir programas directamente en lenguaje Arduino (y también cargarlos en la placa) mediante una versién modificada de este software, la llamada “CodeBlocks Arduino Edition”, descargable desde la direccién http://www.arduinodev.com/codeblocks. Gnoduino (http://gnome.eu.org): IDE libre que intenta imitar en aspecto y funcionalidd al oficial, pero que evita su dependencia de Java, ya que esté escrito en otro lenguaje, Python. Esto hace que sea especialmente ligero y rapido. No obstante, solo funciona en Linux, y mas especificamente dentro el escritorio GNOME debido a sus dependencias. Codebender (http:/Awww.codebender.cc): este IDE en realidad es una aplicacién web, por lo que funciona enteramente de forma “online” dentro del navegador, sin necesidad de instalar nada. Incluye un completo editor de textos, un compilador y un cargador de sketches, todo sin salir del navegador. Ademds, previo registro gratuito, permite almacenar “en la nube” el conjunto de cédigos realizados. Este proyecto es libre, por lo que uno se puede descargar ¢ instalar el software necesario para montar una plataforma Codebender propia Visualmicro (http://visualmicro.codeplex.com): en realidad se trata de un complemento (“plug-in”) para usar el lenguaje Arduino dentro del entorno de programacién Visual Studio (http://www.microsoft.com/visualstudio), de Microsoft. Desgraciadamente, no funciona en la version Express de este entorno (la gratuita), por lo que se ha de comprar alguna edicién superior, como por ejemplo la Professional. 150 © RC Libros CAPITULO 3: SOFTWARE ARDUINO EmbedXcode (http://embedxcode.weebly.com): en realidad se trata de un complemento (“plug-in”) del entorno de programacién oficial de Apple, llamado XCode (https://developer.apple.com/xcode). Permite trabajar con un IDE “todo en uno” mediante el cual se pueden programar de forma unificada diversas plataformas, como Arduino, chipKIT, Maple, MSP430 0 Wiring, (aunque cada una mediante su lenguaje de programacién propio). De todas formas, si no queremos utilizar ninguno de los entornos de desarrollo compatibles anteriores, atin tenemos la posibilidad de escribir cédigo Arduino con absolutamente cualquier otro IDE que queramos. Para ello, deberemos tener instalado tanto nuestro IDE favorito como el entorno oficial de Arduino, y seguir los pasos indicados a continuacién. De esta forma lograremos utilizar todas las funcionalidades para la edicién de cédigo que ofrezca IDE favorito y utilizar el entorno oficial solo para compilar y cargar. 1. Ejecutar el IDE Arduino y abrir el fichero “ino” que deseemos editar. 2. Ir al cuadro de preferencias del IDE y activar la opcién “Use external editor”. Automaticamente, el editor de cédigo aparecera en color gris, indicando que esté deshabilitado. 3. Ejecutar el IDE que deseemos, y abrir el mismo fichero “ino”. Realizar la edicién necesaria 4. Grabar los cambios en el editor utilizado. Es importante que el fichero “ino” grabado mantenga el mismo nombre que el fichero “ino” originalmente abierto en el IDE Arduino, porque si no este no se enterara. 5. Utilizar los botones de “Verify” y “Upload” del IDE Arduino de la forma habitual, cuando se considere oportuno. Por otro lado, conviene destacar también la existencia de un tipo de entornos de desarrollo para Arduino un tanto “especiales”, ya que estén enfocados a la programacién visual de sketches. Es decir: en vez de utilizar instrucciones escritas en un lenguaje abstracto, los cédigos se construyen a partir del “acoplamiento” grafico de diferentes bloques coloreados que representan acciones y estructuras de control. Su objetivo es facilitar a cualquier persona sin ninguna experiencia en programacion {por ejemplo, los nifios) la iniciacién en el mundo de los microcontroladores, matando de esta forma dos pdjaros de un tiro: la introduccién a la programacién y la introduccion a la electronica. Los mas destacables son: © RC Libros 151 ARDUINO. CURSO PRACTICO DE FORMACION Scratch for Arduino -S4A- (http://seaside citilab.eu/scratch/arduino): es un plug-in del entorno visual de programacion Scratch (http://scratch.mit.edu’ que permite usar este para programar e interactuar con placas Arduino. Modkit Micro (htto://www.modk.it): entorno de desarrollo visual muy similar a Scratch. Puede utilizarse en mas arquitecturas ademas de las placas Arduino, y tiene la particularidad de poder funcionar “online” dentro del navegador. También se puede descargar el entorno instalable, pero solo para Windows y MacOSX. Otra caracteristica es que si se desea, se puede trabajar con el cédigo interno mas alld de los bloques visuales, permitiendo una personalizacion mas directa de los sketches. Minibloq (http://blog.miniblog.org): igual que el anterior, es un entorno visual de programacién listo para ser usado en mas arquitecturas que Arduino solamente, pero solamente funciona en Windows. Ardublock {http://blog.erdublock.com): entorno de desarrollo visual pare Arduino programado en Java (y por tanto, multiplataforma). Destacar finalmente, aunque no sea un entorno de desarrollo propiamente dicho, la herramienta Ino (http://inotool.org). Se trata de un programa ejecutable directamente desde el intérprete de comandos que permite compilar y cargar sketches Arduino. Estos sketches, eso si, deben haber sido escritos y guardados previamente utilizando un editor de texto cualquiera. Incorpora ademés una opcién equivalente al “Serial monitor”. Sus detalles de configuracién (como por ejemplo el modelo de placa o el puerto serie a usar en cada momento) se pueden especificar como parémetros del comando o bien dentro de un archivo de configuracion especifico. Se recomienda consultar |a documentacién existente en su pagina web oficial para aprender su uso. Desgraciadamente, no funciona en sistemas Windows 152 © RC Libros LENGUAJE A MI PRIMER SKETCH ARDUINO Conecta la placa Arduino a tu computador y ejecuta el IDE oficial. Selecciona 10 lo esta ya) el tipo de placa adecuado (en el ment Tools->Board) y el puerto USB utilizado (en el meni Tools->Serial port). Ejemplo 4.1: Crea un nuevo sketch con el siguiente contenido. /*Declaracién e inicializacién de una variable global llamada *mivaziable’ */ int mivariable=§55 void setup() ( Serial.begin(9600) ; } void loop() { Serial print In(mivariable) ; mivariable-mivariable+i; Pulsa en el boton “Verify” y seguidamente en el botén “Upload”. No deberias de observar ningun error en la consola de mensajes. Abre ahora el “Serial monitor” y verds que alli van apareciendo en tiempo real muchos nimeros uno tras otro, empezando por el 555 y siguiendo por el 556, 557, 558, 559, etc., aumentando sin parar. ¢Por qué? éQué significa este texto (este codigo) que hemos introducido en la memoria del microcontrolador de la placa? ARDUINO. CURSO PRACTICO DE FORMACION ESTRUCTURA GENERAL DE UN SKETCH Un programa disefiado para ejecutarse sobre un Arduino (un “sketch”) siempre se compone de tres secciones: La seccién de declaraciones de variables globales: ubicada directamente al principio del sketch. La seccién llamada “void setup()”: delimitada por llaves de apertura y cierre. La seccién llamada “void loop()”: delimitada por llaves de apertura y cierre. La primera seccién del sketch (que no tiene ningun tipo de simbolo delimitador de inicio 0 de final) esté reservada para escribir, tal como su nombre indica, las diferentes declaraciones de variables que necesitemos. En un apartado posterior explicaremos ampliamente qué significa todo esto. En el interior de las otras dos secciones (es decir, dentro de sus llaves} deberemos escribir las instrucciones que deseemos ejecutar en nuestra placa, teniendo en cuenta lo siguiente: Las instrucciones escritas dentro de la seccién “void setup()” se ejecutan una Unica vez, en el momento de encender (0 resetear) la placa Arduino. Las instrucciones escritas dentro de la seccién “void loop()” se ejecutan justo después de las de la seccién “void setup()” infinitas veces hasta que la placa se apague (0 se resetee). Es decir, el contenido de “void loop()” se ejecuta desde [a 1? instruccién hasta la ditima, para seguidamente volver 2 ejecutarse desde la 12 instruccién hasta la dltima, para seguidamente ejecutarse desde la 12 instruccién hasta la ultima, y as/ una y otra vez. Por tanto, las instrucciones escritas en la seccién “void setup()” normaimente sirven para realizar ciertas preconfiguraciones iniciales y las instrucciones del interior de “void loop()” son, de hecho, el programa en si que estd funcionando continuamente. En el caso concreto del ejemplo 4.1, vemos que en la zona de declaraciones de variables globales hay una sola linea (int mivariable=555;) que dentro de “void setup()” se ejecuta una sola instruccion (Serial.begin(9600);) y que dentro de “void loop()” se realiza la ejecucién continua y repetida (hasta que la alimentacién de la placa se interrumpa) de dos instrucciones una tras otra: 154 © RC Libros CAPITULO 4: LENGUAIE ARDUINO Serial .print1n(mivariable); y mivariable-mivariable+1;. Sobre el significado y sintaxis de todas estas lineas hablaremos a continuacion. Sobre las mayusculas, tabulaciones y puntos y comas Conviene aclarar ya pequefios detalles que deberemos tener en cuenta a la hora de escribir nuestros sketches para evitarnos muchos dolores de cabeza. Por ejemplo, es necesario saber que el lenguaje Arduino es “case-sensitive”. Esto quiere decir que es totalmente diferente escribir una letra en mayuscula que en minuscula. Dicho de otra forma: para el lenguaje Arduino “HolA” y “hOLa” son dos palabras distintas. Esto tiene una implicacion muy importante: no es lo mismo escribir por ejemplo “Serial. begin(9600);” que “serial.begin(9600);”. En el primer caso la instruccién estaria correctamente escrita, pero en el segundo, en el momento de compilar el cédigo el IDE se quejaria porque para él “serial” (con “s” mindscula) no tiene ningun sentido. Asi que hay que vigilar mucho con respetar esta distincién en los codigos que escribamos. gn Otro detalle: las tabulaciones de las instrucciones contenidas dentro de las secciones “void setup()” y “void loop()” del sketch del ejemplo 4.1 no son en absoluto necesarias para que la compilacién del sketch se produzca con éxito. Simplemente son una manera de escribir el cédigo de forma ordenada, clara y cémoda para el programador, facilitandole la tarea de leer codigo ya escrito y mantener una cierta estructura a la hora de escribirlo. En los préximos ejemplos de este libro se ird viendo mejor su utilidad. Otro detalle: todas las instrucciones (incluyendo también las declaraciones de variables) acaban con un punto y coma. Es indispensable afiadir siempre este signo para no tener errores de compilacién, ya que el compilador necesita localizarlo para poder detectar el final de cada instruccién escrita en el sketch. Si se olvida, se mostraré un texto de error que puede ser obvio (“falta un punto y coma”) 0 no. Si el texto del error es muy oscuro o sin légica, es buena idea comprobar que la causa no sea la falta de un punto y coma en las lineas justamente anteriores a la marceda por el compilador como causante del problema. COMENTARIOS La primera linea del sketch del ejemplo 4.1 contiene un comentario {concretamente, son las dos primeras lineas: desde los simbolos /* hasta los simbolos */). Un “comentario” es un texto escrito intercalado con el cédigo del sketch que se © RC Libros 155 ARDUINO. CURSO PRACTICO DE FORMACION utiliza para informar sobre cémo funciona ese codigo a la persona que en algun momento lo esté leyendo. Es decir, los comentarios son texto de ayuda para los seres humanos que explica el cédigo asociado y ayudan a entenderlo y recordar su funcién Los comentarios son completamente ignorados y desechados por el compilador, por lo que no forman parte nunca del cédigo binario que ejecuta el microcontrolador (asi que no ocupan espacio en su memoria). Los comentarios pueden aparecer dentro del codigo de diferentes formas: Comentarios compuestos por una linea entera (o parte de ella): para afiadirlos deberemos escribir dos barras ( // ) al principio de cada linea que queramos convertir en comentario. También podemos comentar solamente una parte de la linea, si escribimos las barras en otro punto que no sea el principio de esta; de esta manera solamente estaremos comentando lo que aparece detrds de las barras hasta el final de la linea, pero lo anterior no. Comentarios compuestos por un bloque de varias lineas seguidas: pare afiadirlos deberemos escribir una barra seguida de un asterisco ( /* ) al principio del bloque de texto que queramos convertir en comentario, y un asterisco seguido de una barra ( */) al final de dicho bloque. Todos los caracteres y lineas ubicados entre estas dos marcas de inicio y final serén tratadas automaticamente como comentarios. Hay que tener en cuenta, por otro lado, que comentarios unilineales se pueden escribir dentro un comentario multilineal, pero uno multilineal dentro de otro no. Este es el tipo de comentario escrito en el sketch del ejemplo 4.1. Una practica bastante habitual en programacién es comentar en algun momento una (o mas) partes del cédigo. De esta forma, se “borran” esas partes (es decir, se ignoran, y por tanto, ni se compilan ni se ejecutan) sin borrarlas realmente Normalmente, esto se hace para localizar posibles errores en el cédigo observando el comportamiento del programa con esas determinadas lineas comentadas. A lo largo de los ejemplos de este libro se ird viendo su utilidad, VARIABLES La primera linea del sketch del ejemplo 4.1 consiste en declarar una variable global de tipo “int” llamada “mivariable”, e inicializarla con el valor de 555. “int Expliquemos todo esto. 156 © RC Libros CAPITULO 4: LENGUAIE ARDUINO Una variable es un elemento de nuestro sketch que acta como un pequeiio “cajoncito” (identificado por un nombre elegido por nosotros) que guarda un determinado contenido. Ese contenido (lo que se llama el valor de la variable) se podré modificar en cualquier momento de la ejecucién del sketch: de ehi el nombre de “variable”. La importancia de las variables es inmenso, ya que todos los sketches hacen uso de ellas para alojar los valores que necesitan para funcionar. El valor de una variable puede haberse obtenido de diversas maneras: puede haber sido asignado literalmente (como el del ejemplo 4.1, donde nada mas empezar asignamos explicitamente a la variable llamada “mivariable” el valor 555), pero también puede ser el dato obtenido por un sensor, 0 el resultado de un célculo, ete Provenga de donde provenga inicialmente, ese valor podré ser siempre cambiado en cualquier instante posterior de la ejecucién del sketch, si asi lo deseamos. Declaracién e inicializacién de una variable Antes de poder empezar a utilizar cualquier variable en nuestro sketch; no obstante, primero deberemos crearla. Al hecho de crear una variable se le suele llamar “declarar una variable”. En el lenguaje Arduino, cuando se declara una variable es imprescindible ademds especificar su tipo. El tipo de una variable lo elegiremos segtin el tipo de datos (nimeros enteros, nimeros decimales, cadena de caracteres, etc.) que queramos almacenar en esa variable. Es decir: cada variable puede guardar solamente valores de un determinado tipo, por lo que deberemos decidir en su declaracién qué tipo de variable es la que nos interesa mas segtin el tipo de datos que preveamos almacenar. Asignar un valor a una variable que sea de un tipo diferente al previsto para esta provoce un error del sketch. Los tipos posibles del lenguaje Arduino los detallaremos en los pérrafos siguientes, pero ya se puede saber que la sintaxis general de una declaracién es siempre una linea escrita asi: tipoVariable nombreVariable;. En el caso concreto de querer declarar varias variables del mismo tipo, en vez de escribir una declaracion por separado para cada una de ellas, es posible declararlas todas en una misma linea, genéricamente asi: tipoVariable nombreVariable1, nombreVariable2; Opcionalmente, a la vez que se declara la variable, se le puede establecer un valor inicial: a esto se le llama “inicializar una variable”. Inicializar una variable cuando se declara no es obligatorio, pero si muy recomendable. En el ejemplo 4.1, declaramos la variable llamada “mivariable” de tipo “int” (que es un tipo de dato de entre los varios existentes pensados para guardar numeros enteros) y ademés, también [a inicializamos con el valor inicial de 55S. De ahi ya se puede deducir que la sintaxis general de una inicializacién es siempre una linea escrita asi: tipoVarioble nombreVariable = valorinicialVariable;. © RC Libros 157

You might also like