Using stepper motor at constant speed and DHT22 in one scetch

Hi all,

I have got a problem concerning running a stepper motor at constant speed and reading the sensor value from a DHT22 in one scetch.
For the project I am working on the main goal is to run a stepper motor at a constant speed with a defined rpm. Since I expect the motor driver Pololu DRV8825 to heat up during operation a fan shall be activated if the air temperature above the board exceeds 50 °C. Therefore I measure the temperature with a DHT22 Temperature and Humidity Sensor. Moreover I want to send the temperature and board information via serial to my PC to track the operation stati in the serial monitor.

Now my problem ist that reading the DHT22 sensor value takes so long that the stepper motor is “stuttering” at lower rpm as set. The “stuttering” increases (rpm decreases) if the serial connection is used.
I fixed the problem by reading the DHT22 sensor value and sending data via serial only once per minute by using an if query with millis() to add the commands to the loop only once per minute.
Unfortunately that leads to that the motor stops once per minute for about a second, before it starts running again. This solution is okay, but I would prefer doing those tasks without the stepper motor stopping.

I would be glad to get any hints on how or if this issue can be fixed.
Thanks for all ideas.

I’m using the following equipment:

  • arduino uno rev.3
  • arduino protoshield
  • stepper motor (Nema 17 ST4209L1704-A)
  • gear (GP42-S1-4-SR)
  • stepper motor driver DRV8825
  • temperature and humidity sensor DHT22 (AM2302)
  • 2x red/greed LED
  • 2x standard LED
  • 2x switch
  • 1x button
  • 1x pc fan
  • 1x potentiometer
  • serial via usb

This is my actual coding

int redPin1=11;
int greenPin1=9 ;
int redPin2=5;
int greenPin2=10;
int FanPin=7;
int input_rpm=A0;
int max_rpm=80;
float poti_value=;
float rpm=map(poti_value,0,1023,0,max_rpm);

bool switched = true;      // switched is for saving the switch state of a button for de-activating the stepper motor
bool switcher=false;          // switched is for saving the switch state of a switcher for de-activating the stepper motor
bool Fan=false;                            
int ledPin = 13;                     
int ScrewSwitchPin = 8;
int Emergency_ShutdownPin=6;

float TempandHumidity;
float Temperature;
float Temp_Fan_crit=50;   //Temperature when Fan should be activated
float Humidity;

unsigned long previousMillis=0;
unsigned long currentMillis;
const long Measuring_frequency=60000; //time between 2 temperature and humidity measurements

int i=0;
int z=0;

//------Temperature and Humidity Sensor
#include "DHT.h"

#define DHTPIN 2

#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE); //use function for accessing data base

//------Stepper Motor

#include <AccelStepper.h>

AccelStepper stepper(AccelStepper::DRIVER, 12, 4);

int DIR_pin=4;      //Routing pin for direction control
float gear_ratio=3.93;
float step_angle=0.9;
float steps_per_revolution=360/0.9;
float n_eff=0.0;          //desired rotation frequency on gear-side
float steps_per_second=0.0; //steps per second corresponding to n_eff

//------settings LED

void setColor1(int redValue1, int greenValue1) {
analogWrite(redPin1, redValue1);
analogWrite(greenPin1, greenValue1);
void setColor2(int redValue2, int greenValue2){
analogWrite(redPin2, redValue2);
analogWrite(greenPin2, greenValue2);

void setup() {

//------Routing Switch for stepper motor and emergency shutdown

pinMode( ScrewSwitchPin, INPUT);
pinMode( ledPin, OUTPUT);
pinMode( Emergency_ShutdownPin, INPUT_PULLUP);

//------Temperature and humidity sensor

Serial.print("Temperature, humidity and Screw Status");   //header for serial monitor
Wire.begin();     //initiate wire library

dht.begin();    //initiate dht library

pinMode(redPin1, OUTPUT);
pinMode(redPin2, OUTPUT);
pinMode(greenPin1, OUTPUT);
pinMode(greenPin2, OUTPUT);

pinMode(FanPin, OUTPUT);

//------settings stepper motor
stepper.setMaxSpeed(2200.0);       //set max speed in steps/second (Angle of Stepper is 0.9° so there are 400 Steps per revolution) 2200 (84 rpm)!                                   
pinMode(DIR_pin, OUTPUT);
digitalWrite(DIR_pin, LOW);      //Direction pin low lets motor turn clockwise, direction pin high lets motor turn counter clockwise

digitalWrite(FanPin, LOW);

void loop() {


if (Fan==true){
digitalWrite(FanPin, HIGH);
else {digitalWrite(FanPin, LOW);}

//------Switch Stepper Motor-State

if (digitalRead(ScrewSwitchPin) == LOW)
else {switcher=true;

//------Button Emergency Shutdown - State

if (digitalRead(Emergency_ShutdownPin) == LOW)  // query if button is pressed 
if (switched == false) {        // if button is not pressed, query if switch was switched of
switched = false;              // if query reveals that the switch was switched off, than it remains switched off, since the button was not pressed.
else {                          // query if button is pressed 
if (switched == false) {        // if button is  pressed, query if switch was switched of
switched = true;              // if query reveals that the switch was switched off, than it is switched on, since the button was pressed.
switched = false;               // if query reveals that the switch was switched on, than it is switched off, since the button was pressed.
//------Switch Stepper Motor - Control
if (switcher==true&&switched==true) {           // if the switch is switched on, than the LED should shine
// LED and Serial Monitor
digitalWrite(ledPin, HIGH);

//Stepper Motor
n_eff=39.0;//set velocity to n_eff in rpm
else if (switcher==false||switched==false) {          // if the switch is switched on, than the LED should not shine
// LED
digitalWrite(ledPin, LOW);

//Stepper Motor
n_eff=0;//set velocity to 0 rpm (stop motor)

//Stepper Motor
steps_per_second=n_eff*gear_ratio*steps_per_revolution/60;//steps per second corresponding to n_eff (desired rotation frequency on gear-side)
 stepper.setSpeed(steps_per_second);          //set speed in steps/second (Angle of Stepper is 0.9° so there are 400 Steps per revolution)

//------Temperature and humidity sensor

 float temp_hum_val[2] = {0};       //Show data with 2 decimal places
// Reading temperature or humidity takes about 250 milliseconds!

if (currentMillis-previousMillis>Measuring_frequency) {

Humidity = dht.readHumidity();                      //read sensor data for Humidity
Temperature = dht.readTemperature();          //read sensor data for Temperature

//------Show data in serial monitor
if (!dht.readTempAndHumidity(temp_hum_val)) {       //If signal is received
Serial.print("Humidity: ");
Serial.print("Temperature: ");

Serial.print("Failed to get temperature and humidity value.");      //error if no signal is received
//------Temperature LED indication

if((Temperature>30&&Temperature<50)){         //if 30°C < T < 50°C LED with yellow light
setColor1(255, 255); //yellow color
Serial.print("Board heated!");

else if(Temperature>50&&Temperature<70){      //if T > 50°C LED with red light
Serial.print("Board overheated");
setColor1(255, 0); //Red color 

else if(Temperature>70){                          //if T > 70°C LED with red flashing light and emergency shut down of particle screw (stepper motor)
while(i<3){                                         //while loop unnecessary since general loop time reduced by sparing delay times. while loop may not be used, because then switch will not work while loop is running (for ca. 3 sek.).
switched = false;     //emergency shut down of particle screw (stepper motor)
Serial.print("Warning! Board overheat shut off");
setColor1(255, 0); //Red color flashing on
//digitalWrite(tonePin, HIGH); // Accoustig alarm on
setColor1(0, 0); //Red color flashing off
//digitalWrite(tonePin, LOW);// Accoustig alarm off
setColor1(255, 0); //Red color

else{                                                  //if T < 30°C LED with green light
setColor1(0, 255); //Green color
Serial.print("Board status ok");

else {}

I don't have one of those temperature sensors but I suspect the problem is the way the library executes the readTempAndHumidity() function. I guess that it initiates a read and then waits for the result.

It is probably possible to start a reading and come back later for the result - that way neither action would take an appreciable amount of time and should not interfere with the motor.

Using a stepper motor with 200 steps per revolution would leave more time between steps for other activities.

Another option may be to use simpler temperature sensor such as an LM35 - or just leave the fan running all the time.


DS18B12 may be faster to read.

This is the problem with using single-purpose libraries. :roll_eyes:

Thanks for your replies.
I suppose you're right concerning the readTempAndHumidity() function.
I will do some research on that, but I'm going to test a simpler temperature sensor first. That seems to be the easiest solution to me.
If nothing else works I could run the fan all the time, but controlling the temperature would be a better solution. The motor is expected to run about 8-9 h at a time since it suports a mini plant in a lab.

Thanks for your suggestions so far. :slight_smile:

When using the DS18B20 make sure you use the library in asynchronous mode, as otherwise it will block and wait (up to half a second or so depending on settings) for the sensor to complete its conversion and respond.