触摸屏

例程讲解

该例程在 例程的xxx ,可以在 CanMV IDE 中打开

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import touchscreen as ts
import lcd
import image

lcd.init()
ts.init()

img = image.Image()
img.draw_string(100, 0, "Please touch the screen", color=(0, 0, 255), scale=1)

status_last = ts.STATUS_IDLE
x_last = 0
y_last = 0

while True:
    (status, x, y) = ts.read()
    if status_last != status:
        print(status, x, y)
        status_last = status

    if status == ts.STATUS_MOVE:
        img.draw_line(x_last, y_last, x, y)
    elif status == ts.STATUS_PRESS:
        img.draw_line(x, y, x, y)
    lcd.display(img)
    x_last = x
    y_last = y

实验准备

  1. 野火K210 AI视觉相机 连接到 CanMV IDE

  2. 执行程序

运行结果

1.运行之后,可以看到屏幕上显示蓝色字体 Please touch the screen

野火logo

2.在触摸屏上触摸屏幕,在屏幕上写

野火logo

3.在串口终端上可以看到对应的打印信息

野火logo

程序分析

1
2
import touchscreen as ts
import lcd, image
  • import touchscreen as ts :导入触摸屏模块,并为其指定别名 ts

  • import lcd :导入用于控制LCD显示屏模块

  • import image :导入用于处理图像模块

1
2
lcd.init()
ts.init()
  • lcd.init() :初始化LCD显示屏。

  • ts.init() : 初始化触摸屏。

1
2
img = image.Image()
img.draw_string(100, 0, "Please touch the screen", color=(0, 0, 255), scale=1)
  • img = image.Image() :创建一个新的图像对象。

  • img.draw_string(100, 0, "Please touch the screen", color=(0, 0, 255), scale=1) : 在图像上绘制文本”Please touch the screen”,颜色为蓝色,坐标为(100, 0),缩放比例为1。

1
2
3
status_last = ts.STATUS_IDLE
x_last = 0
y_last = 0
  • status_last = ts.STATUS_IDLE :初始化上一个触摸状态为空闲。

  • x_last = 0 :初始化上一个触摸点的x坐标为0。

  • y_last = 0 :初始化上一个触摸点的y坐标为0。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
while True:
    (status, x, y) = ts.read()
    if status_last != status:
        print(status, x, y)
        status_last = status

    if status == ts.STATUS_MOVE:
        img.draw_line(x_last, y_last, x, y)
    elif status == ts.STATUS_PRESS:
        img.draw_line(x, y, x, y)
    lcd.display(img)
    x_last = x
    y_last = y
  • while True: :开始一个无限循环。

  • (status, x, y) = ts.read() :读取触摸屏的状态、x坐标和y坐标。

  • if status_last != status : 如果触摸状态发生变化,打印新的状态和坐标。

  • status_last = status :更新上一个触摸状态。

  • if status == ts.STATUS_MOVE : 如果触摸状态为移动。

  • img.draw_line(x_last, y_last, x, y) : 在图像上从上一个点到当前点绘制一条线。

  • elif status == ts.STATUS_PRESS : 如果触摸状态为按下。

  • img.draw_line(x, y, x, y) :在图像上绘制一个点(实际上是一条长度为0的线)

  • lcd.display(img) :显示图像

  • x_last = x : 更新上一个触摸点的x坐标。

  • y_last = y 更新上一个触摸点的y坐标。