ATMEGA328P-PU需要上传,但无法通过Serial进行通信

问题描述 投票:2回答:1

我使用独立式ATMEGA328P-PU从mpu6050获取加速度计数据,并以波特率115200发送到串行,并将数据发送到另一个串口(到HC05蓝牙模块)。但问题是,有时我面临一个奇怪的场景,atmega328p-pu接受程序通过usb到ttl转换器,但控制器不能通过串口发送任何数据。 hc05 bluetooth和usb serial中的串行数据都是空白的。任何人都知道任何可能的原因。我使用以下代码。

我已经尝试检查veroboard上的连接,但这种情况有时会修复,有时会重新出现。

#include <SoftwareSerial.h>
#include "I2Cdev.h" // include the I2Cdev library
#include "MPU6050.h" // include the accelerometer library

SoftwareSerial bt(3,4); /* (Rx,Tx) */
MPU6050 accelgyro;  // set device to MPU6050
int16_t ax, ay, az, gx, gy, gz;  // define accel as ax,ay,az
int baselineX = 0;

void setup() {
  Wire.begin();      // join I2C bus
  Serial.begin(115200);    //  initialize serial communication
  bt.begin(9600);
  accelgyro.initialize();  // initialize the accelerometer
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
  baselineX = gz;
}
void loop() {
  // read measurements from device
  sendAverage();
}

long sendAverage() {
  long totalX = 0, totalY = 0, totalZ = 0;
  long X, Y, Z;
  for (int i = 0; i < 20; i++) {
    accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
    totalX = totalX + ax;
    totalY = totalY + ay;
    totalZ = totalZ + az;
    delay(1);
  }
  X = 500+ ((totalX/20)*0.05);
  Y = 500+ ((totalY/20)*0.05);
  Z = 500+ ((totalZ/20)*0.05);

  Serial.print(X);Serial.print(";");
  Serial.print(Y);Serial.print(";");
  Serial.println(Z);

  bt.print(X);bt.print(";");
  bt.print(Y);bt.print(";");
  bt.print(Z);bt.print("#");
}

arduino arduino-uno usbserial mpu6050 hc-05
1个回答
0
投票

您正在使用SoftwareSerial类来更改串行传输的引脚,但在setup()中,您没有设置两个引脚的属性。如果你想通过SoftwareSerial类传输,请添加pinMode

SoftwareSerial bt =  SoftwareSerial(rxPin, txPin);

void setup()  {
  // define pin modes for tx, rx of SoftwareSerial:
  pinMode(3, INPUT);
  pinMode(4, OUTPUT);
  // set the data rate for the SoftwareSerial port
  bt.begin(9600);
}

有关完整参考,请参阅SoftwareSerial.begin documentation page

© www.soinside.com 2019 - 2024. All rights reserved.