slik-dispenser/arduino/arduino.ino

87 lines
1.7 KiB
Arduino
Raw Normal View History

#include <Arduino_MKRIoTCarrier.h>
#include <WiFiNINA.h>
#include <ArduinoMqttClient.h>
#include "state.h"
#include "motor.h"
#include "secrets.h"
MKRIoTCarrier carrier;
WiFiSSLClient wifi_client;
MqttClient mqtt_client(wifi_client);
2023-12-20 20:32:14 +00:00
// Motor control variables
2023-11-29 15:00:54 +00:00
int motor_count = 0;
2023-12-20 15:43:56 +00:00
int motor_count_max = 64;
2023-12-20 16:29:11 +00:00
uint32_t green_led_color = carrier.leds.Color(0, 255, 0);
void setup()
{
Serial.begin(9600);
Serial.println("Started");
carrier.noCase();
carrier.begin();
carrier.display.init(240, 240);
motor_setup();
pinMode(TFT_BACKLIGHT, OUTPUT);
digitalWrite(TFT_BACKLIGHT, HIGH);
change_state(STATE_CONNECTING);
Serial.println("Connecting to WiFi...");
if (wifi_enterprise) WiFi.beginEnterprise(wifi_ssid, wifi_username, wifi_password);
else WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) delay(1000);
Serial.println("Connected to WiFi, connecting to MQTT...");
mqtt_client.setUsernamePassword(mqtt_username, mqtt_password);
if (!mqtt_client.connect(mqtt_server, 8883)) {
Serial.print("MQTT connection failed with error code: ");
Serial.println(mqtt_client.connectError());
return;
}
Serial.println("Connected to MQTT");
carrier.Buzzer.beep();
mqtt_client.subscribe("dispense");
change_state(STATE_LOGGED_OUT);
2023-11-26 22:16:48 +00:00
}
void loop()
{
carrier.Buttons.update();
2023-11-29 15:25:57 +00:00
// Rotate motor if needed
if (motor_count) {
motor_clockwise();
motor_count--;
}
2023-11-29 15:00:54 +00:00
2023-11-29 15:25:57 +00:00
// Receive MQTT messages
int message_size = mqtt_client.parseMessage();
if (message_size) {
Serial.print("Got message with topic: ");
Serial.println(mqtt_client.messageTopic());
if (mqtt_client.messageTopic() == "dispense") {
Serial.println("Dispensing...");
2023-11-29 15:00:54 +00:00
// Start rotating motor
2023-11-29 15:25:57 +00:00
motor_count = motor_count_max;
}
}
2023-12-20 16:29:11 +00:00
loop_state();
2023-11-29 15:00:54 +00:00
}