首页 文章

为什么client.available()返回0? (Arduino的)

提问于
浏览
1

我正在研究一种基于Arduino的RFID用户访问 Logger ,但我在阅读服务器响应时遇到了一些问题 .

我的设置如下:

  • Arduino Mega连接到MFRC522读卡器和ENC28J60以太网模块(MFRC522的SS和RST引脚被更改以避免SPI总线内的冲突) .

  • 本地主机服务器(在端口100上),包含MySQL数据库和必要的php文件 .

目前卡正确读取,Arduino成功更新数据库中的变量,但是我无法通过串行监视器显示php文件中的回声 . 为了测试服务器端是否一切正常,我创建了一个小的html表单,如果我发送它,我会在浏览器中显示必要的回声 .

我打印client.available()返回的值,虽然client.connected()返回true,但我总是得到false . 将我的代码与在线发现的其他代码进行比较,没有太大区别 . 在这一点上,我不知道该尝试什么,我在跳,你可以帮我这个!

我附上以下代码:

Arduino:

#include <SPI.h>
#include <MFRC522.h>
#include <UIPEthernet.h>

#include <Wire.h> 
#include <LiquidCrystal_I2C.h>

//----RFID----/
MFRC522 rfid(8, 9); //(SS pin, RST pin)
byte nuidPICC[4];

//----ETHERNET----/
#define DEBUG
EthernetClient client;
char server[] = "192.168.xxx.xxx";   //<-Localhost
byte mac[] = { 0x54, 0x34, 0x41, 0x30, 0x30, 0x40 };

//----LCD----/
LiquidCrystal_I2C lcd(0x3F, 16, 2);

//----VARIABLES----/
int userid=0;

void setup() { 
  Serial.begin(9600);
  SPI.begin(); // Init SPI bus
  lcd.begin();
  pinMode(2,OUTPUT);

  //----RFID----/
  rfid.PCD_Init(); // Init MFRC522 

  //----ETHERNET----/
  Ethernet.begin(mac);
  #ifdef DEBUG
    Serial.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
    Serial.print("IP Address        : ");
    Serial.println(Ethernet.localIP());
    Serial.print("Subnet Mask       : ");
    Serial.println(Ethernet.subnetMask());
    Serial.print("Default Gateway IP: ");
    Serial.println(Ethernet.gatewayIP());
    Serial.print("DNS Server IP     : ");
    Serial.println(Ethernet.dnsServerIP());
    lcd.print("IP Address");
    lcd.setCursor(0,1);
    lcd.print(Ethernet.localIP());
    delay(2000);
    lcd.clear();
    lcd.noBacklight();
  #endif
}

void sender(){

  /*lcd.clear();
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("identifying");
  tone(2,900,400);*/

  if(client.connect(server, 100)){
    Serial.println("Conected");
  }
  //String query = "GET /uploader.php?userid=";
  //query=query+String(userid);
  //Serial.println(query);
  //client.print(query);

  client.print( "GET /uploader.php?userid=");
  client.print(12345);
  client.println(" HTTP/1.1");
  client.print("HOST: ");
  client.println(server);
  client.println();
  client.println();
  Serial.println("Data sent");

  delay(1000);

  Serial.println(client.connected());
  Serial.println(client.available());

  if(client.available())
        {
            Serial.println("ARDUINO: HTTP message received");
            Serial.println("ARDUINO: printing received headers and script response...\n");

            while(client.available())
            {
                char c = client.read();
                Serial.print(c);
            }
            //Code to display info through the serial monitor and the LCD
        }
        else
        {
            Serial.println("ARDUINO: no response received / no response received in time");
        }
  client.stop();
}

void reader(){
    userid=0;
  // Look for new cards
  if ( ! rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if ( ! rfid.PICC_ReadCardSerial())
    return;

  // Store NUID into nuidPICC array
  for (byte i = 0; i < 4; i++) {
    nuidPICC[i] = rfid.uid.uidByte[i];
    userid=userid+nuidPICC[i];
  }

  rfid.PICC_HaltA();

  rfid.PCD_StopCrypto1();

  sender();
}

void loop(){
  reader();
}

Uploader.php

<?php
$conexion = mysql_connect("localhost", "user", "pass");
mysql_select_db("db_name", $conexion);
mysql_query("SET NAMES 'utf8'");

$userid = $_GET ['userid'];

$sql1 = "SELECT nombre, ultima_entrada, ultimo_pago, dentro FROM usuarios WHERE id = '$userid'";
$retval = mysql_query( $sql1, $conexion );

if(! $retval ) {
  die('Could not get data: ' . mysql_error());
  echo "return error";
}

$row = mysql_fetch_array($retval, MYSQL_ASSOC);

$month = date('n',strtotime($row['ultimo_pago']));

$date = date('n');



if($month < $date){
    echo "El usuario:{$row['nombre']} es moroso  <br> ";   
}else{
   if($row['dentro']==0){
       echo "Usuario:{$row['nombre']} accediendo al lab <br>";
       $sql2 = "UPDATE usuarios SET dentro='1', ultima_entrada = CURRENT_TIMESTAMP WHERE id = '$userid'";
       mysql_query($sql2);
   }elseif($row['dentro']==1){
       echo "Usuario:{$row['nombre']} saliendo del lab <br>";
       $sql3 = "UPDATE usuarios SET dentro='0', ultima_salida = CURRENT_TIMESTAMP WHERE id = '$userid'";
       mysql_query($sql3);
   }
}

mysql_close();

?>

SQL table

CREATE TABLE `usuarios` (
  `id` varchar(11) NOT NULL,
  `nombre` tinytext NOT NULL,
  `admin` tinyint(1) NOT NULL DEFAULT '0',
  `ultima_entrada` timestamp NULL DEFAULT NULL,
  `ultima_salida` timestamp NULL DEFAULT NULL,
  `tiempo_total` time DEFAULT NULL,
  `ultimo_pago` date DEFAULT NULL,
  `dentro` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `usuarios` (`id`, `nombre`, `admin`, `ultima_entrada`, `ultima_salida`, `tiempo_total`, `ultimo_pago`, `dentro`) VALUES
('12345', 'John', 0, '2018-03-06 16:41:44', '2018-03-06 16:41:36', '00:00:00', '2018-03-01', 1);

注意:我正在使用虚拟用户ID,将来这将被更改,现在我只想从服务器获得响应 .

先感谢您!

1 回答

  • 0

    傻我!我在本博客的评论部分找到了我的问题的解决方案(来自UIPEthernet lib本身的作者!):

    https://www.tweaking4all.com/hardware/arduino/arduino-ethernet-data-push/#comment-21572

    如果您阅读评论,诺伯特说应该避免延误,这就是我错了 . 在我的代码中,我在GET请求后有一个漂亮的1秒延迟 . 删除它解决了这个问题 . 我的代码是基于这个:http://www.smartsustainability.org/CIS508/?page_id=2203但它是针对不同的WIFI /以太网屏蔽而制作的,而不是针对ENC28J60,这就是问题所在 . (虽然不是说这是一个糟糕的代码) .

    总之,解决方案是替换这一行:

    delay(1000);
    

    使用此循环,等待客户端可用:

    while(!client.available()){}
    

    希望这将避免未来的头痛!

相关问题