找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 2326|回复: 1
打印 上一主题 下一主题
收起左侧

esp8266智能电子秤 Arduino源程序

[复制链接]
跳转到指定楼层
楼主


Arduino源程序如下:
  1. // DIY Smart Scale with Alarm Clock v0.1 by Igor Fonseca @2018
  2. // Based on Instructables Internet of Things Class sample code and SparkFun HX711 example
  3. // Saves weight online on Adafruit.io.
  4. // Displays measured weight on a local display.
  5. // Read and display current time from an internet server.
  6. // Configurable alarm clock with buzzer.
  7. //
  8. // Modified by Igor Fonseca 2018
  9. // based on Instructables Internet of Things Class sample code by Becky Stern 2017
  10. // based on Example using the SparkFun HX711 breakout board with a scale by Nathan Seidle 2017
  11. //
  12. // Adafruit invests time and resources providing this open source code.
  13. // Please support Adafruit and open source hardware by purchasing
  14. // products from Adafruit!
  15. //
  16. // Written by Todd Treece for Adafruit Industries
  17. // Copyright (c) 2016 Adafruit Industries
  18. // Licensed under the MIT license.
  19. //
  20. // All text above must be included in any redistribution.

  21. /************************ Adafruit IO Configuration *******************************/

  22. // visit io.adafruit.com if you need to create an account,
  23. // or if you need your Adafruit IO key.
  24. #define IO_USERNAME    "XXXXX"
  25. #define IO_KEY         "YYYYY"

  26. /******************************* WIFI Configuration **************************************/

  27. #define WIFI_SSID       "ZZZZZ"
  28. #define WIFI_PASS       "WWWWW"

  29. #include <AdafruitIO_WiFi.h>
  30. AdafruitIO_WiFi io(IO_USERNAME, IO_KEY, WIFI_SSID, WIFI_PASS);

  31. /************************ Main Program Starts Here *******************************/

  32. /******************************** Libraries **************************************/
  33. #include <ESP8266WiFi.h> // ESP8266 library
  34. #include <AdafruitIO.h>  // Adafruit IO library
  35. #include <Adafruit_MQTT.h> // Adafruit MQTT library
  36. #include <ArduinoHttpClient.h>  // http Client
  37. #include <HX711.h>  // HX711 library for the scla
  38. #include "DFRobot_HT1632C.h" // Library for DFRobot LED matrix display
  39. #include <EEPROM.h> // Library for reading/writing on the memory

  40. /******************************* Definitions *************************************/

  41. #define calibration_factor -22795.0 //-7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch

  42. #define DOUT 0  // Pin connected to HX711 data output pin
  43. #define CLK  12  // Pin connected to HX711 clk pin

  44. #define NUM_MEASUREMENTS 10 // Number of measurements
  45. #define THRESHOLD 2                        // Measures only if the weight is greater than 2 kg. Convert this value to pounds if you're not using SI units.
  46. #define THRESHOLD1 0.2  // Restart averaging if the weight changes more than 0.2 kg.

  47. #define DATA D6 // Pin for DFRobot LED matrix display
  48. #define CS D2   // Pin for DFRobot LED matrix display
  49. #define WR D7   // Pin for DFRobot LED matrix display

  50. #define MEM_ALOC_SIZE 8

  51. DFRobot_HT1632C ht1632c = DFRobot_HT1632C(DATA, WR,CS); // set up LED matrix display

  52. AdafruitIO_Feed *myWeight = io.feed("my-weight");     // set up the 'iot scale' feed
  53. AdafruitIO_Feed *alarmTime = io.feed("alarm-clock");  // set up the 'iot scale' feed

  54. String TimeDate = ""; // Variable used to store the data received from the server
  55. int hours;    // Current hour
  56. int minutes;  // Current minute
  57. int seconds;  // Current second
  58. int seconds0; // Last time the clock was updated
  59. #define TIMEZONE  3 // Current time zone. Used for correction of server time

  60. int alarmhour;    // Alarm hour
  61. int alarmminute;  // Alarm minute
  62. boolean alarm = false; // Alarm status. True = turn on the buzzer
  63. boolean latch = false; // This variable inhibits the alarm until next minute

  64. int bedtimehour = 23;      // Disables the display from this time until next morning
  65. int bedtimeminute = 00;    // Disables the display from this time until next morning
  66. boolean displayStatus = true;  // Display status. True = display on

  67. HX711 scale(DOUT, CLK);  // Scale initialization
  68. float weight = 0.0;      // Last measured weight
  69. float prev_weight = 0.0; // Previous measeured weigt

  70. int frequency = 600; // Sound frequency specified in Hz
  71. #define buzzer  D3   // Buzzer positive pin
  72. #define groundPin  D5 // Buzzer negative pin. It's used as a ground pin.
  73. int timeOn = 200;     // Duration for buzzer on (specified in milliseconds)
  74. int timeOff = 200;    // Duration for buzzer off (specified in millisecods)

  75. /********************************** Setup ****************************************/

  76. void setup() {

  77.   // Configure IO pins
  78.   pinMode(buzzer, OUTPUT);
  79.   pinMode(groundPin, OUTPUT); // this pin was used to emulate a GND pin
  80.   digitalWrite(groundPin, LOW);

  81.   // Start the serial connection
  82.   Serial.begin(115200);
  83.   Serial.println("");
  84.   Serial.println("***************************************************");
  85.   Serial.println("DIY Smart Scale with Alarm Clock v0.1 by Igor @2018");
  86.   Serial.println("***************************************************");
  87.   
  88.   // Setup LED matrix display
  89.   ht1632c.begin();
  90.   ht1632c.isLedOn(true);
  91.   ht1632c.clearScreen();
  92.   delay(500);
  93.   
  94.   // Connect to io.adafruit.com
  95.   Serial.print("Connecting to Adafruit IO");
  96.   io.connect();
  97.   
  98.   // Set up a message handler for the 'my weight' feed.
  99.   // The handleMessage function (defined below)
  100.   // will be called whenever a message is
  101.   // received from adafruit io.
  102.     alarmTime->onMessage(handleMessage);

  103.   // Wait for a connection
  104.   ht1632c.print("connecting...",50);
  105.   while(io.status() < AIO_CONNECTED) {
  106.     Serial.print(".");
  107.     ht1632c.print("...",50);
  108.     ESP.wdtFeed();
  109.     delay(500);
  110.   }

  111.   // We are connected
  112.   Serial.println(io.statusText());
  113.   ESP.wdtFeed();
  114.   ht1632c.print("connected...",50);
  115.   ht1632c.clearScreen();

  116.   // Scale calibration
  117.   scale.set_scale(calibration_factor); //This value is obtained by using the SparkFun_HX711_Calibration sketch
  118.   scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0

  119.   // Get current time from server
  120.   getTime();
  121.   seconds0 = millis();

  122.   // Read alarm values from EEPROM memory
  123.   EEPROM.begin(MEM_ALOC_SIZE);
  124.   alarmhour = EEPROM.read(0);
  125.   alarmminute = EEPROM.read(1);
  126.   EEPROM.end();
  127.   Serial.print("Alarm set to: ");
  128.   if (alarmhour < 10) {
  129.     Serial.print("0");
  130.   }
  131.   Serial.print(alarmhour);
  132.   Serial.print(":");
  133.   if (alarmminute < 10) {
  134.     Serial.print("0");
  135.   }
  136.   Serial.println(alarmminute);
  137. }

  138. void loop() {

  139.   // io.run(); is required for all sketches.
  140.   // it should always be present at the top of your loop
  141.   // function. it keeps the client connected to
  142.   // io.adafruit.com, and processes any incoming data.
  143.   io.run();
  144.   ESP.wdtFeed();

  145.   // Read current weight
  146.   weight = scale.get_units();
  147.   float avgweight = 0;
  148.   if (weight > THRESHOLD) { // Takes measures if the weight is greater than the threshold
  149.     float weight0 = scale.get_units();
  150.     delay(1000);
  151.           for (int i = 0; i <= NUM_MEASUREMENTS; i++) {  // Takes several measurements
  152.                   weight = scale.get_units();
  153.       delay(100);
  154.       Serial.println(weight);
  155.                   avgweight = avgweight + weight;
  156.       if (abs(weight - weight0) > THRESHOLD1) {
  157.         avgweight = 0;
  158.         i = 0;
  159.       }
  160.       weight0 = weight;
  161.           }
  162.           avgweight = avgweight / NUM_MEASUREMENTS; // Calculate average weight
  163.           Serial.print("Measured weight: ");
  164.           Serial.print(avgweight, 1);
  165.           Serial.println(" kg");
  166.    
  167.     alarm = false; // disable alarm
  168.     latch = true;  // disable alarm for one minute
  169.    
  170.     char result[8]; // Buffer big enough for 7-character float
  171.     dtostrf(avgweight, 6, 1, result);
  172.     ht1632c.clearScreen();
  173.           ht1632c.print(result);  // Display measured weight on LED display
  174.    
  175.           //save myWeight to Adafruit.io
  176.           myWeight->save(avgweight);
  177.           
  178.           // wait while there's someone on the scale
  179.           while (scale.get_units() > THRESHOLD) {
  180.             ESP.wdtFeed();
  181.     }
  182.           
  183.           //keep LEDs on for two seconds then restart
  184.           delay(2000);
  185.     ht1632c.clearScreen();
  186.   }

  187.   // update clock on display every 5 seconds
  188.   if ((millis() - seconds0) > 5000) {
  189.     seconds = seconds + 5;

  190.     // synchronize with the server every 60 seconds
  191.     if (seconds > 59) {
  192.       getTime();
  193.       latch = false;
  194.     }

  195.     // verify bed time
  196.     if ((hours == bedtimehour) && (minutes == bedtimeminute)) {
  197.       displayStatus = false; // disable display if it's already bed time
  198.     }

  199.     // display clock
  200.     char clocktime[5];   // Buffer big enough for 5-character float
  201.     char hourstime[1];   // Buffer big enough for 2-character float
  202.     char minutestime[2]; // Buffer big enough for 2-character float

  203.     // format clock value for the display
  204.     if ((hours < 10) && (minutes < 10)) {
  205.       sprintf(clocktime,"0%d:0%d",hours,minutes);  // Concatenate string for display
  206.     }
  207.     if ((hours < 10) && (minutes >= 10)) {
  208.       sprintf(clocktime,"0%d:%d",hours,minutes);  // Concatenate string for display
  209.     }
  210.     if ((hours >= 10) && (minutes < 10)) {
  211.       sprintf(clocktime,"%d:0%d",hours,minutes);  // Concatenate string for display
  212.     }
  213.     if ((hours >= 10) && (minutes >= 10)) {
  214.       sprintf(clocktime,"%d:%d",hours,minutes);  // Concatenate string for display
  215.     }
  216.     ht1632c.clearScreen();
  217.     if (displayStatus == true) {
  218.       ht1632c.print(clocktime);  // Display current time on LED matrix
  219.     }
  220.     seconds0 = millis();
  221.   }
  222.   
  223.   // trigger alarm clock
  224.   if ((hours == alarmhour) && (minutes == alarmminute) && (latch == false)) {
  225.       alarm = true;
  226.       displayStatus = true; // turn on display
  227.   }
  228.   // activate buzzer
  229.   if (alarm == true) {
  230.     tone(buzzer, frequency);
  231.     delay(timeOn);
  232.     noTone(buzzer);
  233.     delay(timeOff);
  234.   }
  235. }


  236. // this function is called whenever a message
  237. // is received from Adafruit IO. it was attached to
  238. // the feed in the setup() function above.
  239. void handleMessage(AdafruitIO_Data *data) {

  240.     String commandStr = data->toString(); // store the incoming commands in a string
  241.    
  242.     // read alarm time
  243.     alarmhour = commandStr.substring(0,2).toInt();
  244.     alarmminute = commandStr.substring(3,5).toInt();
  245.    
  246.     // serial output received values
  247.     Serial.print("Alarm set to: ");
  248.     if (alarmhour < 10) {
  249.       Serial.print("0");
  250.     }
  251.     Serial.print(alarmhour);
  252.     Serial.print(":");
  253.     if (alarmminute < 10) {
  254.       Serial.print("0");
  255.     }
  256.     Serial.println(alarmminute);

  257.     // store time on EEPROM memory
  258.     EEPROM.begin(MEM_ALOC_SIZE);
  259.     EEPROM.write(0,alarmhour);
  260.     EEPROM.write(1,alarmminute);
  261.     EEPROM.end();
  262. }

  263. //Get current time Google server
  264. void getTime() {

  265.   // connect server
  266.   WiFiClient client;
  267.   while (!!!client.connect("google.com", 80)) {
  268.     Serial.println("connection failed, retrying...");
  269.     ESP.wdtFeed();
  270.   }
  271.   client.print("HEAD / HTTP/1.1\r\n\r\n");

  272.   delay(500); //wait a few milisseconds for incoming message

  273.   //if there is an incoming message
  274.   if(client.available()){
  275.     while(client.available()){
  276.       if (client.read() == '\n') {   
  277.         if (client.read() == 'D') {   
  278.           if (client.read() == 'a') {   
  279.             if (client.read() == 't') {   
  280.               if (client.read() == 'e') {   
  281.                 if (client.read() == ':') {   
  282.                   client.read();
  283.                   String theDate = client.readStringUntil('\r');
  284.                   client.stop();

  285.                   TimeDate = theDate.substring(7);
  286.                   String strCurrentHour = theDate.substring(17,19);
  287.                   String strCurrentMinute = theDate.substring(20,22);
  288.                   String strCurrentSecond = theDate.substring(23,25);
  289.                   // store received data on global variables
  290.                   hours = strCurrentHour.toInt();
  291.                   hours = hours - TIMEZONE; // compensate for TIMEZONE
  292.                   if (hours < 0) {
  293.                     hours = hours + 24;
  294.                   }
  295.                   minutes = strCurrentMinute.toInt();
  296.                   seconds = strCurrentSecond.toInt();
  297.                 }
  298.               }
  299.             }
  300.           }
  301.         }
  302.       }
  303.     }
  304.   }
  305.   //if no message was received (an issue with the Wi-Fi connection, for instance)
  306.   else{
  307.     seconds = 0;
  308.     minutes += 1;
  309.     if (minutes > 59) {
  310.       minutes = 0;
  311.       hours += 1;
  312.       if (hours > 23) {
  313.         hours = 0;
  314.       }
  315.     }
  316.   }

  317.   // serial output current time
  318.   Serial.print("Current time: ");
  319.   if (hours < 10) {
  320.    Serial.print("0");
  321.   }
  322.   Serial.print(hours);
  323.   Serial.print(":");
  324.   if (minutes < 10) {
  325.    Serial.print("0");
  326.   }
  327.   Serial.println(minutes);
  328.   
  329. }

复制代码

所有资料51hei提供下载:
iot-scale-clock-firebeetle-v0-1.zip (4.1 KB, 下载次数: 15)



分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏2 分享淘帖 顶 踩
回复

使用道具 举报

沙发
ID:1 发表于 2019-5-31 18:23 | 只看该作者
本帖需要重新编辑补全电路原理图,源码,详细说明与图片即可获得100+黑币(帖子下方有编辑按钮)
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表