Skip to content

Instantly share code, notes, and snippets.

@Jahziel43
Created October 25, 2025 21:59
Show Gist options
  • Select an option

  • Save Jahziel43/52c5d7c12e1d993733eb59e8451f958d to your computer and use it in GitHub Desktop.

Select an option

Save Jahziel43/52c5d7c12e1d993733eb59e8451f958d to your computer and use it in GitHub Desktop.

Nombre: Jahziel Amado López Angulo
Número de Control: 22211593
Correo electrónico: l22211593@tectijuana.edu.mx
GitHub: Jahziel43


💻 Práctica 6-1 para Microbit

Lectura del puerto serial del micro:bit y visualización del dato de sonido en terminal.


🧩 Parte 1 — Python 🐍

import serial
import json
import time

# === Configuración del puerto serial del micro:bit ===
PORT = "COM8"      # Cambia si tu micro:bit usa otro puerto
BAUD = 115200

print("Esperando datos del micro:bit...\n")

with serial.Serial(PORT, BAUD, timeout=2) as s:
    while True:
        line = s.readline().decode(errors='ignore').strip()
        if line.startswith("{") and line.endswith("}"):
            try:
                data = json.loads(line)
                sound = data.get("sound_lvl")
                print(f"Nivel de sonido: {sound}")
            except Exception as e:
                print("⚠️ Error al procesar JSON:", e)
        time.sleep(1)

💠 Parte 2 — C# 💬

using System;
using System.IO.Ports;
using System.Text.Json;
using System.Threading;

class Program
{
    static void Main()
    {
        string portName = "COM8";
        int baudRate = 115200;

        SerialPort port = new SerialPort(portName, baudRate);
        port.Open();
        Console.WriteLine("Esperando datos del micro:bit...\n");

        while (true)
        {
            try
            {
                string line = port.ReadLine().Trim();
                if (line.StartsWith("{") && line.EndsWith("}"))
                {
                    using (JsonDocument doc = JsonDocument.Parse(line))
                    {
                        if (doc.RootElement.TryGetProperty("sound_lvl", out JsonElement sound))
                        {
                            Console.WriteLine($"Nivel de sonido: {sound}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"⚠️ Error: {ex.Message}");
            }
            Thread.Sleep(1000);
        }
    }
}

🧱 Parte 3 — Java ☕

import com.fazecast.jSerialComm.SerialPort;
import java.io.InputStream;
import java.util.Scanner;
import org.json.JSONObject;

public class MicrobitReader {
    public static void main(String[] args) {
        SerialPort port = SerialPort.getCommPort("COM8");
        port.setBaudRate(115200);
        port.openPort();

        System.out.println("Esperando datos del micro:bit...\n");
        InputStream in = port.getInputStream();
        Scanner scanner = new Scanner(in);

        while (scanner.hasNextLine()) {
            try {
                String line = scanner.nextLine().trim();
                if (line.startsWith("{") && line.endsWith("}")) {
                    JSONObject data = new JSONObject(line);
                    int sound = data.getInt("sound_lvl");
                    System.out.println("Nivel de sonido: " + sound);
                }
            } catch (Exception e) {
                System.out.println("⚠️ Error: " + e.getMessage());
            }
        }
        port.closePort();
    }
}

⚙️ Parte 4 — JavaScript (Node.js) 🟨

const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');

const port = new SerialPort.SerialPort({ path: 'COM8', baudRate: 115200 });
const parser = port.pipe(new Readline());

console.log("Esperando datos del micro:bit...\n");

parser.on('data', (line) => {
  line = line.trim();
  if (line.startsWith("{") && line.endsWith("}")) {
    try {
      const data = JSON.parse(line);
      console.log(`Nivel de sonido: ${data.sound_lvl}`);
    } catch (err) {
      console.log("⚠️ Error al procesar JSON:", err.message);
    }
  }
});

💾 Parte 5 — C++ 🧠

#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include "json.hpp" // Biblioteca nlohmann/json

using json = nlohmann::json;

int main() {
    HANDLE hSerial;
    hSerial = CreateFile(L"\\\\.\\COM8", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if (hSerial == INVALID_HANDLE_VALUE) {
        std::cerr << "No se pudo abrir el puerto serial.\n";
        return 1;
    }

    std::cout << "Esperando datos del micro:bit...\n\n";
    char buffer[256];
    DWORD bytesRead;

    while (true) {
        ReadFile(hSerial, buffer, sizeof(buffer) - 1, &bytesRead, NULL);
        if (bytesRead > 0) {
            buffer[bytesRead] = '\0';
            std::string line(buffer);
            if (line.front() == '{' && line.back() == '}') {
                try {
                    json data = json::parse(line);
                    std::cout << "Nivel de sonido: " << data["sound_lvl"] << std::endl;
                } catch (...) {
                    std::cout << "⚠️ Error al procesar JSON.\n";
                }
            }
        }
        Sleep(1000);
    }

    CloseHandle(hSerial);
    return 0;
}

🧮 Parte 6 — Go (Golang) 🦫

package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"go.bug.st/serial"
	"strings"
	"time"
)

type Data struct {
	SoundLvl int `json:"sound_lvl"`
}

func main() {
	mode := &serial.Mode{BaudRate: 115200}
	port, err := serial.Open("COM8", mode)
	if err != nil {
		fmt.Println("Error al abrir el puerto:", err)
		return
	}
	defer port.Close()

	fmt.Println("Esperando datos del micro:bit...\n")

	scanner := bufio.NewScanner(port)
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if strings.HasPrefix(line, "{") && strings.HasSuffix(line, "}") {
			var data Data
			if err := json.Unmarshal([]byte(line), &data); err == nil {
				fmt.Printf("Nivel de sonido: %d\n", data.SoundLvl)
			} else {
				fmt.Println("⚠️ Error al procesar JSON:", err)
			}
		}
		time.Sleep(time.Second)
	}
}
@Jahziel43
Copy link
Author

@IoTeacher
Hola profesor, aquí se encuentra mi documentación de la práctica 6-1 para Microbit , no me di cuenta cuando puso la asignación en iDoceo, cuando me di cuenta ya era fuera de fecha, y no pude entregarla, iDoceo no manda notificaciones ni nada, asi que no puedo saber si pone la asignación, espero que acepte mi trabajo por favor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment