How Do I Make My Program in Qt Continually Send A String to My Arduino?

前端 未结 3 1271
忘了有多久
忘了有多久 2020-12-04 04:20

I am having trouble trying to get my program to continually send the string \"move 200\" while I hold down a button. I have the button set to auto repeat howeve

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 04:53

    I suggest you expand on your design somewhat:

    • have a repeating QTimer with an interval depending on the rate you want to send the string at, and the timer to the function that sends the string
    • connect the button's pressed signal to start the timer
    • connect the button's released signal to stop the timer

    Events are sent only once, thus the handlers will be executed only once, if you want to keep on repeating it, you will have to use a timer or some other event driven way. You cannot use a loop as that would block the GUI thread and your application will stop responding.

    Sure, you could use the button's auto repeat, and there is the option to adjust the triggering and repeating intervals, but a solution that puts a line between logic and GUI is better. You should really rely on the GUI for storing data or controlling the internal logic. The GUI should only be a front end.

    You need more work on the serial port though. If you are going to use it from the GUI thread, you will have to use the non-blocking API. Which will require to extend on your implementation a little bit more. There is a good example on how to achieve that, you only need to modify it to simply enable the sending of further payloads once the previous payload has been successfully sent. In pseudo code:

    on button press
      start timer
    on button release
      stop timer
    onTimeout
      if (can send) 
        send
        can send = false
    onBytesWritten
      accumulate bytes
      if (payload is completed)
        can send = true
        reset payload byte counter
    

    Of course, you will also have to do some error checking, you can't just expect it to work. The example linked contains basic error handling.

提交回复
热议问题