Read data from DHT11 using Android Things and i.MX7D - android-things

since a couple of days I'm struggling with a problem in reading temperature/humidity data from sensor (DHT11) using Android Things kit (i.MX7D). I've googled many examples and all of them were made using Arduino, Raspberry Pi or STM's (so C/C++), but none for i.MX7D and Java.
My problem is that I cannot read real values of temperature/humidity, because all I get from the sensor is only a boolean value indicating HIGH/LOW state. I haven't found any library for this sensor that would somehow help to convert it to real degrees/percent values.
Do you know if it's even possible to obtain these real values using the hardware that I have? If it is, could you please give me a hint or show some code how to do that, so that I can finally make some progress? I will much appreciate all kind of help.
Here is my piece of code:
import android.app.Activity;
import android.os.Bundle;
import com.google.android.things.pio.Gpio;
import com.google.android.things.pio.GpioCallback;
import com.google.android.things.pio.PeripheralManager;
public class MainActivity extends Activity {
private Gpio gpio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PeripheralManager manager = PeripheralManager.getInstance();
try {
gpio = manager.openGpio("GPIO2_IO05");
configureInput(gpio);
configureOutput(gpio);
} catch (IOException e) {
e.printStackTrace();
}
}
private GpioCallback gpioCallback = new GpioCallback() {
#Override
public boolean onGpioEdge(Gpio gpio) {
try {
if (gpio.getValue()) {
System.out.println("high");
} else {
System.out.println("low");
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
#Override
public void onGpioError(Gpio gpio, int error) {
System.out.println(gpio + ": Error event " + error);
}
};
public void configureInput(Gpio gpio) throws IOException {
gpio.setDirection(Gpio.DIRECTION_IN);
gpio.setActiveType(Gpio.ACTIVE_HIGH);
gpio.setEdgeTriggerType(Gpio.EDGE_BOTH);
gpio.registerGpioCallback(gpioCallback);
}
public void configureOutput(Gpio gpio) throws IOException {
gpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_HIGH);
gpio.setActiveType(Gpio.ACTIVE_LOW);
gpio.setValue(true);
}
}

It's not possible to read from that sensor from Android things. It uses a one wire protocol similar to I2C but the speed required for the GPIO port to be able to read it is too fast for Android things.
As suggested, you can read it using an Arduino and then connect the Arduino as I2C slave, of you can use a different temperature and humidity sensor, like the BME280 which communicate via I2C and it's still reasonably cheap

Related

How do you send message using NFC with Xamarin.Android?

I am developing and app to demostrate how NFC works. My goal is to make and app that will work very similary to Android Beam. I am using Xamarin.Android. The goal is to type message to one device, press button and it should be send to another device with the same app where it should be shown. I have tried almost everything even the documentation but it seems like it doesnt work. Does anyone have any experience with this technology? Is this technology even available nowadays?
There is some of my code to get you an idea about what i am trying to do:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
mNfcAdapter = NfcAdapter.GetDefaultAdapter(this);
myButton.Click += (e, o) => {
mNfcAdapter.SetNdefPushMessageCallback(this, this);
mNfcAdapter.SetOnNdefPushCompleteCallback(this, this);
};
}
public NdefMessage CreateNdefMessage(NfcEvent e)
{
DateTime time = DateTime.Now;
var text = (time.ToString("HH:mm:ss") + message2);
NdefMessage msg = new NdefMessage(
new NdefRecord[] { CreateMimeRecord (
text, Encoding.UTF8.GetBytes (text))});
return msg;
}
private NdefRecord CreateMimeRecord(string mimeType, byte[] payload)
{
byte[] mimeBytes = Encoding.UTF8.GetBytes(mimeType);
NdefRecord mimeRecord = new NdefRecord(
NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], payload);
return mimeRecord;
}
public void OnNdefPushComplete(NfcEvent e)
{
Toast.MakeText(this.ApplicationContext, "Message sent", ToastLength.Long).Show();
}
protected override void OnResume()
{
base.OnResume();
if (NfcAdapter.ActionNdefDiscovered == Intent.Action)
{
ProcessIntent(Intent);
}
}
protected override void OnNewIntent(Intent intent)
{
Intent = intent;
}
void ProcessIntent(Intent intent)
{
IParcelable[] rawMsgs = intent.GetParcelableArrayExtra(
NfcAdapter.ExtraNdefMessages);
NdefMessage msg = (NdefMessage)rawMsgs[0];
var textViewMsg = FindViewById<TextView>(Resource.Id.textViewMsg);
textViewMsg.Text = Encoding.UTF8.GetString(msg.GetRecords()[0].GetPayload());
}
Thank you all :)
OnNdefPushComplete and the whole Android Beam was deprecated and removed from Android 10
https://developer.android.com/reference/android/nfc/NfcAdapter.OnNdefPushCompleteCallback
If you want to do Device to Device NFC going forward then it should be possible with one phone doing Host Card Emulation (HCE) and the other using enableReaderMode
But Google recommend using Bluetooth or Wifi Direct as a more reliable replacement for Android Beam. One of the replacement methods Google provided was Android Nearby https://developers.google.com/nearby

QR code screen popup issue with BlackBerry os 6

I am trying to scan QR code with my code. My code is running fine with 5.0(Bold) and 7.1(Torch) OS phones. It is running fine with 7.1 and 5.0. but giving problem while running with 6.0 OS(Bold 9700). The problem is - "While trying to scan QR code, app scans the QR code but camera screen doesn't pop and it remains at the front. Event it is not able to hide by using Esc key". please help me to resolve the issue with os6.
Edit:
Code while opening camera screen for QR code scan:
Hashtable hints = new Hashtable();
// The first thing going in is a list of formats. We could look for
// more than one at a time, but it's much slower.
Vector formats = new Vector();
formats.addElement(BarcodeFormat.QR_CODE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, formats);
// We will also use the "TRY_HARDER" flag to make sure we get an
// accurate scan
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
// We create a new decoder using those hints
BarcodeDecoder decoder = new BarcodeDecoder(hints);
// Finally we can create the actual scanner with a decoder and a
// listener that will handle the data stored in the QR code. We put
// that in our view screen to handle the display.
try {
_scanner = new BarcodeScanner(decoder, new LeadQRcodeDecoderListener());
_QRcodeScreen = new LeadQRcodeScannerViewScreen(_scanner);
// If we get here, all the QR code scanning infrastructure should be set
// up, so all we have to do is start the scan and display the viewfinder
_scanner.startScan();
UiApplication.getUiApplication().pushScreen(_QRcodeScreen);
}
catch (Exception e) {
e.printStackTrace();
return;
}
code for closing screen is:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().popScreen(_QRcodeScreen);
}
});
I am calling this code after scanning of QR code.
This is a problem with OS6 in some devices that has been asked before on this site. Last one was two days ago:
Blackberry OS6 camera wont shut down after capture
AFAIK there's no API to close the camera app, so it has to be done with key injection hacks, that are tricky because they need accurate timing and as CPUs are different in some models, and also because the camera app has a different design in some OSes.
So either you use JSR135 and use a renamed Zxing package to provide a camera view contained in your app, or just follow your approach but instead of closing the camera app you just bring to foreground your own app.
I have solved my same issue for os 6. After scanning of QR code, close all player and scanner connection.
You can use-
if (_scanner != null && _scanner.getPlayer() != null) {
_scanner.getPlayer().close();
}
It is helpful to me.
This will definitely help you.
here is my code , it's working perfectly in OS 6.0 device 9830
/**
* First Invoke the QR Scanner
*/
ViewFinderScreen _viewFinderScreen =
new ViewFinderScreen(ShoopingCartScreen.this); // ShoopingCartScreen.this Current Screen Object
UiApplication.getUiApplication().pushScreen(_viewFinderScreen);
package com.application.qrScanner;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
import net.rim.device.api.barcodelib.BarcodeDecoder;
import net.rim.device.api.barcodelib.BarcodeDecoderListener;
import net.rim.device.api.barcodelib.BarcodeScanner;
import net.rim.device.api.io.Base64InputStream;
import net.rim.device.api.io.http.HttpDateParser;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Keypad;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.container.MainScreen;
import com.application.data.ShoopingCartObj;
import com.application.global.Global;
import com.application.log.Log;
import com.application.main.MessageScreen;
import com.application.main.orderDetail.orderSection.InputPopUpScreen;
import com.application.main.shoopingSection.ShoopingCartScreen;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
public class ViewFinderScreen extends MainScreen
{
private BarcodeScanner _scanner;
private short _frequency = 1046;
private short _duration = 200;
private int _volume = 100;
private VideoControl vc;
private ButtonField _btnCancel;
private ShoopingCartScreen _shoopingCartScreen;
/**
* Creates a new ViewFinderScreen object
*/
public ViewFinderScreen(ShoopingCartScreen _shoopingCartScreen)
{
this._shoopingCartScreen = _shoopingCartScreen;
_btnCancel = new ButtonField("Cancel" , ButtonField.USE_ALL_WIDTH)
{
protected boolean navigationClick(int status, int time)
{
fieldChangeNotify(1);
return true;
}
};
_btnCancel.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
stopScan();
UiApplication.getUiApplication().popScreen(ViewFinderScreen.this);
}
});
// Initialize Hashtable used to inform the scanner how to
// recognize the QR code format.
Hashtable hints = new Hashtable();
Vector formats = new Vector(1);
formats.addElement(BarcodeFormat.QR_CODE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, formats);
// Initialize the BarcodeDecoder
BarcodeDecoder decoder = new BarcodeDecoder(hints);
// Create a custom instance of a BarcodeDecoderListener to pop the
// screen and display results when a QR code is recognized.
BarcodeDecoderListener decoderListener = new BarcodeDecoderListener()
{
/**
* #see BarcodeDecoderListener#barcodeDecoded(String)
*/
public void barcodeDecoded(String rawText)
{
try {
String encoded = rawText;
byte[] decoded = Base64InputStream.decode( encoded );
rawText = new String(decoded);
System.out.println( new String( decoded ) );
}
catch (Throwable t) {
System.out.println( "Unable to decode string: " + t.getMessage() );
}
displayMessage(rawText);
ViewFinderScreen.this. _shoopingCartScreen.beep();
}
};
try
{
// Initialize the BarcodeScanner object and add the associated
// view finder.
_scanner = new BarcodeScanner(decoder, decoderListener);
vc = _scanner.getVideoControl();
vc.setDisplayFullScreen(true);
add(_scanner.getViewfinder());
setStatus(_btnCancel);
}
catch(Exception e)
{
displayMessage("Initilize Scanner: " + e.getMessage());
}
startScan();
}
/**
* Informs the BarcodeScanner that it should begin scanning for QR Codes
*/
public void startScan()
{
try
{
_scanner.startScan();
}
catch(MediaException me)
{
displayMessage(" Start Scan Error: " + me.getMessage());
}
}
public void stopScan()
{
try
{
Player p = _scanner.getPlayer() ;
if(p != null)
{
p.stop();
p.deallocate();
p.close();
}
}
catch (Exception e)
{
MessageScreen.msgDialog("Exception in Stop Scanning "+e.toString());
}
}
/**
* Pops the ViewFinderScreen and displays text on the main screen
*
* #param text Text to display on the screen
*/
private void displayMessage(final String text)
{
Log.d("QR Code String ", text);
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
stopScan();
}
});
}
protected boolean keyDown(int keycode, int time)
{
if (Keypad.key(keycode) == Keypad.KEY_ESCAPE)
{
stopScan();
return true;
}
return super.keyDown(keycode, time);
}
}

Unable to connect BlackBerry phone with Bluetooth SPP device

I am trying to connect to a bluetooth device from the blackberry 9900 phone using the following code;
public final class AppMainScreen extends MainScreen {
private BluetoothspInfo[] spInfo;
private StreamConnection bConn;
private DataInputStream diStream;
private String text;
public AppMainScreen() {
spInfo = BluetoothSerialPort.getSerialPortInfo();
try {
bConn = (StreamConnection) Connector.open(
spInfo[0].toString(), Connector.READ);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
UiApplication.getUiApplication().invokeLater(new TextScanner());
}
// ...
// ...
// ...
}
But its always throwing the exception java.io.IOException: Unable to connect. I am not able to get the full trace.
What is the problem here, can anybody please point me in the right direction.
I am using the BlackBerry Java on BlackBerry Eclipse Plugin with Platform version 4.5.

How to silence an incoming call

I am trying to silence an incoming call and prevent the BlackBerry device from ringing. I tried Alert.setVolume(0) and some EventInjector keys but this didn't work.
So how to silence an incoming call?
I was puzzled by your question and decided to take up the challenge. I tried different thing including
Playing a "silence" audio file hoping to overlap the device's ringing or occupy the media player
Hacking the phone screen via UiApplication.getUiApplication().getActiveScreen()
Injecting keyboard events
Eventually, injecting VOLUME UP key (VOLUME DOWN key works as well) event worked for me and muted the device ringing on incoming call. The drawback with this approach is that sometimes the device did ring for a fraction of second before muting.
import net.rim.blackberry.api.phone.AbstractPhoneListener;
import net.rim.blackberry.api.phone.Phone;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.EventInjector;
import net.rim.device.api.ui.Keypad;
class Muter extends AbstractPhoneListener {
public void callIncoming(int callId) {
Thread muterThread = new Thread(new Runnable() {
public void run() {
EventInjector.invokeEvent(new EventInjector.KeyCodeEvent(EventInjector.KeyCodeEvent.KEY_DOWN, (char) Keypad.KEY_VOLUME_UP, 0));
EventInjector.invokeEvent(new EventInjector.KeyCodeEvent(EventInjector.KeyCodeEvent.KEY_UP, (char) Keypad.KEY_VOLUME_UP, 0));
}
});
muterThread.setPriority(Thread.MAX_PRIORITY);
muterThread.start();
}
}
public class MuterApp extends Application {
public static void main(String[] args){
Phone.addPhoneListener(new Muter());
new MyApp().enterEventDispatcher();
}
}
The following also works (replace Muter thread in callIncoming() method with the following code).
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
EventInjector.invokeEvent(new EventInjector.KeyCodeEvent(EventInjector.KeyCodeEvent.KEY_DOWN, (char) Keypad.KEY_VOLUME_UP, 0));
EventInjector.invokeEvent(new EventInjector.KeyCodeEvent(EventInjector.KeyCodeEvent.KEY_UP, (char) Keypad.KEY_VOLUME_UP, 0));
}
});
You won't be able to disable the sound programmatically (found a couple other sources that said the same thing). The best workaround people have seemed to come up with was to use the EventInjector to change the phone's sound profile to silent.
Some Blackberry phones have a mute key. You may try the following idea:
public void callIncoming(int callId) {
if (KeyPad.hasMuteKey()) {
/* Inject KEY_SPEAKERPHONE event */
}
else {
/* Inject KEY_VOLUME_DOWN event N times, so that you get the mute effect */
}
}
i am quite new to all this...but i thought i might as well put in my 2 cents worth...
i have been trying to find ways to programatically change the profile settings...
i have found that, while we cannot(yet) change the profile settings, we can change the setting that we are using( change the profile thats in use, i think)- this is something i came across searching for info-though i should give credit to alishaik786 for the code.
public final class LoadingScreen extends MainScreen implements FieldChangeListener
{
public LoadingScreen()
{
createGUI();
}
private void createGUI()
{
try
{
ApplicationManager.getApplicationManager().launch("net_rim_bb_profiles_app");
}
catch (Exception e)
{
//Exception
}
}
public void fieldChanged(Field field, int context)
{
}
}

How can I get FilePicker working properly on certain BlackBerry handsets?

I'm implementing a Filepicker in my app to allow users to choose photos from their phones. The code I'm using is as follows:
Calling the Filepicker:
try
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
FilePicker fp = FilePicker.getInstance();
fileListener = new FilePickListener();
fp.setListener(fileListener);
fp.show();
}
});
}
catch (Exception e)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Please check your data card..");
}
});
}
And the method to get the filename in my FilePickListener:
public void selectionDone(String str)
{
this.currFileName = str;
int index = str.lastIndexOf('/');
Dialog.alert("Filename: "+str.substring(index+1).trim());
}
This works perfectly in most handsets that I've tried it on (which have been a mix of handsets with some running OS5 and some running OS6). But on some, like the 8900 (running OS v5.0.0.411) it doesn't work properly. The Filepicker gets called and appears, but when any file gets selected, the selectionDone method doesn't get called. I've tested it on two separate 8900s and both have the same problem.
Does anyone have an idea why it works on certain handsets and not other?
You are a victim of a known RIM issue: FilePicker throws ControlledAccessException.
The issue is marked as "Fixed". However there is no info in which OS version they fixed it. (Is it so difficult to tell such a useful info?)
But from the comments to the issue:
We experience the very same issue with OS 5.0.0.321 on a Bold 9700. However, the issue does NOT appear on OS 5.0.0.464
so my guess would be they fixed it in OS 5.0.0.464. But that's not the end - in OS 6 FilePicker appears broken in early versions of OS 6 again. The conclusion - just don't use it. Use a custom file browser screen to pick a file. There is a sample in SDK 4.7.0 named FileExplorerDemo, check it for implementation details.
This is a known issue. FilePicker does not open on some devices and return an error, like the 8900 device. You can catch this error on some devices by adding the catch (Error e) { }
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
FilePicker fp = FilePicker.getInstance();
fileListener = new FilePickListener();
fp.setListener(fileListener);
fp.show();
}
});
}
catch (Exception e)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Please check your data card..");
}
});
}
catch (Error e)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("This device does not support File Picker");
}
});
}

Resources