使用Ardunio STM32F103C8T6发送 433/315Hz ASK信号
ARDUINO找不到合适的库
在ARDUINO中最比较好的库rc-switch(https://github.com/sui77/rc-switch),但是他对STM32不太兼容,需要修改,但修改后发现通信无法与我之前的解码不兼容,无奈之下只好再这个库里抽取代码以便适应原有的解码。
#define nTransmitterPin PA5
struct HighLow {
uint8_t high;
uint8_t low;
};
struct Protocol {
int pulseLength;
HighLow syncFactor;
HighLow one;
HighLow zero;
bool invertedSignal;
};
static const Protocol PROGMEM proto[] = {
{115, {85, 10}, {10, 3}, {3, 10}, false },
{50, {100, 12}, {12, 4}, {4, 12}, false }
};
Protocol protocol;
int nRepeatTransmit;
unsigned char code[8];
void transmit(HighLow pulses) {
uint8_t firstLogicLevel = (protocol.invertedSignal) ? LOW : HIGH;
uint8_t secondLogicLevel = !firstLogicLevel;
digitalWrite(nTransmitterPin, firstLogicLevel);
delayMicroseconds(protocol.pulseLength * pulses.high);
digitalWrite(nTransmitterPin, secondLogicLevel);
delayMicroseconds(protocol.pulseLength * pulses.low);
}
void send() {
protocol=proto[0];
digitalWrite(nTransmitterPin, LOW);
delayMicroseconds(500);
for (int nRepeat = 0; nRepeat < 8; nRepeat++) {
transmit(protocol.syncFactor);
for(int Cmds=0;Cmds<8;Cmds++){
for (int i = 7; i >= 0; i--) {
if (code[Cmds] & (1 << i)){
transmit(protocol.one);
}else{
transmit(protocol.zero);
}
}
}
digitalWrite(nTransmitterPin, HIGH);
delayMicroseconds(100);
}
}
void SendData(char Cmd1,char Cmd2,char Value1,char Value2){
Serial.print("Send Data[");
code[0]=0x55;
code[1]=0xAA;
code[2]=Cmd1;
code[3]=Cmd2;
code[4]=Value1;
code[5]=Value2;
code[6]=0x80;
unsigned char Crc = 0;
for (int k = 0; k <= 6; k++) {
Serial.print(code[k]);Serial.print(",");
Crc += code[k];
}
code[7]=Crc;
Serial.print(code[7]);
Serial.println("]");
code[8]=0x3A;
send();
}
void setup() {
Serial.begin(115200);
pinMode(nTransmitterPin, OUTPUT);
pinMode(PC13, OUTPUT);
while (!Serial) {
;
}
delay(500);
Serial.println("Start...");
}
char Value_H=0;
char Value_L=0;
void loop() {
SendData('0','1',Value_H,Value_L);
Value_L++;
if(Value_L>=255){
Value_H++;
Value_L=0;
if(Value_H>=255) Value_H=Value_L=0;
}
}
用示波器看看ARDUNIO的delay()和delayMicroseconds()的时间是否是正确的
我再时间调试中发现这两个函数的时间与实际时间不同,因此在程序中的时间不是正常的 例如我想同步时先发送5000微妙的高电平再发送600微妙的低电平,那么应该写
digitalWrite(nTransmitterPin, firstLogicLevel); delayMicroseconds(5000); digitalWrite(nTransmitterPin, secondLogicLevel); delayMicroseconds(600);
但实际需要写为
digitalWrite(nTransmitterPin, firstLogicLevel);
delayMicroseconds(9770);
digitalWrite(nTransmitterPin, secondLogicLevel);
delayMicroseconds(1150);
因此这些在实际调试中的问题都需要我们仔细的去发现问题和解决问题。 虽然ARDUNIO给我我们方便的开发环境,但是某些坑还得自己慢慢爬。
|