Ultrasonic ranger & Encoder interference


I want to grab data from this Ultrasonic Ranger and from this encoder. and sent the data trough serial to MAX MSP. I got both of them working separately but I am running in to issues when I try to grab both inputs.

I think the encoder is not registering the right direction and or is skipping steps.

I tried messing around with this library that is supposed to allow for coroutines but I couldn’t even get the examples to work properly.

Here is the code I have at the moment (without the coroutine stuff):

unsigned long echo = 0;
int ultraSoundSignal = 7;

int tempValue = 0;
int sensorValue0 = 0;
int sensorValue1 = 0;

int n = LOW;
int encoderA = 3;
int encoderB = 4;
int encoderPos = 0;
int encoderALast = LOW;

void setup() {
  pinMode (ultraSoundSignal, OUTPUT);
  pinMode (encoderA, INPUT);
  pinMode (encoderB, INPUT);

void loop() {
  encode ();
  tempValue = ping ();

  // Keeps Ultrasonic data withing range
  if (tempValue < 8000) {
    if (tempValue < 0) {
      tempValue = 9999;
    sensorValue0 = tempValue;

  sensorValue1 = encoderPos;
  Serial.print(" ");

//Grabs data from ultrasonic ranger V1.0
unsigned long ping () {
  pinMode (ultraSoundSignal, OUTPUT);
  digitalWrite (ultraSoundSignal, LOW);
  digitalWrite (ultraSoundSignal, HIGH);
  digitalWrite (ultraSoundSignal, LOW);
  pinMode (ultraSoundSignal, INPUT);
  digitalWrite (ultraSoundSignal, HIGH);

  echo = pulseIn(ultraSoundSignal, HIGH);
  return echo;

//Grabs data from rotary encoder
void encode () {
  n = digitalRead(encoderA);
  if ((encoderALast == LOW) && (n == HIGH)) {
    if (digitalRead (encoderB) == HIGH) {
      if (encoderPos < 0) {
          encoderPos = 1000;
    } else {
      if (encoderPos > 1000) {
          encoderPos = 0;
  encoderALast = n;

The encoder gives strange values back, but if you comment out the line with tempValue = ping (); it works fine. The Ultrasonic Ranger seems to be working fine either way.

Can anybody point me in the right direction of doing this sort of thing?

While pulseIn() is waiting for a return echo, nothing else happens. You will miss encoder steps, if the encoder is changing with any speed at all.

You really should be using interrupts to read the encoder, and you really should be using NewPing to read the ultrasonic sensor.

Thanks, working great now using the interrupts. I was unable to get NewPing working with the Grove sensor though, but it does what it needs to be doing so I am not complaining.