/**
main.c
RP2040 FreeRTOS Template
@copyright 2024, Tony Smith (@smittytone)
@version 1.5.0
@licence MIT
*/
#include "main.h"
#include "pico/binary_info.h"
#include "pico/stdlib.h"
#include "dht22.h"
#include "lcd_i2c.h"
// Global Mutexes and Task Handles
SemaphoreHandle_t xMutexSensorData;
SemaphoreHandle_t xMutexMotorControl;
SemaphoreHandle_t xMutexLCD, xMutexLCDData;
QueueHandle_t queue = NULL; // Inter-task queue
TaskHandle_t lighting_control_handle = NULL;
TaskHandle_t temperature_monitor_handle = NULL;
TaskHandle_t motion_detection_handle = NULL;
TaskHandle_t MotorControlTaskHandle = NULL;
TaskHandle_t lcd_handle = NULL;
TaskHandle_t xSemaphoreOwner = NULL; // Global variable to track the semaphore owner
// Sensor data
uint16_t ldr_value;
uint16_t sharedlightLevel;
typedef struct {
double humidity;
double temperature;
} SensorData;
static SensorData sharedSensorData = {0, 0};
static int motionStatus = 0;
static int shared_motionStatus = 0;
int currentPosition = 0; // Current position from encoder
int targetPosition = 512; // Target position (middle)
// Constants
const TickType_t ms_delay = 500 / portTICK_PERIOD_MS;
float previousTemperature = 0.0;
float temperature = 21;
int temp;
float humidity;
int light;
int motion;
volatile int32_t encoder_count = 0; // Counter for encoder position
// Function prototypes
void blocking_task(void* unused_arg);
void lighting_control_task(void *pvParameters);
void temperatureMonitorTask(void *pvParameters);
void motionDetectionTask(void *pvParameters);
void motionDetectionInit(void);
void update_lcd_display(void);
// Initialize I2C (for LCD)
void init_i2c() {
i2c_init(I2C_PORT, 100000); // Initialize I2C
gpio_set_function(I2C_SDA_PIN, GPIO_FUNC_I2C);
gpio_set_function(I2C_SCL_PIN, GPIO_FUNC_I2C);
gpio_pull_up(I2C_SDA_PIN);
gpio_pull_up(I2C_SCL_PIN);
}
// Initialize and read LDR
uint16_t read_ldr() {
adc_select_input(0); // Select ADC input 0 (GPIO26)
uint16_t ldr_value = adc_read(); // Read raw ADC value (0-4095)
return ldr_value;
}
void motor_init()
{
// Initialize GPIO pins
gpio_init(MOTOR_STEP_PIN);
gpio_set_dir(MOTOR_STEP_PIN, GPIO_OUT);
gpio_init(MOTOR_DIR_PIN);
gpio_set_dir(MOTOR_DIR_PIN, GPIO_OUT);
}
void motorControl(int step) {
printf("motor motion");
// Assuming step and direction control using GPIO pins
gpio_put(MOTOR_DIR_PIN, step > 0 ? 1 : 0); // Set direction
for (int i = 0; i < abs(step); i++) {
gpio_put(MOTOR_STEP_PIN, 1); // Step pulse HIGH
//vTaskDelay(pdMS_TO_TICKS(2000)); // Adjust for motor speed
gpio_put(MOTOR_STEP_PIN, 0); // Step pulse LOW
vTaskDelay(pdMS_TO_TICKS(5)); // Adjust for motor speed
}
}
// Interrupt handler for encoder signals
// Interrupt handler for encoder CLK pin
void encoder_isr(uint gpio, uint32_t events) {
bool dt_state = gpio_get(ENCODER_DT); // Read Data pin state
bool direction = dt_state == 0; // Determine direction based on DT state
encoder_count += direction ? 1 : -1; // Increment or decrement the counter
}
void monitor_task_health(void)
{
TaskHandle_t taskHandles[] = {
lighting_control_handle,
temperature_monitor_handle,
motion_detection_handle,
MotorControlTaskHandle,
lcd_handle
};
const char *taskNames[] = {
"Lighting Control",
"Temperature Monitor",
"Motion Detection",
"Motor Control PID",
"lcd_handle"
};
size_t numTasks = sizeof(taskHandles) / sizeof(taskHandles[0]);
printf("\n-- Task States --\n");
for (size_t i = 0; i < numTasks; i++)
{
if (taskHandles[i] != NULL)
{
eTaskState state = eTaskGetState(taskHandles[i]);
printf("%s Task: ", taskNames[i]);
switch (state)
{
case eRunning:
printf("Running\n");
break;
case eReady:
printf("Ready\n");
break;
case eBlocked:
printf("Blocked\n");
break;
case eSuspended:
printf("Suspended\n");
break;
case eDeleted:
printf("Deleted\n");
break;
default:
printf("Unknown State\n");
break;
}
}
else
{
printf("%s Task: Handle not created\n", taskNames[i]);
}
}
}
void checkMutexOwnership() {
TaskHandle_t taskHolder = xSemaphoreGetMutexHolder(xMutexSensorData);
if (taskHolder == NULL) {
printf("No task currently holds the mutex.\n");
} else {
printf("Mutex is currently held by task handle: %s\n", pcTaskGetName(taskHolder));
}
}
void encoder_init()
{
// Initialize encoder pins as inputs with pull-up resistors
gpio_init(ENCODER_CLK);
gpio_set_dir(ENCODER_CLK, GPIO_IN);
gpio_pull_up(ENCODER_CLK);
gpio_init(ENCODER_DT);
gpio_set_dir(ENCODER_DT, GPIO_IN);
gpio_pull_up(ENCODER_DT);
gpio_init(ENCODER_SW);
gpio_set_dir(ENCODER_SW, GPIO_IN);
gpio_pull_up(ENCODER_SW);
// Set up an interrupt for the CLK pin
gpio_set_irq_enabled_with_callback(ENCODER_CLK, GPIO_IRQ_EDGE_RISE, true, &encoder_isr);
}
// Update LCD Display with sensor data
void update_lcd_display()
{
// Copy shared data into local variables
// if (xSemaphoreTake(xMutexSensorData, portMAX_DELAY) == pdTRUE) {
temp = (int)sharedSensorData.temperature;
humidity = sharedSensorData.humidity;
// xSemaphoreGive(xMutexSensorData); // Release semaphore quickly
// }
// Copy shared data into local variables
// if (xSemaphoreTake(xMutexLCDData, pdMS_TO_TICKS(200)) == pdTRUE) {
light = sharedlightLevel;
// xSemaphoreGive(xMutexLCDData); // Release semaphore quickly
//}
// Assume direct access or other synchronization
motion = motionStatus;
lcd_clear();
lcd_set_cursor(0, 0);
// Use local variables to send data to LCD
lcd_clear();
lcd_set_cursor(0, 0);
char buffer[32];
snprintf(buffer, sizeof(buffer), "Temp: %d C", temp);
lcd_print(buffer);
lcd_set_cursor(1, 0);
snprintf(buffer, sizeof(buffer), "Humidity: %.2f %%", humidity);
lcd_print(buffer);
vTaskDelay(pdMS_TO_TICKS(500));
lcd_clear();
lcd_set_cursor(0, 0);
snprintf(buffer, sizeof(buffer), "Light: %d", light);
lcd_print(buffer);
lcd_set_cursor(1, 0);
lcd_print(motion == 1 ? "Security: Alert" : "Security: Safe");
}
// Task to read temperature and humidity
void temperatureMonitorTask(void *pvParameters) {
dht_reading reading;
for (;;) {
vTaskDelay(pdMS_TO_TICKS(500));
if (DHT22_Read_Data(&reading) == 0) {
// Successful reading
if (xSemaphoreTake(xMutexSensorData, portMAX_DELAY) == pdTRUE) {
// xSemaphoreOwner = xTaskGetCurrentTaskHandle();
sharedSensorData.humidity = reading.humidity;
sharedSensorData.temperature = reading.temp_celsius;
xSemaphoreGive(xMutexSensorData);
}
printf("Temperature: %.1f°C, Humidity: %.1f%%\n", reading.temp_celsius, reading.humidity);
} else {
printf("Failed to read from DHT22 sensor\n");
}
vTaskDelay(pdMS_TO_TICKS(2000)); // Delay for 2 seconds
}
}
// Task to control lighting based on LDR value
void lighting_control_task(void *pvParameters) {
gpio_init(LED_PIN);
gpio_set_dir(LED_PIN, GPIO_OUT);
adc_init();
adc_gpio_init(LDR_ADC_PIN); // Initialize the GPIO pin for ADC
while (1) {
ldr_value = read_ldr(); // Read LDR value
printf("LDR Value: %d\n", ldr_value);
if (ldr_value > LDR_THRESHOLD) {
gpio_put(LED_PIN, 1); // Turn on LED if light is dim
} else {
gpio_put(LED_PIN, 0); // Turn off LED if light is bright
}
// if (xSemaphoreTake(xMutexLCDData, 100) == pdTRUE) {
sharedlightLevel = ldr_value;
// xSemaphoreGive(xMutexLCDData);
// }
vTaskDelay(pdMS_TO_TICKS(2000)); // Delay for 2 seconds
}
}
// Initialize PIR sensor and alarm LED
void motionDetectionInit() {
gpio_init(PIR_SENSOR_PIN);
gpio_set_dir(PIR_SENSOR_PIN, GPIO_IN);
gpio_pull_down(PIR_SENSOR_PIN);
gpio_init(ALARM_LED_PIN);
gpio_set_dir(ALARM_LED_PIN, GPIO_OUT);
gpio_put(ALARM_LED_PIN, 0); // Ensure LED is off initially
}
// Task to detect motion and trigger alarm
void motionDetectionTask(void *pvParameters) {
for (;;) {
if (gpio_get(PIR_SENSOR_PIN)) {
motionStatus = 1; // Motion detected
gpio_put(ALARM_LED_PIN, 1); // Turn on alarm LED
printf("Motion detected! Alarm triggered.\n");
} else {
gpio_put(ALARM_LED_PIN, 0); // Turn off alarm LED
}
//if (xSemaphoreTake(xMutexSensorData, 100) == pdTRUE) {
//xSemaphoreOwner = xTaskGetCurrentTaskHandle();
shared_motionStatus = motionStatus;
//xSemaphoreGive(xMutexSensorData);
//}
//monitor_task_health();
vTaskDelay(pdMS_TO_TICKS(500)); // Delay for 500 milliseconds
}
}
// Blocking task to show preemption on LCD
void lcd_task(void* unused_arg) {
lcd_set_cursor(0, 1);
while (true) {
update_lcd_display();
vTaskDelay(pdMS_TO_TICKS(1000)); // Update LCD every 2 seconds
}
}
// Task to check who is holding the semaphore
void monitorSemaphoreOwnershipTask(void *pvParameters) {
for (;;) {
// monitor_task_health();
checkMutexOwnership();
vTaskDelay(pdMS_TO_TICKS(2000)); // Delay for 1 second
}
}
void motorControlTask() {
while (1) {
if ( xSemaphoreTake(xMutexSensorData, portMAX_DELAY) == pdTRUE) {
xSemaphoreOwner = xTaskGetCurrentTaskHandle();
temperature = sharedSensorData.temperature;
xSemaphoreGive(xMutexSensorData);
}
//monitor_task_health();
//printf("encoder count :%d\n", encoder_count);
// Check if temperature has changed significantly or target position is not reached
if (temperature != previousTemperature || currentPosition != targetPosition) {
// If temperature has changed, update the target position
if (temperature > 30.0) {
targetPosition = 0; // Close the blinds (position 0)
} else if (temperature < 20.0) {
targetPosition = 50; // Open the blinds (position 1023)
}
// Check the health of tasks
//monitor_task_health();
// Update the previous temperature
previousTemperature = temperature;
// Calculate PID output
// int pidOutput = pidControl(currentPosition, targetPosition);
int error = targetPosition - currentPosition;
// Move motor based on PID output
//motorControl(pidOutput);
motorControl(error);
//motorControl(1000);
currentPosition = targetPosition;
// Sleep for PID loop delay (100 ms)
vTaskDelay(pdMS_TO_TICKS(100));
}
}
}
int main() {
// Initialize peripherals
stdio_init_all();
init_i2c();
bi_decl(bi_2pins_with_func(I2C_SDA_PIN, I2C_SCL_PIN, GPIO_FUNC_I2C));
lcd_init();
DHT22_Init();
motionDetectionInit(); // Initialize PIR sensor and alarm LED
motor_init();
encoder_init();
// Create mutexes for synchronization
xMutexSensorData = xSemaphoreCreateMutex();
xMutexLCD = xSemaphoreCreateMutex();
xMutexMotorControl = xSemaphoreCreateMutex();
xMutexLCDData = xSemaphoreCreateMutex();
xSemaphoreGive(xMutexSensorData);
//xSemaphoreGive(xMutexLCDData);
// Create tasks for different system functions
xTaskCreate(lighting_control_task, "Lighting Control", 256, NULL, 1, &lighting_control_handle);
xTaskCreate(temperatureMonitorTask, "Temperature Monitor", 256, NULL, 1, &temperature_monitor_handle);
xTaskCreate(motionDetectionTask, "Motion Detection", 256, NULL, 1, &motion_detection_handle);
// Create task for controlling motor position
xTaskCreate(motorControlTask, "Motor Control PID", 256, NULL, 2 , &MotorControlTaskHandle);
// Create task to update LCD display
xTaskCreate(update_lcd_display, "LCD Update", 256, NULL, 1, &lcd_handle);
// Monitor task health
xTaskCreate(monitor_task_health, "Monitor Task Health", 256, NULL, 1, NULL);
// Check whether semaphores were created successfully
// checkSemaphoreCreation();// Start the FreeRTOS scheduler
// if (lighting_control_status == pdPASS && temperature_status == pdPASS && motionDetection_status == pdPASS && motor_status == pdPASS) {
vTaskStartScheduler();
// }
// We should never get here, but just in case...
while (true) {
// NOP
}
}