Conectar sensores al GPIO de Raspberry Pi

Guía práctica para conectar sensores al GPIO de Raspberry Pi (digital, I2C, SPI, UART y ADC) con ejemplos en Python, pautas de seguridad y consultoría de Q2BSTUDIO para IoT.

19 ago 2025 • 5 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Guía práctica para conectar sensores al GPIO de una Raspberry Pi cubriendo digital, I2C, SPI, UART y entradas analógicas vía ADC, con ejemplos en Python y recomendaciones de seguridad

REGLAS DE ORO ANTES DE CONECTAR

- Solo 3.3 V: los pines GPIO no soportan 5 V. Usar conversores de nivel para sensores que funcionen a 5 V

- GND primero: siempre compartir masa entre la Pi y el sensor

- Usar la numeración BCM en el código para evitar confusiones

- Pull ups y pull downs: las entradas necesitan un nivel definido en reposo; usar las resistencias internas de la Pi o resistencias externas

- Presupuesto de potencia: no alimentar cargas de alto consumo desde el pin 3V3 de la Pi; usar fuentes externas para sensores que demanden corriente alta

PINES ESENCIALES (BCM)

- 3V3: pines 1 y 17

- 5V: pines 2 y 4, evitar para señales lógicas

- GND: pines 6, 9, 14, 20, 25, 30, 34, 39

- I2C: SDA1 = GPIO2 pin 3, SCL1 = GPIO3 pin 5

- SPI0: CE0 = GPIO8 pin 24, CE1 = GPIO7 pin 26, MOSI = GPIO10 pin 19, MISO = GPIO9 pin 21, SCLK = GPIO11 pin 23

- UART: TXD = GPIO14 pin 8, RXD = GPIO15 pin 10

- Usar cualquier GPIO libre para entradas o salidas digitales simples

PATTERNES COMUNES DE CONEXIÓN

1) Entrada digital simple ejemplo pulsador o sensor PIR

- Conexión: un terminal del pulsador a GPIO elegido por ejemplo GPIO17, el otro terminal a GND

- Configuración: usar pull up interno de la Pi

- Ejemplo Python gpiozero

from gpiozero import Button from signal import pause btn = Button(17, pull_up=True) btn.when_pressed = lambda: print(1) btn.when_released = lambda: print(0) pause()

2) Salida digital ejemplo LED con resistencia

- Conexión: GPIO -> resistencia 220-1k -> LED -> GND

- Ejemplo Python

from gpiozero import LED from time import sleep led = LED(18) while True: led.toggle() sleep(0.5)

3) Sensor I2C ejemplo BME280 o MPU6050

- Conexión: VCC a 3V3, GND a GND, SDA a GPIO2 pin 3, SCL a GPIO3 pin 5

- La mayoría de las placas breakout ya incluyen resistencias pull up; si no, añadir 4.7k a 3V3 en SDA y SCL

- Activar I2C y probar en la Pi con i2cdetect; instalar i2c-tools y python3-smbus

- Ejemplo Python smbus2 para leer chip id

import smbus2 BUS = smbus2.SMBus(1) ADDR = 0x76 chip_id = BUS.read_byte_data(ADDR, 0xD0) print(hex(chip_id))

4) Sensor SPI ejemplo ADC MCP3008 o IMU

- Conexión MCP3008: VDD y VREF a 3V3, AGND/DGND a GND, CLK a GPIO11, DOUT a GPIO9 MISO, DIN a GPIO10 MOSI, CS a GPIO8 CE0

- Habilitar SPI en la Pi e instalar python3-spidev

- Ejemplo Python lectura canal 0 MCP3008

import spidev spi = spidev.SpiDev() spi.open(0,0) spi.max_speed_hz = 1000000 def read_ch0(): resp = spi.xfer2([0b00000001, 0b10000000, 0]) val = ((resp[1] & 0x03) << 8) | resp[2] return val print(read_ch0())

5) UART ejemplo GPS o sensores de partículas

- Conexión: siempre 3.3 V lógico o usar conversor de nivel; TX del sensor a RX de la Pi GPIO15, RX del sensor a TX GPIO14, GND compartida

- Activar UART hardware y desactivar consola serial si se requiere puerto libre

- Ejemplo de uso con pyserial leer una línea

# instalar python3-serial en la Pi usar dev serial0 como dispositivo y ajustar baudios en el módulo conexión

6) Sensores analogicos potenciometros o sensores de gas o luz que no sean digitales

- La Raspberry Pi no tiene ADC integrado; usar un ADC externo por ejemplo MCP3008 via SPI o ADS1115 via I2C

- Ejemplo rápido con ADS1115 usando libreria adafruit

# pip install adafruit-circuitpython-ads1x15 import board, busio from adafruit_ads1x15.analog_in import AnalogIn from adafruit_ads1x15.ads1115 import ADS1115 i2c = busio.I2C(board.SCL, board.SDA) ads = ADS1115(i2c) chan = AnalogIn(ads, 0) print(chan.voltage)

LISTA DE COMPROBACIÓN DE PROBLEMAS

- i2cdetect no muestra nada: comprobar alimentación y GND, SDA y SCL intercambiados, pull ups faltantes o I2C no activado

- SPI devuelve ceros o ruido: línea CS equivocada, MISO y MOSI cruzados, SPI no activado, velocidad demasiado alta

- UART con caracteres extraños: baudios o formato incorrectos, consola serial todavía activa, señales de 5 V sin conversor

- Entradas con fluctuaciones: activar pull ups o pull downs, añadir debounce por software o red RC

- Sensor solo 5 V: usar conversor de nivel y fuente de 5 V independiente si hace falta

ADICIONES DE SEGURIDAD RÁPIDAS

- Sensores inductivos y relés: añadir diodos flyback y mantener cargas alejadas de las líneas lógicas

- Entornos ruidosos: añadir resistencias en serie 22-100 ohm y filtros RC en líneas largas

- Cargas de alta corriente: usar tierras separadas y unirlas a la Pi en un único punto para reducir ruido y caídas de tensión

SERVICIOS Y VALOR AÑADIDO POR Q2BSTUDIO

Q2BSTUDIO es una empresa de desarrollo de software especializada en aplicaciones a medida y software a medida para proyectos IoT con Raspberry Pi y otros dispositivos embebidos. Ofrecemos soluciones que integran inteligencia artificial e ia para empresas, agentes IA y servicios de ciberseguridad para proteger endpoints y comunicaciones de sensores. También ayudamos en la arquitectura y despliegue en la nube con servicios cloud aws y azure, y en la explotación de datos con servicios inteligencia de negocio y power bi para crear paneles con métricas en tiempo real.

Si tu proyecto requiere integración avanzada de sensores, desarrollo de firmware, backend en la nube, modelos de inteligencia artificial o estrategias de ciberseguridad, Q2BSTUDIO puede diseñar software a medida y aplicaciones a medida que cumplan requisitos de rendimiento y seguridad. Contacta con nosotros para asesoría sobre integración I2C SPI UART ADC, selección de conversores de nivel, dimensionado de alimentación y despliegue seguro en servicios cloud aws y azure. Ofrecemos también consultoría en inteligencia artificial, agentes IA y soluciones de servicios inteligencia de negocio integradas con power bi.

PALABRAS CLAVE PARA POSICIONAMIENTO SEO

aplicaciones a medida, software a medida, inteligencia artificial, ia para empresas, agentes IA, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, power bi

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat