Read barcodes with the trigger button
What this example shows
The scanner stays in its default manual mode: press the trigger button on the
board, and the code it reads prints in the shell. The example only polls
readBarcode(); the button starts each scan.
Wire the controller's pin 5 (TX) to the scanner's RX and its pin 4 (RX) to
the scanner's TX, plus 3V3 and GND, or change tx and rx to match your
wiring. Switch the scanner to UART first by scanning the POR232 configuration
barcode.
The example code
from machine import UART
from de2120 import DE2120
import time
# Adjust tx and rx to match the pins you have wired on your board.
scanner = DE2120(tx=5, rx=4)
if not scanner.begin():
print("DE2120 not detected. Check wiring.")
raise SystemExit
print("DE2120 ready. Press the button on the scanner to read a barcode.")
while True:
barcode = scanner.readBarcode()
if barcode:
print("Scanned:", barcode)
time.sleep_ms(20)
🔗Open the complete example
Examples/de2120-readBarcode.py at commit 848e03e
Expected result:
DE2120 ready. Press the button on the scanner to read a barcode.
Each code you scan then prints as Scanned: followed by the code's contents.
When the scanner does not answer, the example prints
DE2120 not detected. Check wiring. and stops.
Functions used
DE2120(uart=None, tx=None, rx=None, uart_id=1)returns DE2120Creates the scanner object. Pass a UART you made yourself as uart, or pass tx and rx pin numbers and the module creates UART(uart_id) at 9600 baud on them. With neither, it raises ValueError.
ReturnsThe scanner object.
Parameters
| Type | Name | Description |
|---|---|---|
UART | uart | A ready machine.UART object. Optional. |
int | tx | The controller pin that transmits, wired to the scanner's RX. The example uses 5. |
int | rx | The controller pin that receives, wired to the scanner's TX. The example uses 4. |
int | uart_id | Which UART to create when you pass tx and rx. 1 by default. |
scanner.begin()returns boolChecks that the scanner answers. It sets the UART to 9600 baud and asks for the firmware version. Without an answer it retries at 115200 baud, tells the scanner to switch to 9600 baud, and asks again. On success it empties the receive buffer.
ReturnsTrue when the scanner answered, False when it did not.
scanner.readBarcode()returns str or NoneCollects the bytes waiting from the scanner. A scan ends with a carriage return; when one arrives, the function returns the code without it. Call it repeatedly in a loop. A single code keeps at most 256 bytes.
ReturnsThe scanned code, or None when no complete scan has arrived yet.
Putting it together
DE2120(tx=5, rx=4) sets up the UART, and begin() makes sure the scanner is
there and running at 9600 baud. The loop then calls readBarcode() every
20 ms. It returns None until a whole code has arrived, so the if barcode:
check prints each code once.
To read without pressing the button, see Read barcodes continuously.