Reading 2 sensors and controlling a stepper motor is not functioning properly

I have a project (using an Arduino UNO) that involves reading data from 2 sensors (using ADS1115 ADC) and start/stop control for a stepper motor (controlled via Pulse and Direction pins) but whenever the function printvoltstopc() runs it slows down the motor so much to the point where the motor is not useful, and to troubleshoot the problem I commented out printvoltstopc() and then the motor runs fine so I think the problem here is that printvoltstopc() is too slow any suggestions on how I can make this work, here is my code:

#include <Wire.h>
#include <Adafruit_ADS1X15.h>

const int pulsePin = 9;
const int dirPin = 8;
bool startCollecting = false;
int motorSpeed = 0; 

Adafruit_ADS1115 _ADC;

void motorPulse(int speed)
{
  digitalWrite(pulsePin, HIGH);
  delayMicroseconds(speed); 
  digitalWrite(pulsePin, LOW);
  delayMicroseconds(50);  
}

void printVoltsToPc()
{
  int16_t adc0 = _ADC.readADC_SingleEnded(0);  // Read from A0
  int16_t adc2 = _ADC.readADC_SingleEnded(2);  // Read from A2
  float volts0 = _ADC.computeVolts(adc0);
  float volts2 = _ADC.computeVolts(adc2);

  Serial.print(volts0);
  Serial.print(",");
  Serial.println(volts2);
}

void recieveCommand()
{
  if (Serial.available()) 
  {
    String command = Serial.readStringUntil('\0');
    if (command.startsWith("R")) 
    { 
      motorSpeed = command.substring(2).toInt();
      digitalWrite(dirPin, HIGH);
      startCollecting = true;
    } 
    else if (command.startsWith("L"))
    { 
      motorSpeed = command.substring(2).toInt();
      digitalWrite(dirPin, LOW);
      startCollecting = true;
    } 
    else if (command == "S")
    {
      startCollecting = false;
      digitalWrite(pulsePin, LOW);
    }
  }
}

void setup() 
{
  pinMode(pulsePin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  Serial.begin(9600);
  _ADC.begin();
}

void loop() 
{
  recieveCommand();
  if (startCollecting) 
  {
    printVoltsToPc();
    motorPulse(motorSpeed);
  }
}
 

Your printVoltsToPc() basically does two things - reads the ADC and sends the data over the serial link. Your serial speed is set to a very small value of 9600, try at least 115200 and if no problem increase as much as possible. Also, instead of printing this data constantly, you can only do it at a certain time period, for example, every 50 milliseconds. According to the data sheet, this ADC has to be programmed at what speed to operate with the possibilities being from 8sps to 860sps. Make sure it runs at 860sps because 8sps is very slow and even 860sps may not be fast enough but it depends on your needs. If you don't necessarily need 16 bits, the Arduino UNO has a much faster built-in 10 bit ADC that runs at ~10ksps (10000sps) by default but could be speed up a lot more at the cost of losing accuracy.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.