我目前正在开展一个arduino项目,我在一个草图中使用两个ds18b20温度传感器和一个Nema 17步进电机。 因此,我为ds18b20温度传感器制作了草图,为Nema 17步进电机制作了另一个,两者都完美无缺! 然而,当我试图将它们组合在一个草图中时,nema 17将不再运行!经过一段头脑风暴后,我发现我正在使用Delay()和Delaymicroseconds()它们阻止arduino接收任何中断,这就是为什么我继续使用micros()尝试arduino多任务但是我遇到了同样的问题时间。 然后我进入调试模式,以确定哪个命令阻止步进电机运行,我发现Serial.print()和Serial.println()正在减慢电机速度。 PS:我正在使用TB6560驱动程序和1/8步进模式。 这是草图:
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float Celsius1 = 0;
float Celsius2 = 0;
const int SensorDuration = 500;
unsigned long TempcurrentMillis = 0;
unsigned long TemppreviousLedMillis = 0;
const int stepPin = 9;
const int dirPin = 8;
int motor = 3;
int msg;
const int offDuration = 150;
const int interval = 50;
unsigned long currentMillis = 0;
unsigned long previousLedMillis = 0;
byte targetLedState = HIGH;
void setup() {
sensors.begin();
// Sets the two pins as Outputs
Serial.begin(9600);
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(motor, OUTPUT);
digitalWrite(motor, LOW);
digitalWrite(dirPin, HIGH);
}
void loop() {
currentMillis = micros();
TempcurrentMillis = micros();
GetTemp();
RunMotor();
}
void RunMotor() {
if (targetLedState == LOW) {
if ((unsigned long) currentMillis - previousLedMillis >= interval) {
targetLedState = HIGH;
digitalWrite(stepPin, HIGH);
previousLedMillis += interval;
}
}
else {
if ((unsigned long) currentMillis - previousLedMillis >= offDuration) {
targetLedState = LOW;
digitalWrite(stepPin, LOW);
previousLedMillis += offDuration;
}
}
}
void GetTemp() {
if ((unsigned long) TempcurrentMillis - TemppreviousLedMillis >= SensorDuration) {
targetLedState = HIGH;
sensors.requestTemperatures();
Celsius1 = sensors.getTempCByIndex(0);
Celsius2 = sensors.getTempCByIndex(1);
Serial.print("T");
Serial.println(Celsius1);
Serial.print("H");
Serial.println(Celsius2);
TemppreviousLedMillis += SensorDuration;
}
}