I have an Arduino MKR Wifi 1010, with a HC-SR04 ultrasonic sensor plugged in
What I want to do is get some measures and send them in a post request using the wifi network
Everything works fine if I use the USB port to power the Arduino, if I plug in the battery (LiPo, 3.7V) the sensor will get just 0 measure all the time, any idea why? Is it because the sensor should work at 5V?
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoJson.h>
#include "arduino_secrets.h"
#define TRIG_PIN 6 // TRIG pin
#define ECHO_PIN 7 // ECHO pin
#define SAMPLES 7
char ssid[] = SECRET_SSID; // your network SSID (name)
char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS; // the Wifi radio's status
float ultraSonicMeasures[SAMPLES]; // array to store data samples from sensor
float distance; // store the distance from sensor
int baskets = 0;
IPAddress server(192,168,1,110);
WiFiClient client;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
// check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
// don't continue
while (true)
;
}
String fv = WiFi.firmwareVersion();
if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
Serial.println("Please upgrade the firmware");
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(3000);
}
Serial.println("Connected to wifi");
printWifiStatus();
// configure the trigger and echo pins to output mode
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
Serial.println("Getting ultrasonic measures");
for (int sample = 0; sample < SAMPLES; sample++) {
ultraSonicMeasures[sample] = ultrasonicMeasure();
delay(10); // to avoid untrasonic interfering
}
Serial.println("Sending measures");
postData(ultraSonicMeasures);
}
float ultrasonicMeasure() {
// generate 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// measure duration of pulse from ECHO pin
float duration_us = pulseIn(ECHO_PIN, HIGH);
// calculate the distance, 0.017 -> sound speed/2
float distance_cm = 0.017 * duration_us;
return distance_cm;
}