Invalid characters Arduino, Bluetooth (HM10 ) and Xamarin.Forms - xamarin

I am having an issue trying to send commands to my Arduino Mega from my Android Xamarin.Forms app. When i use Bluetooth terminal app from play store it works, but my code does not. In the Arduino terminal i am just getting squares as if it is a baud rate issue or something. but from what i can see the baud rate is always determined by the device, which defaults to 9600 for the HM10.
I am using this library for the bluetooth https://github.com/xabre/xamarin-bluetooth-le
Arduino Sketch (works with bt terminal app)
void loop()
{
// Read from the Bluetooth module and send to the Arduino Serial Monitor
if (Serial3.available())
{
byte y = Serial3.read();
//int x = (int)y;
Serial.write(y);
}
// Read from the Serial Monitor and send to the Bluetooth module
if (Serial.available())
{
c = Serial.read();
// do not send line end characters to the HM-10
if (c != 10 & c != 13)
{
Serial3.write(c);
}
// Echo the user input to the main window.
// If there is a new line print the ">" character.
if (NL) { Serial.print("\r\n>"); NL = false; }
Serial.write(c);
if (c == 10) { NL = true; }
}
}
Then my send code in my Xamarin.Forms app
private async Task Button_ClickedAsync(object sender, EventArgs e)
{
if (_charataristice != null && _charataristice.CanWrite)
{
var data = Convert.ToByte(16);
_charataristice.WriteType = CharacteristicWriteType.WithoutResponse;
await _charataristice.WriteAsync(new[] { data });
}
}
Would appreciate any help, the value i am trying to revive is alwasy a number and should fall within one byte.

Related

TTGO ESP32 + GSM 800l - Read SMS - TinyGSM

on my code i can send an sms to my target number but i don't know how to read or receive sms from target number
the tinyGSM library doesn't have the read member function and i don't know how to use AT commands
void setup() {
// Set console baud rate
SerialMon.begin(115200);
// Keep power when running from battery
Wire.begin(I2C_SDA, I2C_SCL);
bool isOk = setPowerBoostKeepOn(1);
SerialMon.println(String("IP5306 KeepOn ") + (isOk ? "OK" : "FAIL"));
// Set modem reset, enable, power pins
pinMode(MODEM_PWKEY, OUTPUT);
pinMode(MODEM_RST, OUTPUT);
pinMode(MODEM_POWER_ON, OUTPUT);
digitalWrite(MODEM_PWKEY, LOW);
digitalWrite(MODEM_RST, HIGH);
digitalWrite(MODEM_POWER_ON, HIGH);
// Set GSM module baud rate and UART pins
SerialAT.begin(115200, SERIAL_8N1, MODEM_RX, MODEM_TX);
delay(3000);
// Restart SIM800 module, it takes quite some time
// To skip it, call init() instead of restart()
SerialMon.println("Initializing modem...");
modem.restart();
// use modem.init() if you don't need the complete restart
// Unlock your SIM card with a PIN if needed
if (strlen(simPIN) && modem.getSimStatus() != 3 ) {
modem.simUnlock(simPIN);
}
// To send an SMS, call modem.sendSMS(SMS_TARGET, smsMessage)
String smsMessage = "Hello from ESP32!";
/*if(modem.sendSMS(SMS_TARGET, smsMessage))
{
SerialMon.println(smsMessage);
}
else{
SerialMon.println("SMS failed to send");
}*/
SerialAT.println("AT"); //Once the handshake test is successful, it will back to OK
SerialAT.println("AT+CMGF=1"); // Configuring TEXT mode
SerialAT.println("AT+CNMI=1,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
}
void loop()
{
//readSMS(1);
//delay(1);
}

3-wheel robot not moving back or left using voice commands

I am working on 3-wheel robot. I want to move my robot front, back, right, left using voice commands. I am using arduino electronics as my mobile app. By using that app I want to control my robot. I am using an arduino uno board and L293D motor driver. Below is my code for 3-wheel robot:
String readvoice;
void setup() {
//BT.begin(9600);
Serial.begin(9600);
pinMode(7, OUTPUT);
digitalWrite(7, HIGH);
}
//-----------------------------------------------------------------------//
void loop() {
while (Serial.available()) { //Check if there is an available byte to read
delay(10); //Delay added to make thing stable
char c = Serial.read(); //Conduct a serial read
readvoice += c; //build the string- "forward", "reverse", "left" and "right"
}
if (readvoice.length() > 0) {
Serial.println(readvoice);
if (readvoice == "go")
{
//Serial.println("front"); //Writing values to motor driver
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
digitalWrite(7,LOW);
digitalWrite(6,HIGH);
}
if (readvoice == "left")
{
//Serial.println("left");
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
digitalWrite(7,HIGH);
digitalWrite(6,LOW);
}
if(readvoice == "right")
{
//Serial.println("right");
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
digitalWrite(7,LOW);
digitalWrite(6,HIGH);
}
if (readvoice == "back")
{
//Serial.println("back");
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
digitalWrite(7,HIGH);
digitalWrite(6,LOW);
}
if (readvoice == "stop")
{
//Serial.println("stop");
digitalWrite(4,LOW);
digitalWrite(5,LOW);
digitalWrite(7,LOW);
digitalWrite(6,LOW);
}
readvoice = "";
}
}
I kept all the connections correctly, but my robot is able to move only right and front. I am not able to run my robot either left or back. Is there any problem in the code? Or any problem with hardware. If i had any problem with hardware, my robot should not move front or right either, but it is moving. Any idea what is wrong with back and left?

Pulse sensor coding for Netduino Plus 2 gone wrong

I'm currently doing a project on Netduino Plus 2 using .net micro framework which requires me to code for a pulse sensor. I have tried finding codes for pulse sensor but to no avail. I tried using AnalogInput codes for pulse sensor but the output values seemed wrong (there was a constant high value despite no heartbeat placed near the sensor). Please advise!
Here are my current codes for the heartbeat sensor:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
namespace heartrate
{
public class Program
{
public static void Main()
{
SecretLabs.NETMF.Hardware.AnalogInput rate =
new SecretLabs.NETMF.Hardware.AnalogInput(Pins.GPIO_PIN_A0);
int sensorvalue = 0;
while (true)
{
sensorvalue = rate.Read();
Debug.Print("" + sensorvalue);
Thread.Sleep(1000);
}
}
}
}
Here are the specs of the sensor, how it looks like and how it is connected.
http://www.elecrow.com/wiki/index.php?title=Pulse_Sensor
(This tutorial is for arduino, but I think the wiring is similar to that of Netduino)
Hard to tell without specs on your pulse device and how it is attached. For Analog input & output in my latest project (https://github.com/osstekz/cncBuddy) I use classes InputPort & OutputPort (Microsoft.SPOT.Hardware)
ex:
public NESControllerAdapter(Cpu.Pin pinClk, Cpu.Pin pinLatch, Cpu.Pin pinData1/*, Cpu.Pin pinData2 = Cpu.Pin.GPIO_NONE*/) {
// Binds to all pins
this._outpClk = new OutputPort(pinClk, false);
this._outpLatch = new OutputPort(pinLatch, false);
this._inpData1 = new InputPort(pinData1, false, Port.ResistorMode.Disabled);
//if (pinData2 != Cpu.Pin.GPIO_NONE) this._inpData2 = new InputPort(pinData2, false, Port.ResistorMode.Disabled);
}
...then like your rate.Read(); loop
public int ButtonPressed() {
// Locks all parms
this._PinTick(this._outpLatch);
// Reads plug state value
for (int i = 0; i < CncBuddyShared.iTOTALNESCONTROLLERBUTTONS; ++i) {
// Read the value, if true return this index as the first pressed button
if (this._inpData1.Read() == false) return i;
// Selects the next value
this._PinTick(this._outpClk);
}
return NESCONTROLLER_PRESSEDBUTTOM_NONE;
}

Receiving SMS by Arduino GSM Shield and control the LED with the content of this SMS?

I am using Arduino GSM Shield receiving SMS from an Android app. And the content of this SMS will control a LED. If the content of this SMS is not "off", the LED will be on and the content will be printed in the serial monitor. But if it is "off", the LED will be off immediately. Besides, the LED will keep being on until the "off" message coming. For now, I used the code from the example of the software. But I cannot use the content of this SMS to control the status of LED. With the code below, the LED could not be turned on and the content could not be displayed on the monitor. I think it was because the sketch failed to get the whole content of this SMS. Could anybody tell me how to solve this problem? Thanks.
#include <GSM.h>
GSM gsmAccess;
GSM_SMS sms;
char senderNumber[20];
int led=13;
void setup()
{
Serial.begin(9600);
pinMode(led,OUTPUT);
digitalWrite(led,LOW);
while (!Serial) {
;
}
Serial.println("SMS Messages Receiver");
boolean notConnected = true;
while(notConnected)
{
if(gsmAccess.begin("6442")==GSM_READY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
Serial.println("Waiting for messages");
}
void loop()
{
char c;
int val=0;
val=digitalRead(led);
if (val==HIGH){
digitalWrite(led,HIGH);
}
if (sms.available())
{
Serial.println("Message received from:");
sms.remoteNumber(senderNumber, 20);
Serial.println(senderNumber);
if(sms.peek()=='#')
{
Serial.println("Discarded SMS");
sms.flush();
}
while(c=sms.read())
if(c='off'){
digitalWrite(led,LOW);
}else{
digitalWrite(led,HIGH);
Serial.print(c);
}
Serial.println("\nEND OF MESSAGE");
sms.flush();
Serial.println("MESSAGE DELETED");
}
delay(1000);
}
With this line
if(c='off'){
you are setting the value of c to "off". I guess you want to compare the value of c to the string "off" instead. Use == instead of =.
Also, what happens if someone sends "OFF" instead of "off"......? you need to handle that case as well. Try converting the SMS to lower characters before you do the compare.

Developing iTunes like application in c#

I need to develop an application in c# that could automatically detect an iPhone when it is connected to the system and read a particular file for the iPhone file system. I basically want this file to be downloaded automatically from device to the PC. I used USBpcap tool that suggests that iTunes connects to phone using some XML format. Any help or insight greatly appreciated. Is there any documentation of Third party APIs that can get me started? There are some applications that can replicate iTunes functionality e.g Copytrans
Is there any protocol or APIs provided by Apple?
I have been digging the internet and found this link Layered communication for iPhone.
Also I am using the LibUsbDotNet libraries for communicating to the usb device(Example). Can any one suggest which EndPoints should be used.
It seems to me that I have to implement usbmuxd in windows application. It is a multilayer protocol. There must be some libraries that implement usbmuxd(I dont think I have to implement the protocol all by my self)
I dont have much idea about iTunes communication as well as USB communication. I am adding as much information as I can(of course with the things I come up with in my R&D). Any help is highly appreciated.
public static DateTime LastDataEventDate = DateTime.Now;
public static UsbDevice MyUsbDevice;
#region SET YOUR USB Vendor and Product ID!
public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(1452, 4768);
#endregion
private void LibUSB()
{
ErrorCode ec = ErrorCode.None;
try
{
// Find and open the usb device.
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
// If the device is open and ready
if (MyUsbDevice == null)
throw new Exception("Device Not Found.");
// If this is a "whole" usb device (libusb-win32, linux libusb)
// it will have an IUsbDevice interface. If not (WinUSB) the
// variable will be null indicating this is an interface of a
// device.
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
// This is a "whole" USB device. Before it can be used,
// the desired configuration and interface must be selected.
// Select config #1
wholeUsbDevice.SetConfiguration(1);
// Claim interface #0.
wholeUsbDevice.ClaimInterface(0);
}
// open read endpoint 1.
UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep03);
// open write endpoint 1.
UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
int bytesWritten;
ec = writer.Write(usbmux_header.GetBytes(), 2000, out bytesWritten);
if (ec != ErrorCode.None)
throw new Exception(UsbDevice.LastErrorString);
byte[] readBuffer = new byte[1024];
while (ec == ErrorCode.None)
{
int bytesRead;
// If the device hasn't sent data in the last 100 milliseconds,
// a timeout error (ec = IoTimedOut) will occur.
ec = reader.Read(readBuffer, 10000, out bytesRead);
if (ec == ErrorCode.Win32Error)
throw new Exception("port not open");
if (bytesRead == 0)
throw new Exception("No more bytes!");
// Write that output to the console.
Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
}
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
}
finally
{
if (MyUsbDevice != null)
{
if (MyUsbDevice.IsOpen)
{
// If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
// it exposes an IUsbDevice interface. If not (WinUSB) the
// 'wholeUsbDevice' variable will be null indicating this is
// an interface of a device; it does not require or support
// configuration and interface selection.
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
// Release interface #0.
wholeUsbDevice.ReleaseInterface(0);
}
MyUsbDevice.Close();
}
MyUsbDevice = null;
// Free usb resources
UsbDevice.Exit();
}
}
}
class usbmux_header
{
public static UInt32 length = 10; // length of message, including header
public static UInt32 reserved = 0; // always zero
public static UInt32 type = 3; // message type
public static UInt32 tag = 2; // responses to this query will echo back this tag
public static byte[] GetBytes()
{
byte[] lgth = BitConverter.GetBytes(length);
byte[] res = BitConverter.GetBytes(reserved);
byte[] tpe = BitConverter.GetBytes(type);
byte[] tg = BitConverter.GetBytes(tag);
byte[] retArray = new byte[16];
lgth.CopyTo(retArray, 0);
res.CopyTo(retArray, 4);
tpe.CopyTo(retArray, 8);
tg.CopyTo(retArray, 12);
return retArray;
}
};
I have been trying to send hello packet bytes to iPhone but I am not able to read any response from phone.
To play with ipod you can use SharePodLib
As I understand it, only one client can use the USB connection to iOS at one time. On both macOS and Windows, that one client is usbmux. That library multiplexes TCP connections with higher-level clients, including iTunes, Photos, and (on macOS) the open-source peertalk library.
So on Windows, you wouldn't want to implement your own usbmux, but rather a client that sits on top of that, analogous to peertalk. I haven't seen anything open-source that does this, but a number of developers have accomplished it with their own proprietary software.
If anybody else has pointers about using usbmux on Windows, I'd love to hear about it.
—Dave
You can use imobiledevice-net. It provides a C# API to connect to iOS devices using your PC.
For example, to list all iOS devices connected to your PC, you would run something like this:
ReadOnlyCollection<string> udids;
int count = 0;
var idevice = LibiMobileDevice.Instance.iDevice;
var lockdown = LibiMobileDevice.Instance.Lockdown;
var ret = idevice.idevice_get_device_list(out udids, ref count);
if (ret == iDeviceError.NoDevice)
{
// Not actually an error in our case
return;
}
ret.ThrowOnError();
// Get the device name
foreach (var udid in udids)
{
iDeviceHandle deviceHandle;
idevice.idevice_new(out deviceHandle, udid).ThrowOnError();
LockdownClientHandle lockdownHandle;
lockdown.lockdownd_client_new_with_handshake(deviceHandle, out lockdownHandle, "Quamotion").ThrowOnError();
string deviceName;
lockdown.lockdownd_get_device_name(lockdownHandle, out deviceName).ThrowOnError();
deviceHandle.Dispose();
lockdownHandle.Dispose();
}

Resources