1
我正在從Qt發送「R」字符到Arduino
並等待該R,使LED在Arduino上閃爍。但它不起作用...將Arduino連接到Qt
我認爲這可能是一個waitFotBytesWritten或ASCI的問題...
N.B:任何信號是好的;不需要成爲字符。
我的Qt代碼:
QSerialPort serial;
serial.setPortName("PORT_NAME");
serial.open(QIODevice::ReadWrite);
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
if (serial.isOpen() && serial.isWritable())
{
qDebug() << "Ready..." << endl;
serial.write("R");
if(serial.flush())
{
qDebug() << "ok" << endl;
}
qDebug() <<"value sent!!! "<< endl;
serial.close();
}
我的Arduino代碼
int led = 13;
void setup()
{
pinMode(led, OUTPUT);
}
void loop()
{
if (Serial.read() == 'R') //blink on 5sec
{
digitalWrite(led, HIGH);
delay(5000);
digitalWrite(led, LOW);
}
else //Blink on and off 1 sec,1sec
{
digitalWrite(led, HIGH);
delay(1000);
digitalWrite(led, LOW);
delay(1000);
}
}
Qt的輸出說:
Manufacturer: "Arduino (www.arduino.cc)"
Busy: false
Ready...
ok
value sent!!!
任何幫助會感激
下面是完整的代碼:
的Qt:
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QString>
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSerialPortInfo info("usbmodem621");
// Check info of the port
qDebug() << "Name : " << info.portName();
qDebug() << "Manufacturer: " << info.manufacturer(); //if showing manufacturer, means Qstring &name is good
qDebug() << "Busy: " << info.isBusy() << endl;
// Initialize Serial
QSerialPort serial;
serial.setPortName("usbmodem621");
serial.open(QIODevice::ReadWrite);
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
if (serial.isOpen() && serial.isWritable())
{
qDebug() << "Is open : " << serial.isOpen() << endl;
qDebug() << "Is writable : " << serial.isWritable() << endl;
QString string("R\n");
QByteArray ba("R\n");
serial.write(ba);
if (serial.bytesToWrite() > 0)
{
serial.flush();
if(serial.waitForBytesWritten(1000))
{
qDebug() << "data has been send" << endl;
}
}
if(serial.flush())
{
qDebug() << "ok" << endl;
}
qDebug() <<"value sent!!! "<< endl;
serial.close();
}
else
{
qDebug() << "An error occured" << endl;
}
return 0;
}
的Arduino:
int led = 13;
void setup()
{
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop()
{
if (Serial.available() > 0)
{
digitalWrite(led, HIGH);
delay(5000);
if(Serial.read() == 'R')
{
digitalWrite(led, LOW);
delay(1000);
}
}
else
{
digitalWrite(led, HIGH);
delay(1000);
digitalWrite(led, LOW);
delay(1000);
}
}
那麼接收端究竟發生了什麼,你從閱讀中得到了什麼?另外,你如何等待閱讀?這不是完整的代碼。 – lpapp
那麼,Arduino領導的閃爍1秒(他處於第二狀態),但從未進入第一狀態。 我正在等待'if(serial.Read())'條件讀取... 誰在循環... – gr3g
這是一個等待信號的好方法嗎? 我只想發送一個信號,而不是一個字符 – gr3g