SoftwareSerial问题。仅在电源插孔上时

时间:2014-08-18 00:18:38

标签: bluetooth serial-port arduino software-serial

我的代码:

#include <SoftwareSerial.h>
SoftwareSerial bluetooth(2,3);
// Output
int redPin = 6;   // Red LED, 
int grnPin = 11;  // Green LED,
int bluPin = 5;  // Blue LED, 

// Color arrays
int black[3]  = { 0, 0, 0 };
int white[3]  = { 100, 100, 100 };
int red[3]    = { 100, 0, 0 };
int green[3]  = { 0, 100, 0 };
int blue[3]   = { 0, 0, 100 };
int yellow[3] = { 40, 95, 0 };
int dimWhite[3] = { 30, 30, 30 };
// etc.

// Set initial color
int redVal = black[0];
int grnVal = black[1]; 
int bluVal = black[2];

int wait = 10;      // 10ms internal crossFade delay; increase for slower fades
int hold = 0;       // Optional hold when a color is complete, before the next crossFade
int r = 0;
int g = 0;
int b = 0;
char mode = '\0';
// Initialize color variables
int prevR = redVal;
int prevG = grnVal;
int prevB = bluVal;

// Set up the LED outputs
void setup()
{
  pinMode(redPin, OUTPUT);   // sets the pins as output
  pinMode(grnPin, OUTPUT);   
  pinMode(bluPin, OUTPUT); 

 Serial.begin(9600);
 delay(1000);
 bluetooth.begin(115200);
 delay(100);
 bluetooth.print("$$$");
 delay(100);
 bluetooth.println("U,9600,N");
 bluetooth.begin(9600);
 delay(100);
 analogWrite(redPin, 0); 
 analogWrite(grnPin, 0);      
 analogWrite(bluPin, 0); 
 Serial.println("Bluetooth initiated.");
}

void printHEX() {
  Serial.print(r, HEX);
  Serial.print(g, HEX);
  Serial.println(b, HEX);
  bluetooth.print(r, HEX);
  bluetooth.print(g, HEX);
  bluetooth.println(b, HEX);
}

// Main program: list the order of crossfades
void loop()
{
  //Read from bluetooth and write to usb serial
  while(bluetooth.available())
  {
    if(mode == '\0') {
      mode = (char)bluetooth.read();
    }
    if(mode == 'c'){
      int r1 = bluetooth.parseInt();
      int g1 = bluetooth.parseInt();
      int b1 = bluetooth.parseInt();
      if (bluetooth.read() == '\n') {
        if(r1 != r || g1 != g || b1 != b) {
          r = r1;
          g = g1;
          b = b1;
          analogWrite(redPin, r);
          analogWrite(grnPin, g);      
          analogWrite(bluPin, b); 
          printHEX();
          mode = '\0';
        } else {
          printHEX();
          mode = '\0';
        }
      }
  } else if(mode == 'p') {
    if (bluetooth.read() == '\n') {
      printHEX();
      mode = '\0';
    }
  }
}

  //Read from usb serial to bluetooth
  if(Serial.available())
  {
    char toSend = (char)Serial.read();
    bluetooth.print(toSend);
  }
}

如果我运行此代码,一切都很好。直到我把它插入电源而没有别的。

如果我将其插入电源,程序无法启动(无蓝牙响应)。如果我将它插入usb和power或usb,程序可以工作。如果我在插入USB和电源后拔掉usb,程序仍可正常工作!我尽可能多地尝试调试,但我不知道错误在哪里。电源额定电压为12V 2安培,以点亮LED灯条。

更新:我发现如果我在开机后按下重置按钮,一切都会开始工作。有没有办法在启动时自动重置arduino ???

1 个答案:

答案 0 :(得分:-1)

我认为你正在使用arduino leonardo。

在设置的最初阶段尝试:

while(!Serial){}
while(!bluetooth){}

arduino leonardo在一段时间后准备串口,可能会引起一些问题。