how do I set up an ultrasonic sensor in pros?

on http://pros.cs.purdue.edu/tutorials/ultrasonic/ it says that in main.h you should put Ultrasonic sonar; and in init you should put sonar = ultrasonicInit(orange_port_number, yellow_port_number); Here’s my main.h

#ifndef MAIN_H_
#define MAIN_H_
#include <API.h>
#ifdef __cplusplus
extern "C" {
#endif
#define claw_piston_pin 2
#define knocker_piston_pin 3
#define left_motor_a 1
#define left_motor_b 2
#define left_motor_c 3
#define right_motor_a 8
#define right_motor_b 9
#define right_motor_c 10
#define arm_motor_a 4
#define arm_motor_b 5
#define arm_motor_c 6
#define arm_motor_d 7
#define left_sonar_orange = 6
#define left_sonar_yellow = 7
#define right_sonar_orange = 5
#define right_sonar_yellow = 4
Ultrasonic left_sonar;
Ultrasonic right_sonar;

void autonomous();
void initializeIO();
void initialize();
void operatorControl();
#ifdef __cplusplus
}
#endif
#endif

and here’s my init.h


#include "main.h"


void initializeIO() {
}


void initialize() {
  pinMode(claw_piston_pin, OUTPUT);
  pinMode(knocker_piston_pin, OUTPUT);
  digitalWrite(knocker_piston_pin, LOW);
  digitalWrite(claw_piston_pin, LOW);
  left_sonar = ultrasonicInit(left_sonar_orange, left_sonar_yellow);
  right_sonar = ultrasonicInit(left_sonar_orange, left_sonar_yellow);
}

and when I try to compile, it gives an error at


left_sonar = ultrasonicInit(left_sonar_orange, left_sonar_yellow); 

and


right_sonar = ultrasonicInit(left_sonar_orange, left_sonar_yellow);

that reads “expected expression before ‘=’ token” What did I do wrong and how do I fix it?

When you write


#define right_sonar_yellow = 4

, everything after the identifier (


right_sonar_yellow

) is inserted wherever the preprocessor sees


right_sonar_yellow

. So after the preprocessor does those replacements, your code looks like


left_sonar = ultrasonicInit(= 6, = 7);
right_sonar = ultrasonicInit(= 5, = 4);

which isn’t valid C syntax.

Also, your code may not work the way you expect, when you


#include "main.h"

, all of the contents of


main.h

are copied into your C file. This means that each time you compile,


Ultrasonic left_sonar

and


Ultrasonic right_sonar

will refer to different pieces of memory (so you’ll initialize an ultrasonic in


initialize

but it won’t be seen in auto.c or opcontrol.c). To get around this, put your Ultrasonic variable definitions in something like init.c and use


extern Ultrasonic left_ultrasonic;

to let other files know that


left_ultrasonic

is defined somewhere else.

e.g.
init.c:


Ultrasonic left_sonar;
Ultrasonic right_sonar;

void initialize() {
    left_sonar = ultrasonicInit(orange, yellow);
    // etc. like you had
}

main.h:


#define left_sonar_orange 6
#define left_sonar_yellow 7
#define right_sonar_orange 5
#define right_sonar_yellow 4
extern Ultrasonic left_sonar;
extern Ultrasonic right_sonar;

Great, THANKS!