我和ATmega8在一个小项目中间。我想从DS18B20传感器读取温度,然后使用rf433变送器发送结果。一切都很好,但我的源的大小... ATmega只有7 168字节的内存,但我的二进制是8 310字节。我删除了任何不道德的东西,但仍然太多了。你能帮我减小尺寸吗?我使用Arduino IDE编写代码,也许在纯C中它会更轻?
任何帮助表示赞赏:)
代码:
// RF433
#include <VirtualWire.h>
// Dallas
#include <DallasTemperature.h>
#include <OneWire.h>
//const char *message; // Our message to send
const int ONE_WIRE_BUS = 2; //DS18S20 Signal pin on digital 2
//Temperature chip i/o
OneWire oneWire(ONE_WIRE_BUS); // on digital pin 2
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature Sensors(&oneWire);
void setup() {
// RF433
vw_set_ptt_inverted(true);
vw_setup(2000);
Sensors.begin();
}
void loop() {
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Sensors.requestTemperatures(); // Send the command to get temperatures
float dTmp = Sensors.getTempCByIndex(0);
// Why "byIndex"?
// You can have more than one IC on the same bus.
// 0 refers to the first IC on the wire
char buf[6];
dtostrf(dTmp, 6, 3, buf);
char Msg[9];
strcpy(Msg, "TP:");
strncat(Msg, buf, 6);
// Send temp.
for (int i = 0; i < 10; ++i) // avoid loosing packets
{
vw_send((uint8_t *)Msg, strlen(Msg));
vw_wait_tx();
delay(300);
}
// Sleep 1 min.
delay(60000);
}
答案 0 :(得分:0)
谢谢你们所有人,伙计们。 昨天我找到了如何完成这项任务的方法。也许有人会在将来寻找答案,所以这里是: 我放弃了达拉斯图书馆,最后证明这不是第一次需要。
#include <OneWire.h>
// RF433
#include <VirtualWire.h>
int DS18S20_Pin = 2; //DS18S20 Signal pin on digital 2
//Temperature chip i/o
OneWire ds(DS18S20_Pin); // on digital pin 2
int led = 13;
void setup(void) {
// RF433
vw_set_ptt_inverted(true);
vw_setup(2000);
pinMode(led, OUTPUT);
}
void loop(void) {
float dTmp = getTemp();
char buf[6];
dtostrf(dTmp, 6, 3, buf);
char Msg[10];
strcpy(Msg, "TMP:");
strncat(Msg, buf, 6);
digitalWrite(led, HIGH);
for (int i = 0; i < 10; ++i) // avoid loosing packets in the air
{
vw_send((uint8_t *)Msg, strlen(Msg));
vw_wait_tx();
delay(300);
}
digitalWrite(led, LOW);
// Sleep 15 s.
delay(15000);
}
float getTemp(){
//returns the temperature from one DS18S20 in DEG Celsius
byte data[12];
byte addr[8];
if ( !ds.search(addr)) {
//no more sensors on chain, reset search
ds.reset_search();
return -1000;
}
if ( OneWire::crc8( addr, 7) != addr[7]) {
// Serial.println("CRC is not valid!");
return -1000;
}
if ( addr[0] != 0x10 && addr[0] != 0x28) {
// Serial.print("Device is not recognized");
return -1000;
}
ds.reset();
ds.select(addr);
ds.write(0x44,1); // start conversion, with parasite power on at the end
byte present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
for (int i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
}
ds.reset_search();
byte MSB = data[1];
byte LSB = data[0];
float tempRead = ((MSB << 8) | LSB); //using two's compliment
float TemperatureSum = tempRead / 16;
return TemperatureSum;
}
上面的代码作为二进制文件需要大约6300个字节,因此仍有一些空间可以进行一些改进。
希望你会发现它有用:)