Send data to arduino as long as the button is being pressed

为君一笑 提交于 2019-12-12 04:18:46

问题


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;

回答1:


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

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.

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.




回答2:


You have to set the flag of bt.sendData to false when button is released which seems to be absent in your code.

It's like you open tap for water but forget to close the tap when you are finished. Hope it helps



来源:https://stackoverflow.com/questions/34830916/send-data-to-arduino-as-long-as-the-button-is-being-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!