【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);
}
相关推荐
FreakStudio1 天前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
✎ ﹏梦醒͜ღ҉繁华落℘6 天前
单片机基础知识---stm32单片机的优先级
stm32·单片机·mongodb
zd8451015006 天前
RS485 总线详解
单片机·嵌入式硬件
✎ ﹏梦醒͜ღ҉繁华落℘6 天前
编程基础 --高内聚,低耦合
c语言·单片机
科芯创展6 天前
1A,1MHz,30VIN,XZ4115,降压恒流LED驱动芯片
单片机·嵌入式硬件
集芯微电科技有限公司6 天前
四通道2A输出集成功率电感降压模块专为紧凑型方案设计
人工智能·单片机·嵌入式硬件·生成对抗网络·计算机外设
踏着七彩祥云的小丑6 天前
嵌入式测试学习第 37 天:异常场景测试:断电、拔插、干扰、非法指令
单片机·嵌入式硬件·学习
意法半导体STM326 天前
【官方原创】如何为STM32CubeMX2配置Visual Studio Code配置方案
vscode·stm32·单片机·嵌入式硬件·策略模式·stm32cubemx·嵌入式开发
雾削木6 天前
B语言经典教程现代化重构
java·前端·stm32·单片机·嵌入式硬件
Hello-FPGA6 天前
Camera Link 与 CoaXPress 技术对比 如何选择你的相机接口
单片机·嵌入式硬件