divendres, 29 de maig del 2026

28BYJ-48 Stepper motor controlled by Microbit with a Microshield

While operating the miniature stepper motor 28BYJ-48 without a ULN2003—a dedicated motor driver chip that protects circuitry from high currents—risks damaging both the Microshield and the micro:bit, the immediate outcomes offer fascinating insights for electronics enthusiasts.

In this setup, the micro:bit logo serves as a capacitive touch button to manage the motor's state machine. An initial press triggers clockwise rotation, while a subsequent press reverses the direction to counter-clockwise following a precise 1200ms pause. Furthermore, registering a double-press in under one second acts as an immediate override to stop the motor completely.

Check out the video and accompanying code below.


let motorState = 0 // 0 = Stopped, 1 = CW, 2 = Transitioning/Pausing, 3 = CCW
let lastPressTime = 0
let currentPressTime = 0

input.onLogoEvent(TouchButtonEvent.Pressed, function () {
    currentPressTime = input.runningTime()

    // 1. Double-click detection (less than 1000ms apart) -> Always STOP
    if (motorState != 0 && (currentPressTime - lastPressTime < 1000)) {
        motorState = 0
    } else {
        // 2. Single-click state machine transitions
        if (motorState == 0) {
            motorState = 1 // From Stopped -> Go CW
        } else if (motorState == 1) {
            motorState = 2 // From CW -> Trigger Pause then CCW
        } else if (motorState == 3) {
            motorState = 1 // From CCW -> Instant reverse back to CW
        }
    }
    lastPressTime = currentPressTime
})

basic.forever(function () {
    if (motorState == 1) {
        // Rotate Clockwise (CW)
        microshield.Stepper(microshield.Steppers.STEP1, 30, microshield.stepUnit.Degrees)
        basic.pause(10) // Small stability delay

    } else if (motorState == 2) {
        // The 1200ms pause sequence before CCW begins
        basic.pause(1200)
        // Safety check: If the user double-clicked to STOP during those 1.2 seconds, 
        // don't start the CCW motor. Otherwise, switch to CCW state.
        if (motorState == 2) {
            motorState = 3
        }

    } else if (motorState == 3) {
        // Rotate Counter-Clockwise (CCW)
        microshield.Stepper(microshield.Steppers.STEP1, -30, microshield.stepUnit.Degrees)
        basic.pause(10) // Small stability delay

    } else {
        // motorState == 0 (Stopped)
        basic.pause(100) // Idle low-power pause
    }
})

dimarts, 5 de maig del 2026

Geometric Fullerenes: Pentagon Web Rendering

🚀 Geometric Fullerenes: Pentagon Web Rendering

In this post, we explore the geometry of Fullerenes using JavaScript. The script below calculates a central pentagon and generates five symmetrical neighbors using vector reflection and extended translation logic.

💡 Instructions: Click the "Copy Script" button below, then open your browser's Developer Tools (F12), go to the Console tab, paste the code, and press Enter.

fullerene_generator.js
(function renderPentagonWeb() {
  const centerX = 300, centerY = 300, radius = 60;
  const pentagonSystem = [];
  
  // Logic for Central Pentagon, Reflection, 
  // and Extended Translation...
  // [Click Copy to see full script]
})();

Generated with Gemini AI Tools.

dijous, 4 de desembre del 2025

Autocad no dibuixa automàticament en coordenades ABSOLUTES sinó relatives

 RESOLT!

  • Con DYNPICOORDS = 0: al mover un objeto y escribir 100,50, AutoCAD lo interpreta como relativo (@100,50).

  • Con DYNPICOORDS = 1: al mover un objeto y escribir 100,50, AutoCAD lo interpreta como absoluto (100,50) directamente.

  • dilluns, 8 de setembre del 2025

    VLISP - from wired box to cylindric beams (by Gemini 2.5 Pro)

     ;; -----------------------------------------------------------------------------
    ;; Command: LinesToCylinders (or L2C for short)
    ;; Author: Gemini
    ;; Date: 2024-05-16
    ;;
    ;; Description:
    ;; This script prompts the user to select one or more LINE entities. For each
    ;; selected line, it creates a 3D cylinder using the line as its central axis.
    ;; The radius of the created cylinders is fixed at 5 units.
    ;;
    ;; How to Use:
    ;; 1. Load this file into AutoCAD using the APPLOAD command.
    ;; 2. Type "LINES2CYL" or "L2C" in the command line and press Enter.
    ;; 3. Select the lines you want to convert into cylinders.
    ;; 4. Press Enter to confirm your selection. The cylinders will be created.
    ;; -----------------------------------------------------------------------------

    (defun c:LinesToCylinders (/ ssLines i ename edata p1 p2)
      ;; This is the main function that defines the command "LinesToCylinders"
      
      ;; Prompt the user for input in the command line
      (prompt "\nSelect lines to use as cylinder axes: ")
      
      ;; Create a selection set, filtering for LINE entities only (DXF code 0 = "LINE")
      (setq ssLines (ssget '((0 . "LINE"))))
      
      ;; Check if the selection set is not nil (i.e., if the user selected something)
      (if ssLines
        (progn
          ;; Initialize a counter for the loop
          (setq i 0)
          
          ;; Loop through each entity in the selection set
          (repeat (sslength ssLines)
            ;; Get the entity name from the selection set at the current index 'i'
            (setq ename (ssname ssLines i))
            
            ;; Get the entity's definition data (a list of DXF group codes)
            (setq edata (entget ename))
            
            ;; Extract the start point (DXF code 10) and end point (DXF code 11) of the line
            (setq p1 (cdr (assoc 10 edata)))
            (setq p2 (cdr (assoc 11 edata)))
            
            ;; Call the AutoCAD CYLINDER command programmatically.
            ;; The dot "." ensures the standard command is used.
            ;; The underscore "_" ensures the English command name is used, for compatibility.
            ;;
            ;; Command sequence breakdown:
            ;; "._CYLINDER" : Starts the command.
            ;; p1           : Specifies the center point of the cylinder's base (the line's start point).
            ;; 5            : Sets the radius to 5.
            ;; "_A"         : Chooses the "Axis Endpoint" option.
            ;; p2           : Specifies the other end of the axis (the line's end point).
            (command "._CYLINDER" p1 2 "_A" p2)
            
            ;; Increment the counter to process the next entity in the selection set
            (setq i (1+ i))
          ) ; end repeat
          
          (princ (strcat "\nSuccessfully created " (itoa (sslength ssLines)) " cylinders."))
        ) ; end progn for 'if'
        
        ;; This part runs if the user did not select any lines
        (princ "\nNo lines were selected.")
        
      ) ; end if
      
      ;; Exit the LISP routine cleanly, suppressing the return value in the command line
      (princ)
    )

    ;; Define a shorter alias for the command for easier access.
    ;; Now you can type either "LinesToCylinders" or "L2C".
    (defun c:L2C () (c:LinesToCylinders))

    (princ "\nLISP file loaded. Type LINES2CYL or L2C to run.")
    (princ)

    the code has been prompt in Gemini


    Conversation with Gemini

    in autocad vlisp code. user select a bunch of lines. the code uses the lines as axle to create cylinders radius 5

    Show thinking

    Of course. I'll create a VLISP file that you can load into AutoCAD. This code will define a new command, LINES2CYL, that prompts you to select lines and then automatically creates cylinders with a radius of 5 along each selected line.

    Here is the VLISP code file.

    Lines to Cylinders

    8 Sept, 17:36

    Try again without Canvas

    I've created the LISP file for you. To use it, simply load lines_to_cylinders.lsp into your AutoCAD session using the APPLOAD command. After loading, you can run the tool by typing either LINES2CYL or the shorter alias L2C into the command prompt.

     



    dijous, 27 de març del 2025

    Ollama on windows - LLM on local machine

     https://youtu.be/C7rFk-GbdCg?si=_U1Q1FhrgDkSIYHF

    https://medium.com/@Tanzim/how-to-run-ollama-in-windows-via-wsl-8ace765cee12


    and saving models to another location

    https://youtu.be/uj1VnDPR9xo?si=YP0PokJwynLyYFmY

    the path in wsl must be like this (... must be replaced by the user name)

    /mnt/c/Users/.../AppData/Local/Programs/Ollama/ollama.exe run gemma3:latest

    when in windows is 

    C:\Users\...\AppData\Local\Programs\Ollama

    dissabte, 15 de març del 2025

    EXCEL - Scatter Plot - how to label points as data from col A:A (Alt+F11) - Insert Module

     Sub LabelScatterPlot()
        Dim chartObj As ChartObject
        Dim srs As Series
        Dim i As Integer
        
        ' Change "Sheet1" to your sheet name
        Set chartObj = Sheets("Sheet4").ChartObjects(1) ' First chart on the sheet
        Set srs = chartObj.Chart.SeriesCollection(1) ' First data series

        For i = 1 To srs.Points.Count
            srs.Points(i).ApplyDataLabels
            srs.Points(i).DataLabel.Text = Sheets("Sheet4").Range("A" & (i + 1)).Value
        Next i
    End Sub


    dimecres, 12 de març del 2025

    Dave Thomas al Happy Path Programming (LM Notebook digest)

     El document de "La Joia de Programar amb Dave Thomas" resumeix la conversa amb Dave Thomas al podcast "Happy Path Programming" sobre diversos aspectes de la programació.

    La joia de la programació per a Dave Thomas rau en la realització d'una idea o en lliurar alguna cosa, idealment amb un toc distintiu. La necessitat és el motor principal de la seva exploració en la programació, gaudint de buscar múltiples solucions i trobar la "correcta". Compara la programació amb la feina d'un poeta construint "castells al cel", destacant la capacitat única de la indústria per crear des de zero. També ressalta la resiliència davant la fallada com a característica dels bons programadors, veient-la com una oportunitat d'aprenentatge.

    Pel que fa a l'impacte de la Intel·ligència Artificial (IA), es mostra escèptic sobre la idea que reemplaçarà completament els programadors, assenyalant les possibles limitacions actuals en la generació i prova de codi. Subratlla la importància de la flexibilitat i l'exploració contínua per part dels programadors.

    Dave Thomas expressa una crítica a la programació orientada a classes i defensa els paradigmes funcionals. Argumenta que la gent practica "programació orientada a classes" en lloc de la veritable programació orientada a objectes. Critica l'ús excessiu de la herència.

    Feature Using Inheritance (extends Vehicle) Using Composition (implements Movable)
    Code Structure Forces everything into a single hierarchy Each class is independent
    Flexibility Hard to add new types Easy to add new vehicles
    Inheritance Problems Multiple inheritance issues No inheritance problems
    Readability Unnecessary properties (e.g., speed for a boat) Each class defines only what it needs

    Contrasta la programació OO amb la funcional, argumentant que la funcional aconsegueix més resultats. La seva programació actual tendeix a utilitzar classes només per a l'encapsulació bàsica, amb la major part del codi sent funcions externes. Presenta la idea d'un "super reductor" com l'operació fonamental de la computació. També discuteix el principi de substitució de Liskov (LSP) i la seva rellevància en contextos de "pipelines".

    Sobre el Manifest Agile, Dave Thomas considera que la part més valuosa són els quatre valors inicials, que són oberts a la interpretació i representen preferències, no regles. Lamenta com Agile va ser convertit en processos comercials rígids, perdent l'esperit original d'adaptabilitat. Creu que s'hauria de donar als desenvolupadors autonomia i temps per pensar en el seu treball. Critica la tendència a buscar la novetat en tecnologies en lloc de la resolució de problemes reals.

    Pel que fa a l'arquitectura de software, proposa un enfocament "agile": començar amb la solució més senzilla possible per obtenir retroalimentació primerenca. Emfatitza la importància de desenvolupar codi aïllat. Sugereix acceptar les decisions dels altres sobre "qüestions religioses".

    Finalment, destaca la importància d'entendre les necessitats reals dels clients, distingint entre "vull" i "necessito". Valora un enfocament iteratiu amb entregues primerenques. Qüestiona si la solució sempre és crear software personalitzat. Reflexiona sobre el valor de les interaccions humanes. Menciona l'ús de la IA per refinar preguntes.

    En resum, la conversa amb Dave Thomas ofereix una perspectiva reflexiva sobre la programació, emfatitzant la joia, l'exploració, la flexibilitat i la comprensió de les necessitats reals. La seva defensa de la programació funcional i la seva crítica a la programació orientada a classes conviden a la reflexió. La seva perspectiva sobre el Manifest Agile recorda els valors fonamentals d'adaptabilitat.


    dissabte, 18 de gener del 2025

    Autocad - Script doesn't draw properly

     https://help.autodesk.com/view/ACD/2025/ENU/?guid=GUID-94994960-5E62-4044-BEF7-9CF91667F641

    Solved



    Then lines on notes are drawn properly




    dilluns, 18 de novembre del 2024

    Google Sheets - script to list all formulas in selected range of current sheet

     function getFormulasFromSelectedRange() {

      var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var range = sheet.getActiveRange(); // Gets the currently selected range
      var formulas = range.getFormulas(); // Retrieves the formulas in the selected range
      var output = [];
     
      for (var i = 0; i < formulas.length; i++) {
        for (var j = 0; j < formulas[i].length; j++) {
          if (formulas[i][j]) { // Only add if there's a formula
            output.push(
              "Cell " + range.getCell(i + 1, j + 1).getA1Notation() + ": " + formulas[i][j]
            );
          }
        }
      }
     
      Logger.log(output.join("\n")); // Logs all formulas and their locations
    }

    dimarts, 10 de setembre del 2024

    JSON into EXCEL

    Explica com convertir un JSON en XLSX

    https://youtu.be/T_Jp2X9owQk 

    volem analitzar amb EXCEL els projectes del CDTI, accessibles des de l'enllaç:

    https://www.cdti.es/datos-abiertos-creditos-subvenciones-y-lineas


    Amb el Python

    import pandas as pd
    import json

    # Path to your JSON file
    json_file_path = r'C:\Users\1664\proyectos_CDTI\proyectos_CDTI.json'

    # Path to save the CSV file
    csv_file_path = r'
    C:\Users\1664\proyectos_CDTI\proyectos_CDTI.csv'

    # Load JSON data
    with open(json_file_path, 'r', encoding='utf-8') as f:
        data = json.load(f)

    # Convert JSON to DataFrame
    df = pd.DataFrame(data)

    # Save DataFrame to CSV
    df.to_csv(csv_file_path, index=False, encoding='utf-8')

    print(f"CSV file saved to {csv_file_path}")


    dilluns, 8 de juliol del 2024

    moodle - border line in a table

    <table>
        <tbody>
            <tr>
                <td style="
                           border: 4px solid red; 
                           background-color: #92a8d1; 
                           padding: 10px; 
                           text-align: right;">sde</td>


                <td style="
                           border: 1px solid blue;
                           text-align: right;
                           text-decoration: line-through;">d</td>
                <td style="
                           border: 3px solid orange;
                           text-align: right;"><s>h</s></td>
            </tr>
        </tbody>
    </table>

    diumenge, 23 de juny del 2024

    avaluació - ponderar RA amb Latex

     QMP = \frac{19}{100} \text{Q}_{RA1} + \frac{15}{100} \text{Q}_{RA2} + \frac{15}{100} \text{Q}_{RA3} + \frac{12}{100} \text{Q}_{RA4} + \frac{19}{100} \text{Q}_{RA5} + \frac{12}{100} \text{Q}_{RA6} + \frac{8}{100} \text{Q}_{RA7}

    Latex

    From Latex