【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);
}
相关推荐
etcix1 小时前
implement copy file content to clipboard on Windows
windows·stm32·单片机
谱写秋天1 小时前
在STM32F103上进行FreeRTOS移植和配置(STM32CubeIDE)
c语言·stm32·单片机·freertos
globbo4 小时前
【嵌入式STM32】I2C总结
单片机·嵌入式硬件
玖別ԅ(¯﹃¯ԅ)5 小时前
SysTick寄存器(嘀嗒定时器实现延时)
stm32·单片机·嵌入式硬件
Blossom.1186 小时前
把 AI 推理塞进「 8 位 MCU 」——0.5 KB RAM 跑通关键词唤醒的魔幻之旅
人工智能·笔记·单片机·嵌入式硬件·深度学习·机器学习·搜索引擎
桃源学社(接毕设)8 小时前
基于人工智能和物联网融合跌倒监控系统(LW+源码+讲解+部署)
人工智能·python·单片机·yolov8
玖別ԅ(¯﹃¯ԅ)8 小时前
PID学习笔记6-倒立摆的实现
笔记·stm32·单片机
清风66666613 小时前
基于51单片机的手机蓝牙控制8位LED灯亮灭设计
单片机·嵌入式硬件·智能手机·毕业设计·51单片机·课程设计
anghost15021 小时前
基于单片机的超市储物柜设计
单片机·嵌入式硬件·超市储物柜设计
尘似鹤1 天前
旋钮键盘项目---foc讲解(开环)
单片机·嵌入式硬件