I am currently working on an arduino project where i'm using two ds18b20 Temp Sensors and a Nema 17 Stepper motor in one single sketch. So i have made a sketch for the ds18b20 Temp Sensors and another one for the Nema 17 Stepper motor and both works perfectly! However, When i tried to combine them in one single sketch, the nema 17 won't run anymore! After a bit of brainstorming i figure out that i am using Delay() and Delaymicroseconds() which they block the arduino from receiving any interrupt that's why i moved on to the micros() trying the arduino multitasking however i got the same problem happening every time. Then i went to a debug mode in order to figure out which command is blocking the stepper motor from running and i discovered that the Serial.print() and Serial.println() are slowing down the motor. PS: i am using a TB6560 Driver and a 1/8 step mode. and here are the sketch:
#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;
}
}