- Kivy Cookbook
- Hugo Solis
- 890字
- 2021-07-16 20:39:56
Working with the accelerometer
Nowadays, it is common that mobile devices are equipped with an accelerometer. Thereby, it is relevant to consider this input to develop fancy apps. The accelerometer is one kind of event that is considered as a no-touch event because it has neither start nor an end, it is always providing information.
Getting ready
In this recipe, we will use the Kv language for the design of the widgets, so, again, you will need to be familiar with the Kv language. Also, this recipe will use the common button and label widgets for reference. Obviously, to get more benefit, a device with an accelerometer is useful to run the code.
It is necessary to install a package for the use of the accelerometer in any mobile device; there is a way to deal with every specific device, but we do not have to reinvent the wheel. Let's use a Plyer
package, which is an effort from many of the Kivy developers. To install the package from the shell, use:
$ sudo pip plyer install
Here where we are using pip
to install the Plyer
package, if you do not have pip
installed in your computer, see the recipe Using Kivy Garden in Chapter 1, Kivy and the Kv language.
How to do it…
To complete this recipe, follow these steps:
- In the KV file, define the four labels and the button:
<Accel>: Label: id: label1 pos: 150, 300 text: 'X: ' Label: id: label2 pos: 150, 250 text: 'Y: ' Label: id: label3 pos: 150, 200 text: 'Z: ' Label: id: status pos: 150, 150 text: '' Button: id: button1 pos: 150, 50 text: 'Start' on_press: root.pressed1()
- In the Python file, import the usual packages to use Kivys.
- Import the
Clock
andPlyer
packages. - In the class for the rule, define a class to standby the accelerometer.
- Define the method to start to retrieve data from the accelerometer.
- Define the method when the button is pressed:
from kivy.app import App from kivy.properties import ObjectProperty from kivy.uix.widget import Widget from kivy.clock import Clock from plyer import accelerometer class Accel(Widget): def __init__(self): super(Accel, self).__init__() self.sensorEnabled = False def get_acceleration(self, dt): val = accelerometer.acceleration self.ids.label1.text = "X: " + str(val[0]) self.ids.label2.text = "Y: " + str(val[1]) self.ids.label3.text = "Z: " + str(val[2]) def pressed1(self): try: if not self.sensorEnabled: accelerometer.enable() Clock.schedule_interval(self.get_acceleration, 1 / 20.) self.sensorEnabled = True self.ids.button1.text = "Stop" else: accelerometer.disable() Clock.unschedule(self.get_acceleration) self.sensorEnabled = False self.ids.button1.text = "Start" except NotImplementedError: import traceback; traceback.print_exc() self.ids.status.text =\ "Accelerometer is not supported for your platform" class e3App(App): def build(self): return Accel() if __name__ == '__main__': e3App().run()
How it works…
First, review the KV file. Note that the first line is the name of the rule, similar to the class in the Python file. Included in the next lines are the definitions of the four labels that we will use, so note the text of the label with the ID status. It will likely be blank, but it will be visible only when we modify this field from the Python code.
In the Python code, the first three lines are usual to import kivy
and the widgets. The fourth line:
from kivy.clock import Clock
This will import the clock, which is used to get the accelerometer value in a time lap because, as we already said, this input is continuously providing data. The fifth line:
from plyer import accelerometer
This is importing the package plyer
, which is the one that makes it possible to retrieve the data from an iOS or Android device. The sixth line:
class Accel(Widget):
This is the line where the class for the rule starts. Its name must be the same as the Kivy rule. The seventh, eighth, and ninth lines are:
def __init__(self): super(Accel, self).__init__() self.sensorEnabled = False
These define the method that initializes the class and put in standby the accelerometer to be used later. The tenth, eleventh, twelfth, thirteenth, and fourteenth lines are:
def get_acceleration(self, dt): val = accelerometer.acceleration self.ids.label1.text = "X: " + str(val[0]) self.ids.label2.text = "Y: " + str(val[1]) self.ids.label3.text = "Z: " + str(val[2])
These lines are used to retrieve the data of the accelerometer and will modify the text of the first three labels with the data of the acceleration. Now, look at the fifteenth line:
def pressed1(self):
This is where we define the method performed when the button is pressed. In the sixteenth line, we start a try
sentence to start getting data from the accelerometer. In the seventeenth line, it is shown that if the accelerometer is disabled, enable it or vice versa. The eighteenth line is:
Clock.schedule_interval(self.get_acceleration, 1 / 20.)
In this line, we do the acquisition of the acceleration in time intervals. The acceleration is acquired by calling the get_acceleration
method. The next class is usual to display our Kivy interface.
- Flutter開(kāi)發(fā)實(shí)戰(zhàn)詳解
- Android Jetpack開(kāi)發(fā):原理解析與應(yīng)用實(shí)戰(zhàn)
- vSphere High Performance Cookbook
- Java Web基礎(chǔ)與實(shí)例教程(第2版·微課版)
- Getting Started with Hazelcast(Second Edition)
- Instant Nancy Web Development
- Python深度學(xué)習(xí)原理、算法與案例
- Java SE實(shí)踐教程
- 匯編語(yǔ)言編程基礎(chǔ):基于LoongArch
- 機(jī)器學(xué)習(xí)微積分一本通(Python版)
- App Inventor少兒趣味編程動(dòng)手做
- Visual C++從入門(mén)到精通(第2版)
- Python硬件編程實(shí)戰(zhàn)
- Android編程權(quán)威指南(第4版)
- UML基礎(chǔ)與Rose建模實(shí)用教程(第三版)