wokwi / rp2040js

A Raspberry Pi Pico Emulator in JavaScript
MIT License
400 stars 44 forks source link

Toggling pins from JavaScript #82

Closed jmdevy closed 3 years ago

jmdevy commented 3 years ago

Sorry to keep making issues. These can at least serve as basis of documentation for others.

Is there a way to directly change the state of a GPIO pin from Javascript? I assume there is some way since elements like the push button can interact with the rp2040.

Does it take a direct write to the correct register?

jmdevy commented 3 years ago

Looks like I figured it out!

the 'setInputValue(value)' value means I can set the pin to '0' or '1' from Javascript

Example:

const mcu = new RP2040();

# Load bootrom + uf2...

function sendStringToNormal(str){
  for (const byte of str) {
    cdc.sendSerialByte(byte.charCodeAt(0));
  }

  cdc.sendSerialByte('\r'.charCodeAt(0));
  cdc.sendSerialByte('\n'.charCodeAt(0));
}

const cdc = new USBCDC(mcu.usbCtrl);
cdc.onDeviceConnected = () => {
  // We send a newline so the user sees the MicroPython prompt
  cdc.sendSerialByte('\r'.charCodeAt(0));
  cdc.sendSerialByte('\n'.charCodeAt(0));

  mcu.gpio[0].setInputValue(1);       # This can be '0' or '1'
  sendStringToNormal("import machine");
  sendStringToNormal("pin = machine.Pin(0, machine.Pin.IN)");
  sendStringToNormal("pin.value()");  # This will display '0' or '1' in REPL
};
urish commented 3 years ago

Yes, you found it!

Note that setInputValue actually expects a boolean (true/false). It'll probably work with 0/1 too, but it's not officially supported by the API.

It's good to ask questions. Even better when you figure out the answers :-)

You are also invited to join our discord chat, there's a dedicated channel for rp2040js.