Recently I am learning the Rust language and practicing writing some projects.
I am writing a project that connects wifi on the esp32S2 and then emits an infrared signal to control the air conditioner.
I use the template of esp-idf and use the function to connect wifi, it works and connected wifi successfully. Then I write a function to emits infrared signal, it also works and the air conditioner can be controlled. But when I emits infrared signal after wifi connected, it does not work.
Below is the function to emit infrared signal, I use LedcDriver and thread::sleep.
const K_GREE_HDR_MARK: u64 = 9000;
const K_GREE_HDR_SPACE: u64 = 4500;
const K_GREE_MSG_SPACE: u64 = 20_000;
const K_GREE_BIT_MARK: u64 = 656;
const K_GREE_ONE_SPACE: u64 = 1640;
const K_GREE_ZERO_SPACE: u64 = 544;
pub struct IrPwm<'d> {
driver: LedcDriver<'d>,
}
impl<'d> IrPwm<'d> {
pub fn new<C: LedcChannel, T: LedcTimer>(
_timer: impl Peripheral<P = T> + 'd,
_channel: impl Peripheral<P = C> + 'd,
pin: impl Peripheral<P = impl OutputPin> + 'd,
) -> Result<Self, EspError> {
let timer_driver =
LedcTimerDriver::new(_timer, &TimerConfig::default().frequency(38.kHz().into()))?;
let mut driver = LedcDriver::new(_channel, timer_driver, pin)?;
let max_duty = driver.get_max_duty();
driver.set_duty(max_duty / 3)?;
driver.disable();
Ok(Self { driver })
}
pub fn send(&mut self, data_code: u128) {
let bytes = data_code.to_be_bytes();
let temp: String = bytes.iter().map(|byte| format!("{:08b}", byte)).collect();
let (data_code1, data_code2) = (&temp[0..35], &temp[35..67]);
println!("{}, {}", data_code1, data_code2);
self.driver.enable();
thread::sleep(Duration::from_micros(K_GREE_HDR_MARK));
self.no_send_ir(K_GREE_HDR_SPACE);
for i in data_code1.bytes() {
if i == b'0' {
self.send_ir_zero();
} else {
self.send_ir_one();
}
}
self.send_ir_zero();
self.no_send_ir(K_GREE_MSG_SPACE);
for i in data_code2.bytes() {
if i == b'0' {
self.send_ir_zero();
} else {
self.send_ir_one();
}
}
self.send_ir_zero();
}
fn no_send_ir(&mut self, t: u64) {
self.driver.disable();
thread::sleep(Duration::from_micros(t));
}
fn send_ir(&mut self, e_t: u64, d_t: u64) {
self.driver.enable();
thread::sleep(Duration::from_micros(e_t));
self.driver.disable();
thread::sleep(Duration::from_micros(d_t));
}
// 发送二进制数据 1
fn send_ir_one(&mut self) {
self.send_ir(K_GREE_BIT_MARK, K_GREE_ONE_SPACE);
}
// 发送二进制数据 0
fn send_ir_zero(&mut self) {
self.send_ir(K_GREE_BIT_MARK, K_GREE_ZERO_SPACE);
}
}
I do not know the reason why it happened, I need your help!