Module 1Módulo 1

General AspectsAspectos Generales

Before we write code, we must understand the machine. From basic logic gates to complex architectures. Antes de escribir código, debemos comprender la máquina. Desde puertas lógicas básicas hasta arquitecturas complejas.

Santi Scagliusi, PhD

Digital Electronics ReviewRepaso de Electrónica Digital

The building blocks of everything we do.Los bloques fundamentales de todo lo que hacemos.

science The Magic of XORLa Magia del XOR

The Exclusive OR (XOR) is critical in assembly for toggling bits and comparing values.
Output is 1 only if inputs are different.
La OR Exclusiva (XOR) es fundamental en ensamblador para alternar bits y comparar valores.
La salida es 1 solo si las entradas son diferentes.

INTERACTIVE LABLABORATORIO INTERACTIVO
0 A 0 B XOR 0
TRUTH TABLETABLA DE VERDAD
Input AEntrada A Input BEntrada B Output (A^B)Salida (A^B)
000
011
101
110

lightbulb Remember BasesRecuerda las Bases

Embedded systems live in Hexadecimal.Los sistemas embebidos viven en Hexadecimal.

BinaryBinario
1010
Decimal
10
Hex
0xA

Real World SignalsSeñales del Mundo Real

In code, we see 0 and 1. In the real world, these are voltage levels. En código, vemos 0 y 1. En el mundo real, estos son niveles de tensión.

show_chart Voltage = LogicTensión = Lógica

Between HIGH and LOW lies the dangerous "Undefined Region" (Noise Margin). Entre ALTO y BAJO se encuentra la peligrosa "Región Indefinida" (Margen de Ruido).

  • VCC (3.3V): Logic 1 (High)Lógica 1 (Alto)
  • Undefined:Indefinido: Unpredictable behaviorComportamiento impredecible
  • VSS (0V): Logic 0 (Low/GND)Lógica 0 (Bajo/GND)
Logic 1 (>2.0V)Lógica 1 (>2.0V)
Noise Margin / UndefinedMargen de Ruido / Indefinido
Logic 0 (<0.8V)Lógica 0 (<0.8V)

What are Embedded Systems?¿Qué son los Sistemas Embebidos?

It is a computing system dedicated to a specific task within a larger system. Unlike a PC (General Purpose), an embedded system does one thing, and does it efficiently. Es un sistema de computación dedicado a una tarea específica dentro de un sistema mayor. A diferencia de un PC (Propósito General), un sistema embebido hace una sola cosa, y la hace eficientemente.

bolt Resource Constrained (Power, Memory)Recursos Limitados (Energía, Memoria)
timer Real-time RequirementsRequisitos de Tiempo Real
settings_input_component Direct Hardware InteractionInteracción Directa con el Hardware
local_laundry_service ControlControl Washing MachinesLavadoras
directions_car SafetySeguridad ABS / Airbags
router IoT Smart SensorsSensores Inteligentes
ecg_heart MedicalMédico PacemakersMarcapasos

Scales of IntegrationEscalas de Integración

From the first chips to microprocessors, microcontrollers and SoCs.Desde los primeros chips hasta microprocesadores, microcontroladores y SoCs.

1970s: The DawnAños 70: El Amanecer

Intel 4004 & TI TMS1000. The first "computers on a chip".Intel 4004 y TI TMS1000. Las primeras "computadoras en un chip".

1980s-90s: IntegrationAños 80-90: Integración

More peripherals (ADC, UART). 8-bit dominates (8051, PIC).Más periféricos (ADC, UART). Dominan los 8 bits (8051, PIC).

Now: Efficiency & PowerAhora: Eficiencia y Potencia

16/32-bit (MSP430, ARM). Low Power for battery devices.16/32 bits (MSP430, ARM). Bajo consumo para dispositivos con batería.

µP

MicroprocessorMicroprocesador

CPU only. Needs external RAM, Flash, I/O.Solo CPU. Necesita RAM, Flash, E/S externos.

x86, Ryzen
OUR FOCUSNUESTRO ENFOQUE
µC

MicrocontrollerMicrocontrolador

CPU + RAM + FRAM + Peripherals in one chip.CPU + RAM + FRAM + Periféricos en un solo chip.

MSP430, PIC
SoC

System on Chip

CPU + GPU + Radio + DSP. Extreme integration.CPU + GPU + Radio + DSP. Integración extrema.

M1, Snapdragon

Computer Building BlocksBloques de un Computador

Before comparing architectures, identify the four actors that appear in every diagram.Antes de comparar arquitecturas, identifiquemos los cuatro actores que aparecen en todos los diagramas.

CPU

Registers, ALU and control unit. The part that executes instructions.Registros, ALU y unidad de control. La parte que ejecuta instrucciones.

MemoryMemoria

Stores code and data. In many systems it becomes the main bottleneck.Almacena código y datos. En muchos sistemas se convierte en el principal cuello de botella.

I/OE/S

Peripherals that connect the processor with sensors, actuators and the outside world.Periféricos que conectan el procesador con sensores, actuadores y el mundo exterior.

BusesBuses

The shared roads that move addresses, data and control signals.Las carreteras compartidas que mueven direcciones, datos y señales de control.

Von Neumann vs HarvardVon Neumann vs Harvard

How does the CPU fetch data and instructions: through one shared path or through separate ones?¿Cómo obtiene la CPU datos e instrucciones: por un camino compartido o por caminos separados?

CPU
Unified BusBus Unificado
Unified MemoryMemoria Unificada
InstructionsInstrucciones
DataDatos

Von Neumann ArchitectureArquitectura Von Neumann

Used by MSP430. Simpler, flexible, but creates a "Bottleneck".Usada por el MSP430. Más simple, flexible, pero crea un "Cuello de Botella".

CPU
Instr BusBus Instr
Data BusBus Datos
Program MemMem Programa
Data MemMem Datos

Harvard ArchitectureArquitectura Harvard

Separate paths allow simultaneous access. Faster, but more complex.Caminos separados permiten acceso simultáneo. Más rápida, pero más compleja.

Single Bus, Arbitration & DMABus Único, Arbitraje y DMA

A shared bus simplifies hardware, but it also forces arbitration: only one transfer can occupy the road at a time.Un bus compartido simplifica el hardware, pero obliga a arbitrar: solo una transferencia puede ocupar la carretera a la vez.

BUS CPU MASTER Memory I/O
BUS CPU 💤 DMA MASTER Memory I/O

I/O → Memory directly. No CPU needed.E/S → Memoria directo. Sin CPU.

What the Bus Visual MeansQué Significa el Dibujo del Bus

The diagram matters because it changes who controls transfers, how many transactions are needed, and who has to wait.El diagrama importa porque cambia quién controla las transferencias, cuántas transacciones hacen falta y quién tiene que esperar.

Master-SlaveMaestro-Esclavo

The CPU is the bus master. Every peripheral access must go through it, so moving one I/O datum into memory can require several transactions.La CPU es el maestro del bus. Todo acceso a periféricos pasa por ella, así que mover un dato desde E/S a memoria puede requerir varias transacciones.

ArbitrationArbitraje

A single shared bus means contention. If code fetch, memory access and I/O all want it, someone has to wait.Un único bus compartido implica contención. Si la búsqueda de código, la memoria y la E/S lo quieren a la vez, alguien tiene que esperar.

DMA

Direct Memory Access lets a peripheral or DMA controller become the temporary master to move blocks without burning CPU cycles.El acceso directo a memoria permite que un periférico o el controlador DMA sea maestro temporal para mover bloques sin gastar ciclos de CPU.

RISC vs CISC

CISC

Complex Instruction Set Computer
  • check_box_outline_blank Many complex instructions (variable length).Muchas instrucciones complejas (longitud variable).
  • check_box_outline_blank Hardware is complex, Coding is "easier" (fewer lines).El hardware es complejo, programar es "más fácil" (menos líneas).
  • check_box_outline_blank Example: Intel x86.Ejemplo: Intel x86.
MSP430

RISC

Reduced Instruction Set Computer
  • check_box Few, simple instructions (fixed/predictable length).Pocas instrucciones simples (longitud fija/predecible).
  • check_box Hardware is simple/fast, Compiler does the heavy lifting.El hardware es simple/rápido, el compilador hace el trabajo pesado.
  • check_box MSP430 is RISC-like. Optimized for efficiency.MSP430 es tipo RISC. Optimizado para eficiencia.
Same task: add two parameters stored in memoryMisma tarea: sumar dos parámetros almacenados en memoria
CISC style — one complex instructionEstilo CISC — una instrucción compleja
ADD Parametro1, Parametro2
Reads from memory, performs the sum, and writes back as part of one rich instruction.Lee de memoria, realiza la suma y reescribe el resultado como parte de una sola instrucción rica.
RISC style — several simple instructionsEstilo RISC — varias instrucciones simples
MOV &Parametro1, R4 ; load first operand; cargar primer operando
MOV &Parametro2, R5 ; load second operand; cargar segundo operando
ADD R5, R4 ; ALU works on registers; la ALU trabaja sobre registros
MOV R4, &Parametro1 ; store result; guardar resultado
Pipeline Advantage in RISCVentaja del Pipeline en RISC

Simple, regular instructions are easier to overlap. Compare a dependency stall against a clean flow.Las instrucciones simples y regulares son más fáciles de solapar. Compara un atasco por dependencia frente a un flujo limpio.

IF = fetchbúsqueda · D = decodedecodificación · E = executeejecución · M = memorymemoria · WB = write backescritura

C1
C2
C3
C4
C5
C6
1 MOV [R1], R2
IF
D
E
M
WB
2 ADD R2, R3
IF
D
S
E
WB
3 SUB R6, R7
IF
D
E
WB

Instruction 2 depends on the value loaded by instruction 1, so the pipeline inserts a stall.La instrucción 2 depende del valor cargado por la instrucción 1, así que el pipeline inserta un bloqueo.

C1
C2
C3
C4
C5
C6
1 MOV [R1], R2
IF
D
E
M
WB
2 XOR R8, R8
IF
D
E
WB
3 ADD R6, R7
IF
D
E
WB

When instructions are simple and independent, fetch, decode and execute can overlap almost like an assembly line.Cuando las instrucciones son simples e independientes, búsqueda, decodificación y ejecución pueden solaparse casi como una cadena de montaje.

Programming LanguagesLenguajes de Programación

How does code become machine instructions?¿Cómo se convierte el código en instrucciones de máquina?

InterpreterIntérprete

Python, JavaScript
line 1 line 2 line 3 EXEC One at a timeUna a una Translates each line, then runs it.Traduce cada línea y la ejecuta. Slower, but instant feedback.Más lento, pero feedback instantáneo.
C for MSP430C para MSP430

CompilerCompilador

C, C++, Rust
.c src code ... COMPILE + optimize .exe 01101 11010 All at onceTodo de golpe Translates everything, then runs native.Traduce todo, luego ejecuta nativo. Fast execution. ⚡Ejecución rápida. ⚡
HYBRIDHÍBRIDO

Mixed LanguagesLenguajes Mixtos

Java is the classic example: part compile stage, part virtual-machine execution.Java es el ejemplo clásico: parte de compilación y parte de ejecución sobre máquina virtual.

.java SourceFuente CompileCompilar → Bytecode JVM InterpretInterpretar Machine CodeCódigo Máquina 01101110...

"Write once, run anywhere.""Escribir una vez, ejecutar en cualquier lugar."

Operating SystemsSistemas Operativos

Managing resources so multiple programs can coexist.Gestión de recursos para que múltiples programas coexistan.

Without OSSin SO
Your ProgramTu Programa manages EVERYTHINGgestiona TODO 🖥️ 💾 ⌨️ ← This course!← ¡Este curso!
With OSCon SO
App A App B App C OS 🖥️ 💾 ⌨️
SchedulingPlanificación

Chooses which task gets CPU time and when a context switch must happen.Decide qué tarea usa la CPU y cuándo debe ocurrir un cambio de contexto.

MemoryMemoria

Allocates and protects memory regions so programs can coexist safely.Asigna y protege regiones de memoria para que varios programas puedan coexistir con seguridad.

StorageAlmacenamiento

Abstracts disks or files so applications do not talk to raw storage directly.Abstrae discos o ficheros para que las aplicaciones no hablen directamente con el almacenamiento físico.

DevicesDispositivos

Provides drivers and standard interfaces for screens, keyboards, network cards and sensors.Proporciona drivers e interfaces estándar para pantallas, teclados, tarjetas de red y sensores.

Multitasking ModelsModelos de Multitarea

Different systems share CPU time in very different ways, and RTOS is not the same as multicore parallelism.Los sistemas comparten tiempo de CPU de formas muy distintas, y un RTOS no es lo mismo que el paralelismo multinúcleo.

A B C A decides when to yieldA decide cuándo ceder

Each task voluntarily yields. If A hangs → everything freezes.Cada tarea cede voluntariamente. Si A se cuelga → todo se congela.

Windows 3.1, Classic Mac OS

A OS B OS C OS A OS ⏱ timer interrupts

OS forces context switches. No task can monopolize CPU.El SO fuerza cambios de contexto. Ninguna tarea monopoliza la CPU.

Windows 95+, Linux, macOS

CORE 0 CORE 1 Task A Task B Task C Task D

Here there is actual simultaneity: different tasks are running at the same time on different cores.Aquí sí hay simultaneidad real: distintas tareas se están ejecutando al mismo tiempo en núcleos diferentes.

Typical in multicore CPUs and modern SoCsTípico en CPUs multinúcleo y SoCs modernos

B ⚡ IRQ CRITICALCRÍTICO B A A

Guaranteed bounded response time. What matters is not only multitasking, but deterministic latency.Tiempo de respuesta garantizado y acotado. Lo importante no es solo la multitarea, sino la latencia determinista.

FreeRTOS, VxWorks, QNX

Why the MSP430?¿Por qué el MSP430?

Why did we choose this specific chip for the course?¿Por qué elegimos este chip específico para el curso?

16-bit

The Goldilocks ZoneEl Punto Justo

8-bit is too limiting. 32-bit is complex. 16-bit is perfect for learning: clean architecture, powerful enough for math, simple enough to understand every bit. 8 bits es muy limitado. 32 bits es complejo. 16 bits es perfecto para aprender: arquitectura limpia, suficientemente potente para cálculos, suficientemente simple para entender cada bit.

battery_charging_full

Ultra Low PowerUltra Bajo Consumo

Designed to run on batteries for years. It has sophisticated Low Power Modes (LPM) that we will master. Diseñado para funcionar con baterías durante años. Tiene sofisticados Modos de Bajo Consumo (LPM) que dominaremos.

settings_remote

Modern PeripheralsPeriféricos Modernos

It's not just a CPU. It includes Timers, ADCs, and Communication modules on-chip. Real-world capabilities. No es solo una CPU. Incluye Timers, ADCs y módulos de comunicación en el chip. Capacidades del mundo real.