Skip to content

pin

ts
import {pinMode, digitalWrite, digitalRead, analogRead, analogReadMillivolts} from 'mikrojs/pin'

Control GPIO pins for digital and analog I/O.

New to GPIO?

GPIO (General-Purpose Input/Output) pins are physical connections on your microcontroller that you can control from code. Set a pin HIGH to send voltage, LOW to turn it off. Use INPUT mode to read sensors or buttons, OUTPUT mode to drive LEDs or relays.

Functions

pinMode(pin, mode)

Configure a pin's direction.

ts
function pinMode(pin: number, mode: PinMode): Result<void, PinError>

Parameters:

  • pin: GPIO pin number
  • mode: 'INPUT', 'OUTPUT', or 'INPUT_PULLUP'
ts
pinMode(20, 'OUTPUT').orPanic('Failed to configure pin')

digitalWrite(pin, value)

Set a pin HIGH (1) or LOW (0).

ts
function digitalWrite(pin: number, value: 0 | 1): Result<void, PinError>
ts
digitalWrite(20, 1) // pin HIGH
digitalWrite(20, 0) // pin LOW

digitalRead(pin)

Read the current state of a pin.

ts
function digitalRead(pin: number): 0 | 1
ts
const state = digitalRead(5)
console.log(state ? 'HIGH' : 'LOW')

analogRead(pin, options?)

Read the raw ADC value from a pin.

ts
function analogRead(pin: number, options?: AnalogReadOptions): Result<number, PinError>

Returns a 12-bit integer (0–4095) proportional to the input voltage.

ts
const result = analogRead(2)
if (result.ok) {
  console.log('ADC value:', result.value)
}

analogReadMillivolts(pin, options?)

Read a calibrated voltage from a pin.

ts
function analogReadMillivolts(pin: number, options?: AnalogReadOptions): Result<number, PinError>

Returns the input voltage in millivolts.

ts
const result = analogReadMillivolts(2)
if (result.ok) {
  console.log('Voltage:', result.value, 'mV')
}

Types

PinMode

ts
type PinMode = 'INPUT' | 'OUTPUT' | 'INPUT_PULLUP'

Attenuation

ADC attenuation setting, controls the measurable voltage range.

ts
type Attenuation = '0db' | '2.5db' | '6db' | '11db'
ValueVoltage range
'0db'0–750 mV
'2.5db'0–1050 mV
'6db'0–1300 mV
'11db'0–2500 mV (default)

AnalogReadOptions

ts
interface AnalogReadOptions {
  attenuation?: Attenuation // default: '11db'
}

Errors

PinError

VariantFieldsDescription
SetModeFailedmessage: stringFailed to configure pin mode
WriteFailedmessage: stringFailed to write to pin
AdcInitFailedmessage: stringFailed to initialize ADC
InvalidAdcPinPin does not support analog reads