extern "C" {
#include "ABS_Controller.h" // ต้องใช้ extern "C" เพื่อให้ C++ เรียก C ได้
}
// กำหนดขา Pin สำหรับจำลอง
const int ABS_ONPin = D12; // รับค่า '<Root>/ABS_ON'
const int slpPin = A5; // ตัวบน (A5) -> ใช้เป็นตัวตั้ง Limit
const int PhanuphongPin = A1; // ตัวล่าง (A1) -> ใช้เป็นตัววิ่งเข้าหา Limit
const int brakeLedPin = D5; // LED แสดงสถานะวาล์วเบรก (Dominant/Recessive)
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, STM32!");
// 1. กำหนดโหมดของ Pin
pinMode(ABS_ONPin, INPUT);
pinMode(slpPin, INPUT);
pinMode(PhanuphongPin, INPUT);
pinMode(brakeLedPin, OUTPUT);
// 2. เรียกฟังก์ชัน Initialize ของ Model
ABS_Controller_initialize();
}
void loop() {
// put your main code here, to run repeatedly:
// --- ช่วงที่ 1: รับค่า Input จากโลกจริง (Simulator) ---
int rawABS_ON = digitalRead(ABS_ONPin);
int rawslp = analogRead(slpPin);
int rawPhanuphong = analogRead(PhanuphongPin);
// แปลงค่า Analog (0-1023) ให้เป็น Unit ที่ Model ต้องการ
bool ABS_ON = rawABS_ON;
float slp = (rawslp / 1023.0) * 1; // ตัวบน (Limit)
float Phanuphong = (rawPhanuphong / 1023.0) * 1; // ตัวล่าง
// --- ช่วงที่ 2: ส่งค่าเข้า Model ---
ABS_Controller_U.ABS_ON = ABS_ON;
ABS_Controller_U.slp = slp;
ABS_Controller_U.Phanuphong = Phanuphong;
// --- ช่วงที่ 3: ประมวลผล Logic (Step Function) ---
ABS_Controller_step();
// --- ช่วงที่ 4: นำค่า Output ไปสั่งการ Hardware ---
bool valveState = ABS_Controller_Y.controllerout_Hansome; // รับค่าผลลัพธ์จาก Model
// เงื่อนไข: ถ้าตัวล่าง (Phanuphong) มากกว่าหรือเท่ากับตัวบน (slp) และ Model สั่งทำงาน
if (Phanuphong >= slp && valveState == 1) {
digitalWrite(brakeLedPin, HIGH); // ไฟติด
} else {
digitalWrite(brakeLedPin, LOW); // ไฟดับ
}
delay(10); // this speeds up the simulation
// --- ช่วงที่ 5: Debug แสดงผลขึ้นจอ ---
int static Debug_cnt;
Debug_cnt++;
if (Debug_cnt > 100) // 1 sec
{
Debug_cnt = 0;
Serial.print("ABS_ON : ");
Serial.println(ABS_ON);
Serial.print("Limit (slp - A5) : ");
Serial.println(slp);
Serial.print("Value (Phanuphong - A1) : ");
Serial.println(Phanuphong);
Serial.print("valveState : ");
Serial.println(valveState);
Serial.print("ABS_Controller_Y.controllerout_Hansome : ");
Serial.println(ABS_Controller_Y.controllerout_Hansome);
Serial.println("-------------------------");
}
}