#include<Wire.h>
#include<SparkFunSX1509.h>
// Define the pin numbers for SX1509
constint SX1509_ADDR = 0x3E; // I2C address of SX1509
constint N_SLEEP_PIN = 15;
constint EN_PIN = 8; // EN/IN1 pin for PWM input
constint PH_PIN = 7; // PH/IN2 pin for direction input
constint N_FAULT_PIN = 9;
SX1509 ioExpander;
voidsetup() {
// Initialize I2C communication
Wire.begin();
// Initialize SX1509
if (!ioExpander.begin(SX1509_ADDR)) {
Serial.println("SX1509 not found!");
while (1);
}
// Set pins as outputs
ioExpander.pinMode(N_SLEEP_PIN, OUTPUT);
ioExpander.pinMode(EN_PIN, ANALOG_OUTPUT); // EN/IN1 pin for PWM
ioExpander.pinMode(PH_PIN, OUTPUT); // PH/IN2 pin for direction
ioExpander.pinMode(N_FAULT_PIN, INPUT);
ioExpander.digitalWrite(N_SLEEP_PIN, HIGH);//nsleep to high
delay(1000);
ioExpander.digitalWrite(N_SLEEP_PIN, LOW);
delayMicroseconds(30); // Added a delay to meet the wake-up pulse requirement
ioExpander.digitalWrite(N_SLEEP_PIN, HIGH);//set to high
delay(1000);
}
voidloop() {
// Rotate the motor forward for 2 seconds, then stop for 2 seconds, then reverse for 2 seconds
rotateForward();
delay(2000);
stopMotor();
delay(2000);
rotateReverse();
delay(2000);
stopMotor();
delay(2000);
}
voidrotateForward() {
// Set direction forward
ioExpander.digitalWrite(PH_PIN, HIGH);
// Set PWM for forward rotation
ioExpander.analogWrite(EN_PIN, 255);
}
voidrotateReverse() {
// Set direction reverse
ioExpander.digitalWrite(PH_PIN, LOW);
// Set PWM for reverse rotation
ioExpander.analogWrite(EN_PIN, 255);
}
voidstopMotor() {
// Set PWM to 0 to stop the motor
ioExpander.analogWrite(EN_PIN, 0);
}