【Arduino32】PWM控制直流电机速度

硬件准备

震动传感器:1个

红黄绿LED灯:各一个

旋钮电位器:1个

直流电机:1个

1K电阻:1个

220欧电阻:3个

杜邦线:若干

硬件连线

【Arduino32】PWM控制直流电机速度_第1张图片

软件程序

const int analogInPin = A0;//PWM输入引脚
const int analogOutPin = 3;//PWM输出引脚
const int vibPin = 4;//震动传感器

const int RLed = 10;
const int YLed = 9;
const int GLed = 8;

int sensorValue = 0;//电位器电压值
int outputValue = 0;//模拟量输出装(PWM)
int vibValue = 0;//震动传感器值

void setup() {
  Serial.begin(9600);
  pinMode(analogOutPin,OUTPUT);
  pinMode(RLed,OUTPUT);
  pinMode(YLed,OUTPUT);
  pinMode(GLed,OUTPUT);
}

void loop() {
  //读取模拟值
  sensorValue = analogRead(analogInPin);
  vibValue = digitalRead(vibPin);
  //变换数据区间
  outputValue = map(sensorValue, 0, 1023, 0, 255);

  //判断速度,相应的灯亮
  if (outputValue < 110) {
    digitalWrite(GLed, HIGH);
    digitalWrite(YLed, LOW);
    digitalWrite(RLed, LOW);
    Serial.println("绿灯亮");
    delay(1000);
  } else if (outputValue < 180) {
    digitalWrite(GLed, LOW);
    digitalWrite(YLed, HIGH);
    digitalWrite(RLed, LOW);
    Serial.println("黄灯亮");
    delay(1000);
  } else if (outputValue < 255) {
    digitalWrite(GLed, LOW);
    digitalWrite(YLed, LOW);
    digitalWrite(RLed, HIGH);
    Serial.println("红灯亮");
    delay(1000);
  }else{
    Serial.println("都不亮");
  }

  Serial.print("震动值:");
  Serial.println(vibValue);

  //输出对应的PWM值
  if (vibValue == 1) {
    analogWrite(analogOutPin, outputValue);
    Serial.println("电机转动");
  }
  else {
    analogWrite(analogOutPin, 0);
  }


  //打印结果到串口监视器
  Serial.print("sensor = ");
  Serial.println(sensorValue);
  Serial.print("output = ");
  Serial.println(outputValue);
  Serial.println("");

  delay(2);
}

你可能感兴趣的:(单片机)