I am working on a Micromouse and it has three sensors. Call it S1,S2 and S3. For now, I have to use S1. The idea is this S1 controls the left motor and S3, the right motor. S2 will detect wall in the front.

Anyways, I am trying to write a code in C for the dsPIC30F4011 MCU which would continuously read Sensor values and after reading two consecutive values, it will compare the two values. Read happens every 0.1ms.

The Flow of the Code is as follows:

// Initialize timer for generating interrupts every 0.1ms
// Pseudo-Code
void __attribute__((interrupt, auto_psv)) _T1Interrupt(void)
  int count = 0;      //Read Sensor1 and store value in Sensor1Value
  Sensor1Value = Sensor1;
  int i = count++;

  //Now this is part where I am lost :(
  // I want to do this
* diff_S1Value = Sensor1Value(i = n+1) - Sensor1Value(i = n); // n is in the mathematical sense, like n+1 is 2 and n is 1

  // So I want to compare the new value with the previous sensor value
  if (diff_S1Value != 0) // Checks if the difference is zero
  { //Duty Cycle of PWM that controls the Speed of the Motor
    Sensor1Value = Sensor1Value(i = n+2) + or - diff_S1Value;
    PDC1 = float k/Sensor1Value;

So if you look at the line with the *, how do I compare two sensor values in real-time every 0.1ms ? Let me know if one wants to more info!!


1 Answer 1


You need to store the previous value somewhere, e.g. in a static:

void ...
  static int previous_value = 0;
  int current_value = Sensor1;
  diff = current_value - previous_value;
  previous_value = current_value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.