现在我需要随机从0到80给100个数字#include<math.h> #define PWM 9 #define STBY 8 #define Leftmotor0 3 #define Leftmotor1 4 void setup() { pinMode(PWM, OUTPUT); // 设置模拟输出引脚为输出模式 digitalWrite(STBY,HIGH); pinMode(Leftmotor0,OUTPUT); pinMode(Leftmotor1,OUTPUT); } void xuanzhuan()//电机转 { digitalWrite(Leftmotor0,HIGH); digitalWrite(Leftmotor1,LOW); } void ting() { digitalWrite(Leftmotor0,LOW);//电机停 digitalWrite(Leftmotor1,LOW); } float genhao(float a) { float result; result=sqrt(a); return(result); } void loop() { // 模拟量数值,可根据需要调整(范围为 0 - 1023) float a=80; float b,c; b=genhao(a*a); c=(1-b/80)*255; analogWrite(PWM, c); // 使用PWM输出模拟信号 xuanzhuan(); }这是我的代码我想要通过随机的数字的大小来控制电机的转动,数字越小转动的速度越大
时间: 2024-01-22 21:02:23 浏览: 40
好的,您可以在 `loop()` 函数中使用 `random()` 函数生成随机数,并将其传递给 `genhao()` 函数进行计算。然后,您可以将计算结果用于控制电机的转速。以下是修改后的代码示例:
```c++
#include <math.h>
#define PWM 9
#define STBY 8
#define Leftmotor0 3
#define Leftmotor1 4
void setup() {
pinMode(PWM, OUTPUT); // 设置模拟输出引脚为输出模式
digitalWrite(STBY, HIGH);
pinMode(Leftmotor0, OUTPUT);
pinMode(Leftmotor1, OUTPUT);
}
void xuanzhuan() { // 电机转
digitalWrite(Leftmotor0, HIGH);
digitalWrite(Leftmotor1, LOW);
}
void ting() { // 电机停
digitalWrite(Leftmotor0, LOW);
digitalWrite(Leftmotor1, LOW);
}
float genhao(float a) {
float result;
result = sqrt(a);
return (result);
}
void loop() {
for (int i = 0; i < 100; i++) { // 生成 100 个随机数并控制电机
float a = random(0, 81); // 生成随机数
float b, c;
b = genhao(a * a);
c = (1 - b / 80) * 255;
analogWrite(PWM, c); // 使用 PWM 输出模拟信号
xuanzhuan(); // 电机转
delay(1000); // 持续时间
ting(); // 电机停
delay(1000); // 停止时间
}
}
```
在这个示例中,我们使用 `for` 循环生成 100 个随机数,并将它们传递给 `genhao()` 函数进行计算。然后,我们将计算结果传递给 `analogWrite()` 函数以控制电机的转速。我们还添加了一些 `delay()` 函数来控制电机的运行时间和停止时间。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)