#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/i2c.h"
#include "driver/adc.h"
// إعدادات الـ I2C والعناوين
#define I2C_MASTER_NUM I2C_NUM_0
#define LCD_ADDR 0x27
// بتات التحكم في شاشة LCD
#define LCD_RS 0x01
#define LCD_EN 0x04
#define LCD_BACKLIGHT 0x08
// وظائف مساعدة لإرسال البيانات للشاشة
void lcd_send(uint8_t data, uint8_t mode) {
uint8_t high = (data & 0xF0) | mode | LCD_BACKLIGHT;
uint8_t low = ((data << 4) & 0xF0) | mode | LCD_BACKLIGHT;
uint8_t buf[4] = {high | LCD_EN, high, low | LCD_EN, low};
i2c_master_write_to_device(I2C_MASTER_NUM, LCD_ADDR, buf, 4, 1000 / portTICK_PERIOD_MS);
}
void lcd_init() {
vTaskDelay(pdMS_TO_TICKS(50));
lcd_send(0x30, 0); vTaskDelay(pdMS_TO_TICKS(5));
lcd_send(0x30, 0); vTaskDelay(pdMS_TO_TICKS(1));
lcd_send(0x32, 0); // وضع 4-bit
lcd_send(0x28, 0); // سطرين
lcd_send(0x0C, 0); // تشغيل الشاشة وإخفاء المؤشر
lcd_send(0x01, 0); // مسح الشاشة
vTaskDelay(pdMS_TO_TICKS(2));
}
void lcd_put_cur(int row, int col) {
int pos = (row == 0) ? (0x80 + col) : (0xC0 + col);
lcd_send(pos, 0);
}
void lcd_send_string(char *str) {
while (*str) lcd_send(*str++, 0x01);
}
void app_main() {
// 1. إعداد I2C (Pins 21 SDA, 22 SCL كما في الـ JSON)
i2c_config_t conf = {
.mode = I2C_MODE_MASTER,
.sda_io_num = 21,
.scl_io_num = 22,
.sda_pullup_en = 1,
.scl_pullup_en = 1,
.master.clk_speed = 100000,
};
i2c_param_config(I2C_MASTER_NUM, &conf);
i2c_driver_install(I2C_MASTER_NUM, conf.mode, 0, 0, 0);
// 2. تهيئة الشاشة والـ ADC
lcd_init();
adc1_config_width(ADC_WIDTH_BIT_12);
adc1_config_channel_atten(ADC1_CHANNEL_6, ADC_ATTEN_DB_11);
gpio_set_direction(GPIO_NUM_2, GPIO_MODE_OUTPUT);
char line1[16], line2[16];
while (1) {
int raw = adc1_get_raw(ADC1_CHANNEL_6);
float volt = (raw * 3.3) / 4095.0;
float percent = (raw / 4095.0) * 100.0;
// تحديث النصوص
sprintf(line1, "Voltage: %.2fV", volt);
sprintf(line2, "Level: %.1f%% ", percent);
// العرض على الشاشة
lcd_put_cur(0, 0);
lcd_send_string(line1);
lcd_put_cur(1, 0);
lcd_send_string(line2);
// التحكم في الـ LED للتنبيه
gpio_set_level(GPIO_NUM_2, (percent > 80.0));
vTaskDelay(pdMS_TO_TICKS(200));
}
}