ChatGPT prompt - Fabio Coelho Ribeiro

In HTML and JavaScript, using the Web Serial API, add a button to connect to a serial port and toggle the state of a LED by sending "LED ON" or "LED OFF".

Here's a minimal working example using the Web Serial API with two buttons:

• Connect → opens serial port

• Toggle LED → sends "LED ON" / "LED OFF"

This assumes your microcontroller (Arduino, ESP32, etc.) is programmed to read those strings.

________________________________________

✅ Full Example (HTML + JavaScript)


                                        let port;
                                        let writer;
                                        let ledState = false;

                                        const connectBtn = document.getElementById("connectBtn");
                                        const toggleBtn = document.getElementById("toggleBtn");
                                        const statusEl = document.getElementById("status");

                                        connectBtn.addEventListener("click", async () => {
                                        try {
                                            // Request a serial port
                                            port = await navigator.serial.requestPort();

                                            // Open the port (match baud rate to your device)
                                            await port.open({ baudRate: 9600 });

                                            const textEncoder = new TextEncoderStream();
                                            const writableStreamClosed = textEncoder.readable.pipeTo(port.writable);
                                            writer = textEncoder.writable.getWriter();

                                            statusEl.textContent = "Connected";
                                            toggleBtn.disabled = false;
                                        } catch (err) {
                                            console.error(err);
                                            statusEl.textContent = "Connection failed";
                                        }
                                        });

                                        toggleBtn.addEventListener("click", async () => {
                                        if (!writer) return;

                                        ledState = !ledState;
                                        const command = ledState ? "LED ON\n" : "LED OFF\n";

                                        await writer.write(command);
                                        statusEl.textContent = `Sent: ${command.trim()}`;
                                        });
                                    

________________________________________

🔧 What your microcontroller should expect

Your device should read incoming serial text like:

LED ON

LED OFF

For example (Arduino-style logic):


                                        if (command == "LED ON") digitalWrite(LED_PIN, HIGH);
                                        if (command == "LED OFF") digitalWrite(LED_PIN, LOW);
                                    

________________________________________

⚠️ Important notes

• Works only in secure context: https:// or http://localhost

• Supported in Chromium-based browsers (Chrome, Edge)

• User must manually grant serial permission

• Baud rate must match your device

________________________________________

If you want, I can extend this to:

• read responses back from the device

• show live serial logs in the browser

• auto-reconnect to last port

• or build a React version

Add a text box like input and another button to send a text to the serial port.

Here's an updated version that adds:

• a text input box

• a Send button

• sends any typed text to the serial port (ending with \n)

It keeps your LED toggle functionality too.

________________________________________

✅ Updated HTML + Web Serial Example


                                        let port;
                                        let writer;
                                        let ledState = false;

                                        const connectBtn = document.getElementById("connectBtn");
                                        const toggleBtn = document.getElementById("toggleBtn");
                                        const sendBtn = document.getElementById("sendBtn");
                                        const textInput = document.getElementById("textInput");
                                        const statusEl = document.getElementById("status");

                                        connectBtn.addEventListener("click", async () => {
                                        try {
                                            port = await navigator.serial.requestPort();
                                            await port.open({ baudRate: 9600 });

                                            const textEncoder = new TextEncoderStream();
                                            textEncoder.readable.pipeTo(port.writable);
                                            writer = textEncoder.writable.getWriter();

                                            statusEl.textContent = "Connected";

                                            toggleBtn.disabled = false;
                                            sendBtn.disabled = false;

                                        } catch (err) {
                                            console.error(err);
                                            statusEl.textContent = "Connection failed";
                                        }
                                        });

                                        toggleBtn.addEventListener("click", async () => {
                                        if (!writer) return;

                                        ledState = !ledState;
                                        const command = ledState ? "LED ON\n" : "LED OFF\n";

                                        await writer.write(command);
                                        statusEl.textContent = `Sent: ${command.trim()}`;
                                        });

                                        sendBtn.addEventListener("click", async () => {
                                        if (!writer) return;

                                        const message = textInput.value.trim();
                                        if (!message) return;

                                        await writer.write(message + "\n");

                                        statusEl.textContent = `Sent: ${message}`;
                                        textInput.value = "";
                                        });

                                        // Optional: send on Enter key
                                        textInput.addEventListener("keydown", (e) => {
                                        if (e.key === "Enter") {
                                            sendBtn.click();
                                        }
                                        });
                                    

________________________________________

🔧 What this gives you

You can now:

• Click Connect Serial

• Toggle LED with button → sends:

- LED ON

- LED OFF

• Type any command like:

- STATUS

- MOTOR 100

- HELLO

• Press Send or hit Enter

________________________________________

⚠️ Tip for microcontroller side

Make sure your device reads line-based input (ending in \n), for example:


                                        String cmd = Serial.readStringUntil('\n');
                                        cmd.trim();
                                    

________________________________________

If you want next step improvements, I can add:

• live serial output console in the browser

• dropdown of available ports (auto reconnect)

• structured JSON commands instead of plain text

• or a clean dashboard UI for multiple devices

In Visual Studio, using a windows forms app, create a blue rectangle, a black line starting at the top center of the rectangle and a red circle at the top of the line. Make it so the red circle is draggable and with my mouse so i can rotate it left and right modify its angle, add a text box inside the rectangle showing the current angle of the line.

Below is a simple WinForms example (C#) that does exactly what you described:

• Draws a blue rectangle

• A line starting from the top-center of the rectangle

• A red draggable circle at the end of the line

• Dragging the circle updates the angle of the line

• A TextBox inside the rectangle shows the current angle

________________________________________

✅ How it works

• The rectangle is drawn in the middle of the form

• The pivot point is the top-center of the rectangle

• The line length is fixed

• The circle position is computed from the angle

• Mouse drag updates the angle using Math.Atan2

________________________________________

🧠 Full Code (Form1.cs)

Replace your Form1.cs with this:


                                        using System;
                                        using System.Drawing;
                                        using System.Windows.Forms;

                                        namespace WinFormsAngleDemo
                                        {
                                            public partial class Form1 : Form
                                            {
                                                private Rectangle rect;
                                                private PointF pivot;

                                                private float angle = -90f; // start pointing up
                                                private float lineLength = 120f;

                                                private bool dragging = false;

                                                private TextBox angleBox;

                                                public Form1()
                                                {
                                                    InitializeComponent();

                                                    this.DoubleBuffered = true;
                                                    this.BackColor = Color.White;

                                                    this.Width = 600;
                                                    this.Height = 500;

                                                    // Rectangle setup
                                                    rect = new Rectangle(200, 150, 200, 150);
                                                    pivot = new PointF(rect.Left + rect.Width / 2f, rect.Top);

                                                    // TextBox inside rectangle
                                                    angleBox = new TextBox();
                                                    angleBox.ReadOnly = true;
                                                    angleBox.Width = 100;
                                                    angleBox.Location = new Point(rect.Left + 50, rect.Top + 60);
                                                    this.Controls.Add(angleBox);

                                                    this.MouseDown += Form1_MouseDown;
                                                    this.MouseMove += Form1_MouseMove;
                                                    this.MouseUp += Form1_MouseUp;

                                                    UpdateAngleBox();
                                                }

                                                protected override void OnPaint(PaintEventArgs e)
                                                {
                                                    base.OnPaint(e);

                                                    Graphics g = e.Graphics;

                                                    // Draw rectangle (blue)
                                                    using (Pen pen = new Pen(Color.Blue, 2))
                                                    {
                                                        g.DrawRectangle(pen, rect);
                                                    }

                                                    // Recompute pivot in case layout changes
                                                    pivot = new PointF(rect.Left + rect.Width / 2f, rect.Top);

                                                    // Compute circle position
                                                    PointF circle = GetCirclePosition();

                                                    // Draw line
                                                    using (Pen pen = new Pen(Color.Black, 2))
                                                    {
                                                        g.DrawLine(pen, pivot, circle);
                                                    }

                                                    // Draw circle (red)
                                                    float r = 10;
                                                    using (Brush b = new SolidBrush(Color.Red))
                                                    {
                                                        g.FillEllipse(b, circle.X - r, circle.Y - r, r * 2, r * 2);
                                                    }
                                                }

                                                private PointF GetCirclePosition()
                                                {
                                                    float rad = angle * (float)Math.PI / 180f;

                                                    return new PointF(
                                                        pivot.X + lineLength * (float)Math.Cos(rad),
                                                        pivot.Y + lineLength * (float)Math.Sin(rad)
                                                    );
                                                }

                                                private void Form1_MouseDown(object sender, MouseEventArgs e)
                                                {
                                                    PointF circle = GetCirclePosition();
                                                    float dx = e.X - circle.X;
                                                    float dy = e.Y - circle.Y;

                                                    if (dx * dx + dy * dy <= 15 * 15)
                                                    {
                                                        dragging = true;
                                                    }
                                                }

                                                private void Form1_MouseMove(object sender, MouseEventArgs e)
                                                {
                                                    if (!dragging) return;

                                                    float dx = e.X - pivot.X;
                                                    float dy = e.Y - pivot.Y;

                                                    angle = (float)(Math.Atan2(dy, dx) * 180f / Math.PI);

                                                    UpdateAngleBox();
                                                    Invalidate(); // redraw
                                                }

                                                private void Form1_MouseUp(object sender, MouseEventArgs e)
                                                {
                                                    dragging = false;
                                                }

                                                private void UpdateAngleBox()
                                                {
                                                    angleBox.Text = $"Angle: {angle:F1}°";
                                                }
                                            }
                                        }
                                    

________________________________________

🎯 What you can easily extend next

If you want, you can enhance this with:

• Limit angle range (e.g. -90° to +90°)

• Snap-to-grid angles (15° steps)

• Make line length adjustable with mouse wheel

• Add rotation around both axes (2D joystick style)

• Replace circle with a knob UI

________________________________________

If you want, I can also turn this into a custom control (reusable component) or make it behave like a servo motor / joystick simulator.