只需一步,快速开始
bool transmitting_IR; bool receiving_IR; void turn_off_IR () { TCCR2A = 0; // Disconnect PWM TCCR2B = 0; // Stops the timer OCR2A = 0; // No timer top digitalWrite(11, LOW); // Ensure output is off transmitting_IR = false; } void turn_on_IR () { TCCR2A = _BV(WGM21) | _BV(COM2A0); // This mode toggles output once per timer cycle TCCR2B = _BV(CS20); OCR2A = 210; 38 khz transmitting_IR = true; } bool detect_IR() { return receiving_IR = ! digitalRead(12); } void setup () { Serial.begin(9600); pinMode (11, OUTPUT); // IR LED pinMode (12, INPUT); // IR receiver turn_off_IR(); // My helper function for controlling the IR LED detect_IR(); // Ensure the state is correct. } void loop () { detect_IR(); char ch; if(receiving_IR) ch = readch(); ch = Serial.read(); if(ch>0) sendch(ch); } unsigned long p=500; char readch() { char ch = 0; unsigned long start_time = micros(); while(micros() < start_time + p); for(int i = 0; i < 8; i++) { unsigned long bit_time = micros(); while(micros() < bit_time + 2*p); int result = detect_IR(); ch = ch | (result << i); } Serial.print(ch); } void sendch(char ch) { turn_on_IR(); unsigned long start_time = micros(); while(micros() < start_time + 2*p); for(int i = 0; i < 8; i++) { int result = (ch >> i) & 1; if(result == 1) { turn_on_IR(); unsigned long bit_time = micros(); while(micros() < bit_time + 2*p); } else { turn_off_IR(); unsigned long bit_time = micros(); while(micros() < bit_time + 2*p); } } turn_off_IR(); unsigned long end_time = micros(); while(micros() < end_time + 2*p); }
举报
本版积分规则 发表回复 回帖后跳转到最后一页
小黑屋|Archiver|手机版|Arduino中文社区
GMT+8, 2024-12-4 03:57 , Processed in 0.082494 second(s), 16 queries .
Powered by Discuz! X3.4
Copyright © 2001-2021, Tencent Cloud.