Try a number-and-answer page

… visits
Parent Previous Next

Enter a number on a web page. The PIC checks it, calculates its square and sends back an answer linked to that request. This example includes the firmware changes and the complete HTML page.

1. Set up the slots

Set capacity 3, values per response 3, and input slots 1. Name the output slots number, answer, sequence, in that order. Their generated definitions should include:

$define USB_NET_MAX_VALUES 3

$define USB_NET_INITIAL_COUNT 3

$define USB_NET_NAME_1 "number"

$define USB_NET_NAME_2 "answer"

$define USB_NET_NAME_3 "sequence"

$define USB_NET_RX_VALUES 1

Keep these definitions before Include "USB_Device.inc", along with the rest of the generated settings. Add the following application variables after the include, before the generated Clear and startup code:

Dim sdRequested As SDword

Dim sdAnswer As SDword

Dim sdCompletedSequence As SDword

Dim wRequestSequence As Word

Dim bNumberValid As Byte

2. Calculate the answer in the PIC

Keep the generated board setup and USB_Init(). Replace the generated value initialization and main loop with this code. This example accepts −1000 to 1000 so the square fits in a signed 32-bit number. The library can receive larger numbers, but your application must check its own safe range.

USB_NetSetValue(0, 0)

USB_NetSetNull(1)

USB_NetSetValue(2, 0)

USB_NetSetCount(3)

If USB_Result <> USB_OK Then Stop


Do

    USB_NetworkService()

    USB_NetReadValue(0)

    If USB_Result = USB_OK Then

        sdRequested = USB_NetRxValue

        wRequestSequence = USB_NetRxSequence

        bNumberValid = 1

        If sdRequested < -1000 Then bNumberValid = 0

        If sdRequested > 1000 Then bNumberValid = 0


        USB_NetSetValue(0, sdRequested)

        If bNumberValid = 1 Then

            sdAnswer = sdRequested * sdRequested

            USB_NetSetValue(1, sdAnswer)

        Else

            USB_NetSetNull(1)

        EndIf


        ' Publish completion last, before the next service call.

        sdCompletedSequence = wRequestSequence

        USB_NetSetValue(2, sdCompletedSequence)

    EndIf

Loop

The output for input 12 might be {"number":12,"answer":144,"sequence":17}. An out-of-range command is consumed and acknowledged by its published sequence, but its answer is null. This prevents an invalid command from blocking the mailbox indefinitely.

3. Make the browser page

Save the complete example below as a UTF-8 HTML file. If the PIC serves the page, leave DEVICE empty. If the page stays on the PC, set it to "http://192.168.7.1" and choose External HTML mode.

<!doctype html>

<html lang="en">

<meta charset="utf-8">

<meta name="viewport" content="width=device-width,initial-scale=1">

<title>PIC number test</title>

<style>

body { font: 18px system-ui; max-width: 34rem; margin: 3rem auto;

       padding: 0 1rem; }

input, button { font: inherit; padding: .5rem; }

#message { min-height: 3em; }

</style>

<h1>PIC number test</h1>

<form id="form">

  <label>Integer −1000 to 1000

    <input id="number" type="number" min="-1000" max="1000"

           step="1" value="12" required>

  </label>

  <button id="send">Send</button>

</form>

<p id="message" role="status">Ready.</p>

<script>

const DEVICE = ""; // External HTML: "http://192.168.7.1"

const form = document.getElementById("form");

const input = document.getElementById("number");

const button = document.getElementById("send");

const message = document.getElementById("message");

let busy = false;

const pause = ms => new Promise(resolve => setTimeout(resolve, ms));


async function request(path, options = {}) {

  const controller = new AbortController();

  const timer = setTimeout(() => controller.abort(), 4000);

  try {

    const response = await fetch(DEVICE + path, {

      ...options, cache: "no-store", credentials: "omit",

      signal: controller.signal

    });

    if (!response.ok) {

      if (response.status === 409)

        throw new Error("Input slot busy: the PIC has not read it yet.");

      throw new Error("HTTP " + response.status);

    }

    return await response.json();

  } finally {

    clearTimeout(timer);

  }

}


form.addEventListener("submit", async event => {

  event.preventDefault();

  if (busy) return;

  const text = input.value.trim();

  const number = Number(text);

  if (!/^-?\d+$/.test(text) || !Number.isInteger(number) ||

      number < -1000 || number > 1000) {

    message.textContent = "Enter a whole number from −1000 to 1000.";

    return;

  }

  busy = true;

  button.disabled = true;

  let receiptReceived = false;

  try {

    message.textContent = "Sending…";

    const receipt = await request("/write?index=0&value=" + number, {

      method: "POST", headers: { "X-USB-Write": "1" }

    });

    if (receipt.accepted !== true || receipt.index !== 0 ||

        !Number.isInteger(receipt.sequence) || receipt.sequence < 1)

      throw new Error("Unexpected command receipt.");

    receiptReceived = true;

    message.textContent = "Accepted; waiting for the calculated answer…";

    const deadline = Date.now() + 10000;

    while (Date.now() < deadline) {

      const data = await request("/status");

      if (data.sequence === receipt.sequence && data.number === number) {

        if (data.answer === null)

          throw new Error("The PIC rejected the application value.");

        if (!Number.isInteger(data.answer))

          throw new Error("The PIC returned an invalid answer.");

        message.textContent = number + " squared = " + data.answer;

        return;

      }

      await pause(250);

    }

    throw new Error("No matching completed answer arrived.");

  } catch (error) {

    const detail = error.name === "AbortError" ? "Request timed out."

                                                     : error.message;

    message.textContent = detail + (receiptReceived

      ? " The command was accepted; check the PIC application."

      : " No completion is confirmed. Check the PIC before sending again.");

  } finally {

    busy = false;

    button.disabled = false;

  }

});

</script>

</html>

The page sends the command once, then asks for /status one request at a time. It shows the answer only when both sequence and number match. Each request has a timeout, and reads and writes never overlap. Do not add a separate setInterval() reader. In a larger page, put all requests through one queue and pause normal polling while waiting for a command reply.

See also

Created with the Personal Edition of HelpNDoc: Leave the tedious WinHelp HLP to CHM conversion process behind with HelpNDoc