Reading cloud variable

Hi guys,

am building a small app in android studio that reads the electron sensor variable from the particle cloud every ten seconds. It works fine, i can read the variables from the sensor values on my app, its all good. Just that i am only able to get the values when the electron is connected to the usb cable, when i unplug the usb cable and use battery power, i get a zero reading on the sensor values. As soon as i plug in the usb cable to the electron, i get normal values, and when i unplug i get a zero reading on my app.

here’s my android studio and electron code if you need to see it

android studio :

package com.example.smart_trashcan;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IntegerRes;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TimerTask;

import io.particle.android.sdk.cloud.ParticleCloud;
import io.particle.android.sdk.cloud.ParticleCloudSDK;
import io.particle.android.sdk.cloud.ParticleDevice;
import io.particle.android.sdk.cloud.exceptions.ParticleCloudException;
import io.particle.android.sdk.utils.Async;
import io.particle.android.sdk.utils.Toaster;

public class MainActivity extends AppCompatActivity {

    ArrayList canNumbers = new ArrayList<>(Arrays.asList("Trash Can 1"));//, "Trash Can 2", "Trash Can 3", "Trash Can 4", "Trash Can 5", "Trash Can 6", "Trash Can 7","Trash Can 8", "Trash Can 9", "Trash Can 10", "Trash Can 11", "Trash Can 12", "Trash Can 13", "Trash Can 14"));
    ArrayList trashCanImgs = new ArrayList<>(Arrays.asList(R.mipmap.trash));//,R.mipmap.trash,R.mipmap.trash, R.mipmap.trash, R.mipmap.trash, R.mipmap.trash, R.mipmap.trash,R.mipmap.trash,R.mipmap.trash,R.mipmap.trash,R.mipmap.trash,R.mipmap.trash,R.mipmap.trash, R.mipmap.trash));

    RecyclerView recyclerView;
    private static final String ARG_DEVICEID = "ARG_DEVICEID";
    double bucketHeight;
    ProgressDialog progressDialog;
    private NotificationManager mNotificationManager;
    private static String DEFAULT_CHANNEL_ID = "default_channel";
    private static String DEFAULT_CHANNEL_NAME = "Default";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ParticleCloudSDK.init(this);
        setContentView(R.layout.activity_main);
// get the reference of RecyclerView
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

// set a LinearLayoutManager with default vertical orientaion
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager); // set LayoutManager to RecyclerView

        Button refresh = (Button) findViewById(R.id.loadmore);

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("Loading...");
        progressDialog.show();

        final String email = "itwabi@gmail.com";
        final String password = "tellepie123";

        System.out.println("async task is executing now");

        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //RunAsync(recyclerView, email, password, bucketHeight, canNumbers, trashCanImgs, canLevel);
                Async.executeAsync(ParticleCloudSDK.getCloud(), new Async.ApiWork<ParticleCloud, Object>() {


                    @Override
                    public Object callApi(@NonNull ParticleCloud sparkCloud) throws ParticleCloudException, IOException {
                        sparkCloud.logIn(email, password);

                        sparkCloud.getDevices();
                        ParticleDevice device = sparkCloud.getDevice("37005a000551353431383736");
                        System.out.println(device.getVariables().size());
                        Object obj;


                        try {
                            obj = device.getVariable("analogvalue");
                            int looper = Integer.parseInt(obj.toString());
                            Log.d("BANANA", "distance: " + obj);
                            System.out.println("getting variable");

                        } catch (ParticleDevice.VariableDoesNotExistException e) {
                            Toaster.s(MainActivity.this, e.getMessage());
                            obj = -2;
                        }

                        return obj;
                    }

                    @Override
                    public void onSuccess(@NonNull Object value) {
                        //Toaster.l(MainActivity.this, "Logged in");
                        //Toaster.l(MainActivity.this, "raw value: " + value.toString());

                        ArrayList<Double> canLevel = new ArrayList<>();

                        double raw = Double.valueOf(value.toString());
                        //double percentage = (raw/bucketHeight) * 100;
                        canLevel.add(raw);

                        System.out.println("raw : " + raw);
                        if(raw < 5.0){
                            sendNotification("TrashCan 1", "at physics dpt, trash is ready for collection");
                            System.out.println("notification sent");
                        }

                        CustomAdapter customAdapter = new CustomAdapter(MainActivity.this, canNumbers, trashCanImgs, canLevel);
                        bucketHeight = canLevel.get(0);
                        recyclerView.setAdapter(customAdapter);
                        progressDialog.dismiss();
                        //Intent intent = MainActivity.buildIntent(MainActivity.this, 123, mDevice.getID());
                        //startActivity(intent);
                    }

                    @Override
                    public void onFailure(@NonNull ParticleCloudException e) {
                        Toaster.l(MainActivity.this, e.getBestMessage());
                        e.printStackTrace();
                        Log.d("info", e.getBestMessage());
                    }
                });


            }
        });



        Handler handler = new Handler();
        int delay = 10000; //milliseconds

        handler.postDelayed(new Runnable(){
            public void run(){
                //do something
                System.out.println("am looping!");

                Async.executeAsync(ParticleCloudSDK.getCloud(), new Async.ApiWork<ParticleCloud, Object>() {


                    @Override
                    public Object callApi(@NonNull ParticleCloud sparkCloud) throws ParticleCloudException, IOException {
                        sparkCloud.logIn(email, password);

                        sparkCloud.getDevices();
                        ParticleDevice device = sparkCloud.getDevice("37005a000551353431383736");
                        System.out.println(device.getVariables().size());
                        Object obj;


                        try {
                            obj = device.getVariable("distance");
                            Log.d("BANANA", "distance: " + obj);
                            System.out.println("getting variable");
                        } catch (ParticleDevice.VariableDoesNotExistException e) {
                            Toaster.s(MainActivity.this, e.getMessage());
                            obj = -2;
                        }

                        return obj;
                    }

                    @Override
                    public void onSuccess(@NonNull Object value) {
                        //Toaster.l(MainActivity.this, "Logged in");
                        //Toaster.l(MainActivity.this, "raw value: " + value.toString());
                        ArrayList<Double> canLevel1 = new ArrayList<>();

                        double raw = Double.valueOf(value.toString());
                        //double percentage = (raw/bucketHeight) * 100;
                        canLevel1.add(raw);

                        System.out.println("raw : " + raw);
                        if(raw < 5.0){
                            sendNotification("TrashCan 1", "at physics dpt, trash is ready for collection");
                            System.out.println("notification sent");
                        }

                        CustomAdapter customAdapter = new CustomAdapter(MainActivity.this, canNumbers, trashCanImgs, canLevel1);
                        recyclerView.setAdapter(customAdapter);
                        progressDialog.dismiss();
                        //Intent intent = MainActivity.buildIntent(MainActivity.this, 123, mDevice.getID());
                        //startActivity(intent);
                    }

                    @Override
                    public void onFailure(@NonNull ParticleCloudException e) {
                        Toaster.l(MainActivity.this, e.getBestMessage());
                        e.printStackTrace();
                        Log.d("info", e.getBestMessage());
                    }
                });

                handler.postDelayed(this, delay);
            }
        }, delay);

    }

    public void sendNotification(String title, String message){
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        createNotificationChannel(mNotificationManager);

        //2.Build Notification with NotificationCompat.Builder
        Notification notification = new NotificationCompat.Builder(MainActivity.this, DEFAULT_CHANNEL_ID)
                .setContentTitle(title)   //Set the title of Notification
                .setContentText(message)    //Set the text for notification
                .setSmallIcon(android.R.drawable.ic_menu_view)   //Set the icon
                .build();

        //Send the notification.
        mNotificationManager.notify(1, notification);
    }


    public static void createNotificationChannel(NotificationManager notificationManager) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //Create channel only if it is not already created
            if (notificationManager.getNotificationChannel(DEFAULT_CHANNEL_ID) == null) {
                notificationManager.createNotificationChannel(new NotificationChannel(
                        DEFAULT_CHANNEL_ID, DEFAULT_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT
                ));
            }
        }
    }
}

electron code :

const int trigPin = 2;
const int echoPin = 6;

int tempC;
int analogvalue;
int aString;
// defines variables
long duration;
double distance;

void setup() {
    Particle.variable("distance", &distance, DOUBLE);
    Particle.variable("duration", &duration);
    Particle.variable("analogvalue", &analogvalue, INT);
    pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
    pinMode(echoPin, INPUT); // Sets the echoPin as an Input
    Serial.begin(9600); // Starts the serial communication
    
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);

//analogvalue = addition(distance + 0);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);

analogvalue = 129;
}

long microsecondsToCentimeters(long microseconds) {
   return microseconds / 29 / 2;
}

Your input will be appreciated.

How are you powering the sensor?
With battery only supply you will not get any voltage on the Vin pin.

This syntax is outdated, you should now write it like this

    Particle.variable("distance", distance);
    Particle.variable("duration", duration);
    Particle.variable("analogvalue", analogvalue);

Yah, i am using the Vin pin of the electron, i guess that why i am not getting any readings when i unplug. So considering my project needs to be deployed outside without the usb cable, how do i power my HC-SR04 sensor with only battery power? Coz the sensor needs to be connected to the Vin and the project needs to work outdoors. any ideas?

thanks for the code correction.

This not true - it doesn’t need to be connected to Vin.

Rather, since this sensor requires 5V an the LiPo can only supply about 3.7V (nominal) you will need to step-up the voltage.
You’d typically do that with a step-up converter fed via the 3v3 pin.

okay i will try that. Thanks for your immense help!

1 Like