版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lucky9322/article/details/83118111
adb
连接树莓派,运行程序控制舵机旋转。
效果图
连接舵机
- 树莓派5V电源线连接舵机的中间的红线(不同的舵机正负极连接线可能不一样,需要正确连接,否则可能烧毁舵机)
- 树莓派GND连接舵机棕色的负极
- 树莓派 PWM输出线 连接舵机橙色的线
核心代码
在子线程中动态改变脉冲
private Runnable mChangePWMRunnable = new Runnable() {
@Override
public void run() {
// Exit Runnable if the port is already closed
if (mPwm == null) {
Log.w(TAG, "Stopping runnable since mPwm is null");
return;
}
// Change the duration of the active PWM pulse, but keep it between the minimum and
// maximum limits.
// The direction of the change depends on the mIsPulseIncreasing variable, so the pulse
// will bounce from MIN to MAX.
if (mIsPulseIncreasing) {
mActivePulseDuration += PULSE_CHANGE_PER_STEP_MS;
} else {
mActivePulseDuration -= PULSE_CHANGE_PER_STEP_MS;
}
// Bounce mActivePulseDuration back from the limits
if (mActivePulseDuration > MAX_ACTIVE_PULSE_DURATION_MS) {
mActivePulseDuration = MAX_ACTIVE_PULSE_DURATION_MS;
mIsPulseIncreasing = !mIsPulseIncreasing;
} else if (mActivePulseDuration < MIN_ACTIVE_PULSE_DURATION_MS) {
mActivePulseDuration = MIN_ACTIVE_PULSE_DURATION_MS;
mIsPulseIncreasing = !mIsPulseIncreasing;
}
Log.d(TAG, "Changing PWM active pulse duration to " + mActivePulseDuration + " ms");
try {
// Duty cycle is the percentage of active (on) pulse over the total duration of the
// PWM pulse
mPwm.setPwmDutyCycle(100 * mActivePulseDuration / PULSE_PERIOD_MS);
// Reschedule the same runnable in {@link #INTERVAL_BETWEEN_STEPS_MS} milliseconds
mHandler.postDelayed(this, INTERVAL_BETWEEN_STEPS_MS);
} catch (IOException e) {
Log.e(TAG, "Error on PeripheralIO API", e);
}
}
};
获取连接PWM的引脚端口,不同设备对应的端口名称不一样注意区分
public class BoardDefaults {
private static final String DEVICE_RPI3 = "rpi3";
private static final String DEVICE_IMX6UL_PICO = "imx6ul_pico";
private static final String DEVICE_IMX7D_PICO = "imx7d_pico";
/**
* Return the preferred PWM port for each board.
*/
public static String getPWMPort() {
switch (Build.DEVICE) {
case DEVICE_RPI3:
return "PWM0";
case DEVICE_IMX6UL_PICO:
return "PWM7";
case DEVICE_IMX7D_PICO:
return "PWM1";
default:
throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE);
}
}
}
初始化设置并开启子线程
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "Starting PwmActivity");
try {
String pinName = BoardDefaults.getPWMPort();
mActivePulseDuration = MIN_ACTIVE_PULSE_DURATION_MS;
mPwm = PeripheralManager.getInstance().openPwm(pinName);
// Always set frequency and initial duty cycle before enabling PWM
mPwm.setPwmFrequencyHz(1000 / PULSE_PERIOD_MS);
mPwm.setPwmDutyCycle(mActivePulseDuration);
mPwm.setEnabled(true);
// Post a Runnable that continuously change PWM pulse width, effectively changing the
// servo position
Log.d(TAG, "Start changing PWM pulse");
mHandler.post(mChangePWMRunnable);
} catch (IOException e) {
Log.e(TAG, "Error on PeripheralIO API", e);
}
}