您從不關閉連接。但阻止等待電子郵件確認可能會永遠持續下去。你應該考慮一個小型的狀態機來讓你的網絡連接起作用。
void loop()
{
// when sensor triggered =>
if (client.connect(server, 80)) { // You connect to client, but it's already
// connected the second time around
// send ...
// client() should wait for response, and client.disconnect()
}
// ...
delay(6000); // tip: avoid blocking the main loop, this blocks your ability to
// read your sensor while sending emails.
}
爲您的應用狀態機看起來是這樣的:
enum EmailState {
emIdle, emSendMail, emCheckMailSent, emEmailOK, emEmailError,
};
EmailState email_state;
unsigned long long mail_timer; // can be shared between states.
// small state handlers that do a bit at a time,
// check for an event, wait on some delay (use millis())
// avoid blocking the instruction flow as much as possible.
static void on_emIdle()
{
// read sensor, check timer?
email_state = (triggered) ? emSendMail : emIdle;
}
static void on_sendMail()
{
if (client.connect())
{
// ... prints
email_state = emCheckMailSent;
return;
}
email_state = emEmailError;
}
static void on_emCheckMailSent()
{
// receive HTTP response... can have a long timeout without blocking.
email_state = emCheckMailSent;
// or emEmailOK or emEmailError or retry emSendMail
}
static void on_emEmailOK()
{
if (/*client is connected?*/)
client.disconnect();
if (!mail_timer)
mail_timer = millis();
if (millis() - mail_timer < 6000) // stay in this state for 6 seconds...
{
email_state = emEmailOK;
return;
}
mail_timer = 0; // always reset the timer so it can be used by other states
email_state = emIdle;
}
static void on_emEmailError()
{
if (/*client is connected?*/)
client.disconnect();
// keep a log ?
email_state = emIdle; // or another timer
}
//...
void loop()
{
// update readings, manage other things...
// ...
switch(email_state)
{
default:
case emIdle: on_emIdle(); break;
case emSendMail: on_emSendMail(); break;
case emCheckMailSent: on_emCheckMailSent(); break;
case emEmailOK: on_emEmailOK(); break;
case emEmailError: on_emEmailError(); break;
}
}
也許你需要關閉與'client.stop()'的連接? –
似乎沒有幫助。 – Kashif
你有沒有嘗試做另一個func()並從loop()調用這個func? –