การเก็บข้อมูลจาก Arduino ไปเก็บลงใน Database Mysql (Arduino to database)
หลักการทำงานเราจะใช้ Methol Get ของ php ในการฝาก ข้อมูลไปกับ Url ยกตัวอย่างเช่น
http://www.domain.com/index.php?temp=25
หรือในรูปแบบ ip
http://192.168.1.1/index.php?temp=25
จากนั้นให้ PHP ในการรับข้อมูลและบันทึกลงใน Database
ตัวอย่างไฟล์
Sql Blackup Database Mysql
CREATE TABLE `temp` (
`id` int(11) NOT NULL auto_increment,
`temp` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
INSERT INTO `temp` VALUES (1, '99.2');
Config.php (ใช้ระบุข้อมูลการเชื่อมต่อเข้า Database)
$host = "localhost";
$user = "root";
$pass = "123456";
$db = "send";
mysql_connect($host, $user, $pass) or die("Could not connect to database");
mysql_select_db($db) or die("Could not connect to database");
mysql_query("SET NAMES utf8")
?>
temp.php (ใช้รับค่าจาก Arduino และบันทึกลงใน Mysql)
require_once("config.php");
$temp = $_GET['Temp'];
$sql = "UPDATE temp SET temp = '$temp' WHERE id =1";
$sql_query = mysql_query($sql);
if ($sql_query) {
echo "Complete";
} else {
echo "Error";
}
?>
Code Arduino (เลือกใช้ Arduino Uno R3 + W5100)
#include
#include
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server(192,168,0,101); // ใช้ในกรณีเป็น IP
//char server[] = "www.google.com"; // ใช้ในกรณีเป็น Domain
IPAddress ip(192, 168, 0, 177); // IP ของ Arduino
EthernetClient client;
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
Ethernet.begin(mac, ip);
}
delay(1000);
Serial.println("connecting...");
}
void loop()
{
if (client.connect(server, 80)) {
Serial.println("connected");
client.println("GET /temp/temp.php?temp=25 HTTP/1.1");
client.println("Host: www.google.com");
client.println("Connection: close");
client.println();
}
else {
Serial.println("connection failed");
}
}
Youtube
https://www.youtube.com/watch?v=RytNd_GL9x0
หน้าที่เข้าชม | 4,524,145 ครั้ง |
ผู้ชมทั้งหมด | 2,479,917 ครั้ง |
ร้านค้าอัพเดท | 27 ก.ย. 2568 |