#include "cy_pdl.h"
#include "cybsp.h"
// Define the servo control pins
#define SERVO_1_PIN P2_0
#define SERVO_2_PIN P2_1
#define SERVO_3_PIN P2_2
#define SERVO_4_PIN P2_3
// Define the touch sensor pin
#define TOUCH_SENSOR_PIN P0_0
// Define ultrasonic sensor pins
#define TRIG_PIN P0_1
#define ECHO_PIN P0_2
// Function prototypes
void init_peripherals(void);
void move_servos(uint8_t position);
float measure_distance(void);
int main(void)
{
// Initialize the device and board peripherals
cybsp_init();
__enable_irq(); // Enable global interrupts
// Initialize peripherals
init_peripherals();
while (1)
{
// Check touch sensor state
if (cyhal_gpio_read(TOUCH_SENSOR_PIN) == 1) // Assuming active high
{
move_servos(90); // Move servos to 90 degrees on touch
}
else
{
move_servos(0); // Move servos to 0 degrees
}
// Measure distance using ultrasonic sensor
float distance = measure_distance();
// You can use the distance value for further actions (like obstacle avoidance)
Cy_SysLib_Delay(100); // Delay to avoid rapid toggling
}
}
void init_peripherals(void)
{
// Initialize servo pins as outputs
cyhal_gpio_init(SERVO_1_PIN, CYHAL_GPIO_DIR_OUTPUT, CYHAL_GPIO_DRIVE_STRONG, 0);
cyhal_gpio_init(SERVO_2_PIN, CYHAL_GPIO_DIR_OUTPUT, CYHAL_GPIO_DRIVE_STRONG, 0);
cyhal_gpio_init(SERVO_3_PIN, CYHAL_GPIO_DIR_OUTPUT, CYHAL_GPIO_DRIVE_STRONG, 0);
cyhal_gpio_init(SERVO_4_PIN, CYHAL_GPIO_DIR_OUTPUT, CYHAL_GPIO_DRIVE_STRONG, 0);
// Initialize touch sensor pin as input
cyhal_gpio_init(TOUCH_SENSOR_PIN, CYHAL_GPIO_DIR_INPUT, CYHAL_GPIO_DRIVE_PULLUP, 0);
// Initialize ultrasonic sensor pins
cyhal_gpio_init(TRIG_PIN, CYHAL_GPIO_DIR_OUTPUT, CYHAL_GPIO_DRIVE_STRONG, 0);
cyhal_gpio_init(ECHO_PIN, CYHAL_GPIO_DIR_INPUT, CYHAL_GPIO_DRIVE_NONE, 0);
}
void move_servos(uint8_t position)
{
// Assume position is in degrees and map it to PWM for servos
uint32_t pulse_width = 500 + (position * 10); // Adjust mapping as needed
// Control each servo
cyhal_pwm_set_duty_cycle(SERVO_1_PIN, pulse_width, 20); // Assuming 20 ms period
cyhal_pwm_set_duty_cycle(SERVO_2_PIN, pulse_width, 20);
cyhal_pwm_set_duty_cycle(SERVO_3_PIN, pulse_width, 20);
cyhal_pwm_set_duty_cycle(SERVO_4_PIN, pulse_width, 20);
}
float measure_distance(void)
{
// Send a 10us pulse to the ultrasonic trigger pin
cyhal_gpio_write(TRIG_PIN, 1);
Cy_SysLib_DelayUs(10);
cyhal_gpio_write(TRIG_PIN, 0);
// Measure pulse width on echo pin
uint32_t start_time = Cy_SysTick_GetValue();
while (cyhal_gpio_read(ECHO_PIN) == 0); // Wait for echo to start
uint32_t pulse_start = Cy_SysTick_GetValue();
while (cyhal_gpio_read(ECHO_PIN) == 1); // Wait for echo to end
uint32_t pulse_end = Cy_SysTick_GetValue();
// Calculate pulse duration
uint32_t pulse_duration = pulse_end - pulse_start;
// Calculate distance (speed of sound = 343 m/s)
return (pulse_duration * 0.0343) / 2; // Convert to cm
}
Comments