コンテンツにスキップ

Servo

PWMで、サーバを操作する。

ソース

 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.gclue.myapplication;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.android.things.pio.PeripheralManagerService;
import com.google.android.things.pio.Pwm;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    Servo mServo;
    private final static String TAG = "THINGS";
    private Pwm mPwm;
    private static final String PWM_NAME = "PWM1";
    private Handler mHandler = new Handler();
    private static final int INTERVAL_BETWEEN_BLINKS_MS = 1000;
    private int freqValue = 100;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PeripheralManagerService manager = new PeripheralManagerService();
        try {
           mPwm = manager.openPwm(PWM_NAME);
           initializePwm(mPwm);
           mHandler.post(mBlinkRunnable);
        } catch (IOException e) {
            Log.e(TAG, "Unable to access PWM", e);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mPwm != null) {
            try {
                mPwm.close();
                mPwm = null;
            } catch (IOException e) {
                Log.e(TAG, "Unable to close PWM", e);
            }
        }
    }

    public void initializePwm(Pwm pwm) throws IOException {
        pwm.setPwmFrequencyHz(120);
        pwm.setPwmDutyCycle(25);

        pwm.setEnabled(true);
    }

    private Runnable mBlinkRunnable = new Runnable() {
        @Override
        public void run() {

            if (mPwm == null) {
                return;
            }

            try {
                freqValue+=10;
                if(freqValue > 300) {
                    freqValue = 100;
                }
                mPwm.setPwmFrequencyHz(freqValue);
                mHandler.postDelayed(mBlinkRunnable, INTERVAL_BETWEEN_BLINKS_MS);
            } catch (IOException e) {
                Log.e(TAG, "Error on PWM", e);
            }
        }
    };

}