Ejemplo modificado con ST TOF VL53L4CD

Guía práctica para configurar y usar el VL53L4CD TOF con STM32Cube X-CUBE-TOF1: pasos, código de ejemplo y lectura continua de distancias.

23 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

El VL53L4CD es un sensor TOF Time of Flight capaz de medir distancias desde 1 mm hasta 1200 mm. El datasheet no aporta información detallada de registros, pero ST ofrece una API con documentación limitada y un paquete para STM32Cube llamado X-CUBE-TOF1. Este artículo presenta un ejemplo sencillo y concreto para una placa específica, basado en ese paquete pero evitando capas de abstracción innecesarias.

Pasos para configurar el proyecto: habilitar I2C1; activar X-CUBE-TOF1 en Middleware y Software; seleccionar Board Part Ranging y elegir VL53L4CD; configurar el uso de I2C1 y el pin XShut. El asistente genera un archivo custom_tof_conf.h con defines útiles como #define USE_CUSTOM_RANGING_VL53L4CD 1U, #define CUSTOM_VL53L4CD_XSHUT_PORT GPIOA, #define CUSTOM_VL53L4CD_XSHUT_PIN GPIO_PIN_1, #define CUSTOM_VL53L4CD_I2C_INIT BSP_I2C1_Init, #define CUSTOM_VL53L4CD_I2C_DEINIT BSP_I2C1_DeInit, #define CUSTOM_VL53L4CD_I2C_WRITEREG BSP_I2C1_Send y #define CUSTOM_VL53L4CD_I2C_READREG BSP_I2C1_Recv.

He creado dos archivos muy simples para usar la API: tof.c y tof.h. La lógica principal es: inicializar el dispositivo comprobando la conectividad I2C y leer capacidades; configurar el dispositivo seleccionando perfil de medida continuo; obtener la distancia en bucle y mostrar resultados. En el ejemplo el pin XShut se conecta a VCC 3.3 V para mantener el sensor habilitado, porque la API realiza el toggle automáticamente. Si se usan múltiples sensores en el mismo bus I2C, es necesario manejar la habilitación y deshabilitación vía CUSTOM_VL53L4CD_XSHUT_PORT y CUSTOM_VL53L4CD_XSHUT_PIN antes de cada llamada API o añadir esa lógica en tof.c.

Resumen de funciones implementadas: TOF_Init registra las funciones de I O del bus, lee el identificador del dispositivo, inicializa el sensor y recupera sus capacidades. TOF_Configure setea un perfil de ranging continuo con TimingBudget 30 ms, habilita lectura de señal y ambiente y arranca el modo de medida continua bloqueante. TOF_GetDistance llama a la API para obtener resultados por zonas y, en el ejemplo, imprime por consola el número de objetivos, estado, distancia en mm y valores de señal y ambiente por zona.

Ejemplo de uso en main: llamar a TOF_Init, comprobar retorno, luego TOF_Configure y en el bucle principal llamar TOF_GetDistance con un retardo entre lecturas. Ejemplo de salida por defecto del ejemplo: Targets = 1 |---> Status = 0, Distance = 110 mm, Ambient = 0.00 kcps/spad, Signal = 112.00 kcps/spad Targets = 1 |---> Status = 0, Distance = 112 mm, Ambient = 0.00 kcps/spad, Signal = 113.00 kcps/spad. El formato de impresión se puede adaptar o desactivar según necesidades.

Si buscas integración a medida, Q2BSTUDIO es una empresa de desarrollo de software y aplicaciones a medida especializada en soluciones completas: software a medida, aplicaciones a medida, inteligencia artificial aplicada a procesos empresariales, ciberseguridad, servicios cloud aws y azure, servicios de inteligencia de negocio y dashboards con power bi. Ofrecemos desde consultoría hasta desarrollo e integración de sensores y sistemas embebidos con plataformas cloud y modelos de IA. Conecta tus proyectos hardware con servicios en la nube y soluciones de analítica con nuestra experiencia en software a medida y desarrollo de aplicaciones y en inteligencia artificial para empresas.

Nuestros servicios incluyen diseño de agentes IA para automatizar tareas, IA para empresas, implementaciones seguras y evaluaciones de ciberseguridad, así como integración con servicios cloud AWS y Azure y soluciones de Business Intelligence y Power BI para explotar los datos de tus sensores y procesos. Si necesitas un ejemplo adaptado de integración del VL53L4CD o soporte para montar una cadena de telemetría, análisis y visualización, en Q2BSTUDIO podemos desarrollar la solución completa a medida.

Contacto y siguientes pasos: podemos adaptar el ejemplo presentado para manejar varios sensores en el mismo bus, añadir control de alimentación por XShut, optimizar perfiles de medida según escenarios y enviar las medidas a la nube para procesamiento en tiempo real o análisis batch. Incluimos servicios de ciberseguridad y pentesting para asegurar la solución end to end y capacidades de reporting con Power BI y servicios de inteligencia de negocio.

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