我正在从 Qt 向 Arduino 发送“R”字符
并等待该 R,以使 Arduino 上的 LED 闪烁。但它不起作用...
我认为可能是 waitFotBytesWritten 或 ASCI 的问题...
注意:任何信号都很好;不需要是字符。
我的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!!!
任何帮助将不胜感激
这是完整的代码:
数量:
#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;
}
阿杜诺:
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);
}
}