module main
author 'Kit kidsIOT'
version 1 0 
description 'Reto 7: Transportador. Ultrasonidos (puerto 9), servo de 360° (servo 1)'

script 50 50 {
whenStarted
forever {
  if (('eng distance' 9) < 10) {
    'eng servoToSpeed' '1 (io33)' 50 'kiot;clockwise'
    waitMillis 3000
  } else {
    'eng stopServo' '1 (io33)'
  }
}
}


module 'KidsIOT Engineering'
author MicroBlocks
version 1 0 
depends '_IR Remote' _Servo _Tone '_Distance (HC-SR04)' TFT 'LED Display'
choices eng_twoPins '1' '3' '4' '6' '7' '8' '9'
choices eng_analogSensors 'kiot;potentiometer' 'kiot;steam'
choices eng_allPorts '1' '2' '3' '4' '6' '7' '8' '9' 
choices eng_motor '1' '3' '9' 
choices eng_analogPins '3' '4' '6' '7' '8'
choices eng_rotation 'kiot;clockwise' 'kiot;counter-clockwise'
choices eng_threePins '1' '9' 
choices eng_joystick X Y 'kiot;button pressed?' 
choices eng_digitalSensors 'kiot;button pressed?' 'kiot;receive IR code' 'kiot;touching?' 
choices eng_servo_port  '1 (io33)' '2 (io32)'
description 'Specific library for "KidsIOT Smart Engineering" kit.
Components:
ultrasound, IR receiver, potentiometer, button, buzzer, I2C joystick, steam sensor, capacitive button, servo 270º and servo 360º (continuous rotation)
'

  spec ' ' 'eng play note' '#SVG#square11#0070ff play note _ octave _ for _ port _' 'menu.tone_NoteName num num menu.eng_allPorts' 'nt;c' 0 500 1  
  space
  spec 'r' 'eng buttonPressed' '#SVG#square11#0070ff button pressed? _' 'menu.eng_allPorts' 1
  spec 'r' 'eng touching' '#SVG#square11#0070ff touching? _' 'menu.eng_allPorts' 1
  spec 'r' 'eng receiveIRCode' '#SVG#square11#0070ff receive IR code _' 'menu.eng_allPorts' 1
  space
  spec 'r' 'eng potentiometer' '#SVG#square11#ff0000 potentiometer _' 'menu.eng_analogPins' 3
  spec 'r' 'eng steam' '#SVG#square11#ff0000 steam _' 'menu.eng_analogPins' 3
  space
  spec 'r' 'eng joystick' '#SVG#square11#00c612 joystick _' 'menu.eng_joystick' 'X'
  spec 'r' 'eng distance' '#SVG#square11#fff000 distance (cm) port _' 'menu.eng_twoPins' 1
  space
  spec ' ' 'eng servoToDegrees' '#SVG#square11#C0C0C0 set servo _ to _ degrees (0 to 270) : reversed _' 'menu.eng_servo_port num bool' '1 (io33)' 90 false
  spec ' ' 'eng servoToSpeed' '#SVG#square11#FFA500 set servo _ to speed _ (0 to 100) _ : for _ seconds' 'menu.eng_servo_port num menu.eng_rotation num' '1 (io33)' 100 'kiot;clockwise' 1
  spec ' ' 'eng stopServo' '#SVG#square11#FFA500 stop servo _' 'menu.eng_servo_port' '1 (io33)'
  

to 'eng distance' port {
  if (('[data:find]' ('[data:convertType]' port 'number') ('[data:makeList]' 1 3 4 6 7 8 9)) > 0) {
    local '_kiot_pins' ('[data:makeList]' ('[data:makeList]' 13 14) '' ('[data:makeList]' 26 4) ('[data:makeList]' 27 39) '' ('[data:makeList]' 23 36) ('[data:makeList]' 16 35) ('[data:makeList]' 5 34) ('[data:makeList]' 18 19))
    local 'trig' (at 1 (at ('[data:convertType]' port 'number') _kiot_pins))
    local 'echo' (at 2 (at ('[data:convertType]' port 'number') _kiot_pins))
    return ('distance (cm)' trig echo)
  } else {
    return 'Invalid port number. Valid ports: 1, 3, 4, 6, 7, 8 & 9'
  }
}

to 'eng joystick' param {
  if ('[sensors:i2cExists]' (hexToInt '39')) {
    if (param == 'kiot;button pressed?') {
      return ((i2cGet (hexToInt '39') (hexToInt '31')) > 0)
    } (param == 'X') {
      return ('[misc:rescale]' (((i2cGet (hexToInt '39') (hexToInt '32')) << 2) | ((i2cGet (hexToInt '39') (hexToInt '33')) >> 6)) 0 1023 -100 100)
    } (param == 'Y') {
      return ('[misc:rescale]' (((i2cGet (hexToInt '39') (hexToInt '34')) << 2) | ((i2cGet (hexToInt '39') (hexToInt '35')) >> 6)) 0 1023 100 -100)
    } else {
      return 'Only "kiot;button pressed?", "X" or "Y" are valid inputs'
    }
  } else {
    return 'Joystick not detected'
  }
}

to 'eng play note' note octave time port {
  if (('[data:find]' ('[data:convertType]' port 'number') ('[data:makeList]' 1 2 3 4 6 7 8 9)) > 0) {
    local '_eng_pins' ('[data:makeList]' 13 2 26 27 '' 23 16 5 18)
    if (_eng_buzzer_init != port) {
      'attach buzzer to pin' (at port _eng_pins)
      _eng_buzzer_init = port
    }
    'play tone' note octave time
  } else {
    sayIt 'Invalid port number. Valid ports: 1, 2, 3, 4, 6, 7, 8 & 9'
  }
}

to 'eng servoToDegrees' which degrees reversed {
  if ((size which) == 8) {which = (34 - ('[data:convertType]' ('[data:copyFromTo]' which 1 1) 'number'))}
  if ((pushArgCount) > 2) {if reversed {
    degrees = (270 - degrees)
  }}
  local 'pulseWidth' ('[misc:rescale]' degrees 0 270 600 2400)
  if ('[io:hasServo]') {
    '[io:setServo]' which pulseWidth
  } else {
    atPut ('_servoIndex' which) _servoPulseWidth pulseWidth
  }
}

to 'eng servoToSpeed' which speed rotation seconds {
  if (rotation == 'kiot;counter-clockwise') {speed = (0 - speed)}
  if ((size which) == 8) {which = (34 - ('[data:convertType]' ('[data:copyFromTo]' which 1 1) 'number'))}
  setServoSpeed which ('[data:convertType]' speed 'number')
  if ((pushArgCount) > 3) {
    waitMillis (seconds * 1000)
    stopServo which
  }
}

to 'eng stopServo' servo {
  if ((size servo) == 8) {servo = (34 - ('[data:convertType]' ('[data:copyFromTo]' servo 1 1) 'number'))}
  stopServo servo
}

to 'eng buttonPressed' port {
  if (('[data:find]' ('[data:convertType]' port 'number') ('[data:makeList]' 1 2 3 4 6 7 8 9)) > 0) {
    local 'pin' (at port ('[data:makeList]' 13 2 26 27 '' 23 16 5 18))
    return (not (digitalReadOp pin))
  } else {
    return 'Invalid port number. Valid ports: 1, 2, 3, 4, 6, 7, 8 & 9'
  }
}

to 'eng receiveIRCode' port {
  if (('[data:find]' ('[data:convertType]' port 'number') ('[data:makeList]' 1 2 3 4 6 7 8 9)) > 0) {
    local 'pin' (at port ('[data:makeList]' 13 2 26 27 '' 23 16 5 18))
    attachIR pin
    return (receiveIR)
  } else {
    return 'Invalid port number. Valid ports: 1, 2, 3, 4, 6, 7, 8 & 9'
  }
}

to 'eng touching' port {
  if (('[data:find]' ('[data:convertType]' port 'number') ('[data:makeList]' 1 2 3 4 6 7 8 9)) > 0) {
    local 'pin' (at port ('[data:makeList]' 13 2 26 27 '' 23 16 5 18))
    return (digitalReadOp pin)
  } else {
    return 'Invalid port number. Valid ports: 1, 2, 3, 4, 6, 7, 8 & 9'
  }
}

to 'eng potentiometer' port {
  if (('[data:find]' ('[data:convertType]' port 'number') ('[data:makeList]' 3 4 6 7 8)) > 0) {
    local 'value' (analogReadOp (at ('[data:convertType]' port 'number') ('[data:makeList]' '' '' 4 39 '' 36 35 34)))
    return value
  } else {
    return 'Invalid port number. Valid ports: 3, 4, 6, 7 & 8'
  }
}

to 'eng steam' port {
  if (('[data:find]' ('[data:convertType]' port 'number') ('[data:makeList]' 3 4 6 7 8)) > 0) {
    local 'value' (analogReadOp (at ('[data:convertType]' port 'number') ('[data:makeList]' '' '' 4 39 '' 36 35 34)))
    return value
  } else {
    return 'Invalid port number. Valid ports: 3, 4, 6, 7 & 8'
  }
}


module Servo Output
author MicroBlocks
version 1 4 
tags servo motor angle rotation position 
description 'Control both positional (angle) and rotational servo motors.
'
variables _servoPin _servoPulseWidth 

  spec ' ' 'setServoAngle' 'set servo _ to _ degrees (-90 to 90)' 'num num' 1 90
  spec ' ' 'setServoSpeed' 'set servo _ to speed _ (-100 to 100)' 'num num' 1 100
  spec ' ' 'stopServo' 'stop servo _' 'num' 1
  spec 'r' '_servoIndex' '_servoIndex _' 'num' 1
  spec ' ' '_servoPulse' '_servoPulse pin _ usecs _' 'num num' 1 1500
  spec ' ' '_servoUpdateLoop' '_servoUpdateLoop'

to '_servoIndex' which {
  if (_servoPin == 0) {
    _servoPin = ('[data:makeList]')
    _servoPulseWidth = ('[data:makeList]')
    sendBroadcast '_servoUpdateLoop'
  }
  local 'i' ('[data:find]' which _servoPin)
  if (i < 0) {
    comment 'Add new pin'
    '[data:addLast]' which _servoPin
    '[data:addLast]' 1500 _servoPulseWidth
    i = (size _servoPin)
  }
  return i
}

to '_servoPulse' pin usecs {
  if (usecs == 0) {
    comment 'Servo stopped; do nothing'
    return 0
  }
  usecs = (maximum 500 (minimum usecs 2900))
  comment 'Split wait into a long wait followed by a wait of <= 30 usecs for greater accuracy'
  local 'endTime' ((microsOp) + usecs)
  digitalWriteOp pin true
  waitMicros (usecs - 30)
  waitMicros (endTime - (microsOp))
  digitalWriteOp pin false
}

to '_servoUpdateLoop' {
  forever {
    if (_servoPin != 0) {
      comment 'If the _servoPin list is not 0, update the servos'
      for i (size _servoPin) {
        local 'pin' (at i _servoPin)
        local 'usecs' (at i _servoPulseWidth)
        if (and (pin >= 0) (usecs != 0)) {
          '_servoPulse' pin usecs
        }
      }
      waitMillis 15
    }
  }
}

to setServoAngle which degrees optionalReverse {
  local 'reversed' false
  if ((pushArgCount) > 2) {
    reversed = optionalReverse
  }
  if reversed {
    degrees = (0 - degrees)
  }
  local 'pulseWidth' (1500 - (10 * degrees))
  if ('[io:hasServo]') {
    '[io:setServo]' which pulseWidth
  } else {
    atPut ('_servoIndex' which) _servoPulseWidth pulseWidth
  }
}

to setServoSpeed which speed optionalReverse {
  local 'reversed' false
  if ((pushArgCount) > 2) {
    reversed = optionalReverse
  }
  if reversed {
    speed = (0 - speed)
  }
  local 'pulseWidth' (1500 - (10 * speed))
  if ((absoluteValue speed) < 2) {
    pulseWidth = 0
  }
  if ('[io:hasServo]') {
    '[io:setServo]' which pulseWidth
  } else {
    atPut ('_servoIndex' which) _servoPulseWidth pulseWidth
  }
}

to stopServo which {
  if ('[io:hasServo]') {
    '[io:setServo]' which 0
  } else {
    atPut ('_servoIndex' which) _servoPulseWidth 0
  }
}



module Tone Output
author MicroBlocks
version 1 10 
tags tone sound music audio note speaker 
choices tone_NoteName 'nt;c' 'nt;c#' 'nt;d' 'nt;d#' 'nt;e' 'nt;f' 'nt;f#' 'nt;g' 'nt;g#' 'nt;a' 'nt;a#' 'nt;b' 
description 'Audio tone generation. Make music with MicroBlocks!
'
variables _tonePin _toneInitalized _toneLoopOverhead _toneNoteNames _toneArezzoNotes _toneFrequencies 

  spec ' ' 'play tone' 'play note _ octave _ for _ ms' 'str.tone_NoteName num num' 'nt;c' 0 500
  spec ' ' 'playMIDIKey' 'play midi key _ for _ ms' 'num num' 60 500
  spec ' ' 'play frequency' 'play frequency _ for _ ms' 'num num' 261 500
  space
  spec ' ' 'startTone' 'start tone _ Hz' 'num' 440
  spec ' ' 'stopTone' 'stop tone'
  space
  spec ' ' 'attach buzzer to pin' 'attach buzzer to pin _' 'auto' ''
  space
  spec 'r' '_measureLoopOverhead' '_measureLoopOverhead'
  spec 'r' '_baseFreqForNote' '_baseFreqForNote _' 'auto' 'c'
  spec 'r' '_baseFreqForSemitone' '_baseFreqForSemitone _' 'num' 0
  spec ' ' '_toneLoop' '_toneLoop _ for _ ms' 'num num' 440000 100
  spec 'r' '_trimmedLowercase' '_trimmedLowercase _' 'str' 'A. b C...'
  spec ' ' '_tone init note names' '_tone init note names'

to '_baseFreqForNote' note {
  comment 'Return the frequency for the given note in the middle-C octave
scaled by 1000. For example, return 440000 (440Hz) for A.
Note names may be upper or lower case. Note names
may be followed by # for a sharp or b for a flat.'
  local 'normalized note' ('_trimmedLowercase' note)
  'normalized note' = (ifExpression ((at 1 (v 'normalized note')) == 'n') (v 'normalized note') ('[data:join]' 'nt;' (v 'normalized note')))
  '_tone init note names'
  if (('[data:find]' (v 'normalized note') _toneArezzoNotes) > 0) {
    return ('_baseFreqForSemitone' ('[data:find]' (v 'normalized note') _toneArezzoNotes))
  } else {
    return ('_baseFreqForSemitone' ('[data:find]' (v 'normalized note') _toneNoteNames))
  }
}

to '_baseFreqForSemitone' semitone {
  if (_toneFrequencies == 0) {_toneFrequencies = ('[data:makeList]' 261626 277183 293665 311127 329628 349228 369994 391995 415305 440000 466164 493883 246942 277183 277183 311127 311127 349228 329628 369994 369994 415305 415305 466164 466164 523252)}
  if (and (1 <= semitone) (semitone <= (size _toneFrequencies))) {
    return (at semitone _toneFrequencies)
  } else {
    comment 'Bad note name; return 10 Hz'
    return 10000
  }
}

to '_measureLoopOverhead' {
  comment 'Measure the loop overhead on this device'
  local 'halfCycle' 100
  local 'startT' (microsOp)
  repeat 100 {
    digitalWriteOp _tonePin false
    waitMicros halfCycle
    digitalWriteOp _tonePin false
    waitMicros halfCycle
  }
  local 'usecs' ((microsOp) - startT)
  return ((usecs - 20000) / 200)
}

to '_tone init note names' {
  if (_toneNoteNames == 0) {
    _toneNoteNames = ('[data:makeList]' 'nt;c' 'nt;c#' 'nt;d' 'nt;d#' 'nt;e' 'nt;f' 'nt;f#' 'nt;g' 'nt;g#' 'nt;a' 'nt;a#' 'nt;b' 'nt;c_' 'nt;db' 'nt;d_' 'nt;eb' 'nt;e_' 'nt;e#' 'nt;f_' 'nt;gb' 'nt;g_' 'nt;ab' 'nt;a_' 'nt;bb' 'nt;b_' 'nt;b#')
    _toneArezzoNotes = ('[data:makeList]' 'nt;do' 'nt;do#' 'nt;re' 'nt;re#' 'nt;mi' 'nt;fa' 'nt;fa#' 'nt;sol' 'nt;sol#' 'nt;la' 'nt;la#' 'nt;si' 'nt;do_' 'nt;dob' 'nt;re_' 'nt;reb' 'nt;mi_' 'nt;mi#' 'nt;fa_' 'nt;solb' 'nt;sol_' 'nt;lab' 'nt;la_' 'nt;sib' 'nt;si_' 'nt;si#')
  }
}

to '_toneLoop' scaledFreq ms {
  if (_toneInitalized == 0) {'attach buzzer to pin' ''}
  if ('[io:hasTone]') {
    '[io:playTone]' _tonePin (scaledFreq / 1000)
    waitMillis ms
    '[io:playTone]' _tonePin 0
  } else {
    local 'halfCycle' ((500000000 / scaledFreq) - _toneLoopOverhead)
    local 'cycles' ((ms * 500) / halfCycle)
    repeat cycles {
      digitalWriteOp _tonePin true
      waitMicros halfCycle
      digitalWriteOp _tonePin false
      waitMicros halfCycle
    }
  }
}

to '_trimmedLowercase' s {
  comment 'Return a copy of the given string without whitespace
or periods and all lowercase.'
  local 'result' (newList (size s))
  '[data:delete]' 'all' result
  for i (size s) {
    local 'ch' ('[data:unicodeAt]' i s)
    if (and (ch > 32) (ch != 46)) {
      if (and (65 <= ch) (ch <= 90)) {ch = (ch + 32)}
      '[data:addLast]' ch result
    }
  }
  return ('[data:unicodeString]' result)
}

to 'attach buzzer to pin' pinNumber {
  if (pinNumber == '') {
    comment 'Pin number not specified; use default pin for this device'
    if ((boardType) == 'Citilab ED1') {
      _tonePin = 26
    } ((boardType) == 'M5Stack-Core') {
      _tonePin = 25
    } ((boardType) == 'M5StickC') {
      _tonePin = 26
    } ((boardType) == 'Calliope') {
      digitalWriteOp 23 true
      digitalWriteOp 24 true
      _tonePin = 25
    } ((boardType) == 'D1-Mini') {
      _tonePin = 12
    } ((boardType) == 'CodingBox') {
      _tonePin = 32
    } else {
      _tonePin = -1
    }
  } else {
    _tonePin = pinNumber
  }
  _toneLoopOverhead = ('_measureLoopOverhead')
  _toneInitalized = (booleanConstant true)
}

to 'play frequency' freq ms {
  '_toneLoop' (freq * 1000) ms
}

to 'play tone' note octave ms {
  local 'freq' ('_baseFreqForNote' note)
  if (freq <= 10000) {
    waitMillis ms
    return 0
  }
  if (octave < 0) {
    repeat (absoluteValue octave) {
      freq = (freq / 2)
    }
  }
  repeat octave {
    freq = (freq * 2)
  }
  '_toneLoop' freq ms
}

to playMIDIKey key ms {
  local 'freq' ('_baseFreqForSemitone' ((key % 12) + 1))
  local 'octave' ((key / 12) - 5)
  if (octave < 0) {
    repeat (absoluteValue octave) {
      freq = (freq / 2)
    }
  }
  repeat octave {
    freq = (freq * 2)
  }
  '_toneLoop' freq ms
}

to startTone freq {
  if (_toneInitalized == 0) {'attach buzzer to pin' ''}
  if ('[io:hasTone]') {'[io:playTone]' _tonePin freq}
}

to stopTone {
  startTone 0
}



module 'IR Remote' Comm
author MicroBlocks
version 1 9 
tags ir infrared remote 
description 'Sends and receives infrared remote control messages like the ones used for TV sets or air conditioners. Currently supports only the NEC protocol, which is quite common but not the only IR protocol in use. An NEC message consists of a one byte device number and a one byte command.

Note: Transmitting IR does not work on ESP8266 boards.

Receiving requires an IR receiver module, such as those built into the Circuit Playground Express and ED1 boards. Transmitting requires an IR transmitter LED, such as those built into the Circuit Playground Express and several M5 Stack products. Inexpensive IR LED transmitter and receivers are available for use with other boards.
'
variables _ir_pin _ir_pulse_times _ir_last_code _ir_last_device _ir_transmit_pin 

  spec ' ' 'attachIR' 'attach IR receiver to pin _' 'num' 0
  spec 'r' 'ir_code_received' 'IR code received?'
  spec 'r' 'ir_last_code' 'IR code'
  space
  spec ' ' 'IR_Transmit' 'IR transmit device _ command _' 'num num' 48896 1
  spec ' ' 'attachIRTransmitter' 'attach IR transmitter to pin _' 'num' 0
  space
  spec 'r' 'receiveIR' 'receive IR code'
  space
  spec ' ' '_testIR' '_test IR'
  spec 'r' '_receiveIRFromDevice' '_receive IR code from device _' 'num' 48896
  space
  spec ' ' '_captureIRMessage' '_captureIRMessage' 'any'
  spec ' ' '_dumpIR' '_dumpIR' 'any'
  spec 'r' '_getIRByte' '_getIRByte _' 'auto any' 4
  spec 'r' '_got32Bits' '_got32Bits' 'any'
  spec ' ' '_IR_SendByte' '_IR_SendByte _' 'auto' '10'
  spec ' ' 'timerIRCapture' 'timerIRCapture'
  spec ' ' 'interruptIRCapture' 'interruptIRCapture'

to IR_Transmit device command {
  if (_ir_transmit_pin == 0) {if (or ((boardType) == 'CircuitPlayground') ((boardType) == 'M5Atom-Matrix')) {
    _ir_transmit_pin = 12
  } (or ((boardType) == 'M5StickC') ((boardType) == 'M5StickC+')) {
    _ir_transmit_pin = 9
  }}
  comment 'Message start pulse and space'
  '[io:playTone]' _ir_transmit_pin 38000
  waitMicros 9000
  '[io:playTone]' _ir_transmit_pin 0
  waitMicros 4500
  comment 'Send device and command and their inverses'
  '_IR_SendByte' (device & 255)
  '_IR_SendByte' ((device >> 8) & 255)
  '_IR_SendByte' command
  '_IR_SendByte' ('~' command)
  comment 'Send stop bit'
  '[io:playTone]' _ir_transmit_pin 38000
  waitMicros 562
  '[io:playTone]' _ir_transmit_pin 0
  comment 'Turn off IR transmit LED'
  if (or ((boardType) == 'M5StickC') ((boardType) == 'M5StickC+')) {
    comment 'IR pin is inverted so true means "off"'
    digitalWriteOp _ir_transmit_pin true
  } else {
    digitalWriteOp _ir_transmit_pin false
  }
}

to '_IR_SendByte' byte {
  local 'bit' 1
  repeat 8 {
    if (0 == (byte & bit)) {
      '[io:playTone]' _ir_transmit_pin 38000
      waitMicros 530
      '[io:playTone]' _ir_transmit_pin 0
      waitMicros 530
    } else {
      '[io:playTone]' _ir_transmit_pin 38000
      waitMicros 530
      '[io:playTone]' _ir_transmit_pin 0
      waitMicros 1630
    }
    bit = (bit << 1)
  }
}

to '_captureIRMessage' {
  if (_ir_pulse_times == 0) {
    _ir_pulse_times = (newList 100)
    if (_ir_pin == 0) {
      if ((boardType) == 'CircuitPlayground') {
        _ir_pin = 11
      } ((boardType) == 'Citilab ED1') {
        _ir_pin = 35
      } ((boardType) == 'D1-Mini') {
        _ir_pin = 2
      } ((boardType) == 'MakerPort') {
        _ir_pin = 18
      } ((boardType) == 'MakerPort V3') {
        _ir_pin = 22
      }
    }
  }
  comment 'Capture the next IR message.'
  if (or ((boardType) == 'micro:bit v2') ((boardType) == 'Calliope v3')) {
    timerIRCapture
  } else {
    interruptIRCapture
  }
}

to '_dumpIR' {
  comment 'Print raw pulse timings to the terminal.
Can be used to analyze new protocols.'
  local 'i' 1
  graphIt '-----'
  repeat (size _ir_pulse_times) {
    local 'mark usecs' (at i _ir_pulse_times)
    local 'space usecs' (at (i + 1) _ir_pulse_times)
    graphIt (v 'mark usecs') (v 'space usecs')
    i += 2
    if ((v 'space usecs') == 0) {
      graphIt 'timing entries:' (i - 2)
      return 0
    }
  }
}

to '_getIRByte' position {
  local 'result' 0
  local 'i' position
  local 'bit' 1
  repeat 8 {
    if ((at i _ir_pulse_times) > 1000) {result = (result | bit)}
    bit = (bit << 1)
    i += 2
  }
  return result
}

to '_got32Bits' {
  return (and ((at 67 _ir_pulse_times) != 0) ((at 68 _ir_pulse_times) == 0))
}

to '_receiveIRFromDevice' deviceID {
  forever {
    '_captureIRMessage'
    if ('_got32Bits') {
      local 'id_lowByte' ('_getIRByte' 4 nil)
      local 'id_highByte' ('_getIRByte' 20 nil)
      if (and (id_highByte == (deviceID >> 8)) (id_lowByte == (deviceID & 255))) {
        return ('_getIRByte' 36 nil)
      }
    }
  }
}

to '_testIR' {
  forever {
    '_captureIRMessage'
    if ('_got32Bits') {
      comment 'Four byte message format:
<device low byte><device high byte><command><command, bit-inverted>'
      local 'b1' ('_getIRByte' 4 nil)
      local 'b2' ('_getIRByte' 20 nil)
      local 'b3' ('_getIRByte' 36 nil)
      local 'b4' ('_getIRByte' 52 nil)
      sayIt 'Device:' ((b2 << 8) | b1) 'code:' b3
    }
  }
}

to attachIR pin {
  _ir_pin = pin
}

to attachIRTransmitter pin {
  _ir_transmit_pin = pin
}

to interruptIRCapture {
  comment 'Capture IR pulses using interrupt-based pulse capture system.'
  atPut 'all' _ir_pulse_times 0
  comment 'Wait for IR signal -- this is the start of a new message.
Note: THe pin goes low when an IR signal is detected.'
  waitUntil (not (digitalReadOp _ir_pin))
  local 'start' (millisOp)
  '[sensors:captureStart]' _ir_pin
  comment 'Collect IR pulses until we receive over 67 pulses or until the timeout.'
  repeatUntil (or (('[sensors:captureCount]') > 67) ((millisSince start) > 200)) {
    waitMillis 5
  }
  local 'pulseData' ('[sensors:captureEnd]')
  comment 'If we got at least 67 pulses, copy their absolute values (durations) into _ir_pulse_times.'
  if ((size pulseData) >= 67) {
    for i 67 {
      atPut i _ir_pulse_times (absoluteValue (at i pulseData))
    }
  }
}

to ir_code_received {
  return ((receiveIR) >= 0)
}

to ir_last_code {
  return _ir_last_code
}

to receiveIR {
  forever {
    '_captureIRMessage'
    if ('_got32Bits') {
      local 'id_lowByte' ('_getIRByte' 4 nil)
      local 'id_highByte' ('_getIRByte' 20 nil)
      _ir_last_device = ((id_highByte << 8) | id_lowByte)
      _ir_last_code = ('_getIRByte' 36 nil)
      atPut 'all' _ir_pulse_times 0
      return _ir_last_code
    }
  }
}

to timerIRCapture {
  comment 'Capture IR pulses using the microseconds timer. (Original version, not currently used.)'
  atPut 'all' _ir_pulse_times 0
  local 'i' 1
  comment 'Wait for IR signal -- this is the start of a new message.
Note: THe pin goes low when an IR signal is detected.'
  waitUntil (not (digitalReadOp _ir_pin))
  local 'start' (microsOp)
  forever {
    comment 'Record the time until the end of the current IR pulse ("mark")'
    waitUntil (digitalReadOp _ir_pin)
    local 'end' (microsOp)
    atPut i _ir_pulse_times (end - start)
    i += 1
    start = end
    comment 'Record time until the start of the next IR pulse ("space")'
    repeatUntil (not (digitalReadOp _ir_pin)) {
      if (((microsOp) - start) > 5000) {
        comment 'No IR pulse for 5000 usecs means "end of message"'
        return 0
      }
    }
    local 'end' (microsOp)
    atPut i _ir_pulse_times (end - start)
    i += 1
    start = end
  }
}



module 'Distance (HC-SR04)' Input
author MicroBlocks
version 1 5 
tags sensor 'hc-sr04' distance ultrasound 
description 'Support for the HC-SR04 ultrasound distance sensor.

Originally written by Joan Guillén & Josep Ferràndiz.
Rewritten to use the new pulse capture mechanism.'
variables _sr04_last _sr04_misses 

  spec 'r' 'distance (cm)' 'distance (cm) trigger _ echo _' 'num num' 2 4
  spec 'r' 'sr04_distanceOnePin' 'distance (cm) pin _' 'num' 0
  spec 'r' '_sr04_getEchoData' '_getEchoData _ echo _' 'auto auto' 0 1

to '_sr04_getEchoData' trig echo {
  comment 'Output a 50 usec pulse on trigger pin to
start distance measurement.'
  digitalWriteOp trig false
  waitMicros 2
  digitalWriteOp trig true
  waitMicros 50
  digitalWriteOp trig false
  comment 'Capture the distance pulse. Width of
pulse is proportional to the distance.'
  '[sensors:captureStart]' echo
  local 'start' (millisOp)
  repeatUntil (('[sensors:captureCount]') >= 2) {
    if ((millisSince start) > 24) {exitLoop}
    waitMillis 1
  }
  return ('[sensors:captureEnd]')
}

to 'distance (cm)' trig echo {
  comment 'Take a distance measurement. Pulses will be two element
list if successful. If no echo detected it will have only one
element. In rare error cases the second item will be negative.'
  local 'pulses' ('_sr04_getEchoData' trig echo)
  if (and ((size pulses) >= 2) ((at 2 pulses) > 0)) {
    _sr04_misses = 0
    comment 'The divisor was determined empirically. It is
less than the expected 2 * 343 meter/sec.'
    _sr04_last = ((10 * (at 2 pulses)) / 583)
    return _sr04_last
  } else {
    comment 'No echo, probably because target is out of range.
To avoid short-term glitches, return the last distance
unless the are N misses in a row, then return 400.'
    _sr04_misses += 1
    return (ifExpression (_sr04_misses < 10) _sr04_last 400)
  }
}

to sr04_distanceOnePin pin {
  return ('distance (cm)' pin pin)
}



module TFT Output
author MicroBlocks
version 1 13 
description 'Draw graphics and write text on boards with a TFT display, such as the M5Stack, M5Stick, Citilab ED1 or (discontinued) IoT-Bus.'

  spec ' ' '[tft:clear]' 'clear TFT display'
  space
  spec ' ' '[tft:rect]' 'draw rectangle on TFT at x _ y _ width _ height _ color _ : filled _' 'num num num num color bool' 10 10 40 30 4774633 true
  spec ' ' '[tft:roundedRect]' 'draw rounded rectangle on TFT at x _ y _ width _ height _ radius _ color _ : filled _' 'num num num num num color bool' 10 10 40 30 8 4774633 true
  spec ' ' '[tft:circle]' 'draw circle on TFT at x _ y _ radius _ color _ : filled _' 'num num num color bool' 40 40 30 4774633 true
  spec ' ' '[tft:triangle]' 'draw triangle on TFT at x _ y _ , x _ y _ , x _ y _ color _ : filled _' 'num num num num num num color bool' 20 20 30 80 60 5 4774633 true
  spec ' ' '[tft:line]' 'draw line on TFT from x _ y _ to x _ y _ color _' 'num num num num color' 12 8 25 15 4849436
  spec ' ' 'tft_drawVector' 'draw vector x _ y _ angle _ length _ color _' 'num num num num color' 40 40 45 40 4849436
  space
  spec ' ' '[tft:unicode]' 'unicode _ on TFT at x _ y _ color _ : scale _ wrap _ : bg color _' 'str num num color num bool color' 'Hello World!' 5 5 16716113 1 true
  spec ' ' '[tft:text]' 'write _ on TFT at x _ y _ color _ : scale _ wrap _ : bg color _' 'str num num color num bool color' 'Hello World!' 5 5 16716113 2 true
  spec ' ' 'tft_drawText' 'draw text _ on TFT at x _ y _ color _ : scale _ : bg color _' 'str num num color num color' 'Line 1
Line 2' 50 20 16716113 2
  space
  spec ' ' '[tft:setPixel]' 'set TFT pixel x _ y _ to _' 'num num color' 10 10 16776509
  spec ' ' '[tft:pixelRow]' 'draw pixel row _ x _ y _ : bytesPerPixel _ : palette _' 'auto num num num str' 'aList' 0 0 4
  spec ' ' '[tft:drawBitmap]' 'draw bitmap _ palette _ on TFT at x _ y _' 'str str num num' 'aBitmap' 'a list of colors' 10 10
  space
  spec 'r' 'tft_colorSwatch' '_' 'color' 16718776
  spec 'r' 'makeColor' 'color r _ g _ b _ (0-255)' 'num num num' 0 100 100
  spec 'r' 'makeGray' 'gray _ %' 'num' 50
  spec 'r' 'randomColor' 'random color'
  space
  spec 'r' '[tft:getWidth]' 'TFT width'
  spec 'r' '[tft:getHeight]' 'TFT height'
  space
  spec ' ' '[tft:setBacklight]' 'set TFT backlight _ (0-10)' 'num' 10
  space
  spec ' ' '_deferMonochromeDisplayUpdates' '_defer monochrome display updates'
  spec ' ' '_resumeMonochromeDisplayUpdates' '_resume monochrome display updates'

to '_deferMonochromeDisplayUpdates' {
  '[tft:deferUpdates]'
}

to '_resumeMonochromeDisplayUpdates' {
  '[tft:resumeUpdates]'
}

to makeColor r g b {
  r = (maximum 0 (minimum r 255))
  g = (maximum 0 (minimum g 255))
  b = (maximum 0 (minimum b 255))
  return ((r << 16) | ((g << 8) | b))
}

to makeGray percent {
  gray = ((percent * 255) / 100)
  gray = (maximum 0 (minimum gray 255))
  return ((gray << 16) | ((gray << 8) | gray))
}

to randomColor {
  local 'n1' (random 100 200)
  local 'n2' (random 0 100)
  if (1 == (random 1 3)) {
    return ((n1 << 16) | (n2 << 8))
  } (1 == (random 1 2)) {
    return ((n2 << 16) | n1)
  } else {
    return ((n1 << 8) | n2)
  }
}

to tft_colorSwatch color {
  return color
}

to tft_drawText s x y color optionalScale optionalBGColor {
  s = ('[data:convertType]' s 'string')
  local 'scale' (argOrDefault 5 2)
  local 'bgColor' (argOrDefault 6 '')
  local 'lines' ('[data:split]' s ('[data:unicodeString]' 10))
  for line ('[data:split]' s ('[data:unicodeString]' 10)) {
    if (isType bgColor 'number') {
      '[tft:text]' line x y color scale false bgColor
    } else {
      '[tft:text]' line x y color scale false
    }
    y += (8 * scale)
  }
}

to tft_drawVector x y angle length color {
  local 'endX' (x + ((length * ('[misc:sin]' (100 * (angle + 90)))) >> 14))
  local 'endY' (y + ((length * ('[misc:sin]' (100 * angle))) >> 14))
  '[tft:line]' x y endX endY color
}



module 'LED Display' Output
author MicroBlocks
version 1 15 
choices led_imageMenu heart 'small heart' yes no happy sad confused angry asleep surprised silly fabulous meh 't-shirt' 'roller skate' duck house tortoise butterfly 'stick figure' ghost sword giraffe skull umbrella snake rabbit cow 'quarter note' 'eight note' pitchfork target triangle 'left triangle' 'chess board' diamond 'small diamond' square 'small square' scissors 
description 'Display primitives for the 5x5 LED display on the BBC micro:bit, Calliope mini and M5Atom Matrix. Boards with TFT displays (such as the Citilab ED1 or the M5Stack family) support these primitives with a simulated "fat pixel" display.
'
variables _stop_scrolling_text 

  spec ' ' '[display:mbDisplay]' 'display _' 'microbitDisplay' 15237440
  spec ' ' 'led_displayImage' 'display image _ : x _ y _' 'menu.led_imageMenu num num' 'happy' 1 1
  spec ' ' '[display:mbDisplayOff]' 'clear display'
  space
  spec ' ' '[display:mbPlot]' 'plot x _ y _' 'num num' 3 3
  spec ' ' '[display:mbUnplot]' 'unplot x _ y _' 'num num' 3 3
  space
  spec ' ' 'displayCharacter' 'display character _' 'str' 'A'
  spec ' ' 'scroll_text' 'scroll text _ : pausing _ ms' 'str num' 'HELLO ROSA!' 100
  spec ' ' 'stopScrollingText' 'stop scrolling'
  advanced
  spec ' ' 'set display color' 'set display color _' 'color'
  spec 'r' 'led_image' 'LED image #BR# _' 'microbitDisplay' 15237440
  space
  spec 'r' '_led_namedImage' '_led_namedImage _' 'menu.led_imageMenu' 'happy'
  spec 'r' '_led_imageData' '_led_imageData'

to '_led_imageData' {
  return 'heart:4685802,small heart:145728,yes:2269696,no:18157905,happy:15237440,sad:18284864,confused:22348096,angry:23036241,asleep:459616,surprised:4526090,silly:25984017,fabulous:15008639,meh:2236443,t-shirt:15154043,roller skate:11534104,duck:489702,house:10976708,tortoise:359872,butterfly:29332475,stick figure:18158564,ghost:23068334,sword:4657284,giraffe:10946627,skull:15171246,umbrella:6460398,snake:469859,rabbit:16104613,cow:4685361,quarter note:7573636,eight note:7590276,pitchfork:4357813,target:4681156,triangle:1026176,left triangle:32805985,chess board:11184810,diamond:4539716,small diamond:141440,square:33080895,small square:469440,scissors:20287859,'
}

to '_led_namedImage' name {
  local 'data' ('_led_imageData')
  local 'i' ('[data:find]' name data)
  if (i == -1) {
    comment 'Name not found'
    return 0
  }
  local 'start' (('[data:find]' ':' data i) + 1)
  local 'end' (('[data:find]' ',' data i) - 1)
  return ('[data:convertType]' ('[data:copyFromTo]' data start end) 'number')
}

to displayCharacter s {
  s = ('[data:join]' '' s)
  if ((size s) == 0) {
    '[display:mbDisplayOff]'
    return 0
  }
  '[display:mbDrawShape]' ('[display:mbShapeForLetter]' (at 1 s)) 1 1
}

to led_displayImage imageName optionalX optionalY {
  local 'image' imageName
  if (isType image 'string') {
    image = ('_led_namedImage' imageName)
  }
  '[display:mbDrawShape]' image (argOrDefault 2 1) (argOrDefault 3 1)
}

to led_image twentyFiveBitInt {
  comment 'An LED image is a 25-bit integer'
  return twentyFiveBitInt
}

to scroll_text text optionalDelay {
  text = ('[data:join]' '' text)
  local 'delay' 100
  if ((pushArgCount) > 1) {
    delay = optionalDelay
  }
  _stop_scrolling_text = (booleanConstant false)
  if ('Pico:ed' == (boardType)) {
    for position (((size text) * 6) + 18) {
      if _stop_scrolling_text {return 0}
      '[display:mbDisplayOff]'
      '[tft:text]' text (17 - position) 0 (colorSwatch 125 125 125 255) 1 true
      waitMillis (delay / 2)
    }
  } (or ('KidsIOT' == (boardType)) ('CodingBox' == (boardType))) {
    for position (((size text) * 6) + 21) {
      if _stop_scrolling_text {return 0}
      '[tft:deferUpdates]'
      '[tft:clear]'
      '[tft:text]' text (128 - (6 * position)) 6 (colorSwatch 255 255 255 255) 6 false
      '[tft:resumeUpdates]'
      waitMillis (delay / 8)
    }
  } else {
    for position (((size text) * 6) + 6) {
      if _stop_scrolling_text {return 0}
      for i (size text) {
        '[display:mbDrawShape]' ('[display:mbShapeForLetter]' ('[data:unicodeAt]' i text)) (((i * 6) + 2) - position) 1
      }
      waitMillis delay
    }
  }
}

to 'set display color' color {
  '[display:mbSetColor]' color
}

to stopScrollingText {
  _stop_scrolling_text = (booleanConstant true)
  waitMillis 10
  '[display:mbDisplayOff]'
}

