【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);
}
相关推荐
Dr.kangder5 小时前
嵌入式面试总结(十五)——异常处理
单片机·面试·职场和发展·系统架构·嵌入式
ACP广源盛139246256737 小时前
蚂蚁百灵 Ling‑3.0‑flash 开源 + 昇腾 0‑Day 原生适配@ACP#GSV9001E 在国产算力矩阵中的机会与落地场景
大数据·人工智能·分布式·单片机·嵌入式硬件
振南的单片机世界9 小时前
SysTick硬核拆解:既是HAL_Delay的“心跳”,也是RTOS的“节拍器”
arm开发·stm32·单片机·嵌入式硬件
Lzh编程小栈10 小时前
【嵌入式底层】SPI超透彻详解:通信原理、四线结构、四种模式、寄存器底层 + 面试全集
c语言·stm32·单片机·面试·职场和发展
水果里面有苹果10 小时前
28-DRV8825PWPR步进电机驱动器
单片机
Dr.kangder14 小时前
嵌入式面试总结(十九)——内存泄露
单片机·算法·面试·职场和发展·架构·硬件架构
萌新小白YXY16 小时前
SAE J1587/SAE J1708 协议笔记
笔记·单片机·嵌入式硬件
嘉子的秃头日记16 小时前
机械革命“自动修复”无法修复你的电脑
stm32·单片机·电脑
森旺电子17 小时前
电子负载使用介绍
单片机·嵌入式硬件
大爱编程♡17 小时前
STM32-SPI
stm32·单片机·嵌入式硬件