arduino uno串口通讯

时间:2016-01-30 16:03:24

标签: arduino arduino-uno

`const int ledPin = 9;      // the pin that the LED is attached to

 void setup() 
  {
   // initialize the serial communication:
  Serial.begin(9600);
  // initialize the ledPin as an output:
  pinMode(ledPin, OUTPUT);  
   }

 void loop() {
 byte brightness;

  // check if data has been sent from the computer:
  if (Serial.available()) {
  // read the most recent byte (which will be from 0 to 255):
   brightness = Serial.read();

   Serial.println(brightness);
   // set the brightness of the LED:
   analogWrite(ledPin, brightness);
   }
   }`

我用我的电路板尝试了上面的代码

该代码从串行监视器获取值并调整LED的亮度。但相反,LED卡在HIGH状态,亮度不随输入而改变

也是Serial.println(亮度)在串行监视器上打印的亮度值; 它显示了一些不可读的垃圾字符和符号。 我该怎么办?

2 个答案:

答案 0 :(得分:0)

我认为问题在于您要将ASCII数据从计算机发送到arduino,但是您只读取一个字节。而不是Serial.read(),请使用Serial.readString()(并在之前设置超时Serial.setTimeout())。然后使用atoi()将数字字符串转换为int值。然后检查结果值是否在0到255之间(钳制它)。这使用PWM将此值写入输出(即使用analogWrite())。

查看arduino的Serial类的文档:有一个函数parseInt()可以实现魔术:-) 以下是文档:https://www.arduino.cc/en/Serial/ParseInt

答案 1 :(得分:0)

虽然我不是专家,但我将问题排序如下:

const int ledPin = 12;

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int brightness;
  if (Serial.available()) {
    analogWrite(ledPin, Serial.parseInt());
  }
}

注意:代码不是由我制作的,它是对arduino IDE中预先存在的示例的调整

我做的改变是替换Serial.read();使用Serial.parseInt();

另外请记住,LED具有一定的正向电压,因此根据您使用的LED和整体设置,调光会有所不同。在我的情况下,最小的值是140使用草帽0.5W LED。

祝你好运!