以下內容由 DeepSeek R1 生成 根據問題描述和代碼分析,問題可能出在以下幾個方面: 1. 數據位處理錯誤原代碼中使用unsigned char ir_data(8位)存儲32位數據,導致高位數據丟失。應改用32位變量: unsigned long IrDecodeValue(void) {
unsigned long ir_data = 0;
// ...其余代碼
// 讀取32位數據時,按位存儲到ir_data
ir_data <<= 1;
ir_data |= (當前位值);
// ...
return (ir_data >> 8) & 0xFF; // 返回數據碼(假設第三字節)
}2. 時間閾值與延時函數不匹配STC8G1K08默認使用24MHz時鐘(1T模式),而傳統51多為12MHz(12T模式)。原Delay10us在24MHz下實際延時可能過短。需重新校準: void Delay10us(void) {
unsigned char i = 24; // 調整i的值,用示波器校準
while (--i);
}3. 電平檢測邏輯錯誤NEC協議中,邏輯0/1由高電平時間決定,而非低電平。應修改GetTime函數以測量高電平持續時間: unsigned int GetHighTime(void) {
unsigned int time = 0;
while (P32 == 1) { // 測量高電平時間
Delay10us();
time++;
if(time > 1000) break; // 超時退出
}
return time;
}4. 未正確處理引導碼原代碼未正確檢測9ms低電平+4.5ms高電平的引導碼。需添加引導碼驗證: // 檢測引導碼
while (P32 == 1); // 等待高電平結束
unsigned int low_time = GetTime(); // 測量低電平時間
if (low_time < 800 || low_time > 1000) return 0xFF; // 非引導碼
unsigned int high_time = GetTime(); // 測量高電平時間
if (high_time < 400 || high_time > 500) return 0xFF; // 非引導碼5. 引腳配置問題確保P3.2(紅外輸入)和P1.2(LED)配置正確: void main() {
P1M0 = 0x00; // P1準雙向
P1M1 = 0x00;
P3M0 &= ~0x04; // P3.2準雙向或高阻輸入
P3M1 &= ~0x04;
// ...其余代碼
}修正后的示例代碼 #include "STC8G.h"
#include <intrins.h>
#define IR_DATA_BITS 32
void Delay10us() {
unsigned char i = 24; // 根據24MHz調整
while (--i);
}
unsigned int GetHighTime() {
unsigned int time = 0;
while (P32 == 1) {
Delay10us();
time++;
if (time > 1000) break;
}
return time;
}
unsigned long IrDecode() {
unsigned long data = 0;
unsigned int time;
// 檢測引導碼
while (P32 == 1);
time = 0;
while (P32 == 0) { // 測量低電平時間
Delay10us();
time++;
if (time > 1000) return 0;
}
if (time < 800) return 0; // 9ms低電平應為約900個10us
time = 0;
while (P32 == 1) { // 測量高電平時間
Delay10us();
time++;
if (time > 500) return 0;
}
if (time < 400) return 0; // 4.5ms高電平應為約450個10us
// 讀取32位數據
for (int i=0; i<IR_DATA_BITS; i++) {
while (P32 == 0); // 等待低電平結束
unsigned int high_time = GetHighTime();
data <<= 1;
if (high_time > 100) { // 高電平時間>1ms為邏輯1
data |= 1;
}
}
return data;
}
void main() {
P1M0 = 0x00;
P1M1 = 0x00;
P32 = 1; // 使能P3.2上拉
while (1) {
unsigned long ir_code = IrDecode();
if ((ir_code >> 8) == 0x45) { // 數據碼在第三字節
P12 = !P12; // 翻轉LED
}
}
}調試建議使用示波器:檢查紅外接收頭的輸出波形,確認信號是否符合NEC協議。 打印鍵值:通過串口輸出接收到的鍵值,確認是否正確解析電源鍵(如0x45)。 調整延時參數:根據實際時鐘頻率,校準Delay10us的準確性。 檢查硬件:確認紅外接收器電源穩定,信號線連接正確(P3.2),LED電路無故障。
通過以上修正和調試步驟,應能解決STC8G1K08紅外通信不響應的問題。
|