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

硬件准备

震动传感器:1个

红黄绿LED灯:各一个

旋钮电位器:1个

直流电机:1个

1K电阻:1个

220欧电阻:3个

杜邦线:若干

硬件连线

软件程序

cpp 复制代码
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);
}
相关推荐
科芯创展3 小时前
XZ5129:单节锂电池供电36V升压LED恒流驱动芯片设计解析
stm32·单片机·嵌入式硬件
✎ ﹏梦醒͜ღ҉繁华落℘4 小时前
单片机基础知识 --keil文件乱码,如何转换编码方式?
单片机·嵌入式硬件
创界工坊工作室4 小时前
41-基于STC89C52的避障循迹小车
stm32·单片机·嵌入式硬件·51单片机·proteus
weixin_464078075 小时前
开关电源,反激中rcd电路快速选型
单片机·嵌入式硬件
深圳永探电子5 小时前
磁吸连接器吸上却不充电?从对位、触点到线缆的排查方法
单片机·嵌入式硬件·硬件工程·连接器·弹簧针
sramdram5 小时前
基于32位MCU微控制器的电动扳手控制方案
单片机·嵌入式硬件·微控制器·32位mcu·mcu微控制器
youcans_6 小时前
【嵌入式软件AI编程】21. 整理通用提示词模板
stm32·单片机·嵌入式·ai编程
远翔调光芯片^138287988726 小时前
单节锂电自行车车灯如何实现稳定亮度?FP6291 升压 + IP2332N 充电管理方案分享
人工智能·单片机·嵌入式硬件·物联网·智能家居
逐步前行7 小时前
嵌入式图形库-LVGL v9.6-基础概念
单片机·嵌入式硬件
潜创微科技8 小时前
CH591:成本优化的青稞 RISC-V 无线 MCU
c语言·单片机·risc-v·低延迟·沁恒·青稞