只要按下按钮就将数据发送到arduino [英] Send data to arduino as long as the button is being pressed

查看:18
本文介绍了只要按下按钮就将数据发送到arduino的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只要按下一个按钮,我就想将数据发送到 arduino mega 2560,当该按钮被释放时,它将停止发送信息.我将 onTouchListener 与 MotionEvent 常量一起使用.但是当我在我的手机上运行它时,我按下了按钮,它会发送数据,即使过了一会儿我松开了它.我哪里错了?

I want to send data to an arduino mega 2560 as long as a button is being pressed and when that button is released it will stop sending informations. I am using onTouchListener with MotionEvent constants. But when I run this on my phone I press the button and it sends data even though after a while I release it. Where am I being wrong here?

    switch (v.getId()) {

    case R.id.left1: // check what button is pressed

        while(event.getAction() == MotionEvent.ACTION_DOWN) {

            bt.sendData("1"); // while pressing the button it sends data

        } 
        if(event.getAction() == MotionEvent.ACTION_UP) {

            // when it stops, do nothing

        }

        break;

    }

    return true;

推荐答案

您的问题是在无限循环 while(event.getAction() == MotionEvent.ACTION_DOWN) 中,您在收到第一个时开始活动.

Your problem is in infinite loop while(event.getAction() == MotionEvent.ACTION_DOWN) that you start upon receiving the first event.

OnTouchListener 为每个分派查看的事件调用,down 和 up 是单独的事件,事件在处理时不会改变.

OnTouchListener is called for each event that is dispatched to view, down and up are separate events and event does not change while being processed.

所以要解决您的问题 - 您需要从单独的线程发送数据.在 ACTION_DOWN 上启动它,还有一个标志,将在 ACTION_UP 上修改以指示线程退出.

So to solve your problem - you need to send data from a separate thread. Start it on ACTION_DOWN and also have a flag that will be modified on ACTION_UP to indicate thread to exit.

这篇关于只要按下按钮就将数据发送到arduino的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆