# Code Scanner

## Import KOI 2 Library

```python
from future import *
from koi2 import KOI2
```

## Serial Initialization

```python
koi = KOI2(tx, rx)
```

Initializes the serial connection to KOI.

Parameters:

tx: TX Pin, use P2 for Robotbit EDU

rx: RX Pin, use P12 for Robotbit EDU

## Select Code Scan Mode

```
koi.setModel(256)
```

Sets the KOI mode to Code Scanning.

## Select Code Type

```
koi.scanCodeSwitchType(type)
```

Select code type.

Parameters:

type: 0 for QR Code, 1 for Barcode

## Get Code Attributes

```
koi.xywh[0]
```

Returns data for the detected code.

Parameters:&#x20;

data: The type of data to return.

<table><thead><tr><th width="324">data</th><th>Meaning</th></tr></thead><tbody><tr><td>0</td><td>X coordinates</td></tr><tr><td>1</td><td>Y coordinates</td></tr><tr><td>2</td><td>Width of code</td></tr><tr><td>3</td><td>Height of code</td></tr></tbody></table>

## Get Code Value

```
koi.strVal
```

Returns the value of the code scanned.

## Sample Program: Code Scanner

```
from future import *
from koi2 import KOI2



koi = KOI2('P2', 'P12')
koi.setModel(256)
sleep(15)
koi.direction(2)
koi.mirror(0)
screen.sync = 0
while True:
  koi.read_from_uart()
  if sensor.btnValue('a'):
    koi.scanCodeSwitchType(0)
  if sensor.btnValue('b'):
    koi.scanCodeSwitchType(1)
  screen.fill((0, 0, 0))
  screen.text(koi.strVal,5,10,2,(255, 255, 255))
  screen.text(koi.xywh[0],5,40,1,(255, 255, 255))
  screen.text(koi.xywh[1],5,60,1,(255, 255, 255))
  screen.text(koi.xywh[2],5,80,1,(255, 255, 255))
  screen.text(koi.xywh[3],5,100,1,(255, 255, 255))
  screen.refresh()

```

{% file src="<https://686851495-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7Bv9xBdKh3R9w6Vp7asd%2Fuploads%2FC3slURUcYFQ1l7PITOCy%2FCode%20Scanner.py?alt=media&token=9959134a-9bab-41b3-8e2e-c01ea2e2986f>" %}
