0

我的代码:

#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 和电源或仅 USB,则程序可以工作。如果我在插入 USB 和电源后拔下 USB,程序仍然可以工作!我已经尽可能多地尝试调试,但我不知道错误在哪里。电源的额定电压为 12V 2 安培以点亮 LED 灯条。

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

4

1 回答 1

-1

我认为您正在使用 arduino leonardo。

在设置的最开始尝试这个:

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

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

于 2014-09-22T12:07:31.883 回答