官术网_书友最值得收藏!

  • 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:

  1. 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()
  2. In the Python file, import the usual packages to use Kivys.
  3. Import the Clock and Plyer packages.
  4. In the class for the rule, define a class to standby the accelerometer.
  5. Define the method to start to retrieve data from the accelerometer.
  6. 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.

There's more…

Also, the plyer package allows you to interact with the compass and the GPS of the mobile device using a similar procedure. In the case of the compass, it is very easy to change. The change in the code is the word gyroscope for compass and acceleration for orientation.

See also

To get more details about widgets, see the recipes in Chapter 4, Widgets, and if you want to run the code in a mobile device, see Chapter 9, Kivy for Mobile Devices.

主站蜘蛛池模板: 准格尔旗| 嘉祥县| 新营市| 湖南省| 老河口市| 山丹县| 汶川县| 洞头县| 萨迦县| 大冶市| 绥滨县| 天峨县| 石柱| 舒城县| 馆陶县| 甘孜县| 南木林县| 常山县| 津市市| 个旧市| 定边县| 葵青区| 余江县| 新化县| 石泉县| 岗巴县| 成安县| 河西区| 崇义县| 福鼎市| 宜昌市| 江安县| 军事| 登封市| 平乐县| 三原县| 巴青县| 南投市| 天等县| 永修县| 辽宁省|