Arduino Forum

Using Arduino => Networking, Protocols, and Devices => Topic started by: kas on Jun 21, 2013, 09:17 am

Title: Android Bluetooth joystick
Post by: kas on Jun 21, 2013, 09:17 am
Edit:    **  Current Versions  **

         - Joystick bluetooth Commander:     V5.5 (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result)
         - AndroTest.ino demo sketch:             V2.0 (http://forum.arduino.cc/index.php?topic=173246.msg1766646#msg1766646)


* New *   
Code (http://forums.parallax.com/showthread.php/156970-Bluetooth-App-to-control-ActivityBot) for Parallax Propeller, in "C"
  (thanks twm47099)
Code (http://forums.parallax.com/showthread.php/159920-Android-Control-of-Propeller-using-Joystick-BT-Commander-App-Spin-Code) for Parallax Propeller in "Spin"
  (thanks jonnyMac)


        - Samsumg Galaxy Tab 4 users,
please look here (http://forum.arduino.cc/index.php?topic=173246.msg1820281#msg1820281)

scroll to the end of this message to get latest information


Hi,
I developed an Android application that turns a smartphone into a virtual Bluetooth joystick.
The applications in the robotic field are endless: Home Automation, R/C cars, robotic arms and of course  balancing robots (http://forum.arduino.cc/index.php/topic,8871.0.html) ;)

(http://i.imgur.com/kzT7uLA.jpg) (http://imgur.com/kzT7uLA)

By default, the device transmits data every 200ms
Data format: [STX  X  Y  ETX]   
example: [0X02  0X2A  0X30  0X03]

The application is available (for free 8)) here (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result#?t=W251bGwsMSwxLDEsIm9yZy5wcm9qZWN0cHJvdG8uYnRqb3lzdGljayJd)
From you smartphone, access Google Store and search for "Joystick bluetooth Commander"

This demo Arduino sketch will parse data on the serial monitor, and control the pin13 LED
Code: [Select]
// AndroLED V5
// Arduino test sketch for Joystick BT commander
// LED control for buttons + joystick echo to serial monitor

//    ** deprecated, please use AndroTest_V13.ino **
//    see reply #181


http://www.youtube.com/watch?v=jNiGa_gK2KU

The Hardware setup is rather straightforward, should you need additional info, just let me know

Enjoy

Edit:
Updated Arduino sketch,
set Baud rate to default 9600
removed softserial
For sketch upload, don't forget to disconnect board TX from Arduino D0

Edit2:
Joystick Bluetooth Commander Version 2.3 is now compatible with Android V3.X and V4.X (Honeycomb, Ice Cream Sandwich, Jelly Bean)

Edit3:
added   Serial.println("Bluetooth Commander simulation") in setup() for communication testing purpose

Edit4:
Joystick Bluetooth Commander Version 2.4
(http://i.imgur.com/1f4Nckc.png)
Four toggle buttons with visual feedback

Change Log and Arduino sketch modification: please refer to reply #51

Edit5:
Joystick Bluetooth Commander Version 2.5
(http://i.imgur.com/ovC8KE7.png)

Change Log: refer to reply #70

Edit6:
Joystick Bluetooth Commander Version 3.0

** major Upgrade **
Joystick Bluetooth Commander is now a full blown two way Bluetooth communication application
Arduino sends back a button status Byte and a user defined data Byte to be displayed on the phone/tablet screen (Bot battery level is a nice candidate)

Communication protocol has changed
Joystick data is now transmitted as an integer = 2 Bytes (Most Significant Byte + Less Significant Byte)
<STX  MSB-X  LSB-X  MSB-Y  LSB-Y  ETX>
Your V2.5 Arduino sketch needs to be modified for V3.0


See full change Log at reply #74
Updated demo Arduino sketch at reply #90

Edit7:
Fixed link to Balancing robot for dummies (http://forum.arduino.cc/index.php/topic,8871.0.html)

Edit8:
New Arduino demo sketch (V10.1)
Improve decoding algorithm, see reply #98

Edit9:
Joystick Bluetooth Commander Version 3.1
Maintenance release, see reply #100

Edit10:
New Arduino demo sketch (V10.3)                << for Artouste   ;)
Bug fix, see reply #129

Edit11:
Joystick BT Plus  has been released with 6 buttons and 4 data bytes

(http://i.imgur.com/ei7hs5n.jpg)

The actual number of buttons and data fields is adjustable within the Option menu
Fields and buttons labels are fully customizable
See reply #165

Edit11:
Detailed info re Communication Protocol (send and receive)
See reply #154 & #156

Edit12:
Joystick BT Plus (6 buttons, 3 datafields)
and
Total RC Commander (video from IP camera)
are now available see reply #177

(http://i.imgur.com/LRW6h8p.jpg)
More info here (http://forum.arduino.cc/index.php?topic=173246.msg1998617#msg1998617)


Edit13:
Joystick BT Plus (up to 6 buttons, up to 3 free format datafields) is now
                - Joystick bluetooth Commander V4.0 -
and is available on Google Play (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result#?t=W251bGwsMSwxLDEsIm9yZy5wcm9qZWN0cHJvdG8uYnRqb3lzdGljayJd) as a free upgrade.

To allow text datafield, Communication Protocol has changed
Please use and adapt AndroTest_V13.ino demo sketch to your own needs   
** deprecated, please use AndroTest_V14.ino **
See reply #181


Edit14:
Communication Protocol for Joystick bluetooth Commander V4.x and Total RC Commander
now fully documented
See reply #188


Edit15:
A video showing tank control using Total RC Commander. has been posted in the Exhibition Section  (http://forum.arduino.cc/index.php?topic=236401.msg1699561#msg1699561)
More info here (http://forum.arduino.cc/index.php?topic=173246.msg1998617#msg1998617)

(http://i.imgur.com/Ea7lXGt.png)


Edit16:
AndroTest_V14.ino
This updated sketch features optimized timing and better transmission error management
Make sure your BT board is set @57600bps
(or modify sketch accordingly)
See reply #210

Edit17:
AndroTest_V141.ino
See reply #212

Edit18:
BT boards types and configuration tools
See reply #227

Edit19:
Joystick bluetooth Commander Version 5.0 has just been published on Google Play (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result)

** Communication protocol has changed **    see reply #252 (http://forum.arduino.cc/index.php?topic=173246.msg1766491#msg1766491)
- Change log:   see reply #259 (http://forum.arduino.cc/index.php?topic=173246.msg1768111#msg1768111)
- Demo sketch: AndroTest V2.0      see reply #256 (http://forum.arduino.cc/index.php?topic=173246.msg1766646#msg1766646)

Edit20:
Joystick bluetooth Commander Version 5.2 now on Google Play (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result)
- Change log:   see reply #292 (http://forum.arduino.cc/index.php?topic=173246.msg1768111#msg1768111)
- Demo sketch: AndroTest V2.0      see reply #256 (http://forum.arduino.cc/index.php?topic=173246.msg1766646#msg1766646)

Edit21:
For my new project (http://forum.arduino.cc/index.php?topic=271827), I am testing a robotic claw using Joystick BT Commander



Title: Re: Android Bluetooth joystick
Post by: kas on Jun 24, 2013, 10:39 am
I posted a pan/tilt project based on Joystick Bluetooth Commander, in the Robotic Section  (http://forum.arduino.cc/index.php?topic=173504.0)

(http://i.imgur.com/yFOfMEN.jpg)
Title: Re: Android Bluetooth joystick
Post by: jeffmorris on Jun 24, 2013, 11:31 am
I have Samsung Galaxy Tab 7" tablet and Arduino Uno. The X and Y values on the tablet screen don't display the position of the joystick and nothing is displayed on the serial monitor. How can I fix the problem?
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 24, 2013, 08:15 pm
Bluetooth applications are difficult to debug in Eclipse IDE, as Virtual Devices do not emulate Bluetooth activity
Actual debugging has to be made on a specific real device (Sony Xperia Mini)

Quote
I have Samsung Galaxy Tab 7" tablet

what is your tablet API level and display resolution ??

Quote
The X and Y values on the tablet screen don't display the position of the joystick


Make sure that options are as follow:
Data Range:   -50 to +50
Data display:    Joystick position
Data format:   STX and ETX

Are the buttons and the "not connected" string displayed on the tablet screen ??
Does the Joystick actually move when touched??
does it produce haptic feedback when this option is selected ??

Quote
nothing is displayed on the serial monitor

Your Bluetooth serial board may be still configured @9600BPS
please adjust  mySerial.begin(57600) to your specific Baud rate
Also make sure that your Bluetooth serial board is already paired with your tablet

finally uncomment
Code: [Select]

//        Serial.print(i);  Serial.print(": ");  Serial.println(cmd[i]);
   
and let me know the outcome

@all
My specific configuration is working flawlessly
Should you have installed this application on a different device, please post feedback
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 26, 2013, 12:02 pm
@jeffmorris
I beleave you are facing two non related problems

- Communication with your BT card (your task)
check pairing, Baud rate, connection to Arduino (Menu/Connect)
I use a JY-MCU rev1.05 board (http://www.ebay.com/itm/Wireless-Serial-4-Pin-Bluetooth-RF-Transceiver-Module-RS232-Cable-New-/380619086994?ssPageName=ADME:L:OU:FR:3160)
Onboard LED should be flashing when powered and gets solid red when connected
Connect TX board to RX (D0) Arduino
(http://i43.tinypic.com/2efj77n.jpg)

Above Arduino sketch has been updated to V5 (removed SoftwareSerial)
For sketch upload, don't forget to disconnect board TX from Arduino D0


- UI display on tablets (my task)
I will publish today on Google Play a new version insuring compatibility with tablets

Edit: Joystick Bluetooth Commander V2.2 is now available
Please make sure that application is configured as follow:
- Data Range  -50 to +50
- Data display   Joystick position
- Data format STX and ETX
- Refresh interval   100ms
- Button1 data to send    '1'
- Button2 data to send    '2'

Title: Re: Android Bluetooth joystick
Post by: jeffmorris on Jun 28, 2013, 09:49 pm
The screen shown on the second screenshot at https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result#?t=W251bGwsMSwxLDEsIm9yZy5wcm9qZWN0cHJvdG8uYnRqb3lzdGljayJd doesn't show up. How can I fix this?
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 29, 2013, 06:32 pm
Quote
The X and Y values on the tablet screen don't display the position of the joystick

Can you move the joystick ??
Are the data now displayed on the tablet screen ??


Quote
The screen shown on the second screenshot at https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result#?t=W251bGwsMSwxLDEsIm9yZy5wcm9qZWN0cHJvdG8uYnRqb3lzdGljayJd doesn't show up. How can I fix this?

The menu is displayed when pressing the hardware menu button at the bottom of your tablet
Can you access it ??

You need to enter this menu to establish a Bluetooth communication

Please let me have more detailed information

I will post a new version including a "reset configuration" option
The initial configuration should work right out of the box with the above Arduino sketch
Title: Re: Android Bluetooth joystick
Post by: jeffmorris on Jun 29, 2013, 08:26 pm
I can't find the hardware menu button at the bottom of the tablet screen. When I move the joystick, the X and Y values at the bottom left corner of the screen change. A red message at that corner says "Not Connected".
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 29, 2013, 09:09 pm
Is it your model?
(http://i.imgur.com/DooZTYm.jpg)

What happens when you launch Joystick Bluetooth Commander and press the button on the left ?

EDIT
Not sure this is the right one   :smiley-slim:
The option button is this one (red circle)
(http://i.imgur.com/HEacQPs.jpg)
Can somebody jump in and explain how to access applications menu or options on the Galaxy Tab tablet ??
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 30, 2013, 11:52 am
I now realize that beginning with Android 3.0 (API level 11), Android-powered devices are no longer required to provide a dedicated Menu button  :smiley-sad-blue:

Joystick Bluetooth Commander Version 2.3 (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result#?t=W251bGwsMSwxLDEsIm9yZy5wcm9qZWN0cHJvdG8uYnRqb3lzdGljayJd) now adds full compatibility with Android 3.X  and 4.X
The menu that allows BT connection can be accessed though the added 'action overflow button' (red square)
(http://i.imgur.com/dwuV0Eo.png)
some other devices have a different icon at bottom left

thanks for bringing this point to my attention, sorry for being GingerBread centric

The application has been tested and is fully operative on my son's 7" Samsung Galaxy tablet (jelly beans)
Thanks to Julian for his contribution  ;)
Title: Re: Android Bluetooth joystick
Post by: jeffmorris on Jun 30, 2013, 11:56 am
The Samsung Galaxy Tab 7.0 Plus has display resolution of 1024x600.

http://www.samsung.com/global/microsite/galaxytab/7.0/spec.html?type=find
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 01, 2013, 11:06 am
OK

Just install Version 2.3 (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result#?t=W251bGwsMSwxLDEsIm9yZy5wcm9qZWN0cHJvdG8uYnRqb3lzdGljayJd), and let me know the outcome.
You should now have a Menu button available for establishing connection.
(http://i.imgur.com/P39B02g.jpg)

Next step is to get your BT board connected. With a JY-MCU type, the on board LED should change from blinking to solid red
Title: Re: Android Bluetooth joystick
Post by: jeffmorris on Jul 01, 2013, 09:41 pm
I think that version 2.3 works but I don't see anything on the Serial Monitor after changing #define DEBUG from false to true. I can connect my tablet to the Arduino UNO board with Bluetooth module but the Pin 13 LED doesn't work when I touch the buttons next to the "joystick". The values change when I move the "joystick". The LEDs on the Bluetooth module changed from flashing red to non-flashing green.
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 01, 2013, 10:32 pm
OK

Please check those 3 points:

1) Arduino sketch
Add
Code: [Select]
Serial.println("***");
as the last line of setup()
Please confirm the stars are displayed on the serial monitor

D0 should be disconnected to allow sketch upload
(and reconnected afterward  ;))
   

2) Hardware connection
please refer to message #4
Only 3 wires
5V to 5V
GND to GND
TX board to D0 (Arduino RX)


3)BT board Baud rate
Some BT boards default to 19200BPS
Please adjust "Serial.begin(9600)" and Serial Monitor Baud rate accordingly
Should you require it, I will upload an Arduino sketch for checking BT board Baud rate and/or setting a new value. This sketch also insure that the BT board is OK
Title: Re: Android Bluetooth joystick
Post by: jeffmorris on Jul 02, 2013, 03:13 am
Please send me the sketch that for checking and setting Bluetooth baud rate. I added

Serial.println("***");

as the last line of setup() and the stars show up on the serial monitor.
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 02, 2013, 07:06 am
Here it is
This sketch will scan the BT board and display actual Baud rate and firware rev level
The menu also allows to change Baud value
I suggest to set the board @57600

Connection:
TX BT board pin to Arduino D2
RX BT board pin to Arduino D3
5V BT board pin to Arduino 5V
GND BT board pin to Arduino GND

Finally, for joystick operations:
adjust Serial.begin(XXX) in AndroLED V5  
reload sketch
move D2 cable to DO
remove D3 cable
and you should be all set  8)

Tested with  JY-MCU rev1.05    HC-06 (LINVOR)
Should work with any board
EDIT: doesn't work with Bluetooth Mate Silver board
EDIT 2: another sketch has been developped for HC-05 board

Please confirm actual BT board Baud rate and firmware rev level
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 04, 2013, 06:40 pm
The Arduino sketch is attached to the previous message
You may not have access to it if you browse this forum using a tablet
Please download using a PC, alternatively I can include the sketch code within a new post
Title: Re: Android Bluetooth joystick
Post by: jeffmorris on Jul 04, 2013, 08:48 pm
Searching ............
ERROR: Bluetooth Module not responding!
Make sure there are no active bluetooth connection and try again
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 05, 2013, 06:34 am
this is the Baud rate testing setup, please check:
(http://i.imgur.com/7dDdgRV.jpg)


This is a screenshot of the expected info:
(http://i.imgur.com/h9Z1new.jpg)


Quote
Searching ............
ERROR: Bluetooth Module not responding!
Make sure there are no active bluetooth connection and try again


For checking/setting Baud rate, the BT card should _not_ be connected (Bluetooth connected) to the tablet/Android device,
To enter AT command mode, the BT card LED should _blink_

Just in case, try inverting D2 and D3 cables


Have you already successfully used this board for other projects ??
Please let me have a link to the specific BT board you purchased
Title: Re: Android Bluetooth joystick
Post by: jeffmorris on Jul 05, 2013, 11:14 am
https://www.sparkfun.com/products/10393
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 05, 2013, 01:45 pm
Quote
https://www.sparkfun.com/products/10393

Have you already successfully used this board for other projects ??
JY_MCU_Config configuration sketch won't work with this board as initialization strings are different

The datasheet for your board is here (https://www.sparkfun.com/datasheets/Wireless/Bluetooth/rn-bluetooth-um.pdf)
Please have a look at page 5
Default Baud rate is 115200
Modify AndroLED V5 sketch setup() accordingly, should be OK
Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 06, 2013, 11:45 pm
I just bought an Android tablet with BT [off brand CN thing] to try using BT with my
robots. I know this is asking a lot, but is it possible to get the joystick app, as well as
maybe Sena BTerm, somewhere other than on Google Play? I just find that signing up
for Google Play is very intrusive, and requires giving them personal info that I really
don't want to part with, bummer. Every single Android download website I've looked
at forwards you to Google Play. What a great world.

Other than that, the BT Joystick app looks really cool, :-).
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 07, 2013, 07:12 am
Let me have your email address via PM
Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 07, 2013, 07:58 am
Done.
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 07, 2013, 12:12 pm
Check your mail  ;)
Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 08, 2013, 09:23 am
Hey kas, thanks. Just an update. I received the joystick apk, and got it installed and running on my new Android tablet. I also have a couple of BT modules which are virtual clones of the JY-MCU, and your app pairs ok. Tomorrow, see if I can get the Arduino-BT side of things to go, shake a servo. Cool, :-).
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 08, 2013, 10:19 am
Thanks for the feedback, please keep us updated  :)

Quote
Tomorrow, see if I can get the Arduino-BT side of things to go, shake a servo. Cool, :-).

do not use SoftwareSerial together with the servo library, doesn't work (http://forum.arduino.cc/index.php?topic=173504.0)
Just use hardware serial. You will still be able to display debug info's on the Serial Monitor
Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 08, 2013, 06:00 pm
Yeah, thanks. I've had very poor luck with SoftSerial in the past so will try different things. I do have 1284 boards with 2 UARTs. Also, I did get the little BT dongles to pair with my tablet, and talk to terminal emulators  a couple of days ago, but the AT cmds didn't fully work [only the 'OK' part], plus they won't intercommunicate, so I need to wring that all out. It's always a muckaround with this stuff.
Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 09, 2013, 08:49 am
Hi kas, here's an update - everything works A-Ok. Very cool.

I am running the Arduino sketch shown in your original post, except that I am using an ATmega1284P with 2 UARTs, so the BT data comes in on Serial1 and goes out Serial to the terminal emulator. Joystick, haptic, and button on/off all work good. The control menu on my tablet is as shown in reply #9.

The only question I have is that, when the joystick is at rest position shown as (0,0) on my tablet, the data received at the Arduino end = 60,60, and then it goes from 10...110 as I move the joystick. Obviously, the data range is set to -50,+50. So, what's the 60,60 business, I didn't see it mentioned anywheres?

Here is my system:
1. ATmega1284P board.
2. BT module = generic clone:
http://www.amazon.com/Arduino-Wireless-Bluetooth-Transceiver-Module/dp/B0093XAV4U/
3. 7" tablet, quadcore 1.3Ghz, Android 4.2.1, 1280x800 res, joystick display snapshot is attached.
http://www.walmart.com/ip/Hisense-Sero-7-Pro-7-Tablet-Quad-Core-Processor-with-8GB-Memory/24805142
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 09, 2013, 09:35 am
Quote
Hi kas, here's an update - everything works A-Ok. Very cool.
Thanks for the feedback

Quote
The only question I have is that, when the joystick is at rest position shown as (0,0) on my tablet, the data received at the Arduino end = 60,60, and then it goes from 10...110 as I move the joystick. Obviously, the data range is set to -50,+50. So, what's the 60,60 business, I didn't see it mentioned anywhere?



OK, this is the story   ;)

I am working on V2.4 that will include a calibration screen for fine tuning
This will allow a -10 +10 correction for the Joystick Zero position
I want to fit the transmitted data on a signed Byte, as a positive value (0 to 128)
The maximal range including calibration is -60 to +60
By adding a 60 offset, transmitted data is now 0 to 120, uncalibrated Zero position being 60,60

So far I was unsuccessful transmitting negative values.  Any smarter solution ??

FYI   "Option/Data Display/actual sent Bytes", will display actual transmitted value
Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 09, 2013, 09:13 pm
Hi kas, I got the Android Joystick Commander controlling pan'n'tilt servos connected to my ATmega1284 Arduino board this morning, pretty cool. The one thing I might suggest is providing a shorter Refresh Interval in the Advanced Options menu, eg as little as 20 or 40 msec if possible, then the servo responsiveness would be maximal.

I looked at your data protocol some more, and think it's pretty good the way it is. You use 1-byte to send both control codes and data, so I wouldn't worry about trying to send signed data. It's easy enough to subtract off the offset = 60, once you know what the coding is.

Also, I think the resolution of +/-50 ultimately producing +/-500 usec servo pulse changes is ok, considering you're doing the control manually by moving the on-screen joystick. After all, 10-usec is only 0.9 deg of servo movement.

All in all, nice job, :-).

My next task is learning how to write my own Android BT apps. BTW, can you tell me which tools you used?

EDIT: thinking of the coding a little more, you could actually scale it up to 120 +/-100 and get 2X the current servo movement resolution, and still have space left over at the low end for the various control codes. This would give 0.45 degree servo resolution, although it probably wouldn't be noticeable when using the joystick. OTOH, you'd have an improved format that could also be used by other Android apps for control of the same Arduino h.w. systems, without having to change the latter's code.

EDIT2: FYI, this afternoon, we loaded Joystick Commander into a friend's Samsung Galaxy 3 cellphone running Android 4.1, and it worked perfectly in commanding my BT-Arduino1284 board and servos, so everything good. He was impressed, and not even an Arduino guy.
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 10, 2013, 07:24 am
Quote
The one thing I might suggest is providing a shorter Refresh Interval in the Advanced Options menu, eg as little as 20 or 40 msec if possible, then the servo responsiveness would be maximal.

Easy to do... let's see...

Quote
My next task is learning how to write my own Android BT apps. BTW, can you tell me which tools you used?

Android programming is a fascinating universe
Three very different approches are available on the market, with increasing learning curves
App Inventor  (http://appinventor.mit.edu/explore/)
A full graphic cloud based application, just fitting together puzzle pieces
still in development, very intuitive but a bit limited for the moment

Basic4android (http://www.basic4ppc.com/index.html?utm_expid=3615947-4)  
using a syntax MS Visual Basic syntax, creates native Android applications

Eclipse + Android SDK (http://developer.android.com/sdk/index.html)
for full blown applications, a bit frustrating at startup  :smiley-eek: :smiley-eek: :smiley-eek:
A first experience with Java will definitly help
Tons of help and snippets, at XDA developpers (http://forum.xda-developers.com/forumdisplay.php?f=564)
lots of tuto's on Youtube (http://www.youtube.com/user/profgustin/search?query=android)

I tried App Inventor and finally choosed the hard way... 8)

Quote
this afternoon, we loaded Joystick Commander into a friend's Samsung Galaxy 3 cellphone running Android 4.1, and it worked perfectly in commanding my BT-Arduino1284 board and servos, so everything good. He was impressed, and not even an Arduino guy.

Thanks for this excellent feedback :)

Out of curiosity, where is the Land of sun+snow ??
Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 10, 2013, 09:24 am
Thanks for the dev tool info, will look them up.

BTW, the Galaxy phone guy [non-techie] was totally amazed how he could suddenly use his Android phone to control the world, ;-), ie besides just placing calls and surfing the web. Land here is northern Nevada, hot and sunny desert, sitting below 11,000 foot mountain peaks covered with snow, at least in the winter. Sleep time now.
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 10, 2013, 04:05 pm
Quote

Quote
The one thing I might suggest is providing a shorter Refresh Interval in the Advanced Options menu, eg as little as 20 or 40 msec if possible, then the servo responsiveness would be maximal.

Easy to do... let's see...


Check your mail for V2.35
I added 25ms and 50ms
At 25ms, you may have to increase your BT board Baud rate to 57600

Edit:
I just tested V2.35 with the Pan/Tilt robot (http://forum.arduino.cc/index.php?topic=173504.0)
At 25ms, movements are much smoother  :)
I will upload this version to Google Play later today
Thanks for your suggestion

Edit2:
Quote
BTW, the Galaxy phone guy [non-techie] was totally amazed how he could suddenly use his Android phone to control the world, ;-),

I had this very same feeling 8), this is the reason I decided to share
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 10, 2013, 09:41 pm
Quote
Edit:
I just tested V2.35 with the Pan/Tilt robot
At 25ms, movements are much smoother  smiley
I will upload this version to Google Play later today
Thanks for your suggestion


Done
Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 11, 2013, 05:41 am
Hi kas, I tested the new version of Joystick Commander. The servo movements definitely are much smoother now, especially for very slow changes of the joystick position. Looks good. I also looked at the wording on all the menus like you suggested, and they all look good too, I think.

Considering BT works on the 2.4Ghz band, I'm also surprised that the servo response latency is so quick, as where I live there are about 30 routers that I can pick up. See attached. I might have expected some interference, and slower responsiveness.

The only thing left that I might comment on is that you cannot tell from the Android screen what is the state of the  Led on the Arduino, in the sense that you don't know what was the last keypress made - on or off. I guess there is no option for feedback from the Arduino board back to the Android device, but it might help to put some marker on the Android screen to indicate the last key pressed. Like a little marker that comes on, separate from the on,off keys.
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 11, 2013, 06:35 am
Quote
...you cannot tell from the Android screen what is the state of the  Led on the Arduino, in the sense that you don't know what was the last keypress made - on or off. I guess there is no option for feedback from the Arduino board back to the Android device, but it might help to put some marker on the Android screen to indicate the last key pressed. Like a little marker that comes on, separate from the on,off keys.


I will have a look at it when back from holydays
My background is Process Control, in term of strategy, I agree, a feedback from the Arduino is much better
This should be feasible  :smiley-roll-blue:
Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 11, 2013, 08:17 pm
Holydays? Where the heck does one go on a holiday when he lives in a resort town like you do? LOL. Maybe the beach. Bon chance.

FYI, there appears to be a bunch of BTBees around,
http://www.google.com/search?hl=en&site=imghp&tbm=isch&source=hp&biw=1025&bih=870&q=bluetooth+bee

I happen to have this one on hand, so I plugged it into my Arduino1284 board [which just happens to have a convenient XBee socket], and the JoystickCommander worked right off without any muckaround, so it looks like the "default" mode of the BTBee is the same as for the other small BT modules cited earlier. Again, 2 wire control - Rx, Tx, 9600bps, code=1234 - and go. So, versatility increases.
http://www.robotshop.com/dfrobot-bluetooth-bee-2.html
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 12, 2013, 07:41 pm
Quote
Holydays? Where the heck does one go on a holiday when he lives in a resort town like you do? LOL. Maybe the beach. Bon chance.

I wont tell it over the Web (_your_ Big Brother is watching us) ;)

Quote
I happen to have this one on hand, so I plugged it into my Arduino1284 board [which just happens to have a convenient XBee socket], and the JoystickCommander worked right off without any muckaround, so it looks like the "default" mode of the BTBee is the same as for the other small BT modules cited earlier. Again, 2 wire control - Rx, Tx, 9600bps, code=1234 - and go. So, versatility increases.

Good to know, thank for the information
Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 12, 2013, 08:51 pm
You'll notice that most of the BTBees in those pictures use the same same BT module as the little boards we've been using, and the Bee is just a carrier board to plug into an XBee socket.  And never tell anyone in public what your specific plans are, just general stuff like "Well, maybe we'll head south, or maybe east, have to see how it goes", LOL. Talk about intrusiveness, this article may be of interest! Do a google search on
"WSJ How Kid Apps Are Data Magnets". I find the direct link gets highjacked. "Big Data" knows more about you than your own govt. C'est la vie. Neuromancer in action.
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 13, 2013, 06:58 am
Quote
And never tell anyone in public what your specific plans are, just general stuff like "Well, maybe we'll head south, or maybe east, have to see how it goes", LOL. Talk about intrusiveness, this article may be of interest! Do a google search on
"WSJ How Kid Apps Are Data Magnets". I find the direct link gets highjacked. "Big Data" knows more about you than your own govt. C'est la vie. Neuromancer in action.

I suggest to go back to the original subject of this thread
Words _Google_, _FaceBook_, _NSA_ have nothing to do with Bluetooth control, even if European and Gaia citizens have hard feelings about that  :0 :0 :0

Hoops...  I heard a strange click on my phone line  :smiley-sad-blue:

Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 13, 2013, 07:47 am
Best not to kick the tiger in the a**, when he's sleeping. But that's old news. The WSJ article is about g**gle, yah**, f*ceb**k, am*z*n, and eb*y, the new 4-letter word agencies that know 100X more about you than the g*vt will ever know. L*L.

On other matters, I've started reading a book on Android development. Install about 700-800 MB of dev tools (java sdk, eclipse, eclipse android plugin, android sdk, maybe some others), and learn how they work, and maybe 3 months later you'll have a nice 47KB .apk app. More L*L.
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 13, 2013, 09:03 pm
Quote
I've started reading a book on Android development. Install about 700-800 MB of dev tools (java sdk, eclipse, eclipse android plugin, android sdk, maybe some others), and learn how they work, and maybe 3 months later you'll have a nice 47KB .apk app

You choosed the hard way  :smiley-eek-blue: :smiley-eek-blue:
Bonne chance  ;)
Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 13, 2013, 09:23 pm
I'll look up your links too, but see you also mentioned Eclipse + Android SDK, which is where the book starts from too.
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 18, 2013, 06:07 pm
I posted a BlinkM (RGB LED) project based on Joystick Bluetooth Commander, in the LEDs and Multiplexing Section (http://forum.arduino.cc/index.php?topic=177780.0)

(http://i.imgur.com/yVRwgb1.jpg)
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 19, 2013, 10:14 am
Comment from Google Play:
Quote
Muy buena aplicacion Aplicacion sencilla y de fácil uso, el código facilitado para arduino es muy útil.
Espero más versiones con más botones para seguir trabajando con ello.

Thanks for the nice comments

Regarding additional buttons, I have mixed feelings as my Xperia mini screen is allready cluttered
On the other hand, a screen tablet is another story, with a lot of space (see reply #28)
May be an option to place additional buttons according to the available real estate


Road map for the next versions:
- remove Data range -10 to +10 (useless)
- add Data range -100 to +100 for increased resolution
- add Calibration screen for "Zero" position offset


My Google Play downloads are in the 100 - 500 category
Please let me have additional feedback
- Android device
- Android version
- suggested new features

TIA
Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 19, 2013, 10:13 pm
I guess I've already mentioned it, but to me, having a couple more on/off buttons would really be nice. You'll notice a guy on another thread here wanting an Android app to "control relays".

One way to implement this with little additional screen real estate is fork the current on/off buttons into 2 separate on/off functions, and simply change the button color/etc to indicate last msg state. Actually, on your screen in post #0, I'd think you'd have room for at least 4-6 buttons without too much interference. Just a thought.

[I'm still looking at Android dev, but currently off trying to get my ethernet shield to do tweets and talk to xively, :-)].
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 20, 2013, 02:26 pm
OK, OK...

What's about this layout
(http://i.imgur.com/1f4Nckc.png)

Four toggle buttons with visual feedback
Relays 2 and 3 are supposed to be energized
Title: Re: Android Bluetooth joystick
Post by: Rafolas on Jul 20, 2013, 03:05 pm
Hi! I have liked your application because I allow me to control motors through bluetooth. I use various dispositives to use program: mobile and tablet. The mobiles that we uses are Samsung Galaxy S2 (Ice Cream Sandwich) and  S3 (Jelly Bean), and the tablets are Samsung Galaxy Note 10.1 (Jelly Bean) and Nexus 7 (Jelly Bean).

I like the idea of you to increase the range of -100 to +100 to allow better control. And it's okay to add more buttons to take further action with the robot.

If I have any ideas for your design and can be useful to me I write it on the forum.

A greeting! and sorry for my English is not very good  =(

Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 20, 2013, 08:42 pm
That's great, kas, exactly what I was thinking about, :-).

You might make it so, in the options menu, you can select momentary activation or toggle on the switches [ha - it never ends, people always want more, each solution breeds a new idea, LOL].
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 20, 2013, 09:29 pm
Hi Rafolas, welcome to the forum  :)

Thanks for taking the time to register and to send your very first post in this thread
Your feedback is (and will be) appreciated


@oric_dan
Quote
You might make it so, in the options menu, you can select momentary activation or toggle on the switches
[ha - it never ends, people always want more, each solution breeds a new idea

;) ;) ;)
In Android, Buttons and ToggleButtons are different beast... :smiley-roll-blue:
For the moment, I am creating the option menu for displaying zero, two or four buttons on the screen
Title: ** Version 2.4 **
Post by: kas on Jul 21, 2013, 11:04 am
I will post Joystick Bluetooth Commander V2.4 on Google play later today

Change log:
- Display up to four toggle buttons with visual feedback
- Button visibility option setting (0 - 2 - 4)
- added Timeout count "every 1000 intervals" to support new low refresh intervals
- default refresh interval set to 50ms
- removed buttons data option setting (not relevant anymore)

New buttons protocol:
Button1_ON   < STX  '1'  ETX >
Button1_OFF  < STX  '2'  ETX >
Button2_ON   < STX  '3'  ETX >
.....
Button8_OFF  < STX  '8'  ETX >

The original Arduino setLED() function should be modified:
Code: [Select]
void setLED(int LEDstatus)  {
 switch (LEDstatus) {
   case '1':
     Serial.println("Button_1: ON");
     // your code...      
     break;
   case '2':
     Serial.println("Button_1: OFF");
     // your code...      
     break;
   case '3':
     Serial.println("Button_2: ON");
     // your code...      
     break;
   case '4':
     Serial.println("Button_2: OFF");
     // your code...      
     break;
   case '5':
     Serial.println("Button_3: ON");
     // your code...      
     break;
   case '6':
     Serial.println("Button_3: OFF");
     // your code...      
     break;
   case '7':
     Serial.println("Button_4: ON");
     // your code...      
     break;
   case '8':
     Serial.println("Button_4: OFF");
     // your code...      
     break;
 }
}



Disclaimer:
See reply #36

@ oric_dan
Please let me have a tablet screenshot similar to reply #28

Enjoy


EDIT: Done!
Title: Re: Android Bluetooth joystick
Post by: liuzengqiang on Jul 22, 2013, 06:57 am
Looks great! Will the source code of the joysticker commander be open at some point for use to learn from?
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 22, 2013, 08:21 am
Quote
Looks great! Will the source code of the joysticker commander be open at some point for use to learn from?


I will definitely make the source code available
Need some time to polish it a bit

Inspiration rarely comes from the Vacuum  ;)
Please refer to the "About" section of the Application menu

The code uses a mobile-anarchy (http://code.google.com/p/mobile-anarchy-widgets/source/browse/trunk/Widgets/src/com/MobileAnarchy/Android/Widgets/?r=30#Widgets%2FJoystick) widget combined with the classical BluetoothChat Android SDK example
Title: Re: Android Bluetooth joystick
Post by: liuzengqiang on Jul 22, 2013, 05:53 pm
Awesome. I have several times attempted to program in android system but the barrier is too high for me. I almost never program any GUI on any OS except for occasional Java popup and dialog type of simple GUIs. If at some point in the future I get your code, I can learn from it. Thanks for deciding to share the code.
Title: Re: Android Bluetooth joystick
Post by: oric_dan on Jul 22, 2013, 11:29 pm
You guys are funny. 2 little blue men, ;-).
Title: Re: Android Bluetooth joystick
Post by: liuzengqiang on Jul 23, 2013, 02:29 am
There are more of us. Have you looked into the mirror today? ;)
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 23, 2013, 07:13 am
Hi Liudr

Quote
If at some point in the future I get your code, I can learn from it.

A Bluetooth project is probably not the coolest way to start learning Android :smiley-roll-blue:
There is a lot of video tutorials on Youtube starting from "Hello Word" type
applications and then, gradually, following the (rather steep) learning curve
You will quickly find that Android and Arduino live well together

Please see reply #31
Eclipse IDE is definitly the best tool for serious development

By the way... nice blog http://liudr.wordpress.com/

Title: Re: Android Bluetooth joystick
Post by: liuzengqiang on Jul 24, 2013, 07:24 am
Thanks kas! I have a stack of books on unix. It's never easy to learn to program on a new operating system but if I can hack your program to do a few things (or maybe just use your program), I think I will motivate myself to get a few books on android. At the moment raspberry pi is pulling me in so I may have to wait to learn the android.
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 25, 2013, 08:59 pm
Quote
...but if I can hack your program to do a few things (or maybe just use your program), I think I will motivate myself to get a few books on android

If you really can't wait, send me a PM with your email address  ;)
Title: Re: Android Bluetooth joystick
Post by: _SBC_ on Jul 27, 2013, 01:59 am
Nice application. Thanks!
I'd like to ask... if your application sends X=2, Y=3 (for example) will it be read as 'Button 2 is pressed' by Arduino?
I use a phone with display resolution is only 320x240. Joystich is not fully shown on display =/
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 27, 2013, 02:58 pm
Quote
if your application sends X=2, Y=3 (for example) will it be read as 'Button 2 is pressed' by Arduino?

No
Data in textbox is joystick data only (4 bytes)
Packet size is 3 bytes for button data : <STX  X  ETX>
and 4 Bytes for joystick data: <STX  X  Y  ETX>
Code: [Select]
    if(i==2)    setLED(cmd[1]);
   if(i==3)    setJoystick();  

According to packet length, joystick or buttons will be controlled


Quote
I use a phone with display resolution is only 320x240. Joystick is not fully shown on display =/

Let me have more info re your phone, with possibly a link to specs
Title: Re: Android Bluetooth joystick
Post by: _SBC_ on Jul 28, 2013, 04:23 am
Yes, sorry, checked it ))
About the phone - it is Samsung Galaxy Young (http://www.gsmarena.com/samsung_galaxy_y_s5360-4117.php).
Many thanks in advance!! ;)
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 28, 2013, 09:53 am
Quote
Yes, sorry, checked it ))
About the phone - it is Samsung Galaxy Young.
Many thanks in advance!! smiley-wink


Let me have your email in a private message
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 28, 2013, 05:03 pm
Quote
Let me have your email in a private message

Check your mail  8)

I have no possibility to test screen layouts
Let me have feedback, possibly with a screenshot 
Title: Re: Android Bluetooth joystick
Post by: arRaindog on Jul 28, 2013, 11:07 pm
Thank you for the wonderful app.  I am using it to control my first scratch built rover robot.  I have been able to implement the X,Y joystick function to control the robot but when the joystick is held static the app stops sending data causing the robot to jerk to a stop. 

I am using a google Nexus 7 as my android platform.

I've searched through the options but don't see anything to keep the app transmitting while the joystick is held stationary.  Is this an artifact of my android platform, or is this a design element?

Again thank you for your hard work on this app.
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 29, 2013, 07:26 am
@_SBC_

Quote
Thank you veeeery much! )
Finally I can fully test my bot...

Many thanks again!!!


Glad to help  ;)
please let me have a screen photo
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 29, 2013, 07:52 am
Quote
Thank you for the wonderful app.
...
Again thank you for your hard work on this app.

Thanks for the nice comment and welcome to the Forum  :)


Quote
I've searched through the options but don't see anything to keep the app transmitting while the joystick is held stationary.  Is this an artifact of my android platform, or is this a design element?

To save bandwidth, the application only send data if the joystick position is changed
This is by design
Pseudo code:
Code: [Select]
if data <> dataAnt
 sendData()
 dataAnt = data
endIf


See if you can modify your bot code,
it should not need a constant flow of data to work
Otherwise let me know, I will then create a new option
Title: Re: Android Bluetooth joystick
Post by: arRaindog on Jul 29, 2013, 07:58 am
Thanks for the reply. I can modify my code if I choose to use this. As a fail safe I designed the code so the robot stops in the absence of a control signal. While the short range of Bluetooth reduces the chances of a runaway I can't catch before it breaks something I like the peace of mind. Thanks again.
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 29, 2013, 08:07 am
Quote
As a fail safe I designed the code so the robot stops in the absence of a control signal

Got the point, make sense  :smiley-roll-blue:
I will create the option this week

Title: ** Version 2.5 **
Post by: kas on Jul 30, 2013, 01:43 pm
I just received a new Galaxy Tab3 8" tablet 8)

The application didn't run well on this specific machine :smiley-sad-blue:
- toggle buttons didn't show the green LEDs as per reply #47
- erratic joystick movements
- screen layout was far from optimal on large tablets

Version 2.5 change log:
 layout adapts to device screen size
 better looking buttons
 fixed joystick bug (for the Android nerds: "nested weight")
 removed "Data Format" option (useless)
 buttons/joystick data collision management

(http://i.imgur.com/ovC8KE7.png)

@arRaindog:
Go to Option/Advanced Option/Timeout count
set to "Continually", should now work as expected

@_SBC_:
the display on your Samsung galaxy Y should now be OK with this new version
please confirm

I will test the application and upload it here (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result#?t=W251bGwsMSwxLDEsIm9yZy5wcm9qZWN0cHJvdG8uYnRqb3lzdGljayJd), within 24 hours
Get it directly from your device with Google Play

I definitely can't purchase every Android devices to check layout
Please let me have a feedback, possibly with screenshot
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 01, 2013, 11:07 am
Done

@arRaindog:
Make sure to adjust timeout count to the lowest frequency compatible with your Dead Man (http://en.m.wikipedia.org/wiki/Dead_man's_switch) strategy
Title: Re: Android Bluetooth joystick
Post by: arRaindog on Aug 03, 2013, 06:14 am
Thank you KAS.  I really appreciated your response and modifying your app.  I did have to make some changes to my code to deal with unavailable bluetooth data but now it is working wonderfully.  This is an excellent app that works as designed, is well laid out, and has many options and customizations to make it easy to use.  I've configure button one to engage autonomous mode (just got the three sensor ultrasonic array debugged) and to change the motor PWM (speed) for carpet vs. tile.


Attached is a screen shot on my google nexus 7:
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 03, 2013, 06:19 pm
Quote
Thank you KAS.  I really appreciated your response and modifying your app.  I did have to make some changes to my code to deal with unavailable bluetooth data but now it is working wonderfully.  This is an excellent app that works as designed, is well laid out, and has many options and customizations to make it easy to use.
:smiley-red: :smiley-red: :smiley-red:


Quote
I've configure button one to engage autonomous mode (just got the three sensor ultrasonic array debugged) and to change the motor PWM (speed) for carpet vs. tile

Still a small glitch: the buttons state synchronization can be lost on communication problems or simple Arduino reset
To be a serious control application, Android BT Commander needs two way communication channel and get Arduino acknowledgments to buttons change requests (see Reply #36)
I am working on V3.0 ;)


Please post a photo/video of your new toy   :P

Title: ** Joystick Bluetooth Commander Version 3.0 **
Post by: kas on Aug 10, 2013, 09:21 pm
** Major Upgrade **

Change Log
Full blown two way Bluetooth communication with the associated microcontroller
Arduino sends back a button status Byte and a user defined data Byte to be displayed
on the phone/tablet screen (Bot battery level is a nice candidate)
Device user defined Data textbox can be renamed and/or hidden if unused
Selectable -50/+50 or -100/+100 output range Option
** EDIT: added -180/+180 output range for servo motors **
Auto-connect at start up Option

Communication protocol
Android device data transmission
Joystick data is now transmitted as an integer = 2 Bytes (Most Significant Byte + Less Significant Byte)
<STX  MSB-X  LSB-X  MSB-Y  LSB-Y  ETX>

Code modification:
Code: [Select]
void loop() {
...
else if(i==5)    setJoystick_Int(cmd);  // 6 Bytes
...
}



Integer data is then assembled as follow:
Code: [Select]
void setJoystick_Int(byte data[5])    {
 // Demo
 int joyX = (data[1]<<7) + data[2];
 int joyY = (data[3]<<7) + data[4];
 joyX = joyX - 110;               // Transmission offset = 110   XXXXX
 joyY = joyY - 110;               // to avoid negative numbers   XXXXX
 
 Serial.print("Joystick data:  ");
 Serial.print(joyX);  
 Serial.print(", ");  
 Serial.println(joyY);

 // Your code here ...
}


** EDIT **     please see reply #84
 joyX = joyX - 200;               // Transmission offset = 200
 joyY = joyY - 200;               // to avoid negative numbers


Arduino data transmission:
Arduino sends back buttonStatus and dataByte
<STX  buttonStatus  dataByte  ETX>
(see  bitwise operators (http://arduino.cc/en/Reference/BitwiseAnd))

Code: [Select]

void setLED(int LEDstatus)  {
 switch (LEDstatus) {
   case '1':
     buttonStatus |= B0001;    // Button_1: ON
     Serial.println("Button_1: ON");
     // your code...      
     break;
   case '2':
     buttonStatus &= B1110;    // Button_1: OFF
     Serial.println("Button_1: OFF");
     // your code...      
     break;
   case '3':
     buttonStatus |= B0010;    // Button_2: ON
     Serial.println("Button_2: ON");
     // your code...      
     break;
   case '4':
     buttonStatus &= B1101;    // Button_2: OFF
     Serial.println("Button_2: OFF");
     // your code...      
     break;
   case '5':
     buttonStatus |= B0100;     // Button_3: ON
     Serial.println("Button_3: ON");
     // your code...      
     break;
   case '6':
     buttonStatus &= B1011;     // Button_3: OFF
     Serial.println("Button_3: OFF");
     // your code...      
     break;
   case '7':
     buttonStatus |= B1000;     // Button_4: ON
     Serial.println("Button_4: ON");
     // your code...      
     break;
   case '8':
     buttonStatus &= B0111;    // Button_4: OFF
     Serial.println("Button_4: OFF");
     // your code...      
     break;
 }
 sendData(buttonStatus, dataByte);
}


Advanced hint:
Button status can be monitored at a deeper level by directly manipulating and transmitting Arduino internal ports Byte (see Example Program (http://arduino.cc/en/Reference/BitwiseAnd))

Choose DataByte to taste:

Code: [Select]

byte GetdataByte()  {
 // Demo
 static byte i=0;
 i +=5;
 if(i >100)    i = 0;
 return i;  

 // Your code ...
}



Button status is feeded back by Arduino to the Android device
on a timed basis (every 'interval' milliseconds), and each time a button is pressed:
Code: [Select]

void loop() {
 if(mySerial.available())  {            // received from smartphone
   ...  
 }  else  {
   unsigned long currentMillis = millis();
   if(currentMillis - previousMillis > interval) {
     dataByte = GetdataByte();
     sendData(buttonStatus, dataByte);         // <<<<<
     previousMillis = currentMillis;  
   }
 }
 ...
}


Code: [Select]

void setLED(int LEDstatus)  {
 switch (LEDstatus) {
 ...
 }
 sendData(buttonStatus, dataByte);         // <<<<<
}


Code: [Select]

void sendData(byte button, byte data)    {
 mySerial.write(STX);
 mySerial.write((button<<2)+4);
 mySerial.write(data+4);           // +4: avoid 0x2 & 0x3
 mySerial.write(ETX);
}

button status Byte is left shifted to avoid transmitting 0x02 and 0x03 (STX, ETX) values


As already stated, make sure your BT communication is set to 57600 BPS


The full Arduino sketch will be available shortly for download at the bottom of this post

The  Joystick Bluetooth Commander Version 3.0 is ready and debugged, I will upload it at Google Play as soon as user tests
are finished


Quote
Quote
BTW, the Galaxy phone guy [non-techie] was totally amazed how

he could suddenly use his Android phone to control the world, ;-),

I had this very same feeling 8), this is the reason I decided to share


I believe I did my duty  ;)
According to Google Play, Joystick Bluetooth Commander is now in the 500/1000 downloads ball park  8)
I spent an interesting month  :smiley-roll-blue: :smiley-roll-blue: :smiley-roll-blue: developing the application, but it's now time to move to other projects.

Thanks again for your interest and suggestions  :)

Edit:
Arduino sketch attached

Edit2:
Updated demo Arduino sketch at reply #90
Title: Re: Android Bluetooth joystick
Post by: vrooms23 on Aug 11, 2013, 02:11 pm
Sound amazing! Bluetooth name Linvor what possible use?
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 11, 2013, 04:47 pm
Quote
Sound amazing! Bluetooth name Linvor what possible use?

Not sure I understand your question  :smiley-roll:
Joystick Bluetooth Commander turns a smartphone/tablet into a remote controller
for home automation or robotic applications
This Android application is available on Google Play (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result#?t=W251bGwsMSwxLDEsIm9yZy5wcm9qZWN0cHJvdG8uYnRqb3lzdGljayJd)

BTW, the Arduino demo sketch is now attached to previous post
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 18, 2013, 09:13 am
Hi guys

Sorry for the delay
Everything is ready, except the autoconnect feature

Stay tuned...
Title: Re: Android Bluetooth joystick
Post by: vrooms23 on Aug 19, 2013, 12:53 pm
Sorry, my Bluetooth module brand name Linvor on PCB base, its works, perfect! Great, thanks.
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 20, 2013, 10:31 pm
Quote
its works, perfect! Great, thanks


Thanks!  ;)
Title: Re: Android Bluetooth joystick
Post by: Rosamunda on Aug 21, 2013, 07:09 am
Thank for releasing this fantastic app!
My first steps with Arduino, and with bluetooth were smoother because of your app!!
Is there a recommended post to learn how to control the joytick with servos?
Again, many, many thanks!!!
Rosamunda
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 21, 2013, 06:49 pm
Quote
Thank for releasing this fantastic app!
My first steps with Arduino, and with bluetooth were smoother because of your app!!

Thanks for your feedback  8)


Quote
Is there a recommended post to learn how to control the joytick with servos?

I just posted the Bluetooth robotic dancer source code here (http://forum.arduino.cc/index.php?topic=173504.0)

EDIT: Link is now OK
Title: Re: Android Bluetooth joystick
Post by: starybryg on Aug 21, 2013, 11:46 pm
Firstly: great app!
I have some suggestions:

1. Please add to configuration (Options -> Advanced Options.. -> Data Range) the ability to set a higher resolution - 128 or 180. Servos have 180degree and we lose fluidity of movement: currently every change on joystick is 1,8 degree in servo, but servo can move every 1 degree. I know that it is good to send only one byte, so i think that increase data range to 128 will be good temporary compromise.
2. If you made this communication two-way with checking button status, please think about adding 2 (or more) "reset" buttons (not "on-off").
3. Autoconnect function will be nice!!:)
4. Can you share developer version of the application? Or better yet- the source code? I do not I program for android, but certainly a lot of people will be grateful.

BTW, application looks great on HTC Wildfire S and Samgung Galaxy S. I chose your application (in the beginning in google play) to control the Arduino because it did not require much power/authorization. Please don't change it (do not add something which will need acces to internet, contacts on phone etc;)
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 22, 2013, 10:46 pm
Quote
1. Please add to configuration (Options -> Advanced Options.. -> Data Range) the ability to set a higher resolution - 128 or 180. Servos have 180degree and we lose fluidity of movement: currently every change on joystick is 1,8 degree in servo, but servo can move every 1 degree.

Makes sense, I will add -180 +180 Data range in V3.0 (to be published this week end)

Quote
2. If you made this communication two-way with checking button status, please think about adding 2 (or more) "reset" buttons (not "on-off").

Not sure I understand, please elaborate

Quote
3. Autoconnect function will be nice!!:)

AutoConnect is now ready

Quote
4. Can you share developer version of the application? Or better yet- the source code? I do not I program for android, but certainly a lot of people will be grateful.

Will definitely share source code
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 23, 2013, 05:31 pm
Android Bluetooth joystick V3.0 is now available on Google Play (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result#?t=W251bGwsMSwxLDEsIm9yZy5wcm9qZWN0cHJvdG8uYnRqb3lzdGljayJd)

I have added servo's -180/180 data range as per starybryg suggestion
To avoid transmitting negative number, data offset has been increased to 200

Code from reply #74
Code: [Select]
void setJoystick_Int(byte data[5])    {
 // Demo
 int joyX = (data[1]<<7) + data[2];
 int joyY = (data[3]<<7) + data[4];
 joyX = joyX - 110;               // Transmission offset = 110
 joyY = joyY - 110;               // to avoid negative numbers
 
 Serial.print("Joystick data:  ");
 Serial.print(joyX);  
 Serial.print(", ");  
 Serial.println(joyY);

 // Your code here ...
}


should be modified as follow:
Code: [Select]
void setJoystick_Int(byte data[5])    {
 // Demo
.......
 joyX = joyX - 200;               // Transmission offset = 200
 joyY = joyY - 200;               // to avoid negative numbers
.......  

 // Your code here ...
}


Should you find any glitch, please let me know
I will also appreciate any feed back, especially for screen layout

Enjoy  ;)
Title: Re: Android Bluetooth joystick
Post by: starybryg on Aug 24, 2013, 01:21 pm
I'm sorry that I expressed in imprecise:
-If servo have 180 degree movement, so best range will be from -90 to 90. Hmm, generally, it will be 90+90+"0 position"=181, but it will be no problem I think. Of course now I can divide the range -180 to +180 (it is 360 points) by 2 in arduino program (to have 180 degres), but now is new problem: on small screen resolution (on spartphone) it is imposible to achieve this resolution of joystick movement, and value jumps every 2-3 points/pixels.. My suggestion is to give range (-90 to 90) instead of 100-100 or 180-180, or please think about user-definet values.  
-Maybe "reset button" is not nessesary.. Now in application there are 4 on-of switches: you can turn them on by clicking them, and then you can turn them off by clicking again. "reset button" can be used for example to make an cannon - you will fire only when you press the button. I se two possibilities: sending signal once when pressing button, or sending also signal "off" when you pick up finger from button. But now, if there is two-way communication with button status I think this can be done with existing keys and program on arduino.
-Auto connect is great and convenient, thank you!
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 25, 2013, 10:17 am
Quote
Of course now I can divide the range -180 to +180 by 2 in arduino program, but now is new problem: on small resolution it is imposible to achieve this resolution of joystick movement, and value jumps every 2-3 points.. My suggestion is to give range (-90 to 90) instead of 100-100 or 180-180,

I am not sure that reducing Data Range from -180/180 to -90/90 will help increasing servo resolution
Should you want it, let me have your email via PM, I will send you a special build with -90/90 data range for test


Quote
"reset button" can be used for example to make an cannon ...
But now, if there is two-way communication with button status I think this can be done with existing keys and program on arduino.

You got the point, button behavior is define within the Arduino sketch:
- Latch button (on-off switch):
Code: [Select]
void setLED(int LEDstatus)  {
 switch (LEDstatus) {
   case '1':
     buttonStatus |= B0001;    // Button_1: ON
     Serial.println("Button_1: ON");
     // your code...      
     break;
   case '2':
     buttonStatus &= B1110;    // Button_1: OFF
     Serial.println("Button_1: OFF");
     // your code...      
     break;
   ...............
}


- Momentary button (reset button):
Code: [Select]
void setLED(int LEDstatus)  {
 switch (LEDstatus) {
   case '1':
     Serial.println("Button_1: momentary ON");
     // Fire...
     break;
   case '2':
     // no code here (drop Button1 off case)    
     break;
   .......
}


Title: Re: Android Bluetooth joystick
Post by: kas on Aug 25, 2013, 10:18 pm
I just received this message via PM:
Quote

Hey kas!

First off all, I would like to say that you have done a great job in creating the app to control robots. I have made mine, which is a car, and glad say that it works well.

I built it using the 2.5 ~ 2.6 version, in which the version still had the (2, 60, 60, 3) format. My phone automatically updated to the 3.0 version, and unfortunately, the robot is not working. As I understand, the actual sent data has changed?

Anyway, going to the point, I would like to request links to the previous versions of the application, just so to test my older code. Is that possible?

Thanks in advance.

-Gin319


The Google Play auto update feature is a real pain :smiley-zipper:
For those in the same situation, please let me have your email via PM,
I will send you the previous version

Sorry for the trouble
Title: Re: Android Bluetooth joystick
Post by: CHulla on Aug 25, 2013, 11:02 pm
Seems like i found the right app for my next project.
ill be using LG revolution v2.2 (froyo), arduino Uno and HC05. Hope it will work.

Finally, Thanks Kas.
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 26, 2013, 09:24 pm
Thanks CHulla

Good luck for this new project  ;)
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 28, 2013, 07:16 pm
This is the complete Arduino demo sketch for V3.0

Code: [Select]
// AndroLED V9

// Arduino test sketch for Joystick BT commander
// V9.0: ** Release for Android BT Commander V3.0 AND HIGHER ONLY **

//  Arduino pin#2 to TX BlueTooth module
//  Arduino pin#3 to RX BlueTooth module

#include "SoftwareSerial.h"

#define    DEBUG        false
#define    STX          0x02
#define    ETX          0x03

SoftwareSerial mySerial(2,3);         // BlueTooth module: pin#2=TX pin#3=RX
int i=0;
byte cmd[6] = {0, 0, 0, 0, 0, 0};     // bytes received
byte buttonStatus = 0;                // first Byte sent to Android device
byte dataByte = 0;                    // second Byte sent to Android device
long previousMillis = 0;              // will store last Buttons status was updated

long interval = 1000;                 // interval to transmit Buttons status (milliseconds)

void setup()  {
 Serial.begin(57600);
 mySerial.begin(57600);              // 57600 = max value for softserial
 Serial.println("AndroLED V9 - demo for Joystick BT commander V3.0");
 delay(300);
}

void loop() {
 if(mySerial.available())  {            // received from smartphone
   delay(5);
   cmd[0] =  mySerial.read();  
   if(DEBUG)  Serial.println(cmd[0]);   // to serial monitor
   if(cmd[0] == STX)  {  
     i=1;      
     while(mySerial.available() && ((cmd[i]=mySerial.read()) != ETX)) {
       if(i>5)  break;
       if(DEBUG)    {Serial.print(i); Serial.print(": "); Serial.println(cmd[i]);}
       i++;
     }
   }
   if(i==2)    setLED(cmd[1]);
   else if(i==5)    setJoystick_Int(cmd);  // 6 Bytes
   else Serial.println("****");
 }  else  {
   unsigned long currentMillis = millis();
   if(currentMillis - previousMillis > interval) {
     dataByte = GetdataByte();
     sendData(buttonStatus, dataByte);
     previousMillis = currentMillis;  
   }
 }
 delay(5);
}

void setLED(int LEDstatus)  {
 switch (LEDstatus) {
   case '1':
     buttonStatus |= B0001;    // Button_1: ON
     Serial.println("Button_1: ON");
     // your code...      
     break;
   case '2':
     buttonStatus &= B1110;    // Button_1: OFF
     Serial.println("Button_1: OFF");
     // your code...      
     break;
   case '3':
     buttonStatus |= B0010;    // Button_2: ON
     Serial.println("Button_2: ON");
     // your code...      
     break;
   case '4':
     buttonStatus &= B1101;    // Button_2: OFF
     Serial.println("Button_2: OFF");
     // your code...      
     break;
   case '5':                    // configured as momentary button
//      buttonStatus |= B0100;     // Button_3: ON
     Serial.println("Button_3: ON");
     // your code...      
     break;
//    case '6':
//      buttonStatus &= B1011;     // Button_3: OFF
//      Serial.println("Button_3: OFF");
//      // your code...      
//      break;
   case '7':                    // configured as momentary button
//      buttonStatus |= B1000;     // Button_4: ON
     Serial.println("Button_4: ON");
     // your code...      
     break;
//    case '8':
//      buttonStatus &= B0111;    // Button_4: OFF
//      Serial.println("Button_4: OFF");
//      // your code...      
//      break;
 }
 sendData(buttonStatus, dataByte);
}

void setJoystick_Int(byte data[5])    {
 // Demo
 int joyX = (data[1]<<7) + data[2];
 int joyY = (data[3]<<7) + data[4];
 joyX = joyX - 200;               // Transmission offset = 110
 joyY = joyY - 200;               // to avoid negative numbers

 Serial.print("Joystick data:  ");
 Serial.print(joyX);  
 Serial.print(", ");  
 Serial.println(joyY);

 // Your code here ...
}

byte GetdataByte()  {
 // Demo
 static byte i=0;
 i +=5;
 if(i >100)    i = 0;
 return i;  

 // Your code ...
}

void sendData(byte button, byte data)    {
 mySerial.write(STX); mySerial.write((button<<2)+4); mySerial.write(data+4); mySerial.write(ETX); // +4: avoid 0x2 & 0x3
}


Buttons 1 & 2 are latch buttons
Buttons 3 & 4 are momentary buttons
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 31, 2013, 10:10 am
I got an interesting comment/suggestion
Quote
What about developing the same type of application, but using the android device built in accelerometers
Control would be performed just by tilting the smartphone/tablet.
The joystick would be a "read only" device, reflecting the device inclination.


This sister application could be called Acc Bluetooth Commander
Any interest ???
Title: Re: Android Bluetooth joystick
Post by: balaclava07 on Sep 04, 2013, 04:42 pm
Hey

First I want to thank you for this great app and sharing it for free. Second I would like to ask you, why you don't make joystick ball to turn in circle instead of square like it's now. I hope you understand what I mean.

Thank you for the answer

Title: Re: Android Bluetooth joystick
Post by: kas on Sep 05, 2013, 07:46 am
Quote
First I want to thank you for this great app and sharing it for free

Thanks  ;)

Quote
why you don't make joystick ball to turn in circle instead of square like it's now

To get full range at 45°, 135°, 225° and 315°, the joystick moving area HAS to be square.
With a circle, at 45° max values would be 71 (100/1.414) assuming a -100/+100 data range.

Please let me have your phone/tablet model
Title: Re: Android Bluetooth joystick
Post by: transfinite on Sep 06, 2013, 12:10 am
Quote
What about developing the same type of application, but using the android device built in accelerometers
Control would be performed just by tilting the smartphone/tablet.
The joystick would be a "read only" device, reflecting the device inclination.

      This sister application could be called Acc Bluetooth Commander
       Any interest ???



I think that's a great idea.  Or just add an option to the current app to toggle using the accelerometer instead of your finger to control the joystick.

-transfinite
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 06, 2013, 08:57 pm
Quote
Quote

What about developing the same type of application, but using the android device built in accelerometers
Control would be performed just by tilting the smartphone/tablet.
The joystick would be a "read only" device, reflecting the device inclination.

     This sister application could be called Acc Bluetooth Commander
      Any interest ???


I think that's a great idea.  Or just add an option to the current app to toggle using the accelerometer instead of your finger to control the joystick.

-transfinite


That's another great idea, thanks transfinite
We could call it  "Total BT Commander"   ;)

BTW, any "unexpected behavior" in V3.0 ???
Title: Re: Android Bluetooth joystick
Post by: balaclava07 on Sep 09, 2013, 08:58 am


To get full range at 45°, 135°, 225° and 315°, the joystick moving area HAS to be square.
With a circle, at 45° max values would be 71 (100/1.414) assuming a -100/+100 data range.



Yes that's true, but for my Arduino program I'm using for position calculating Pythagorean theorem and because the moving area is square I'm not getting the right numbers. Numbers are too big at 45°, 135°, 225° and 315°.

Title: Re: Android Bluetooth joystick
Post by: kas on Sep 09, 2013, 03:59 pm
OK...
This feature will be included, as an option, in V3.1
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 13, 2013, 06:46 pm
With range -100/+100, some joystick positions do interfere with ETX (0x3):

X=59, Y=24  is transmitted as  <2  2  3  1  96  3>
X=47, Y=59  is transmitted as  <2  1  119  2  3  3>

In these two examples, a transmission error is generated as ETX is detected earlier than expected
I have modified the Arduino demo sketch to definitely address this situation

AndroLED V10 is attached to this message
I suggest to use the same decoding algorithm in your own program  

EDIT:
replaced   previousMillis = currentMillis - interval*0.9;  
by            previousMillis = currentMillis - interval*0.5;
to avoid possible racing conditions  

please download again (V10.1)
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 25, 2013, 08:11 am
I just realized that the Arduino sketch is not attached to previous post, sorry guys, here it is
EDIT: You must be logged to see the file  :smiley-roll-blue:

some functions have been renamed to more meaningfull names

for this demo
- Button #1:  built in LED control
- Button #2:  enable Debug mode
- Button #3:  configured as momentary
- Button #4:  configured as momentary

EDIT: Please  discard V10.2 and download V10.3 (see reply #129)

Title: ** Version 3.1 **
Post by: kas on Oct 11, 2013, 09:25 pm
V 3.1  maintenance version

- Joystick constraint: box or circle option (as per balaclava07 request)
- better algorithm for data reception from Arduino
- various minor fixes

To be uploaded here (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result#?t=W251bGwsMSwxLDEsIm9yZy5wcm9qZWN0cHJvdG8uYnRqb3lzdGljayJd) later today

Title: Re: Android Bluetooth joystick
Post by: jooheepark on Oct 28, 2013, 09:45 am
Hi, kas.

Thank you for sharing this awesome app.
I've tested it with Bluetooth Mate Silver board.
It works perfectly. However you need to change a baud rate of Bluetooth Mate Silver board.
you can find out how to change a baud rate http://www.buildcircuit.com/how-to-change-baud-rate-of-bluetooth-modem-bluesmirf-gold-using-arduino-terminal/ (http://www.buildcircuit.com/how-to-change-baud-rate-of-bluetooth-modem-bluesmirf-gold-using-arduino-terminal/).

Thank you!
Title: Re: Android Bluetooth joystick
Post by: kas on Oct 29, 2013, 11:05 am
Quote
Thank you for sharing this awesome app


Thanks jooheepark,
I appreciate the time you spent for registering and sharing your experience
Matching baud rate is indeed a key point for success (together with RX/TX proper wiring)

@all
please report
- bugs (if any ;))
- requested new features

and...  info's regarding your new Bluetooth RC toy

I personally use this App for controlling my balancing robot (http://forum.arduino.cc/index.php/topic,8871.0.html), using now the MPU-6050 gyro/acc combo

(http://i.imgur.com/qEoaPqa.jpg) (http://imgur.com/qEoaPqa)
Title: Re: Android Bluetooth joystick
Post by: o_lampe on Oct 31, 2013, 08:07 pm
Hi kas,
thanks a lot for your time and work on this APP.

I tried to use your BT-scanner and BAUD-rate setting program, but with soft_serial I had no luck on my mega2560 board. I tried several pin combinations and reversed TX/RX , but nothing.
Then I rewrote the program and replaced the soft_serial 'myserial' with 'Serial1' commands, and it worked like a charm.

BTW, if you get bored one time, pleeease write a version for stepper motors as well  ;)

Groeten
Olaf

<edit> It seems, that soft_serial only works up to 57600 BAUD. My BT-module was setup to 115200 BAUD, that's why it didn't work

@all, does anybody know the AT-command to change the PIN-code for the BT module?
Title: Re: Android Bluetooth joystick
Post by: kas on Nov 02, 2013, 08:40 am
Hi o_lampe

Quote
BTW, if you get bored one time, pleeease write a version for stepper
motors as well  smiley-wink


What is your specific application that make you choose steppers over servo's ??


Quote
does anybody know the AT-command to change the PIN-code for the BT
module?


Assuming you have a JY-MCU or compatible board, see here (http://wiki.openpilot.org/display/Doc/Serial+Bluetooth+Telemetry) and scroll down to mid page:

AT+PINxxxx  Sets the pairing password of the device
Any 4 digit number can be used, the default pincode is 1234
Response: OKsetPIN


Quote
It seems, that soft_serial only works up to 57600 BAUD. My BT-module was
setup to 115200 BAUD, that's why it didn't work


Using hardware serial, mega2560 board should be OK @115200 baud (and higher with
a third party Serial Monitor)
Title: Re: Android Bluetooth joystick
Post by: o_lampe on Nov 03, 2013, 08:24 am
Quote
What is your specific application that make you choose steppers over servo's ??


I don't have a specific application. Maybe a big camera gimbal controlled by a smartphone. Your app as an OSD overlay of the camera picture? ( with a smaller Joystick or semi seethrough )
But then again, I could use a brushless gimbal and the current app would be fine.
Title: Re: Android Bluetooth joystick
Post by: danihell on Nov 19, 2013, 04:24 pm
Hi kas!

nice project here...congratulations.

I would like to make you a question, it´s possible to do a joystick like your's but instead control servo control step motors,  the joystick send  0 200 300 300.

(tell the stepper with an id of 0, move to a position of 200 steps (one rotation), speed of 300, acceleration of 300)


Is this the best way to control a step motor?

thanks

Title: Re: Android Bluetooth joystick
Post by: rtso489 on Nov 21, 2013, 09:10 am
Hey kas!

Thanks for making this application. It's cool and the controls are easy to use. My friends and I have never worked with Arduinos before and hacked up this robotic ball in a week that uses your app. It was really fun!

http://www.youtube.com/watch?v=EkCU7p1Dk2w

Keep up the good work. We love your app!
Title: Re: Android Bluetooth joystick
Post by: kas on Nov 23, 2013, 10:55 am
Quote

Hey kas!
Thanks for making this application. It's cool and the controls are easy to use. My friends and I have never worked with Arduinos before and hacked up this robotic ball in a week that uses your app. It was really fun!
Keep up the good work. We love your app!


Hi rtso489
Thanks for taking the time to register and post your first comments on the forum

This is a very cool hack  8) 8) 8)
Please let us have more info, link to the original device and possibly photo of the internal mechanism
Thanks again for sharing
Title: Re: Android Bluetooth joystick
Post by: itscoldoutside on Dec 04, 2013, 11:00 pm
Hi all,

Has anyone managed to get this running with a Nano? I can connect fine, on a bluesmirf silver via the app, tried all sorts of configurations with RX/TX and servo pins, but I cant get any further, any guidance would be much appreciated.

Edit, problem solved, Thanks KAS for the time you have put in, I will upload a "dummy's guide" later in a bid to contribte : )
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 05, 2013, 03:44 pm
Quote
Edit, problem solved, Thanks KAS for the time you have put in, I will upload a "dummy's guide" later in a bid to contribte : )

Glad you sorted it out
Your contribution will be very welcome  ;)
Title: Re: Android Bluetooth joystick
Post by: kovacsgellert on Dec 11, 2013, 04:29 pm
First of all thank you. It's really nice to see something this simple and well documented. I'll try it as soon as my exams are over. Referring back to an older post I believe as well that the addition of accelerometer to the available control options would be really nice.  :)
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 13, 2013, 09:29 pm
Hi kovacsgellert, thanks for your comments

Quote
Referring back to an older post I believe as well that the addition of accelerometer to the available control options would be really nice.   :)

I had the idea to develop an accelerometer based application, but it didn't generate enough interest here, to justify development time   :~
Title: Re: Android Bluetooth joystick
Post by: hib1 on Dec 23, 2013, 03:38 am
HI,

I downloaded this sketch for my UNO R3  and have version 3.1 of  BT Joystick Commander on a nexus tablet.

the Bluetooth connection works as follows:

pressing button 1 on the android produces button on, button off on the arduino serial terminal.

no other functions work..

Joystick data is displayed,on the android but not on the arduino terminal

i have read through the many threads on ths topic and see no obvious fixes for the joystick problem.

Please send suggestions.

Title: Re: Android Bluetooth joystick
Post by: kas on Dec 25, 2013, 04:11 pm
Hi hib1,

I am currently on holydays and will be home next week
In the meantime, please make sure you are using the latest AndroLED Arduino demo sketch (V10.2)
modify:
Code: [Select]
boolean DEBUG = false;
to:
Code: [Select]
boolean DEBUG = true;

DEBUG can also be toggled using Button #2

Let me know the outcome

@all
Merry Xmas  :) :)
Title: Re: Android Bluetooth joystick
Post by: juycce on Jan 05, 2014, 11:54 am
Great app KAS, bad thing is not working on IOIO board,just tested out :( ,do u think in a future could make one to be IOIO otg compatible?...once again ,this app is the best,on Google Store ;) Thank you
Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Jan 05, 2014, 11:05 pm
any chance that you  can add a window to show the feed from a wifi camera? Then we will have the ultimate robot controller.
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 06, 2014, 07:57 am
Hi juycce

Quote
do u think in a future could make one to be IOIO otg compatible?

Sorry, no experience yet with IOIO  :~

Quote
this app is the best,on Google Store

Gracias :smiley-red:

Title: Re: Android Bluetooth joystick
Post by: kas on Jan 06, 2014, 08:10 pm
Quote
any chance that you  can add a window to show the feed from a wifi camera? Then we will have the ultimate robot controller
:smiley-roll: :smiley-roll: :smiley-roll:
that's a slightly more complex story  ;)
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 10, 2014, 08:17 am
Quote
Quote
any chance that you  can add a window to show the feed from a wifi camera? Then we will have the ultimate robot controller
:smiley-roll: :smiley-roll: :smiley-roll:
that's a slightly more complex story  


OK
Did some research, looks definitly doable
I will order a Foscam IP camera which is well supported and documented
(http://i.imgur.com/3OS0C2H.jpg)

I already started development using another android device (Sony Xperia Mini) as an IP camera

Thanks tolisn63 for this smart idea, and... for keeping me busy  ;)
Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Jan 10, 2014, 11:47 am
Great news, if you want I can also test. I have a wanscam IP camera (similar  to foscam)
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 10, 2014, 04:39 pm
Quote
Great news, if you want I can also test. I have a wanscam IP camera (similar  to foscam)


Why not  :)

This a screen shot of "Total RC Commander" V0.1B:
(http://i.imgur.com/1nFYamx.jpg)
The application is working but for the moment, the screen is optimized only for a 8" tablet
I suspect the application needs at least 7" to display the information correctly
sorry, no phones  :~ :~

Do you have a tablet ??
Please let me have size and resolution
Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Jan 10, 2014, 06:01 pm
Wow, that was quick.
Yes I do have a tablet. Nexus 7 (2012) 7" 1280*800
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 10, 2014, 07:27 pm
Let me have your email via PM
Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Jan 11, 2014, 12:35 pm
PM sent
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 11, 2014, 09:01 pm
Check your mail
Title: Re: Android Bluetooth joystick
Post by: billcat on Jan 11, 2014, 11:22 pm
Hi, kas!
I am unable to implement your VERY COOL 8) app simply due to  my inability to modify the Arduino sketch to meet my needs.  I have little experience with microcontrollers, or in any programming in general, having started about 6 months ago with the Arduino, and have spent countless brain numbing hours since trying to understand basic sketch examples with little results.  But I am very interested in figuring this out, as you mentioned in post #1, the possibilities are endless!

I have installed V.3.1 of your joystick app on my phone(samsung galaxy s3) and installed the v10.2 sketch from your post #99.  I have the JY_MCU bluetooth module and everything seems to be communicating properly.

I wonder if you would consider my intentions, and provide some guidance on modifying the code/code snippets to ease me along?

      My interest right now is simply to turn on and off three LEDs with the Android buttons(pressing Android button one turns on led1, press it again turns it off, same for button2 for led2 and button3 for led3) and drive one standard r/c servo both directions(CW, 0, CCW) using the joystick x axis.  So far, I have been able to get some results with LEDs by using "digital.write" following several of the eight "case" statements, but for the most part the results are unreliable/unpredictable from what I expect.  In viewing the serial monitor after my sketch modifications, I can not make sense of what is happening and why.  I have not even attempted anything with the joystick, figured the LEDs would be easier first.

Many thanks for sharing your work, it is very nice!
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 12, 2014, 09:19 pm
Quote
I wonder if you would consider my intentions, and provide some guidance on modifying the code/code snippets to ease me along?


OK

First step

1) Which Arduino board are you using ?

2) download and run this sketch and confirm baurate + firmware version

Code: [Select]
// JY-MCU Bluetooth Dongle configurator
// Credit to Jeff Simpson

// Utility will display actual Baud rate and as an option,
// set up a new Baud rate

// TX BT board pin to Arduino D2
// RX BT board pin to Arduino D3
// 5V BT board pin to Arduino 5V
// GND BT board pin to Arduino GND

#include "SoftwareSerial.h"

SoftwareSerial mySerial(2, 3);          // BlueTooth module TX RX
char response[21];                      // responses from module
int rv = 0;                             // return value
boolean found = false;                  // module found
int bps;

void setup()  {
 Serial.begin(57600);
 mySerial.begin(57600);
 delay(300);
 Serial.print("\n\nJY-MCU Bluetooth Dongle configurator ");
 Serial.print("\nSearching ");            // Search for BT module on 12 possible baudrates
 long baud[12] = {1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600, 1382400};
 for(int a = 0; a < 12; a++)
 {  mySerial.begin(baud[a]);
    delay(300);
    mySerial.write("AT");               // "AT" will respond with "OK" if it is working
    delay(20);
    mySerial.readBytes(response, 2);
    delay(20);
    if (strncmp(response, "OK", 2) == 0)
    {  Serial.print("\nBluetooth Module found at BAUD ");
       Serial.println(baud[a]);
       found=true;
       break;
    } else  Serial.print(".");
 }
 if (found==false)
 { Serial.println("\nERROR: Bluetooth Module not responding!");
   Serial.println("Make sure there are no active bluetooth connection and try again");
   while(1);
 }
 
 delay(100);
 mySerial.write("AT+VERSION");           // Check the firmware version
 while(mySerial.available() == 0);
 mySerial.readBytes(response,2);
 if (strncmp(response, "OK", 2)==0)
 { rv = mySerial.readBytes(response, 20);
   response[rv] = 0;
   Serial.print("Firmware Version: ");
   Serial.println(response);
   Serial.println();
 }  else  {  
   Serial.println("Error checking BT Version");
   Serial.println();
   while(1);
 }

 while(Serial.available())   Serial.read();
 Serial.println("To modify Baud rate, enter:");  
 Serial.println("  1  for   1200 bps");  
 Serial.println("  2  for   2400 bps");  
 Serial.println("  3  for   4800 bps");  
 Serial.println("  4  for   9600 bps");  
 Serial.println("  5  for  19200 bps");  
 Serial.println("  6  for  38400 bps");  
 Serial.println("  7  for  57600 bps");  
 Serial.println("  0  to Exit\n");
 Serial.print("Selected: ");
 
 while(Serial.available()==0);
 bps = Serial.read();
 if(bps>=48 & bps<=56)  {    // '0' < bps < '8'
 Serial.println(bps-48);
   if(bps>48)  {
     mySerial.write("AT+BAUD");           // Set the BAUD
     mySerial.write(bps);
     while(mySerial.available()==0);
     mySerial.readBytes(response, 2);
     if (strncmp(response, "OK", 2)==0)  {
       rv = mySerial.readBytes(response, 7);
       response[rv] = 0;
       Serial.print("New BAUD setting: ");
       Serial.println(response);
     }  else  {
       Serial.println("Error Setting BAUD");
       Serial.println(response);
     }
     Serial.println("Bluetooth Setup Completed  ** End **");
     while(1);
   }  else  {
     Serial.println("No modification  ** End **");
     while(1);
   }
 }
 else    Serial.println("non valid entry  ** End **");
}

void loop() { }

Exit code by pressing "0"


3) for the good sake, confirm that the JY_MCU led changes from blinking to solid red when connecting within Android BT Joystick
Title: Re: Android Bluetooth joystick
Post by: billcat on Jan 13, 2014, 02:22 am
hello,
thanks kas for the help! :) ....If I could return the favor in any way...feel free to ask.

1) breadboarded UNO
2)yes, I previously did the BT configuration.  Baudrate is 57600, firmware is limnor(?) 1.8.  I used the openpilot sketch for the configuration if you are familiar.
3) yes the JY-MCU red led goes solid upon connection, I definitely have BT comms working.

since my last post......I have had some success with the led portion.   I am able to turn on and off one led with button1 using the following code snippets.  However, the operation of the green button indicator lights on the phone eludes me.  I would expect the indicator to stay on as long as the ledpin is on, however it just lights briefly after I press the button.  I'm sure this is exactly as the code intends, But I don't understand which portion of the sketch controls this.

I tried blindly playing with this line with no idea what I was doing:
Code: [Select]
buttonStatus &= B0001;  including deleting it altogether, with no obvious affect on the operation.  I can't figure out what action these lines in each of the case blocks perform .

this is the code I modified to some success. Is it reasonable?
Code: [Select]

int b1state=1

switch (buttonStatus) {
   case '1':
     buttonStatus &= B0001;          // Button_1: ON
     if (b1state==1){
     Serial.println("Button_1: ON");  
     digitalWrite(ledPin, HIGH);}
     if (b1state==0){
     Serial.println("Button_1: OFF");
     digitalWrite(ledPin,LOW);}
     b1state= 1- b1state;               // toggle led
     break;

forgot to mention that I also had to comment out the lines following "case 2" or else it would immediately turn the ledpin back off.

edited for clarity

Title: Re: Android Bluetooth joystick
Post by: kas on Jan 13, 2014, 03:47 pm
Hi billcat

I finally could reproduce the problem, my fault   :smiley-red:
Please download and run attached sketch (V10.3)

- button #1 controls on board LED (D13)
- button #2 controls debug mode (output to Serial Monitor)
- button #3 and #4 are just configured as push button (momentary contact)

Please let me know the outcome, especially for button #1
Title: Re: Android Bluetooth joystick
Post by: billcat on Jan 14, 2014, 09:42 pm
Hello kas,
Thanks for the updated sketch, I will try it out when I get a chance, but I wont be able to for a few days.   I will let you know my outcome as soon as I can.

best wishes and thanks again for the cool app.
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 14, 2014, 10:25 pm
Quote
best wishes and thanks again for the cool app

Thanks billcat
Please let us have your feedback whenever you can
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 15, 2014, 06:30 pm
Quote
Great News

I got it working with this URL
http://IPaddress:port/videostream.cgi?user=admin&pwd=&resolution=32&rate=0

Now, let me think out-loud some functionality questions if I may.

1. is it possible to increase the number of buttons ?
2. What data can the controller poll?
can I split it up and show for example
Battery=
Heading=
Lasers=
Mode=
Control=
e.t.c

3. Can you increase the video size ?
4. Can you decrease the size of the joystick ? (to conserve space ?)
5. Can you add another option so instead of a joystick it shows 4 arrows to control the bot?
6. Is it possible to include toggle indicators ?

Sorry for all the loud thinking but I'm really exited with this. I was searching for something like this for a long time.
Thanks very much for all you hard work and sharing


OK  ;)

Previous design:
(http://i.imgur.com/1nFYamx.jpg)


Proposed layout based on your comments:
(http://i.imgur.com/ylTIAWT.jpg)

- 640X480 video stream
- 1 joystick
- 6 buttons (latch or momentary)
- 4 robot parameter displays sent back from Arduino (voltage, heading, rpm, temp ...)


Quote
Actually I had to lower the resolution of the camera (320x240) because there was a terrible video lag of about 1 second or so
I don't get any lag with my Xperia Mini configured as an IP camera, check your camera settings, you may have to reduce fps value

Please let me have your comments
Thanks again for your suggestions and your positive feedback  



Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Jan 15, 2014, 06:40 pm
Boy are you a coding machine. This is perfect.
Lets build on this and see how it works out.
Thanks a million
Title: Re: Android Bluetooth joystick
Post by: billcat on Jan 16, 2014, 10:45 pm

Please let me know the outcome, especially for button #1


Works perfect!  Thanks for the fix, I am now able to do what I want with the leds I mentioned.  Wish I understood the code fully so that I could modify as needed in the future.

Now I need to address the r/c servo scenario. I will try to figure it out myself first, but will probably end up needing advice on that later.

Cheers...
Title: Re: Android Bluetooth joystick
Post by: billcat on Jan 16, 2014, 11:01 pm
hi kas...again,

Sorry but I just now noticed your recent proposed "total rc commander", which looks  :D :D.  I had just been thinking it would be great if there were a few more buttons, and a way to send more data info. 

Do you know if this version would work with my galaxy s3 and if so, is it also available on the google store?
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 17, 2014, 08:51 am
Quote
Works perfect!  Thanks for the fix, I am now able to do what I want with the leds I mentioned

@billcat
Glad it now works  :) :) :)

@all
AndroLEDV10.2 introduced a nasty bug: buttonStatus was both declared as global and local
buttonStatus (global) was therefore never updated  :smiley-red:
Please  discard V10.2 and download V10.3 (see reply #129)

Quote
Now I need to address the r/c servo scenario. I will try to figure it out myself first, but will probably end up needing advice on that later
Joystick Bluetooth Commander was specificaly developped for driving up to two r/c servo's. should you have any problem with the code, please ask  ;)


Quote

I just now noticed your recent proposed "total rc commander", which looks   :D :D :D.  I had just been thinking it would be great if there were a few more buttons, and a way to send more data info.  
Do you know if this version would work with my galaxy s3 and if so, is it also available on the google store?
Total RC Commander (with video stream display) is in development with tolisn63 support, now nearly ready
I invested quite a lot of time (and some money) in this project  :smiley-roll:
My plan is to propose this application on Google Store for a couple of bucks, but I am concerned by Google privacy policy...

@all
Should you be interested by this App, please contact me via PM
Title: Re: Android Bluetooth joystick
Post by: juycce on Jan 19, 2014, 09:46 pm
This is looking better and better Kas, i belive you should go for the app,i am shore more than one would want a app like this,that can control a rc car toy with video ...with your phone.I am going to trie it soon,for the moment i am wayting the bluetooth JY MCU HC6 (hope its compatible)..
My ideea is to fit the Arduino and the JY-MCU with one servo for steering,one TB6612FNG motor driver,and cuple Leds,and a buzzer
If all this will work properly i will try out the camera funcion,so one again,im telling you,this app will have succes,you should look at how many visit this post had.Nice job..Thank you ;)
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 21, 2014, 07:31 am
Quote
This is looking better and better Kas, i belive you should go for the app,...
...,so one again,im telling you,this app will have succes,you should look at how many visit this post had.Nice job..Thank you  ;)

Thanks juycce for the kind word  8)
The App is ready, but rather demanding in term of processing power (bluetooth + wifi)
Together with tolisn63 we are busy optimising the code

@all
Any candidate as a second beta tester ??
required:
- high end tablet (google, Samsung...)
- a different IP camera (not Wanscam)
Title: Re: Android Bluetooth joystick
Post by: juycce on Jan 24, 2014, 05:43 pm
i just recived my JY-MCU V1.06 but i can't figure out how to pair it with the phone...I load the sketch (with the TX,RX pin disconected) search it with the phone pair it (1234) then open the app and it say Unable to connect device" , and Led wont get solid
I guess it is not compatible with the V1.06 :( ....any ideeas

..i tried all the codes you post..even that one that only control 2 servo ...thx
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 24, 2014, 06:30 pm
No needs to load any sketch, this is a pure RF affair between Bluetooth module and Android device  ;)
Arduino board is not involved at this stage

1- Just make sure to connect 3V + Ground to BT board
2- BT board led should blink red
3- Pair the Android device with BT board, if not already done
4- Open BT Joystick Commander
5- Make sure "Option for advanced users/Auto connect" is unchecked
6- (exit/relaunch the application if any change)
7- Press "connect", make sure you see your BT device in the paired section
8- Select your BT device
9- BT device led should change from blinking to solid red
10- Android BT Commander should report: "connected to XXXXXX"

Let me know the outcome
Title: Re: Android Bluetooth joystick
Post by: juycce on Jan 27, 2014, 07:09 pm
Hello Kas,these days i've been diggin more about bluetooth arduino comunicancion and this is what i found:
JY-MCU HC 06 is compatible with android comunicacion (running ArduDroid app,it works flawlesly,i can control all pins on board Digital,PWM,and Analog) with my phone(HTC Wildfire S).But refuse to pair your app...so i tried to run it from another phone (Samsung S3) and yes it pairs just like u said...so i belive the BT Joystick app is not compatible with Android 2.3.5 :(( ....even so...if i had BT connection i couldn't get any movement ,joystick or Leds...i tried default config and changing parameters with no result
Could you post the first versions of the Bluetooth Joystick Aplicacion so i can trie it out? thank you for you help
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 27, 2014, 09:47 pm
Quote
But refuse to pair your app..

Not sure I understand
Pairing is an operation between your phone and the BT card
Apps are not involved in this process
Do you mean "connect" ??
Please clarify
Also let me know at which step (1 to 10) you are getting in trouble

Quote
so i belive the BT Joystick app is not compatible with Android 2.3.5

The app is compatible with Android V2.2 (API level 8 ) and higher

Quote
even so...if i had BT connection i couldn't get any movement ,joystick or Leds.

So you got connected ??
Please clarify

Quote
Could you post the first versions of the Bluetooth Joystick Aplicacion so i can trie it out?

Sure, let me have your email via PM
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 28, 2014, 11:03 am
Quote
I had just been thinking it would be great if there were a few more buttons, and a way to send more data info.  
Do you know if this version would work with my galaxy s3 and if so, is it also available on the google store?


hi Billcat
Check your mail
Six buttons + 4 data bytes  ;)

This is how it looks on my Sony Xperia Mini (3" 320X480)
(http://i.imgur.com/rUzjW6r.jpg)

Please let me have a screen shot from your Samsung galaxy S3 (4.8" 1280X720)

Title: Re: Android Bluetooth joystick
Post by: billcat on Feb 07, 2014, 03:00 pm

Please let me have a screen shot from your Samsung galaxy S3 (4.8" 1280X720)



Hello kas,

sorry for the delay....,

here is the screenshot from Samsung Galaxy S3.  It looks great!  But I have not had a chance to test it with/or the Arduino sketch, hopefully soon and I can let you know the outcome :D

thanks again!
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 12, 2014, 03:34 pm
@Billcat,
Based on your feedback, I will slightly move the joystick on the right, for the next release
I will appreciate you test the app when you have time (no rush ;))

@nemesis159
I will answer you questions later today
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 12, 2014, 06:07 pm
Quote
hi, bro estoy tratando de usar tu app de android, es la mejor que e visto, con la parte de los botones no tengo problemas pero no entiendo como usar la el joystick para controlar motores dc con un puente H, si me pudieras dar una orientacion seria exelente, es lo que me falta para terminar el proyecto, te dejo el link del puente h que yo uso.
http://www.pololu.com/product/713 (http://www.pololu.com/product/713)



Hi nemesis159

For general matters such as DC motor control, Google is your best friend  ;)
This is a quick basic example for one motor, using joyY (joystick vertical moves)
Pin configuration is based on 328P chip

(http://i.imgur.com/u2gdQrd.png)

Code: [Select]

*** AndroLED V10.3 modification: ***

/* add this code in the define section */
#define AIN1  4   // connect AIN1 to Arduino pin 4 ...
#define AIN2  5
#define PWMA  6
#define STBY  7


/* add this code in the setup function */
pinMode(AIN1,OUTPUT);
pinMode(AIN2,OUTPUT);
pinMode(PWMA,OUTPUT);
pinMode(STBY,OUTPUT);
digitalWrite(STBY, HIGH);


/* replace getJoystickState() with this one */
void getJoystickState(byte data[5])    {
 int joyX = (data[1]<<7) + data[2];
 int joyY = (data[3]<<7) + data[4];
 joyX = joyX - 200;               // Offset to avoid
 joyY = joyY - 200;               // transmitting negative numbers
 
 joyY = map(joyY, -100, +100, -255, 255);
 joyX = map(joyX, -100, +100, -255, 255);

 if(!DEBUG)  {
   Serial.print("Joystick data:  ");
   Serial.print(joyX);  
   Serial.print(", ");  
   Serial.println(joyY);
 }

 if(joyY > 0) {
   digitalWrite (AIN1,HIGH);
   digitalWrite (AIN2,LOW);
 }  else if(joyY < 0)  {
   digitalWrite (AIN1,LOW);
   digitalWrite (AIN2,HIGH);
 }  else  {
   digitalWrite (AIN1,LOW);
   digitalWrite (AIN2,LOW);

 analogWrite(PWMA,joyY);
}


Option/Data Range should be set to -100 +100

Please note that DC motors do not work well with low PWM values
Should you have motors with built in rotary encoders, consider adding PID control
Full discussion here (http://forum.arduino.cc/index.php/topic,8652.0.html)

Let us know how it works (can't test it now)
Title: Re: Android Bluetooth joystick
Post by: powermik on Feb 24, 2014, 07:38 pm
Hi!

Just (re-)discovered your software and this thread. Is there a possibility for a second joystick?

Michael
Title: Call for beta tester(s)
Post by: kas on Feb 25, 2014, 07:33 am
I am finalising the video embeded application

(http://i.imgur.com/ylTIAWT.jpg)

and need another beta tester with a different IP camera brand (Foscam or others), not Wanscam
Please contact me via PM
Title: Re: Android Bluetooth joystick
Post by: billcat on Feb 27, 2014, 03:33 pm

@Billcat,
Based on your feedback, I will slightly move the joystick on the right, for the next release
I will appreciate you test the app when you have time (no rush ;))

Hello Kas,

I have made a little time to play....  using Samsung Galaxy S3,
I have partially tested Joy BT Plus with AndroLedVidV11.   Only the buttons, to control some leds.  For the most, all seems to be working well :D

I think the joystick may still be moved slightly more to the right yet....no complaints here :smiley-red:....but since you mentioned it already.

But I remain very confused by how most of the sketch works, so I simply made all 'case' statements similar, and commenting out what I think does the momentary and debug parts here.  At the same time, changing the main debug to true, all joystick motions and button pushes reveal some change in information displayed in serial monitor.

I also think there may be a slight problem when choosing to view the data  as bytes sent....see screenshot.  Seems to be missing the closing ")"  and possibly some data. Perhaps I am mistaken, I still remain very unclear on how 1's and 0's are sent and received!
All of the menus display well with proper grammar, far as I can tell.  Another thing, I cannot seem to get anything out of the haptic feedback options, but it may be some other setting  on the phone.  But, I am able to get the phone to vibrate on ring, if that means anything.

Also, I do have some interest regarding the Beta testing for video.  I do not own an IP camera, but that is a simple fix $) .   Seems a bit out of my league yet, but would be a challenge that should help increase my knowledge base.   Feel free to contact me via PM/email.

Cheers,
Bill
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 27, 2014, 10:08 pm
@Bill
thanks for the feedback

Quote
I think the joystick may still be moved slightly more to the right yet.

The version I sent you yesterday should take care of that

Quote
I also think there may be a slight problem when choosing to view the data  as bytes sent....see screenshot.  Seems to be missing the closing ")"  and possibly some data

Can see that, to be fixed in next revision

Quote
Perhaps I am mistaken, I still remain very unclear on how 1's and 0's are sent and received!

Welcome is the communication protocols Univers  ]:D ]:D ]:D

Quote
I cannot seem to get anything out of the haptic feedback options,

This option brings a vibrating feedback when moving the joystick
It is device dependant (works on my Motorola G, doesn't work on my Galaxy Tab3)
This feature is useless, to be removed in next build

Quote
Also, I do have some interest regarding the Beta testing for video.  I do not own an IP camera, but that is a simple fix  $)

Let me know when you are ready


@powermik
Quote
Just (re-)discovered your software and this thread. Is there a possibility for a second joystick?

Sorry no plan for a second joystick
As most of us, my limiting factor is time  :|
I am currently building a R/C tank with built in IP camera; my focus is embeding the video stream in the App
Title: Re: Android Bluetooth joystick
Post by: kovacsgellert on Mar 01, 2014, 02:44 pm
Nice to hear that you are working at a robot equipped with an IP Camera. I have a similar project, with the difference that my control software is a C# application, so the contorlling machine is a computer not a phone. It may be off/topic but I hope you don't mind if I put a link to my robot here: https://www.youtube.com/watch?v=E7C9-4SR41o&feature=youtube_gdata_player (https://www.youtube.com/watch?v=E7C9-4SR41o&feature=youtube_gdata_player)
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 02, 2014, 03:55 pm
Quote
It may be off/topic but I hope you don't mind if I put a link to my robot here: https://www.youtube.com/watch?v=E7C9-4SR41o&feature=youtube_gdata_player

You are very welcome  :)

This his my own work in progress:
(http://i.imgur.com/bO1pdSJ.jpg)

The bot is based on a Rover 5 (https://www.sparkfun.com/products/10336) frame
PID motor control yet to be finalised
Title: Re: Android Bluetooth joystick
Post by: billcat on Mar 03, 2014, 03:47 pm

@Bill
thanks for the feedback

you're welcome!

The version I sent you yesterday should take care of that

great!

Welcome is the communication protocols Univers  ]:D ]:D ]:D

:smiley-mr-green:

This feature is useless, to be removed in next build

got it...

Let me know when you are ready

Sure, thanks!

Title: Re: Android Bluetooth joystick
Post by: kas on Mar 07, 2014, 12:35 pm
@wildatheart
also for billcat and others  ;)
Quote
Hello Kas.

Thank you for sharing your joystick app.  I am reading 6 bytes (decimal)  2, 1, 72, 1, 72, 3.  I understand the 2 & 3 are framing bytes.  And I also understand that 1 is the MSB and 72 is the LSB, and I believe you subtract 200 (decimal) to eliminate negative values.  But I do not understand the relationship between 173 and 0 being at the center.  Would you please tell me how these values relate to 0,0 with stick in center position.

Thank you


Joystick data is transmitted as an integer = 2 Bytes (Most Significant Byte + Less Significant Byte)
according to this data frame:
        <STX  MSB-X  LSB-X  MSB-Y  LSB-Y  ETX>


This is the relevant Android (Java) code snippet from Joystick Bluetooth Commander:
Code: [Select]

    final int XvalB = Xval + 200;
    final int YvalB = Yval + 200;
    if((((Xant!=Xval) || (Yant!=Yval)) || (mTimeoutCounter>=mMaxTimeoutCount && mMaxTimeoutCount>-1)))   // joystick position changed, or timeout occurred
    sendMessage( new String(new byte[] {STX, (byte) (XvalB / 128), (byte)(XvalB % 128), (byte)(YvalB / 128), (byte)(YvalB % 128), ETX } ));


So, for Xval=0 Yval=0:
 XvalB = YvalB = 200
 XvalB / 128 = YvalB / 128 = 1
 XvalB % 128 = XvalB % 128 = 72
Data frame:   <2  1  72  1  72  3>

for Xval=100 Yval=100:
 XvalB = YvalB = 300
 XvalB / 128 = YvalB / 128 = 2
 XvalB % 128 = XvalB % 128 = 44
Data frame:   <2  2  44  2  44  3>

The data frame is send via BlueTooth to the arduino board and decoded.
This is the Arduino code snippet from Joystick Bluetooth Commander:
Code: [Select]

 int joyX = (data[1]<<7) + data[2];
 int joyY = (data[3]<<7) + data[4];
 joyX = joyX - 200;               // Offset to avoid
 joyY = joyY - 200;               // transmitting negative numbers


Voilà    :)
Should you have additional questions, let me know

EDIT:
The 6 button, 4 data field App and the video App both have a slightly different protocol
(STX & ETX values are different)
Title: Re: Android Bluetooth joystick
Post by: wildatheart on Mar 08, 2014, 04:41 pm
Thx for the explanation.  Got it. 

Joystick BT Commander is working perfectly with the LG G2 phone, the Adafruit  EZ-link 315a bluetooth, and the Parallax Quickstart demo board.

Not sure what "Data XXX" is used for.  Is there any chance the MCU can send and display a serial message in your APP?  The joystick image is displayed a little above center but that's okay - it leaves room below (in line with the displayed x,y position) for a possible sent message.

Title: Re: Android Bluetooth joystick
Post by: kas on Mar 10, 2014, 11:14 am
Quote
Joystick BT Commander is working perfectly with the LG G2 phone, the Adafruit  EZ-link 315a bluetooth, and the Parallax Quickstart demo board.
Nice to hear, I started learning microcontrollers with Basic Stamps  :)
http://forums.parallax.com/showthread.php/103850-Yet-another-balancing-robot?daysprune=-1 (http://forums.parallax.com/showthread.php/103850-Yet-another-balancing-robot?daysprune=-1)

Quote
Not sure what "Data XXX" is used for.  Is there any chance the MCU can send and display a serial message in your APP?
YES !!!      see reply #74
Joystick BT Commander listens to the MCU and expect a 4 Byte data frame
            <STX    button status Byte    data Byte (your choice)    ETX>

This is the relevant code snippet in the Arduino demo sketch (V10.3):
Code: [Select]
 mySerial.write(STX); mySerial.write((button<<2)+4); mySerial.write(data+4); mySerial.write(ETX); // +4: avoid 0x2 & 0x3


There is another version with 4 data bytes and 6 buttons
(http://i.imgur.com/rUzjW6r.jpg)
For those interested, contact me via PM


Quote
The joystick image is displayed a little above center but that's okay

I need that type of feedback, please let me have a screen shot of the App on your LG G2 phone


Title: Re: Android Bluetooth joystick
Post by: wildatheart on Mar 12, 2014, 05:53 am
Kas, this is a screenshot of the LG G2.  The vertical location of the joystick is not a problem but it is a bit above center.

If I could submit a longer text string to the App in the "data" area the current location of the stick would be okay.  But my current problem is... I cannot successfully send serial data from my Quickstart to Joystick.  I guessing the problem is because the Quickstart seems only accept correct data with rx set at  9600, so I can only tx at 9600 too.  Any chance the baud rate can be selectable or otherwise changed in the App?

(Your) Nice write-up and interesting project in the Parallax forums.  I intend to submit your App (with due credit) along with my work to the forums in the near future.
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 13, 2014, 12:27 pm
Quote
If I could submit a longer text string to the App in the "data" area the current location of the stick would be okay

The data field can display a positive signed Byte (0 to 127), not a text string

Quote
I guessing the problem is because the Quickstart seems only accept correct data with rx set at  9600, so I can only tx at 9600 too.  Any chance the baud rate can be selectable or otherwise changed in the App?

There isn't any Baud rate value within Joystick BT Commander code
The Baud rate setting is only for communication between BT card and microcontroller, _NOT_ between Android device and BT card
Try sending   2  4  14  3
the Data field should display 14-4=10, while keeping all buttons to the OFF position

Quote
I intend to submit your App (with due credit) along with my work to the forums in the near future.

What is your current project ??
Please give my regards to my friends from the Alternate Univers (Parallax)  ;)
and post a link here when done
Title: Re: Android Bluetooth joystick
Post by: juycce on Mar 13, 2014, 06:19 pm
Great job KAS , i test again and you was right,your app works great with Android 2.3.5,and the HC-06 also compatible (bad thing is i don't recive any data,i can only send) :D:D    so...
Based on your replay at post #146 i am trying to modify the arduino code with your permision,so that on vertical move a DC Motor, and the orizontal a Servo (for steering)...
the joyY control Vertical joystick movement    ,and "joyX" the horizontal right ?
I will post the code as soon i will get it work ... Thank you ,Congratulations again for the app,Karma up ;)

Title: Re: Android Bluetooth joystick
Post by: wildatheart on Mar 14, 2014, 06:10 am
Along with all others, again.. GREAT APP!  Nice layout.  Easy to use.  And all functions work as designed.  Can even send data now.

I don't expect you to modify anything, but just a couple of observations...

1.  The condition is rare and does not seem to correlate with any certain circumstance, but it has happened that the yellow stick will lock itself in a position other than "center",  usually about the 10 o'clock or the 5 o'clock location.  It seems to lock position at about 1/3 the distance from center to the outer ring.  I've seen it happen 3 or 4 times in testing.

2.  It would be nice if your APP could receive and display a text message.  ie "X axis is clear", "Pump 3 flow rate set to  40%", "Press B1 to launch"  etc.

3.  I am experimenting with a continuous rotation servo.  I may be able to correct this in my own software but as it is - when the stick is released 3 or 4 readings are sent before the stick settles into the center position.  The affect of this is the lack of ability to stop the servo rotation at a precise point.  I've tried several different refresh interval and timeout count settings but it does not seem to help.  You'd know best, but perhaps the remedy lies in my own Propeller code.  The other option would be - upon stick release --> automatic center (100,100) without the intermediate readings.

The above are just observations - no big deal.  Joystick  is a GREAT educational opportunity to learn about Bluetooth control and most will find a way to incorporate it in their projects as is.  Thanks for sharing your work.

Title: Re: Android Bluetooth joystick
Post by: kas on Mar 14, 2014, 10:15 am
@juycce
Quote
Great job KAS , i test again and you was right,your app works great with Android 2.3.5,and the HC-06 also compatible (bad thing is i don't receive any data,i can only send) smiley-grin:D    so...

You mean data from Arduino to Smartphone ??
Provided the connection is established, it should work  :smiley-roll:
You may have to drop SoftSerial communication if you still use it
Please post your current Arduino sketch

Quote
Based on your replay at post #146 i am trying to modify the arduino code with your permision, so that on vertical move a DC Motor, and the orizontal a Servo (for steering)...
the joyY control Vertical joystick movement, and "joyX" the horizontal right ?

Right


@wildatheart
Quote
Along with all others, again.. GREAT APP!  Nice layout.  Easy to use.  And all functions work as designed.  Can even send data now.

Glad it works, thanks for the comments  :)

Quote
it has happened that the yellow stick will lock itself in a position other than "center",  usually about the 10 o'clock or the 5 o'clock location.  It seems to lock position at about 1/3 the distance from center to the outer ring.  I've seen it happen 3 or 4 times in testing.

I tried and couldn't reproduce this "feature"
What is your App version ?? (Option > About...)
When the freezing occurs,
- is the BT connection established
- what is the displayed joystick position

Quote
It would be nice if your APP could receive and display a text message.  ie "X axis is clear", "Pump 3 flow rate set to  40%", "Press B1 to launch"  etc.

I will think about it  ;)

Quote
I am experimenting with a continuous rotation servo.  I may be able to correct this in my own software but as it is - when the stick is released 3 or 4 readings are sent before the stick settles into the center position.  The affect of this is the lack of ability to stop the servo rotation at a precise point.

I understand the point
I may be wrong, but a joystick is not supposed to work that way
For my pan/tilt servo device, I just uncheck Auto return to center (Option > Joystick behavior)
I get a precise positioning, no need to return to center
Am I missing something ??

Quote
Joystick  is a GREAT educational opportunity to learn about Bluetooth control and most will find a way to incorporate it in their projects as is.  Thanks for sharing your work

Thanks, comments appreciated  :)


Still working on my new toy (see reply #152)
For the moment, I am busy tuning my PID motors (more info (http://forum.arduino.cc/index.php/topic,8652.0.html)), while monitoring battery level (8.2V)
I just toggle buttons Up or Down; the actual values are displayed in the data fields.
(http://i.imgur.com/ei7hs5n.jpg)
Title: Re: Android Bluetooth joystick
Post by: wildatheart on Mar 16, 2014, 07:50 am
Kas, thanks for giving thought to the possibility of 'text'.

Started a thread in the Parallax forum using your App and the Propeller Quickstart board as a quick and dirty demo.  We've been doing a lot with C over there and the timing of this is just right to generate added interest.  [font=Verdana]Feel free to join us.[/  I think there'd be great interest in a brief tutorial on writing Android Apps too.

http://forums.parallax.com/showthread.php/154687-EZ-Bluetooth-in-***C***-and-a-nice-App

If the asterisks mess with the link, copy and paste the entire line.  I think its okay if you just click it.
Title: Re: Android Bluetooth joystick
Post by: nemesis159 on Mar 16, 2014, 06:06 pm
hi kas, you could upload the apk with 6 buttons and 4 data  XD XD XD XD(http://i.imgur.com/rUzjW6r.jpg)
Title: Re: Android Bluetooth joystick
Post by: juycce on Mar 16, 2014, 09:05 pm
this is the code i have modified a little so i can control the speed (on Vertical) of a continuous servo ,and the normal servo on horizontal .... in case someone need it ;)  :

Code: [Select]


// Andro_Pan&Tilt      V3.1
// Arduino demo sketch for Joystick BT commander V3.X
// Controls two servo motors

// V3.0: Android BT Commander V3.X compatible, no button data management
// V2.5 can receive both Byte & Integer data
// V2.0: removed SoftwareSerial

// Android BT Commander settings:
// Options/Options for advanced users/Data Range        >>>  -180 to +180
// Options/Options for advanced users/Refresh interval  >>>  25ms

//  Arduino pin #0 to TX BlueTooth module
// BT TX to be disconnected from D0 during sketch upload

#include <Servo.h>

boolean    DEBUG = false;

#define    pinServo_X     9
#define    pinServo_Y     10        //continuous servo
#define    STX            0x02
#define    ETX            0x03
#define    MAX_Y          2000      // max servo speed limit       
#define    ZERO_Y         1500      // middle servo point
#define    MIN_Y          1000      // min servo speed limit
#define    ledPin1        13
#define    ledPin2        12

int i=0;
byte cmd[6] = {0, 0, 0, 0, 0, 0};
Servo myservoX;                       // create servo object
Servo myservoY;
byte buttonStatus = 0;                // first Byte sent to Android device
byte dataByte = 0;                    // second Byte sent to Android device
long previousMillis = 0;              // will store last time Buttons status was updated
boolean setButtonFeedback = false;    // momentary buttons feedback to Android device
long interval = 1000;                 // interval between Buttons status transmission (milliseconds)


void setup()  {
  Serial.begin(9600);
  myservoX.attach(pinServo_X); 
  myservoY.attach(pinServo_Y); 
  pinMode(ledPin1, OUTPUT);     
  pinMode(ledPin2, OUTPUT);   
  if(DEBUG)  Serial.println("Stepper demo for Android BT Commander V3.X");
}

void loop() {
  if(Serial.available())  {                   // data received from smartphone
    delay(5);
    cmd[0] =  Serial.read(); 
    if(cmd[0] == STX)  { 
      i=1;     
      while(Serial.available())  {
        cmd[i] = Serial.read();
        if(cmd[i] == ETX)  {
          if(i==2 && cmd[1]>48)                break;    // Button data
          if(i==5 && cmd[1]<3 && cmd[3]<3)     break;    // Joystick data
        }
        if(i>5)   break;
        i++;
      }
      if     (i==2)   getButtonState(cmd[1]);             // 3 Bytes
      else if(i==5)   setServoPosition(cmd);                                     // 5 Bytes
      else            Serial.println("Communication error");
    }
  }  else  {
    long currentMillis = millis();
    if(setButtonFeedback == true)  {                      // allow momentary button visual effect (500 ms)
      previousMillis = currentMillis - interval*0.5;   
      setButtonFeedback = false;
    } 
  }
  delay(5);
}

void setServoPosition(byte data[5])    {
  int joyX = (data[1]<<7) + data[2];
  int joyY = (data[3]<<7) + data[4];
  joyX = joyX - 200;                     
  joyY = joyY - 200;                       
 
  joyX = map(joyX, -180, 180, 180, 0);      // (-180/+180 JBC range)
  joyY = map(joyY,  0, 423, 0, 1023);       // vertical continuous servo value

  joyY+=ZERO_Y;
  joyY = constrain(joyY, MIN_Y, MAX_Y);
  myservoX.write(joyX);
  myservoY.write(joyY);
  if(DEBUG)  {
  Serial.print(joyX); Serial.print(", ");Serial.println(joyY);}
}

void getButtonState(int bStatus)  {
  switch (bStatus) {
    case '1':
      buttonStatus |= B0001;        // Button_1: ON
      Serial.println("Button_1: ON");
      digitalWrite(ledPin1, HIGH);   // LED 1 "ON"
      break;
    case '2':
      buttonStatus &= B1110;        // Button_1: OFF
      Serial.println("Button_1: OFF");
      // your code...     
      digitalWrite(ledPin1, LOW);    // LED 1 "OFF"
      break;
     
    case '3':
      buttonStatus |= B0010;        // Button_2: ON
      DEBUG = true;
      digitalWrite(ledPin2, HIGH);   // LED 2 "ON"   
      break;
     
    case '4':
      buttonStatus &= B1101;        // Button_2: OFF
      DEBUG = false;
      Serial.println("Button_2: OFF");
      digitalWrite(ledPin2, LOW);     
      break;
  }
}

... now i am working on the hard part...control a DC motor on the vertical axis with the TB6612FNG with the PWM
                                          i will need some help
Title: ** Joystick BT Plus V1.0 **
Post by: kas on Mar 17, 2014, 07:38 am
Quote
hi kas, you could upload the apk with 6 buttons and 4 data   XD XD XD XD


Sorry nemesis159, I missed your recent PM  :smiley-red:

The 6 buttons, 4 data bytes App is now released as Joystick BT Plus
The actual number of buttons and data fields is adjustable within the Option menu
Fields and buttons labels are fully customizable

(http://i.imgur.com/ei7hs5n.jpg)

Road map:
Next revision will include an option to perform control using the android device built-in accelerometers
Control will be performed by tilting the smartphone/tablet  8)
Within this option, joystick will be "read only", reflecting the device inclination.

Please send me your email via PM

EDIT:  now renamed as Joystick bluetooth Commander V4.0, available for free on Google Play


Title: Re: Android Bluetooth joystick
Post by: nemesis159 on Mar 17, 2014, 03:14 pm
Hi, i send you one MP, and thanks for sharing your excellent work  XD XD XD XD
Title: Re: Android Bluetooth joystick
Post by: nemesis159 on Mar 19, 2014, 08:38 pm
Hi people, i need help  :smiley-roll-blue:, I'm trying to use this sketch to send rpm data from arduino to this application, but do not understand how data is sent  :smiley-roll-blue: :smiley-roll-blue:, if I could explain how it works this is the part would greatly appreciate (explanation to children xD)  XD XD XD XD XD XD

byte GetdataByte()  {             
  static byte i=0;
  i +=5;
  if(i >100)    i = 0;
  return i;
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 20, 2014, 08:06 am
Quote
I'm trying to use this sketch to send rpm data from arduino to this application, but do not understand how data is sent   :smiley-roll-blue: :smiley-roll-blue:


Will you use Joystick bluetooth Commander/4 button version, or Joystick BT Plus/6 button version ??
(different communication protocols)

How do you obtain RPM data ??  via encoder(s) ??
Did you allready build the code for RPM data aquisition ??

How is the new layout I sent you for Joystick BT Plus ?
Please post a screen shot
Title: Re: Android Bluetooth joystick
Post by: nemesis159 on Mar 20, 2014, 03:01 pm
hi, i use basically this code for rpm http://playground.arduino.cc/Learning/Tachometer#.Uyr2Qfl5NAJ

my firs intent to send data is in 4 butons and 1 data, but now i trying in 6butons 4 data
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 21, 2014, 07:19 am
Quote
I'm trying to use this sketch to send rpm data from arduino to this application, but do not understand how data is sent    :smiley-roll-blue: :smiley-roll-blue:


Data has to be sent as a positive Byte (0 to 127)
You need to scale RPM value in order to stay within this interval
If your RPM range is 0 to 12000:
Code: [Select]
byte GetdataByte()  {
 double data = rpm / 100;
 data = constain(data, 0, 127);            
 return byte(data);
}


To overcome this 127 steps limited resolution, I will switch from byte to integer in next Joystick BT Plus version
Title: Re: Android Bluetooth joystick
Post by: nemesis159 on Mar 21, 2014, 03:57 pm
XD XD thanks, now i understand,  it was not as complicated as it seems, very grateful for the help
Title: Re: Android Bluetooth joystick
Post by: juycce on Mar 21, 2014, 09:00 pm
Can anyone give me a hand with some errors i have ...
I am trying to run the TB6612FNG on the vertical and a Servo on Horizontal ...so far the code only moves the motor only when you keep moving a little the joystick (i mean if u stay still with the finger on maximum speed i have no movement) :

Code: [Select]


#include <Servo.h>

boolean    DEBUG = true;

#define    pinServo_X     9
#define    PWM_Y          3
#define    STX            0x02
#define    ETX            0x03

#define    MAX_Y          255      // PWM limit
#define    ZERO_Y         0         
#define    MIN_Y          -255       

#define AIN1  4   
#define AIN2  5   // AIN1 and AIN2 as Direction pins
#define STBY  7   // StandBy

int i=0;
byte cmd[6] = {0, 0, 0, 0, 0, 0};
Servo myservoX;                     
Servo myY;                 // ???? it is not a servo
byte buttonStatus = 0;             
byte dataByte = 0;                   
long previousMillis = 0;           
boolean setButtonFeedback = false;   
long interval = 1000;                 


void setup()  {
  Serial.begin(9600);
  myservoX.attach(pinServo_X); 
  myY.attach(PWM_Y);   

pinMode(AIN1,OUTPUT);
pinMode(AIN2,OUTPUT);
pinMode(PWM_Y,OUTPUT);
pinMode(STBY,OUTPUT);
 
}

void loop() {
  if(Serial.available())  {                   // data received from smartphone
    delay(5);
    cmd[0] =  Serial.read(); 
    if(cmd[0] == STX)  { 
      i=1;     
      while(Serial.available())  {
        cmd[i] = Serial.read();
        if(cmd[i] == ETX)  {
          if(i==2 && cmd[1]>48)                break;    // Button data
          if(i==5 && cmd[1]<3 && cmd[3]<3)     break;    // Joystick data
        }
        if(i>5)   break;
        i++;
      }
        if(i==5)   setServoPosition(cmd);                                     // 5 Bytes
      else            Serial.println("Communication error");
    }
  }  else  {
    long currentMillis = millis();
    if(setButtonFeedback == true)  {                      // allow momentary button visual effect (500 ms)
      previousMillis = currentMillis - interval*0.5;   
      setButtonFeedback = false;
    } 
  }
  delay(5);
}

void setServoPosition(byte data[5])    {
  int joyX = (data[1]<<7) + data[2];
  int joyY = (data[3]<<7) + data[4];
  joyX = joyX - 200;                         // Offset to avoid
  joyY = joyY - 200;                         // transmitting negative numbers
 
  joyX = map(joyX, -180, 180, 180, 0);      // (-180/+180 JBC range)
  joyY = map(joyY,  -100, +100, -255, 255);

  joyY+=ZERO_Y;
  joyY = constrain(joyY, MIN_Y, MAX_Y);
  myservoX.write(joyX);
  myY.write(joyY);
  digitalWrite(STBY, HIGH); //disable standby
  if(DEBUG)  {
  //Serial.print(joyX); Serial.print(", ");
  Serial.println(joyY);}


  if(joyY > 0) {
      digitalWrite (AIN1,HIGH);
      digitalWrite (AIN2,LOW);
  } else if(joyY < 0)  {
      digitalWrite (AIN1,LOW);
      digitalWrite (AIN2,HIGH);
  } else if(joyY = 0)  {
      digitalWrite(STBY, LOW); //enable standby

  analogWrite(PWM_Y,joyY);
}
}



I know that i shouldn't use servo library for the Vertical Axis (DC Motor) ....but i don't know how to do it ,i tried to change it with PWM but i got errors...also motor kepp making noise (without moving) when joystick is in the middle posicion
On Serial Monitor i get the right values  :  255 when joystick full up   ----  0 in the middle ---- and -255 when is down
I apreciate your help,thank you,i hope to get this work ;)
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 22, 2014, 07:40 am
Yes,  using servo library with DC Motor makes no sense :smiley-roll:

Standby is enabled and never driven high again
Code: [Select]
  } else if(joyY = 0)  {
      digitalWrite(STBY, LOW); //enable standby


Classical error  ;)
Code: [Select]
} else if(joyY = 0)  {        // assignment operator, always TRUE !! 
should really be
Code: [Select]
} else if(joyY == 0)  {         // comparison operator, the way to go

Sample code for DC motors here (http://forum.arduino.cc/index.php?topic=173246.msg1588264#msg1588264)
Take the easy way, build separate codes for DC motor and servo, make sure they both work, and finally combine them

@nemesis159
How is the new layout I sent you for Joystick BT Plus ?
Please post a screen shot
Title: Re: Android Bluetooth joystick
Post by: juycce on Mar 22, 2014, 12:24 pm
You was right about this ...i just change it
Code: [Select]

} else if(joyY == 0)  {         // comparison operator, the way to go

...as for the Stanby  it   is  enabled again :
Code: [Select]

 myY.write(joyY);
 digitalWrite(STBY, HIGH); //disable standby   <----


Made some small modification and works (but not how it should) : it only have one speed fwd and backword (very very slow :((  ) in the middle get in Standby but it have no speed .On Serial monitor it goes from -255   0  255 ...and i test the motor and it works,
What am i doing rong? I just don't get it,I don't wanna give up this project...shoud i open a new topic and ask for some advice ?
Thank you KAS

Title: Re: Android Bluetooth joystick
Post by: kas on Mar 23, 2014, 09:25 am
juycce,

There are other glitches in your code

Code: [Select]
joyX = map(joyX, -180, 180, 180, 0); 
joyY = map(joyY,  -100, +100, -255, 255);


Second and third parameters should match App Option > Adv properties > Data Range
and should be identical for both joyX and joyY

Did you test the code example at reply #146 ?

For additional help, the Motors Mechanics and Power section seems adequate

Keep us informed  :)
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 31, 2014, 07:47 am
@tolisn63
Quote

I just tried out the new sketch. It is working great. All button now work as well as the data fields.
Also the camera has very little lag (<0.5sec) after  I switched it to a lower res. (320x240) which is absolutely usable.

Thanks for the good new  8) 8) 8)

Quote
1. Is it possible to change the orientation of the settings screen so it is the same as the main control screen ?
2.Also it would be nice if the data receiving fields could also accept incoming text.

Will look into that matter  ;)

Quote
one question, when the buttons are pressed and the color becomes green, does the tablet do that or is it feedback from the arduino ?

This is the real button position
- button first becomes green "locally" as an Android feature
- position is then sent to Arduino
- Arduino sends back the actual button position
See replies #36 and #73

A good example is toggle (momentary) buttons
Button is set green by Android and reset white by Arduino  after 250 milliseconds, to create a visual effect.

Quote
thanks for all your hard work.
Looking forward to trying your newest version.

:)
Title: ** Total RC Commander V1.1A **
Post by: kas on Apr 03, 2014, 06:22 pm
Quote
@tolisn63

Quote
1. Is it possible to change the orientation of the settings screen so it is the same as the main control screen ?
2.Also it would be nice if the data receiving fields could also accept incoming text.

Will look into that matter  ;)


You got it ;) ;) ;)
check your mail

Total RC Commander V1.1A
- Data fields now accept integers, floats and text messages
- Improved video management
- adjustable Option screen orientation

(http://i.imgur.com/LRW6h8p.jpg)

Important:
To allow text messages, Arduino to Android communication protocol has been modified
Please use and adapt "AndroTest_PlusV12_string.ino" demo sketch

Let me have your feedback and a screenshot for your specific Android device

@all
Joystick BT Plus (6 buttons, 3 datafields)
and
Total RC Commander (video from IP camera)
will be available on Google Play within a month for a symbolic fee

In the meantime, please contact me via PM

Next version: remote control using built-in accelerometers (see reply #165)  :P

Enjoy


EDIT:  Joystick BT Plus is now Joystick bluetooth Commander V4.0
available on Google Play as a free upgrade
See reply #181

Title: Total RC Commander demo video
Post by: kas on Apr 30, 2014, 03:19 pm
I just posted a video showing tank control using Total RC Commander.

(http://i.imgur.com/Ea7lXGt.png)

See it in action in the Exhibition Section  (http://forum.arduino.cc/index.php?topic=236401.msg1699561#msg1699561)

To obtain the App, please contact me via PM

Title: Re: Android Bluetooth joystick
Post by: kas on May 06, 2014, 08:56 pm
Quote
Hi Kas
Thanks for the reply
Can I use hardware serial with this on my mega2560 (it has 4 hardware serial ports) and how ?


Hi tolisn63
Not too familiar with the Mega  :|

- remove   #include "SoftwareSerial.h"
- remove   SoftwareSerial mySerial(2,3);
- search/replace  mySerial  >> Serial1

pin#19  to TX bluetooth module
pin#18  to RX bluetooth module

You should be all set  ;)
Let me know the outcome
Title: Re: Android Bluetooth joystick
Post by: tolisn63 on May 08, 2014, 06:15 am
Hi Kas

Thanks for the information. It work great as you suggested.
Title: Joystick bluetooth Commander V4.0 ** major Upgrade **
Post by: kas on May 09, 2014, 11:42 am
Joystick BT Plus (up to 6 buttons, up to 3 free format datafields) is now
                    - Joystick bluetooth Commander V4.0 -
and will be available on Google Play as a free upgrade.

(http://i.imgur.com/RVv40O3.jpg)
RC car remote control


(http://i.imgur.com/iGLSDEt.jpg)
here, Joystick bluetooth Commander is configured as a tool for remotely tuning a PID loop in various projects (DC motor control, balancing bot, Gyro stabilized camera gimbal ...)
For this purpose, buttons are configured as "momentary"


To allow text datafield, Communication Protocol has changed
Please use and adapt this new demo sketch (AndroTest_V13.ino) to your own needs

Code: [Select]

#define VERSION     "AndroTest V1.3 - @kas2014\ndemo for V4.X  (6 button version)"


// V1.3  renamed for publishing
// V1.2  Text display   ** not backward compatible **
// V1.1  Integer display
// V1.0  6 buttons + 4 data char implemented

// Demo setup:
// Button #1 controls pin13 LED
// Button #2 starts DEBUG
// Button #3 displays demo message
// Button #4 toggle datafield display rate
// Button #5 configured as "push" button (momentary)

// Arduino pin#2 to TX BlueTooth module
// Arduino pin#3 to RX BlueTooth module
// make sure your BT board is set @57600 bps
// better remove SoftSerial for PWM based projects

// For Mega 2560:
// remove   #include "SoftwareSerial.h", SoftwareSerial mySerial(2,3);
// search/replace  mySerial  >> Serial1
// pin#18 to RX bluetooth module, pin#19 to TX bluetooth module

#include "SoftwareSerial.h"

#define    STX          0x01
#define    ETX          0x00
#define    ledPin       13
#define    SLOW         1000                           // Datafields refresh rate (ms)
#define    FAST         250                            // Datafields refresh rate (ms)

boolean DEBUG = false;

** The message exceeds the maximum allowed length (9500 characters)  **
See my next message


App will be uploaded within a few hours


As of today, Joystick bluetooth Commander has been downloaded 3720 times   :) :) :)
thanks for your ongoing interest

Title: Joystick bluetooth Commander V4.0 (continued)
Post by: kas on May 09, 2014, 08:26 pm

** deprecated, please use AndroTest V1.41 **                              see reply #212

AndroTest V1.3.ino
Demo sketch for Joystick bluetooth Commander V4.X

Code: [Select]
#define VERSION     "AndroTest V1.3 - @kas2014\ndemo for V4.X  (6 button version)"

// V1.3  renamed for publishing
// V1.2  Text display   not backward compatible
// V1.1  Integer display
// V1.0  6 buttons + 4 data char implemented

// Demo setup:
// Button #1 controls pin13 LED
// Button #2 starts DEBUG
// Button #3 displays demo message
// Button #4 toggle datafield display rate
// Button #5 configured as "push" button (momentary)

// Arduino pin#2 to TX BlueTooth module
// Arduino pin#3 to RX BlueTooth module
// make sure your BT board is set @57600 bps
// better remove SoftSerial for PWM based projects

// For Mega 2560:
// remove   #include "SoftwareSerial.h", SoftwareSerial mySerial(2,3);
// search/replace  mySerial  >> Serial1
// pin#18 to RX bluetooth module, pin#19 to TX bluetooth module

#include "SoftwareSerial.h"

#define    STX          0x01
#define    ETX          0x00
#define    ledPin       13
#define    SLOW         1000                         // Datafields refresh rate (ms)
#define    FAST         250                          // Datafields refresh rate (ms)

boolean DEBUG = false;

SoftwareSerial mySerial(2,3);                         // BlueTooth module: pin#2=TX pin#3=RX
int i=0;
byte cmd[6] = {0, 0, 0, 0, 0, 0};                     // bytes received
byte buttonStatus = 0;                                // first Byte sent to Android device
long previousMillis = 0;                              // last time Buttons status was updated
boolean setButtonFeedback = false;                    // momentary buttons feedback to Android device
long sendInterval = SLOW;                             // interval between Buttons status transmission (milliseconds)
String displayStatus = "xxxx";                        // message to Android device

void setup()  {
 Serial.begin(57600);
 mySerial.begin(57600);                              // adjust to your BT board
 pinMode(ledPin, OUTPUT);    
 Serial.println(VERSION);
 delay(300);
}

void loop() {
 if(mySerial.available())  {                          // data received from smartphone
   delay(5);
   cmd[0] =  mySerial.read();  
   if(cmd[0] == STX)  {  
     i=1;      
     while(mySerial.available())  {
       cmd[i] = mySerial.read();
       if(cmd[i] == ETX)  {
         if(i==2 && cmd[1]>48)                    break;    // Button data
         if(i==5 && cmd[1]<3 && cmd[3]<3)         break;    // Joystick data
       }
       if(i>5)   break;
       i++;
     }
     if     (i==2)   getButtonState(cmd[1]);            // 3 Bytes
     else if(i==5)   getJoystickState(cmd);             // 6 Bytes
     else            Serial.println("**  Communication error **");
     if(DEBUG)       printDebug(i);
   }
 }  else  
     sendBlueToothData();  
 delay(5);
}

void sendBlueToothData()  {
 static long previousMillis = 0;                            
 long currentMillis = millis();
 if(setButtonFeedback == true)  {                      // allow momentary button visual effect
   previousMillis = currentMillis + 250;  
//  previousMillis = currentMillis - 200;  
   setButtonFeedback = false;
 }
 if(currentMillis - previousMillis > sendInterval) {   // send data to smartphone
   previousMillis = currentMillis;

// Data frame transmitted back from Arduino to Android device:
// < 0X02   Buttons state   0X01   DataField#1   0x04   DataField#2   0x05   DataField#3    0x03 >  
// < 0X02       01011       0X01      120.00     0x04      -4500      0x05   Motor enabled  0x03 >    // example

   mySerial.print((char)0x2);                                             // Start of Transmission
   mySerial.print(getButtonStatusString());  mySerial.print((char)0x1);   // buttons status feedback
   mySerial.print(GetdataInt1());            mySerial.print((char)0x4);   // datafield #1
   mySerial.print(GetdataFloat2());          mySerial.print((char)0x5);   // datafield #2
   mySerial.print(displayStatus);                                         // datafield #3
   mySerial.print((char)0x3);                                             // End of Transmission
 }  
}

String getButtonStatusString()  {
 String bStatus = "";
 for(i=0; i<6; i++)  {
   if(buttonStatus & B100000 >>i)      bStatus += "1";
   else                                bStatus += "0";
 }
 return bStatus;
}

int GetdataInt1()  {             // Data dummy values sent to Android device for demo purpose
 static int i= -3000;           // Replace with your own code
 i += 111;
 if(i >0)    i = -3000;
 return i;  
}

float GetdataFloat2()  {           // Data dummy values sent to Android device for demo purpose
 static float i=50;               // Replace with your own code
 i-=.8;
 if(i <-50)    i = 50;
 return i;  
}

void getJoystickState(byte data[5])    {
 int joyX = (data[1]<<7) + data[2];
 int joyY = (data[3]<<7) + data[4];
 joyX = joyX - 200;              // Offset to avoid
 joyY = joyY - 200;              // transmitting negative numbers
 
 if(!DEBUG)  {
   Serial.print("Joystick position:  ");
   Serial.print(joyX);  
   Serial.print(", ");  
   Serial.println(joyY);
 }
// Your code here ...
}

void getButtonState(int bStatus)  {
 switch (bStatus) {
// -----------------  BUTTON #1  -----------------------
   case '1':
     buttonStatus |= B000001;        // ON
     Serial.println("\n** Button_1: ON **");
     // your code...      
     displayStatus = "LED <ON>";
     Serial.println(displayStatus);
     digitalWrite(ledPin, HIGH);
     break;
   case '2':
     buttonStatus &= B111110;        // OFF
     Serial.println("\n** Button_1: OFF **");
     // your code...      
     displayStatus = "LED <OFF>";
     Serial.println(displayStatus);
     digitalWrite(ledPin, LOW);
     break;

// -----------------  BUTTON #2  -----------------------
   case '3':
     buttonStatus |= B000010;        // ON
     Serial.println("\n** Button_2: ON **");
     // your code...      
     displayStatus = "DEBUG <ON>";
     Serial.println(displayStatus);
     DEBUG = true;
     break;
   case '4':
     buttonStatus &= B111101;        // OFF
     Serial.println("\n** Button_2: OFF **");
     // your code...      
     displayStatus = "DEBUG <OFF>";
     Serial.println(displayStatus);
     DEBUG = false;
     break;

// -----------------  BUTTON #3  -----------------------
   case '5':
     buttonStatus |= B000100;        // ON
     setButtonFeedback = true;
     Serial.println("\n** Button_3: ON **");
     // your code...      
     displayStatus = "Motor #1 enabled"; // Demo text message
     Serial.println(displayStatus);
     break;
   case '6':
     buttonStatus &= B111011;      // OFF
     Serial.println("\n** Button_3: OFF **");
     // your code...      
     displayStatus = "Motor #1 stopped";
     Serial.println(displayStatus);
     break;

// -----------------  BUTTON #4  -----------------------
   case '7':
     buttonStatus |= B001000;       // ON
     setButtonFeedback = true;
     Serial.println("\n** Button_4: ON **");
     // your code...      
     displayStatus = "Datafield update <FAST>";
     Serial.println(displayStatus);
     sendInterval = FAST;
     break;
   case '8':
     buttonStatus &= B110111;    // OFF
     Serial.println("\n** Button_4: OFF **");
     // your code...      
     displayStatus = "Datafield update <SLOW>";
     Serial.println(displayStatus);
     sendInterval = SLOW;
    break;

// -----------------  BUTTON #5  -----------------------
   case '9':           // configured as momentary button
//      buttonStatus |= B010000;        // ON
     Serial.println("\n** Button_5: ++ pushed ++ **");
     // your code...      
     displayStatus = "Button_5: ++ pushed ++";
     break;
//   case 'A':
//     buttonStatus &= B101111;        // OFF
//     // your code...      
//     break;

// -----------------  BUTTON #6  -----------------------
   case 'B':
     buttonStatus |= B100000;        // ON
     Serial.println("\n** Button_6: ON **");
     // your code...      
      displayStatus = "Button #6 ON"; // Demo text message
    break;
   case 'C':
     buttonStatus &= B011111;        // OFF
     Serial.println("\n** Button_6: OFF **");
     // your code...      
     displayStatus = "Button #6 OFF";
     break;
 }
// ---------------------------------------------------------------
}

void printDebug(int nByte)  {
 if(nByte ==2)    {  
   Serial.print("buttonStatus: "); Serial.print(buttonStatus);
   Serial.print("  bin: "); Serial.println(getButtonStatusString());    
   Serial.print("Button: < ");
 }
 else if(nByte ==5)  Serial.print("Joystick: < ");
 else                Serial.print("*error*: < ");
 for(int j =0; j<nByte+1; j++) { Serial.print(cmd[j]); Serial.print(" "); }
 Serial.println(">");
}


EDIT:   This sketch assumes that your BT card is configured @57600bps
Title: Re: Android Bluetooth joystick
Post by: hulkpeppe on May 11, 2014, 12:42 am
I have just tried the version 4 of joystick BT controller, but don't get any response in the serial monitor with sketch AndroTest V1.3.ino.
What does Arduino pin #2 and #3 means? I used the same setting as for joystick BT controller v3.1 but it doesn't work. Any ideas what to do?
Title: Re: Android Bluetooth joystick
Post by: kas on May 11, 2014, 09:54 am
Hi hulkpeppe, welcome to the Forum as a new contributor

Quote
What does Arduino pin #2 and #3 means?

Digital I/O #2 to be connected to TX pin from Bluetooth module
Digital I/O #3 to be connected to RX pin from Bluetooth module


Quote
...but it doesn't work. Any ideas what to do?

I need more information to make a clever guess ;)

I understand you are already seasoned with V3.1 and AndroLEDV10_3.ino

Android side (smartphone/tablet screen):
1) go to Option/About and confirm that installed version is V4.0 (or higher)
2) can you move the joystick and display position at bottom left
3) are you connected ("connected to: XXX", green text)

Arduino side:
4) are you using AndroTest V1.3.ino (or higher)
5) are RX/TX connected as per above
6) is your Bluetooth card already configured @57600 bps  (most are 9600bps by default)
7) is your Bluetooth card LED solid red  (blinking red = not connected)
8 ) is your Serial monitor configured @57600 bps

Finally:
9)  your serial monitor should anycase display:
          AndroTest V1.3 - @kas2014
          demo for V4.X  (6 button version)
  does it ??

- any additional information ??

Please advise


@all
Please confirm V4.0 works OK for you




Title: Re: Android Bluetooth joystick
Post by: hulkpeppe on May 11, 2014, 10:42 pm
I'm using Itead BT shield and here are not Arduino pin #2 and #3 routed to BT TX and RX. I made a strap from Arduino pin #2 to BT shield TX and Pin #3 to RX. But still no sucess. :~

Yes, I got the V3.1 and AndroLEDV10_3.ino working with serial monitor and was able to visulize button #1 ON/OFF.

All checkpoints (1-7) in your answer are fulfilled.

In the Androind BT commander I observed some information under Data1 and Data2 (not under Data3). When I push any buttons they only got activated (green) a very short time.
I don't see that LED at Arduino pin#13 got active when pushing button 1.
Title: Re: Android Bluetooth joystick
Post by: kas on May 12, 2014, 01:21 pm
Quote
In the Androind BT commander I observed some information under Data1 and Data2 (not under Data3)

Interesting

IF
- Data1 cycles from -3000 to 0 with 111 increment         (see GetdataInt1)
- Data2 cycles from 50 to -50 with -0.8 increment        (see GetdataFloat2)
- Data3 shows "xxxx"

THEN
Arduino to Android communication is OK
Android to Arduino communication is not wired correctly

Quote
When I push any buttons they only got activated (green) a very short time

Makes sense, Arduino will always feed back its own real buttons position and overwrite the Android display

Assuming you have the "Master/Slave" model (http://imall.iteadstudio.com/im120417010.html):
- make sure the switch is in DAT mode
- place the TX jumper on pin 4 and the RX on Pin 5
- change "SoftwareSerial mySerial(2,3);"  to  "SoftwareSerial mySerial(4,5);"

Should work ;)


Title: Re: Android Bluetooth joystick
Post by: tolisn63 on May 13, 2014, 06:44 am
Hi Kas

Can you please post the communication protocol for  Total RC commander V1.1 ?
The communication from the android device to the arduino and between the arduino and the android device.
Title: Joystick BT Commander V4.x - Communication Protocol -
Post by: kas on May 13, 2014, 05:04 pm
Total RC commander is the "video aware" version of Joystick BT Commander V4.x
They both share the same Communication Protocol with Arduino


Communication from Android to Arduino                   (or to any microcontroller)

- Joystick information:
Joystick data is transmitted as an integer = 2 Bytes (Most Significant Byte + Less Significant Byte)
according to this data frame:
        <0x01  MSB-X  LSB-X  MSB-Y  LSB-Y  0x00>


This is the relevant Android (Java) code snippet from Joystick Bluetooth Commander:
Code: [Select]

    final int XvalB = Xval + 200;
    final int YvalB = Yval + 200;
    if((((Xant!=Xval) || (Yant!=Yval)) || (mTimeoutCounter>=mMaxTimeoutCount && mMaxTimeoutCount>-1)))   // joystick position changed, or timeout occurred
    sendMessage( new String(new byte[] {STX, (byte) (XvalB / 128), (byte)(XvalB % 128), (byte)(YvalB / 128), (byte)(YvalB % 128), ETX } ));


So, for Xval=0 Yval=0:
 XvalB = YvalB = 200
 XvalB / 128 = YvalB / 128 = 1
 XvalB % 128 = XvalB % 128 = 72
Data frame:   <2  1  72  1  72  3>

for Xval=100 Yval=100:
 XvalB = YvalB = 300
 XvalB / 128 = YvalB / 128 = 2
 XvalB % 128 = XvalB % 128 = 44
Data frame:   <2  2  44  2  44  3>

The data frame is send via BlueTooth to the arduino board and decoded.
This is the AndroTest V1.3.ino code snippet:
Code: [Select]

void getJoystickState(byte data[5])    {
 int joyX = (data[1]<<7) + data[2];
 int joyY = (data[3]<<7) + data[4];
 joyX = joyX - 200;               // Offset to avoid
 joyY = joyY - 200;               // transmitting negative numbers
}



- Button information:
Each time an android button is pressed, the following data frame is transmitted
               <0x01, buttonState, 0x00>

buttonState is transmitted as a Byte value and reflects the state of the pushed button
Button #1 ON:  1    Button #1 OFF:  2
Button #2 ON: 3    Button #2 OFF: 4
Button #3  ...

On the Arduino side, data frame is decoded in getButtonState()
Code: [Select]
void getButtonState(int bStatus)  {
 switch (bStatus) {
// -----------------  BUTTON #1  -----------------------
   case '1':
     buttonStatus |= B000001;        // ON
     Serial.println("\n** Button_1: ON **");
     // your code...      
     displayStatus = "LED <ON>";
     Serial.println(displayStatus);
     digitalWrite(ledPin, HIGH);
     break;
   case '2':
     buttonStatus &= B111110;        // OFF
     Serial.println("\n** Button_1: OFF **");
     // your code...      
     displayStatus = "LED <OFF>";
     Serial.println(displayStatus);
     digitalWrite(ledPin, LOW);
     break;

// -----------------  BUTTON #2  -----------------------
   case '3':
     buttonStatus |= B000010;        // ON
     Serial.println("\n** Button_2: ON **");
     // your code...      
     displayStatus = "DEBUG <ON>";
     Serial.println(displayStatus);
     DEBUG = true;
     break;
   case '4':
     buttonStatus &= B111101;        // OFF
     Serial.println("\n** Button_2: OFF **");
     // your code...      
     displayStatus = "DEBUG <OFF>";
     Serial.println(displayStatus);
     DEBUG = false;
     break;

   ....
}



Communication back from Arduino to Android:

Arduino code
Code: [Select]
void sendBlueToothData()  {

 ....

   mySerial.print((char)0x2);                                             // Start of Transmission
   mySerial.print(getButtonStatusString());  mySerial.print((char)0x1);   // buttons status feedback
   mySerial.print(GetdataInt1());            mySerial.print((char)0x4);   // datafield #1
   mySerial.print(GetdataFloat2());          mySerial.print((char)0x5);   // datafield #2
   mySerial.print(displayStatus);                                         // datafield #3
   mySerial.print((char)0x3);                                             // End of Transmission
 
 ....  
}



Data frame transmitted back from Arduino to Android device:  (by default, every 1000ms)
< STX   Buttons state   0X01   DataField#1   0x04   DataField#2   0x05   DataField#3   ETX >  

example: < 0X02    001011    0X01    120.00    0x04   -4500   0x05   Motor enabled   0x03 >

Button state:
This is a six character string reflecting the Arduino state for buttons position
button #1,#2,#4: ON, all others: OFF   >>>  001011
This feedback avoid any discrepancy with the Android device button state
An Arduino Reset will reinitialize the Android buttons, Two way communication is mandatory for "clean" control
Button state string is created in the getButtonStatusString() function.

Code: [Select]
String getButtonStatusString()  {
 String bStatus = "";
 for(i=0; i<6; i++)  {
   if(buttonStatus & B100000 >>i)      bStatus += "1";
   else                                bStatus += "0";
 }
 return bStatus;
}



Datafields:
Data is transmitted as ASCII characters using Serial.print()
Numbers are printed using an ASCII character for each digit
120.00   >>>   0X31, 0X32, 0X30, 0X2E, 0X30, 0X30

So  < 0x02     001011      0x01      120.00     0x04      -4500      0x05     Motor enabled     0x03 >
is actually transmitted as
    < 0x02,   0x30,0x30,0x31,0x30,0x31,0x31,   0X01,   0x31,0x32,0x30,0x2E,0x30,0x30,  
       0x04,  0x2D,0x34,0x35,0x30,0x30,   0x05,   0x4D,0x6F,0x74,0x6F,0x72,0x20,0x65,
       0x6E,0x61,0x62,0x6C,0x65,0x64,  0x03 >

without commas and spaces


Should you have additional questions, let me know  ;)
Title: Re: Android Bluetooth joystick
Post by: Maudey on May 13, 2014, 11:07 pm
Firstly thanks Kas this is a great app/sketch.

I too couldnt get it to work but after some playing around i got this to work with these settings:

// Arduino RX to TX BlueTooth module
// Arduino TX to RX BlueTooth module
// make sure your BT board is set @9600 bps
//Set Serial Monitor rate to 9600 bps

Title: Re: Android Bluetooth joystick
Post by: tolisn63 on May 14, 2014, 05:50 am
Thanks Kas for the protocol information
Title: Re: Android Bluetooth joystick
Post by: kas on May 14, 2014, 07:21 am
@Maudey
Thanks for the feedback
I edited reply #182 based on your comments
Please post an App screenshot, together with your screen size and resolution
This will help me optimizing App display layout

What BT brand are you using ??
Most boards default to 9600bps, which is a bit slow
I strongly suggest to boost your board @57600bps


@tolisn63
Did you try the on board mini router ??
I hardwired connection between IP camera and router and still have to observe any noticiable lag  8)
Title: Re: Android Bluetooth joystick
Post by: tolisn63 on May 15, 2014, 05:54 am
Hi Kas

The mini router did not come in yet. I'm waiting to see how it goes.
Title: Re: Android Bluetooth joystick
Post by: hulkpeppe on May 17, 2014, 08:01 am
Hi kas

Thank's for your help! Now it works fine for me  :)
I really appreciate this app/sketch  :D
Title: Re: Android Bluetooth joystick
Post by: n3kx on May 18, 2014, 03:07 pm
Hi I have a small problem. I didnt get receive any of datafields.
Title: Re: Android Bluetooth joystick
Post by: kas on May 19, 2014, 04:12 pm
Quote
Hi kas
Thanks for your help! Now it works fine for me   :)
I really appreciate this app/sketch    :D

Thanks hulkpeppe for this positive feedback

@n3kx
Quote
Hi I have a small problem. I didn't get receive any of datafields.

I bit more information would definitely help ...
Title: Re: Android Bluetooth joystick
Post by: n3kx on May 22, 2014, 07:55 am
I use your basic sketch and your app, but under datafields in android is only xxxx
Title: Re: Android Bluetooth joystick
Post by: kas on May 23, 2014, 07:20 am
Quote
I use your basic sketch and your app, but under datafields in android is only xxxx

Not a lot of additional info's   ;)

Carefully review those 9 questions and answer YES/NO

Android side (smartphone/tablet screen):
1) go to Option/About and confirm that installed version is V4.0 (or higher)
2) can you move the joystick and display position at bottom left
3) are you connected ("connected to: XXX", green text)

Arduino side:
4) are you using AndroTest V1.3.ino (or higher)
5) are Bluetooth TX connected to D2 and RX connected to D3
6) is your Bluetooth card already configured @57600 bps  (most are 9600bps by default)
7) is your Bluetooth card LED solid red or green  (blinking = not connected)
8 ) is your Serial monitor configured @57600 bps

Finally:
9)  your serial monitor should anycase display:
          AndroTest V1.3 - @kas2014
          demo for V4.X  (6 button version)
  does it ??

- any additional information ??
Title: Re: Android Bluetooth joystick
Post by: Bob1943 on May 23, 2014, 07:23 pm
Hi Kas,
I think your "Joystick bt commander" is brilliant - just what I want for some projects I am looking at.
However, I am having intermittent problems connecting from Android to Arduino via HC-05 module and very rarely get data from Arduino to Android. Is there a correct boot up sequence between Arduino and Anroid or doesn't it matter?
When I changed the baud rate in AT commands I used AT+UART=57600,0,0 - is that correct?
Also I think I may have a mismatch of Wiring diagram/ino code/Android app. Can you email me details of where I can get the latest drawings/codes etc.
Again - brilliant application
Many thanks
Bob
Title: Re: Android Bluetooth joystick
Post by: n3kx on May 23, 2014, 07:26 pm
YES I have 4.0 version
YES I see changing position on bottom left
YES I am conncted

YES I using ArduinoTest V1.3.ino
YES I have Connected Bluetooth in right way
YES I have solid led
YES Is my serial monitor configured @57200 bps

YES My serial monitor display that information
Title: Re: Android Bluetooth joystick
Post by: kas on May 23, 2014, 10:09 pm
Hi Bob1943

Quote
I think your "Joystick bt commander" is brilliant

Thanks  8)

Quote
I am having intermittent problems connecting from Android to Arduino via HC-05 module and very rarely get data from Arduino to Android

Can you be more specific, I would expect the App to always work or always fail... :smiley-roll: :smiley-roll:

Quote
Is there a correct boot up sequence between Arduino and Anroid or doesn't it matter?

No, doesn't matter

Quote
When I changed the baud rate in AT commands I used AT+UART=57600,0,0 - is that correct?

Yes, make sure you have entered the Command mode
I just prepared a sketch for my new HC-05 board.
Will display
- device name
- firmware version
- serial parameters

Code: [Select]
// Iteaduino BT board configurator - BASIC version

// Utility will display actual Baud rate

// TX BT board pin to Arduino D2
// RX BT board pin to Arduino D3
// 5V BT board pin to Arduino 5V
// GND BT board pin to Arduino GND

// set Serial Monitor @57600bps

#include "SoftwareSerial.h"

SoftwareSerial mySerial(2, 3);          // BlueTooth module TX RX
char response[30];                      // responses from module
int rv = 0;                             // return value

void setup()  {
 Serial.begin(57600);
 mySerial.begin(38400);                  //  config mode bps
 mySerial.setTimeout(500);
 delay(300);
 Serial.print("\n\nIteaduino BT board configurator ");
 Serial.print("\nSearching ...");        
 mySerial.write("at\r\n");               // BT card bug ???
 delay(20);
 mySerial.readBytes(response, 15);
 mySerial.write("at\r\n");               // "AT" will respond with "OK" if it is working
 delay(20);
 response[0] = 0;
 rv = mySerial.readBytes(response, 15);
 response[rv] = 0;
 if (strncmp(response, "OK", 2)==0)    Serial.println("\n\nBluetooth Module found");
 else  {
   Serial.println("\nERROR: Bluetooth Module not responding!");
   Serial.println("Make sure there are no active bluetooth connection and try again");
   while(1);
 }
 
 delay(100);
 mySerial.write("at+name?\r\n");               // Check device name
 while(mySerial.available() == 0);
 rv = mySerial.readBytes(response, 30);
 response[rv] = 0;
 if (strncmp(response, "+NAME:", 6)==0)  {
   Serial.print("Name: ");
   Serial.println(response);
 }  else  {  
   Serial.println("Error checking name");
   while(1);
 }

 delay(100);
 mySerial.write("at+version?\r\n");           // Check firmware version
 while(mySerial.available() == 0);
 response[0] = 0;
 rv = mySerial.readBytes(response, 30);
 response[rv] = 0;
 Serial.print("Version: ");
 Serial.println(response);

 delay(100);
 mySerial.write("at+uart?\r\n");           // Check serial parameters
 while(mySerial.available() == 0);
 response[0] = 0;
 rv = mySerial.readBytes(response, 30);
 response[rv] = 0;
 Serial.print("Serial: ");
 Serial.println(response);
}

void loop() { }

Please confirm your BT board baud rate

Quote
Also I think I may have a mismatch of Wiring diagram/ino code/Android app. Can you email me details of where I can get the latest drawings/codes etc.

Bluetooth TX connected to D2 and RX connected to D3
Joystick bluetooth Commander V4.0 is here (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result#?t=W251bGwsMSwxLDEsIm9yZy5wcm9qZWN0cHJvdG8uYnRqb3lzdGljayJd)
AndroTest V1.3.ino is there (http://forum.arduino.cc/index.php?topic=173246.msg1716294#msg1716294)

Please answer the 9 questions as per above



Title: Re: Android Bluetooth joystick
Post by: kas on May 23, 2014, 10:32 pm
@n3kx

Base on your responses, problem is the  BT card  to  Arduino board  serial connection
Is your BT card HC-05 or HC-06 ??
let me have a link to your specific model
You may reverse TX and RX cables just to make sure, this will not harm anything
Did you actuallly check you BT card baud rate ??  they usually default to 9600bps
Have succesfully used this card for other projects ??

Can you see the scrolling Joystick values in the Serial Monitor ??
Title: Re: Android Bluetooth joystick
Post by: n3kx on May 24, 2014, 10:07 am
My model is HC-05 and it work @9600bps. I use your older version and it works, even on version 4.0 it works Arduino receive joystick data as button data no problem. But datafields doesnt change there are always showing XXXX.

I have this type of Bluetooth: http://www.ebay.com/itm/Wireless-Serial-6-Pin-Bluetooth-RF-Transceiver-Module-HC-05-RS232-Master-Slave-D-/400709013564?pt=LH_DefaultDomain_2&hash=item5d4c1e503c (http://www.ebay.com/itm/Wireless-Serial-6-Pin-Bluetooth-RF-Transceiver-Module-HC-05-RS232-Master-Slave-D-/400709013564?pt=LH_DefaultDomain_2&hash=item5d4c1e503c)
Title: Re: Android Bluetooth joystick
Post by: Bob1943 on May 24, 2014, 10:48 am
Hi, thanks for your rapid response. Your assistance in helping is excellent. Hope I have answered your questions so I can get a response from Arduino UNO back to Android

>>>>>>>>I used the AT Command setup at this URL
http://arduinofy.blogspot.co.uk/2013/10/tutorial-programming-hc-05-at-mode-with.html

when completed AT+UART? Returned: 57600,0,0

>>>>>>>>Your sketch headed:
// Iteaduino BT board configurator - BASIC version
Returned the following error message:

    Iteaduino BT board configurator
    Searching ...
    ERROR: Bluetooth Module not responding!
    Make sure there are no active bluetooth connection and try again
I couldn't find anything paired with the HC-05
The red BT LED flashed on/off about every half second

>>>>>>>>Your sketch headed:
AndroTest V1.3 - @kas2014\ndemo for V4.X  (6 button version)
Only Connections:
.Arduino pin#2 to TX BlueTooth module
. Arduino pin#3 to RX BlueTooth module
..Arduino 3.3v to 3.3 BlueTooth module
..Arduino GND to GND
NOTE: Key and 5v not connected

Paired and connected with Android (v4.0.4) OK.
Still only xxx showing bottom left.
Interesting point is that button B5 stays locked the same as other buttons until pressed again to release. (I did notice at one time it did act like a push button - maybe that was when data got fed back). Just a thought
I think the connection problems may be down to me as that problem appears to have gone away.
My only problem now (apart from error in BT board configurator mentioned above) is the failure to get a signal from Arduino to Adoid.

Answers to 9 question in reply #197
1..Version v4.0.4
2. Yes
3. Yes
4. Yes
5. Yes
6. Yes
7. NO - Initially Red LED flashes continuously but when connected it flashes twice every couple of seconds (not solid red as in question)
8. Yes
9. Yes

Observations:
I am not experienced with serial coms., but understand there are parity and stop bits. When I changed the BT module to 57600 baud I sent AT+UART=57600,0,0 and the AT command AT+UART? returned: 57600,0,0
Is that OK?

BT Red LED flashes rapldly before pairing. Then when paired changes to on/off flash every 2 seconds then but when connected it flashes twice every couple of seconds.

UNO TX LED flashes about every 2 seconds and whenever a button is pressed. When the joystick is moved it constantly flickers, then after about 10 seconds of continuous joystick movement the TX LED locks on. Opening the serial monitor window seems to return it  back to normal.
UNO RX LED only ever flashes when uploading code

Hope some of this makes sense - thanks again for your help
Bob

Title: Re: Android Bluetooth joystick
Post by: kas on May 24, 2014, 11:03 am
@ n3kx

Quote
even on version 4.0 it works Arduino receive joystick data as button data no problem. But datafields doesnt change there are always showing XXXX

Interesting
Android to Arduino communication is OK
Arduino to Android communication is not wired correctly

Quote
I have this type of Bluetooth: ...

The link is broken, please double check and let me know

Which Arduino board do you use ??
Can you post a photo of you setup ??
Did you modify the actual demo sketch ??

Quote
My model is HC-05 and it work @9600bps

Although this is not the cause of your problem, 9600bps is too slow for the data stream and generates transmission errors

I strongly urge everybody to set speed @57600bps

Depending on your specific model, I can post a tool for this adjustment


Title: Re: Android Bluetooth joystick
Post by: kas on May 24, 2014, 12:34 pm
@ n3kx

I just downgraded my HC-05 board to 9600bps and could reproduce your situation  ]:)  ]:)  ]:)

Please modify demo sketch as follow:
in void loop()  line #3               change  "delay(5);"   to   "delay(2);"
in void loop()  last line             remove  "delay(5);"

Did you make any change in Option for advanced users ??
Let me know your current settings for
- Refresh interval
- Time out count

Title: Re: Android Bluetooth joystick
Post by: n3kx on May 24, 2014, 07:18 pm
Today I bought HC-06 and it work @9600 pbs. So can you post code how to change it to whatever it need . I try change delay but same results.
Title: Re: Android Bluetooth joystick
Post by: kas on May 24, 2014, 07:39 pm
Quote
Today I bought HC-06 and it work @9600 pbs. So can you post code how to change it to whatever it need . I try change delay but same results.

Glad it works with HC-06
Please scroll up to reply #15 and download the HC-06 config tool

I own HC-05 and HC-06 cards and they both work flawlessly @57600bps

Quote
Did you make any change in "Option for advanced users" ??
Let me know your current settings for
- Refresh interval
- Time out count

Please reply
Title: Re: Android Bluetooth joystick
Post by: kas on May 24, 2014, 09:11 pm
@Bob1943
Quote
Still only xxx showing bottom left

Are you referring to the joystick position field at bottom left of android device screen ??   :smiley-eek:
This should indicate joystick position at App start up, even before any connection
It should read (-100,-100) for South West position and (100,100) for North East position

Quote
Interesting point is that button B5 stays locked the same as other buttons until pressed again to release. (I did notice at one time it did act like a push button - maybe that was when data got fed back).

This is normal behavior when not connected

Quote
My only problem now (apart from error in BT board configurator mentioned above) is the failure to get a signal from Arduino to Android.

- You can follow joystick position and buttons state on you Serial Monitor
- Datafields don't update, B5 is not in "push" mode
Correct ??

Quote
Answers to 9 question in reply #197
1..Version v4.0.4

I was talking about App version, should be V4.0       OK ??

Quote
the AT command AT+UART? returned: 57600,0,0 Is that OK?

Yes
According to documentation
Param2 = stop bit:   0->1 bit  1->2 bits
Param3 = parity bit:   0->None  1->Odd parity  2->Even parity
Arduino serial is 8N1 (1 stop bit, no parity)

Quote
UNO TX LED flashes about every 2 seconds and whenever a button is pressed. When the joystick is moved it constantly flickers,

This reflects the data flowing from Arduino to Serial Monitor

Quote
then after about 10 seconds of continuous joystick movement the TX LED locks on. Opening the serial monitor window seems to return it  back to normal.

Strange  :smiley-slim: :smiley-slim:


Did you change any setting in Advanced options ??
Try "reset Option" to restore initial parameters
EDIT: also set Refresh interval @100ms, Timeout count @every 10 intervals

Finally let me have a link to your specific BT board
Title: Re: Android Bluetooth joystick
Post by: Bob1943 on May 24, 2014, 11:42 pm
Data flow from Arduino to Android problem SOLVED

I am using Joystick BT Commander on an Android Tablet. This allows Apps to be closed by swiping the minimised app icon off the screen. This was the problem.

When I closed the App by using back button (hairpin arrow) and confirm "Total RC Commander - close this controller" and then re-open the App it works OK.
Data received back from Arduino and Button 5 is in push mode.
Apologies for inconvenience and thanks for your time.
It is great to see the care and level of attention that you provide to the users of your App.
Again many thanks - Brilliant App
Bob
Title: Re: Android Bluetooth joystick
Post by: kas on May 25, 2014, 08:58 am
Quote
Data flow from Arduino to Android problem SOLVED
.....
It is great to see the care and level of attention that you provide to the users of your App.
Again many thanks - Brilliant App
Bob
Thanks Bob for the good new and the kind words  8)

I am investing time because this App should bring a lot to the Arduino community
It is a universal remote for most projects, using wide spread (Android) technologies.
I told my friend to download the App and within a minute he took control of my RC tank
He was rather impressed  :smiley-eek: :smiley-eek: :smiley-eek:

During my support session, I did some interesting stress tests yesterday.
I tried various data refresh interval at different baud rates and found some minor glitches.
Please use AndroTest_V14.ino

Code: [Select]
#define VERSION     "\n\nAndroTest V1.4 - @kas2014\ndemo for V4.X  (6 button version)"

// V1.4  improved communication errors handling
// V1.3  renamed for publishing, posted on 09/05/2014
// V1.2  Text display   ** not backward compatible **
// V1.1  Integer display
// V1.0  6 buttons + 4 data char implemented

    **  The message exceeds the maximum allowed length (9500 characters)  **
See next message


This updated sketch features optimized timing and better transmission error management
Again, make sure your BT board is set @57600bps
Avoid using 25ms refresh interval and continuous timeout count, that's too much data
I am also preparing V5.0, with a pure ASCII communication protocol
Title: Re: Android Bluetooth joystick
Post by: Bob1943 on May 25, 2014, 11:40 am
Some thoughts

1. Where is AndroTest_V14.ino - only some lines showing?

2. In the Android app can you recognise when the app has been closed 'illegally' and act upon that action next time the app is opened. Might make it idiot proof.

3. When you first touch the yellow joystick dot, it immediately moves to the centre of the touch point. This changes the xy numbers - most noticeable when you touch the edge. (I want to control two servos but don't want them to move until the joystick is moved intentionally).
Can the touch point be recognised without moving the yellow dot?

4. What do I need to change to alter the data fields fed back to the Android and can it be coded in "Your code here" areas in the Arduino sketch.
I am doing number crunching on Arduino from Joystick positions and would like to send three values back to android.


Title: ** AndroTest.ino V1.41 **
Post by: kas on May 25, 2014, 07:00 pm
Here it is

Code: [Select]
#define VERSION     "\n\nAndroTest V1.41 - @kas2014\ndemo for V4.X  (6 button version)"

// V1.41 minor modifications
// V1.4  improved communication errors handling
// V1.3  renamed for publishing, posted on 09/05/2014
// V1.2  Text display   ** not backward compatible **
// V1.1  Integer display
// V1.0  6 buttons + 4 data char implemented

// Demo setup:
// Button #1 controls pin13 LED
// Button #2 starts DEBUG
// Button #3 displays demo message
// Button #4 toggle datafield display rate
// Button #5 configured as "push" button (momentary)

// Arduino pin#2 to TX BlueTooth module
// Arduino pin#3 to RX BlueTooth module
// make sure your BT board is set @57600 bps
// better remove SoftSerial for PWM based projects

// For Mega 2560:
// remove   #include "SoftwareSerial.h", SoftwareSerial mySerial(2,3);
// search/replace  mySerial  >> Serial1
// pin#18 to RX bluetooth module, pin#19 to TX bluetooth module

#include "SoftwareSerial.h"

#define    STX          0x01
#define    ETX          0x00
#define    ledPin       13
#define    SLOW         1000                           // Datafields refresh rate (ms)
#define    FAST         250                            // Datafields refresh rate (ms)

SoftwareSerial mySerial(2,3);                           // BlueTooth module: pin#2=TX pin#3=RX
int i=0;
byte cmd[6] = {0, 0, 0, 0, 0, 0};                       // bytes received
byte buttonStatus = 0;                                  // first Byte sent to Android device
long previousMillis = 0;                                // will store last time Buttons status was updated
boolean setButtonFeedback = false;                      // momentary buttons feedback to Android device
long sendInterval = SLOW;                               // interval between Buttons status transmission (milliseconds)
String displayStatus = "xxxx";                          // message to Android device

void setup()  {
 Serial.begin(57600);
 mySerial.begin(57600);                                // 57600 = max value for softserial
 pinMode(ledPin, OUTPUT);    
 Serial.println(VERSION);
 while(mySerial.available())  mySerial.read();         // empty RX buffer    //  <<mod XXXXXXXX
}

void loop() {
 if(mySerial.available())  {                            // data received from smartphone
   delay(2);                                                              //  <<mod XXXXXXXX
   cmd[0] =  mySerial.read();  
   if(cmd[0] == STX)  {
     i=1;      
     while(mySerial.available())  {
       delay(1);                                                          //  <<mod XXXXXXXX
       cmd[i] = mySerial.read();
       if(cmd[i]>127 || i>5)                               break;   // Communication error << XXX Mod
       if((cmd[i]==ETX) && ((i==2 && cmd[1]>2) || i==5))   break;   // Button or Joystick data
       i++;
     }
     if     (i==2 && cmd[1]>48 && cmd[1]<68)     getButtonState(cmd[1]);                         // 3 Bytes
     else if(i==5 && cmd[1]<3  && cmd[3]<3 )     getJoystickState(cmd);                          // 6 Bytes
   }
 }
 sendBlueToothData();                                                       //  <<mod XXXXXXXX
//    delay(5);                                                              //  <<mod XXXXXXXX
// your code here
}

void sendBlueToothData()  {
 static long previousMillis = 0;                            
 long currentMillis = millis();
 if(setButtonFeedback == true)  {                      // allow momentary button visual effect
   previousMillis = currentMillis + 250;  
   setButtonFeedback = false;
 }
 if(currentMillis - previousMillis > sendInterval) {   // send data to smartphone
   previousMillis = currentMillis;

// Data frame transmitted back from Arduino to Android device:
// < 0X02   Buttons state   0X01   DataField#1   0x04   DataField#2   0x05   DataField#3    0x03 >  
// < 0X02       01011       0X01      120.00     0x04      -4500      0x05   Motor enabled  0x03 >    // example

   mySerial.print((char)0x2);                                                 // Start of Transmission
   mySerial.print(getButtonStatusString());      mySerial.print((char)0x1);   // buttons status feedback
   mySerial.print(GetDataField_1_int());         mySerial.print((char)0x4);   // datafield #1
   mySerial.print(GetDataField_2_float());       mySerial.print((char)0x5);   // datafield #2
   mySerial.print(displayStatus);                                             // datafield #3
   mySerial.print((char)0x3);                                                 // End of Transmission
 }  
}

String getButtonStatusString()  {
 String bStatus = "";
 for(int i=0; i<6; i++)  {
   if(buttonStatus & (B100000 >>i))      bStatus += "1";
   else                                  bStatus += "0";
 }
 return bStatus;
}

int GetDataField_1_int()  {            // Data dummy values sent to Android device for demo purpose
 static int i= -30;                   // Replace with your own code
 i ++;
 if(i >0)    i = -3000;
 return i;  
}

float GetDataField_2_float()  {       // Data dummy values sent to Android device for demo purpose
 static float i=50;                  // Replace with your own code
 i-=.5;
 if(i <-50)    i = 50;
 return i;  
}

void getJoystickState(byte data[6])    {                             //  <<mod XXXXXXXX   nasty bug, was byte data[5]
 int joyX = (data[1]<<7) + data[2];
 int joyY = (data[3]<<7) + data[4];
 joyX = joyX - 200;                                            // Offset to avoid
 joyY = joyY - 200;                                            // transmitting negative numbers
 if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)    return; // commmunication error
 
 Serial.print("Joystick position:  ");
 Serial.print(joyX); Serial.print(", "); Serial.println(joyY);
   
// Your code here ...
}

void getButtonState(int bStatus)  {
 switch (bStatus) {
// -----------------  BUTTON #1  -----------------------
   case '1':
     buttonStatus |= B000001;        // ON
     Serial.println("\n** Button_1: ON **");    // your code here...
     displayStatus = "LED <ON>";
     Serial.println(displayStatus);
     digitalWrite(ledPin, HIGH);
     break;
   case '2':
     buttonStatus &= B111110;        // OFF
     Serial.println("\n** Button_1: OFF **");    // your code here...
     displayStatus = "LED <OFF>";
     Serial.println(displayStatus);
     digitalWrite(ledPin, LOW);
     break;
// -----------------  BUTTON #2  -----------------------
   case '3':
     buttonStatus |= B000010;        // ON
     Serial.println("\n** Button_2: ON **");    // your code here...
     break;
   case '4':
     buttonStatus &= B111101;        // OFF
     Serial.println("\n** Button_2: OFF **");    // your code here...
     break;
// -----------------  BUTTON #3  -----------------------
   case '5':
     buttonStatus |= B000100;        // ON
    // setButtonFeedback = true;            moved to button #5 (for push buttons)
     Serial.println("\n** Button_3: ON **");    // your code here...
     displayStatus = "Motor #1 enabled"; // Demo text message
     Serial.println(displayStatus);
     break;
   case '6':
     buttonStatus &= B111011;      // OFF
     Serial.println("\n** Button_3: OFF **");    // your code here...
     displayStatus = "Motor #1 stopped";
     Serial.println(displayStatus);
     break;
// -----------------  BUTTON #4  -----------------------
   case '7':
     buttonStatus |= B001000;       // ON
     Serial.println("\n** Button_4: ON **");    // your code here...
     displayStatus = "Datafield update <FAST>";
     Serial.println(displayStatus);
     sendInterval = FAST;
     break;
   case '8':
     buttonStatus &= B110111;    // OFF
     Serial.println("\n** Button_4: OFF **");    // your code here...
     displayStatus = "Datafield update <SLOW>";
     Serial.println(displayStatus);
     sendInterval = SLOW;
    break;
// -----------------  BUTTON #5  -----------------------
   case '9':           // configured as momentary button
//      buttonStatus |= B010000;        // ON
     setButtonFeedback = true;                     // moved from button #3
     Serial.println("\n** Button_5: + pushed + **"); // your code here...
     displayStatus = "Button_5: ++ pushed ++";
     break;
//   case 'A':
//     buttonStatus &= B101111;        // OFF
//     break;
// -----------------  BUTTON #6  -----------------------
   case 'B':
     buttonStatus |= B100000;        // ON
     Serial.println("\n** Button_6: ON **");    // your code here...
      displayStatus = "Button #6 ON"; // Demo text message
    break;
   case 'C':
     buttonStatus &= B011111;        // OFF
     Serial.println("\n** Button_6: OFF **");    // your code here...
     displayStatus = "Button #6 OFF";
     break;
// -----------------------------------------------------
 }
}


EDIT: moved       setButtonFeedback        from button #3 to button #5 (push button)
         Added 1ms delay after while(mySerial.available())
         Renamed to AndroTest V1.41        see Reply #225

Title: Re: Android Bluetooth joystick
Post by: kas on May 25, 2014, 07:23 pm
Quote
2. In the Android app can you recognise when the app has been closed 'illegally' and act upon that action next time the app is opened. Might make it idiot proof.

Not sure to understand, please clarify "This allows Apps to be closed by swiping the minimized app icon off the screen"

Quote
Can the touch point be recognised without moving the yellow dot?
I understand your concern, makes sense, let me think about it...

Quote
4. What do I need to change to alter the data fields fed back to the Android and can it be coded in "Your code here" areas in the Arduino sketch.
I am doing number crunching on Arduino from Joystick positions and would like to send three values back to android.

To send back three values to Android (data_1, data_2,data_3,)  just modify sendBlueToothData()

Code: [Select]
void sendBlueToothData()  {

   ......................
   ......................

   mySerial.print((char)0x2);                                                 // Start of Transmission
   mySerial.print(getButtonStatusString());      mySerial.print((char)0x1);   // buttons status feedback
   mySerial.print(data_1);                       mySerial.print((char)0x4);   // datafield #1
   mySerial.print(data_2);                       mySerial.print((char)0x5);   // datafield #2
   mySerial.print(data_3);                                                    // datafield #3
   mySerial.print((char)0x3);                                                 // End of Transmission
 }  
}
Title: Re: Android Bluetooth joystick
Post by: Bob1943 on May 25, 2014, 09:06 pm
Hi,
Thanks for information

The swipe-to-close feature is about 40 seconds into video at this site:
http://blog.laptopmag.com/9-awesome-android-ice-cream-sandwich-tips (http://blog.laptopmag.com/9-awesome-android-ice-cream-sandwich-tips)

This method is what was causing problem about no data from Arduino to Android. I wonder if this happens with other users?







Title: Re: Android Bluetooth joystick
Post by: kas on May 26, 2014, 03:37 pm
Quote
The swipe-to-close feature is about 40 seconds into video at this site:
http://blog.laptopmag.com/9-awesome-android-ice-cream-sandwich-tips
This method is what was causing problem about no data from Arduino to Android. I wonder if this happens with other users?

I can't replicate the "swipe" problem both on Galaxy Tab3 tablet and Motorola G phone (V4.4.2)
Please let me have a step by step procedure
Title: Re: Android Bluetooth joystick
Post by: Bob1943 on May 26, 2014, 04:42 pm
I am using a 7 inch tablet which doesn't have phone but allows multitasking.
My Samsung GT-S5570 phone won't recognise the HC-05 so I can't test on mobile phone.
However, the link below shows how to swipe on Galaxy 3. Hope this helps.
I think all Android tablets have swipe-to-close so others may also have a problem.
If you want I can video the actions. Just let me know

https://www.youtube.com/watch?v=I5wRaFSDIPo

(anyone know why my Samsung GT-S5570 phone won't recognise the HC-05)


Title: Re: Android Bluetooth joystick
Post by: kas on May 27, 2014, 07:13 pm
@ Bob1943

Quote
Quote
3. When you first touch the yellow joystick dot, it immediately moves to the centre of the touch point. This changes the xy numbers - most noticeable when you touch the edge. (I want to control two servos but don't want them to move until the joystick is moved intentionally).
Can the touch point be recognised without moving the yellow dot?
I understand your concern, makes sense, let me think about it...


I addressed the situation  ;)
Please let me have your email via PM, I will send you V4.1 for testing
Title: Re: Android Bluetooth joystick
Post by: kas on May 28, 2014, 09:59 am
Quote
I addressed the situation  ;)
Please let me have your email via PM, I will send you V4.1 for testing


Check your mail ...
Title: Re: Android Bluetooth joystick
Post by: Bob1943 on May 28, 2014, 10:51 am
Hi Kas,
This version V4.1 works fine.
Wherever you touch on the yellow spot is returned as coordinate 0,0 (x,y) which is exactly what I was looking for.
No jumpy servos anymore. - Many thanks
Title: Re: Android Bluetooth joystick
Post by: Bob1943 on May 28, 2014, 11:12 am
A couple of comments on Joystick BT Commander.

1. As information can be sent from Arduino to Android, is it possible to use the Android like a Serial monitor to display this information with rolling values - just like the USB to computer screen. You could give the option to change from Joystick to Monitor to make space on the Android screen.
An option to rotate the Android to make a deeper window would help, and an added bonus would be to have a button to pause the display if required.

2. Can the Arduino Bluetooth code be put into a library so the bluetooth device can be connected and used as a monitoring/commander tool. This would make the Arduino coding for the main applications more visible.

Just a thought!!!
Title: Re: Android Bluetooth joystick
Post by: kas on May 28, 2014, 07:05 pm
Quote
This version V4.1 works fine.
Wherever you touch on the yellow spot is returned as coordinate 0,0 (x,y) which is exactly what I was looking for.
No jumpy servos anymore. - Many thanks

Thanks, I will include this feature in V5.0 (pure ASCII protocol)

Quote
1. As information can be sent from Arduino to Android, is it possible to use the Android like a Serial monitor to display this information with rolling values - just like the USB to computer screen. You could give the option to change from Joystick to Monitor to make space on the Android screen.

Android Bluetooth joystick is a small footprint App (78Ko), its only task is to emulate a joystick  ;)
There are very good App for serial monitoring, BlueTerm (https://play.google.com/store/apps/details?id=es.pymasde.blueterm) is one of those

Quote
My Samsung GT-S5570 phone won't recognise the HC-05 so I can't test on mobile phone

Try sending AT command
Code: [Select]
AT+CLASS=1
Should work
Title: Joystick bluetooth Commander - older version
Post by: kas on May 29, 2014, 07:29 am
@Topicja
Quote
Hi Kas
I really like your excellent android app but after last update i cannot get it to work. I tried to rewrite my program but i don't receive any data. Could you please send me apk file of older version? Version 3.1 was working well for me. My e-mail address is xxxxxxxx@xxx.com

Thank you for your response and your willingness


I could recompile V3.1, but it makes much more sense to have your own program fixed and working
Joystick transmission has not been modified and should work, does it??
Please let me have your original Arduino sketch, I will fix it for you


@all
Should you encounter same difficulties, please contact me via PM

Title: Re: Android Bluetooth joystick
Post by: n3kx on May 29, 2014, 07:55 am
Sorry for late response. My problem was in bautrate and also you must press 3.rd button to get work .... so yust overwrite setbuttonfeedback=false to  setbuttonfeedback=true and it work for my.
Title: Re: Android Bluetooth joystick
Post by: kas on May 29, 2014, 05:39 pm
@Topicja
Quote
I could recompile V3.1, but it makes much more sense to have your own program fixed and working
Joystick transmission has not been modified and should work, does it??
Please let me have your original Arduino sketch, I will fix it for you

I will send you the modified sketch tomorrow evening
There are too many transmission errors at 9600 bps
Please, in the meantime, configure your BT card at 57600 bps

Are you able to do it by yourself ??
Otherwise, let me have a link to your specific model
Title: Re: Android Bluetooth joystick
Post by: kas on May 30, 2014, 11:58 am

For those who still have a Bluetooth card configured @9600bps, please add a one millisecond delay after the second "while(mySerial.available())"

Code: [Select]
void loop() {
 if(mySerial.available())  {
   delay(2);
   cmd[0] =  mySerial.read();  
   if(cmd[0] == STX)  {
     i=1;      
     while(mySerial.available())  {
    delay(1);                     //  <<mod     <-------------<<<
       cmd[i] = mySerial.read();
       ...........

}
 
This will prevent  while(mySerial.available())  to return before the complete data frame is received
I have modified AndroTest V1.4 to reflect this modification (now Version 1.41)

I only work @57600bps and never bothered checking lower data speeds  :smiley-red:
Thanks Topicja for bringing this point to my attention

A sweet thought for the Microsoft developers who deal with thousands different hardware configurations and get bashed by users because...  "it doesn't work on MY specific setup"   ;)
Title: Re: Android Bluetooth joystick
Post by: kas on May 31, 2014, 12:56 pm
@n3kx
Quote
My problem was in bautrate

Glad it finally works  :)


Quote
and also you must press 3.rd button to get work .... so you overwrite setbuttonfeedback=false to  setbuttonfeedback=true and it work for my

:smiley-roll-blue: :smiley-roll-blue: :smiley-roll-blue:   setButtonFeedback was created for handling push buttons
This is a flag to send an earlier feed back to Android, for a consistent visual effect
setButtonFeedback is reset to False with each sendBlueToothData() call:
Code: [Select]
 if(setButtonFeedback == true)  {                      // allow momentary button visual effect
   previousMillis = currentMillis + 250;  
   setButtonFeedback = false;
 }

This code snippet could be safely omitted (will be removed in next release):

setButtonFeedback is misplaced and should be moved from Button #3 to Button #5 (push button)
I edited accordingly AndroTest V1.4 in response #212

Title: BT card configuration for dummies
Post by: kas on Jun 01, 2014, 10:39 am
Quote
Please show me the way to check and configure my bluetooth card
thanks, Christian
Bluetooth cards come in a many flavors HC-05, HC-06, HC-07, HC-08 ...

I personally own an HC-06
(http://i.imgur.com/jzHoND9.jpg)

and a very convenient Arduino/HC-05 combo
(http://i.imgur.com/4HPW4Rc.jpg)


Configuration methods are quite different according to board type

For 57600 bps setup:
Code: [Select]
HC-05:        AT+UART=57600,0,0\r\n        (with linefeed + return)
HC-06:        AT+BAUD7                     (w/o linefeed + return)

The all point is to access the board configuration mode
My HC-05 board has a built in switch + reset button for easy operation (see above)

Arduino member Nick_Pyner has produced a very interesting document (http://homepages.ihug.com.au/~npyner/Arduino/GUIDE_2BT.pdf), I learned a lot from it
Don't forget to increase Nick's Karma by hitting the green "+" sign below his name

Complete AT command set:
HC-05 (http://www.linotux.ch/arduino/HC-0305_serial_module_AT_commamd_set_201104_revised.pdf)
HC-06 (http://www.micro4you.com/files/ElecFreaks/Bluetooth%20HC-06.pdf)

Further readings here (http://wiki.pinguino.cc/index.php/SPP_Bluetooth_Modules)

Finally, I attach two sketches for configuring HC-05 and HC-06 boards
(http://i.imgur.com/8ZuFcXw.png)

Enjoy the fascinating Bluetooth universe  ;)


@all
Feel free to post your personal experience and additional links

Title: Re: Android Bluetooth joystick
Post by: kas on Jun 02, 2014, 10:16 am
Quote
Hello Kas,

First I would like to say thank you for the great piece of software you have written.  It has made implementing this type of controls into my project SO much easier.

I do have one question for you, but it would probably be better to give you a little background first...

I'm currently developing an autonomous mobile robot platform, with the UI to control it on an Android tablet.  I've developed most of the UI already for my device, and included a button that opens your Joystick BT Commander app directly from within my UI, for when the end user needs to manually control the robot.

However the Joystick BT Commnader app looks nothing like my UI design/theme, most notably you have a dark theme while my UI uses a "light" theme with a white background.

So my question for you is are you planning on implementing any sort of customization in this area into your app in the near future at all?  If not, is there some way that I can change the colors so our software would better compliment eachother?  I know I can go back and redesign my UI to match your app, but for my particular application (outdoors and/or in direct sunlight) a dark theme is a lot harder for the end user to see.

Thanks in advance for any assistance you can provide.  It is greatly appreciated.


Hi joepro
Thanks for the comments
Should be included in V5.0, to be posted within 4 weeks
Title: Re: Android Bluetooth joystick
Post by: jaapdemaat on Jun 03, 2014, 10:26 pm
Hi Kas,
Thanks for the great App!

Im having some difficulties implementing the code into my already excising code based on Miguel Grinberg tutorial (link below)
http://blog.miguelgrinberg.com/post/building-an-arduino-robot-part-iv-a-not-so-basic-robot-firmware
I was wondering if you are able to help me. If so, I can email you the code and explain more about the problem I got.
Obviously if we get it to work, we share it here for everyone else to use.
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 04, 2014, 08:44 pm
Quote
I was wondering if you are able to help me. If so, I can email you the code and explain more about the problem I got.
Obviously if we get it to work, we share it here for everyone else to use


Hi jaapdemaat,
Let me have your email address via PM
Title: Re: Android Bluetooth joystick
Post by: billcat on Jun 10, 2014, 05:39 am
Hi Kas,
I don't know if you have this info...I just installed Joystick BT Plus onto Kindle Fire HD 7" and it appears to be working from first impression :D
Bear in mind that I have not had a chance to test with the Arduino sketch, and sadly may not for some time, but look forward to doing so.
I just thought you may be glad to know this, I don't remember anyone else commenting on trying the app on Kindle.

From the screenshot, the buttons toggle green to white when pressed and the joystick data field in () changes with movement of the joystick, leading me to think the app is working correctly on the device.  The joystick is a bit far to the right and may interfere with the menu there, I am not sure yet.

Cheers, and thanks again for all the work you have done!

Title: Re: Android Bluetooth joystick
Post by: kas on Jun 10, 2014, 10:33 pm
Hi billcat   :)

Thanks for the info
I did know that Fire OS is based on Android, but I wasn't too sure it would work

Quote
The joystick is a bit far to the right and may interfere with the menu there, I am not sure yet

I can easily compile a "billcat's special" with fully visible joystick
Let me know  ;)
Title: Re: Android Bluetooth joystick
Post by: billcat on Jun 11, 2014, 04:42 am


I can easily compile a "billcat's special" with fully visible joystick
Let me know  ;)

      :smiley-mr-green: :smiley-mr-green:
Greetings Kas, well I would feel too guilty to ask, considering all that you have helped out already. But I did get a chance to do very basic testing with the minimal Arduino/BT connections, and sad to confess that yes the joystick location did often interfere with that rightmost menu button,  causing an interruption of control over the stick.

Otherwise,  disregarding the fact that I haven't enough programming wits yet :smiley-red: to adjust the Arduino test sketch and thoroughly exercise all functions, it seems to be providing the appropriate responses via serial monitor when buttons are pressed, or the joystick moved!
I am quite pleased so far, I had doubts if it would work with the Fire, but it seems to be just fine.

As a side note....I was not able to connect to the HC-06 BT while the Kindle was connected to Wifi. I could not get BT comms working unless I disconnected the Wifi internet connection beforehand.  I don't know why, or if this is to be expected, but its not a problem for my purposes.

cheers XD
Title: Re: Android Bluetooth joystick
Post by: thornlv on Jun 11, 2014, 08:25 pm
Hi Kas.

Great work.I have read though all this thread and I find that your app is exactly what I am looking for, for my own project. At 55 I am getting interested in electronics and programming so I could knock up some 'Photoduino' stuff but I am not even passed the 'hello world' stage of programming.

My first project involves something I have had working for about a year now, as a wildlife photographer there are subjects which I can t get close to enough for some natural shots (mostly birds, mostly passerines)

I have a 'radio controlled' pan and tilt gimball tripod head and use this with a 'Cam ranger' WiFi setup - this allows me to control the DSLR settings through live view, focus and shoot from up to 100 feet away, the tripod has 2 servos controlling pan and tilt - But I use a rather cumbersome RC transmitter and a 7 inch tablet - the tablet runs the camranger app and works really well - the problem is the RC side of it - I want to control the pan/tilt with my smartphone.

I have got an Arduino Uno 3 and have run your demo app and every thing is fine there - serial monitor shows the actions as expected - but how do I control the servos - which pins to connect to, is there a sketch I could use or have i missed something ?

Vic (Birdincamera)
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 12, 2014, 07:52 am
Hi Vic,

First, congratulation for your very professional work
I went on your flickr gallery (https://www.flickr.com/photos/birdincamera/) and I am impressed  :smiley-eek:  :smiley-eek:  :smiley-eek:
(http://i.imgur.com/Iey9tpa.jpg)


Back to your gimball project
It should basically operate as this pan/tilt demo project (http://forum.arduino.cc/index.php?topic=173246.msg1290243#msg1290243)

Let me have a link to your tripod


Title: Re: Android Bluetooth joystick
Post by: kas on Jun 12, 2014, 08:21 am
@billcat
Quote
Quote
I can easily compile a "billcat's special" with fully visible joystick
Let me know   ;)
:smiley-mr-green: :smiley-mr-green:    
Greetings Kas, well I would feel too guilty to ask,


Check your mail  8)


@all
Please post a screenshot of the App
This will help me to optimize screen layout

Title: Re: Android Bluetooth joystick
Post by: john_lenfr on Jun 12, 2014, 02:47 pm
Hi,

I can't find the Total RC Commander apk on GooglePlay, is that normal?
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 12, 2014, 03:05 pm
Quote
Hi,
I can't find the Total RC Commander apk on GooglePlay, is that normal?


https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result

Just checked, still there  ;)
(http://i.imgur.com/CaG3HPc.jpg)

I should really change this V1.0 photo  :smiley-roll:
Title: Re: Android Bluetooth joystick
Post by: john_lenfr on Jun 12, 2014, 04:38 pm
[MODE FRENCH ON]
Ok, c'est bien l'appli avec le retour vidéo possible?

Je recherche comment tu as implémenter le retour vidéo? Est-ce qu'on peut utiliser du matériel FPV pour avoir ça ou bien ça doit forcément passer par le réseau? Et si ça doit passer par le réseau on doit utiliser quel matériel?
[/MODE FRENCH ON]
Title: Re: Android Bluetooth joystick
Post by: thornlv on Jun 12, 2014, 05:19 pm
Hi Kas

Glad you liked my photos. will look at your suggested link more tonight. Have just posted a youtube vid of the servo and gimball head controlled by RC. Have been out with it today, it's really hot today - all geared up, tripod set up, camera then camouflaged and RC fully charged, connected to cam ranger and - duh forgot my servo power pack  =(

anyway got some shots albeit from static position so not all lost

Here's the youtube vid - https://www.youtube.com/watch?v=lDpsGqUOG0I&feature=youtu.be (https://www.youtube.com/watch?v=lDpsGqUOG0I&feature=youtu.be)

and here's the camranger - http://camranger.com/ (http://camranger.com/)

Thanks for taking the time.

Vic
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 12, 2014, 07:13 pm
@john_lenfr
Quote
Ok, c'est bien l'appli avec le retour vidéo possible?

oops... désolé  :smiley-red:

The video App is not yet mainstream and will be available after Joystick BT Commander V5.0 release
Not too familiar with FPV equipment...

Video is acquired by any standalone IP camera, or any Android device with integrated camera + IP webcam App
Stream is sent via WiFi to the App through a router (for IP cameras) or directly (for Android cameras)

I use this mini router (http://forum.arduino.cc/index.php?topic=236401.msg1703997#msg1703997)

Did you already test Joystick BT Commander V4.0 ??


Title: Pan & Tilt demo
Post by: kas on Jun 12, 2014, 09:07 pm
@thornlv

I updated the Andro_Pan&Tilt code to make it compatible with Joystick BT commander V4.0,
should work right out of the box  ;)

EDIT:   now  Android BT Commander V5.x  compatible

Code: [Select]
#define VERSION     "\n\nAndro_Pan&Tilt V3.6 - @kas2014\n** Stepper demo for V5.x App **"

// Controls two servo motors

// V3.6: Android BT Commander V5.X compatible, no button data management
// V3.0: Android BT Commander V3.X compatible, no button data management
// V2.5 can receive both Byte & Integer data
// V2.0: removed SoftwareSerial

// Android BT Commander settings:
// Options/Options for advanced users/Data Range        >>>  -100 to +100
// Options/Options for advanced users/Refresh interval  >>>  50ms

//  Arduino pin #0 to TX BlueTooth module
// BT TX to be disconnected from D0 during sketch upload

#include <Servo.h>

boolean    DEBUG =         true;

#define    pinServo_X     9
#define    pinServo_Y     10
#define    STX            0x02
#define    ETX            0x03
#define    MIN_Y          45             // vertical move limitation
#define    MAX_Y          180
#define    ZERO_Y         60             // vertical offset

byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};
Servo myservoX;                         // create servo objects
Servo myservoY;

void setup()  {
 Serial.begin(57600);
 myservoX.attach(pinServo_X);  
 myservoY.attach(pinServo_Y);  
 if(DEBUG)    Serial.println(VERSION);
}

void loop() {
  if(Serial.available())  {                            // data received from smartphone
   delay(2);
   cmd[0] =  Serial.read();  
   if(cmd[0] == STX)  {
     int i=1;      
     while(Serial.available())  {
       delay(1);
       cmd[i] = Serial.read();
       if(cmd[i]>127 || i>7)                 break;     // Communication error
       if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
       i++;
     }
     if(i==7)     setServoPosition(cmd);
   }
 }
}

void setServoPosition(byte data[8])    {
 int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
 int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
 joyX = joyX - 200;                                                  // Offset to avoid
 joyY = joyY - 200;                                                  // transmitting negative numbers

 if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // commmunication error
 
 joyX = map(joyX, -100, 100, 180, 0);   //  << adjust to change motor direction
 joyY = map(joyY, -100, 100, 0, 180);   //  <<

 joyY+=ZERO_Y;
 joyY = constrain(joyY, MIN_Y, MAX_Y);
 myservoX.write(joyX);
 myservoY.write(joyY);
 if(DEBUG)    {Serial.print(joyX); Serial.print(", "); Serial.println(joyY);}
}


Tell me if it works
Title: Re: Android Bluetooth joystick
Post by: billcat on Jun 12, 2014, 09:47 pm

Check your mail  8)
Please post a screenshot of the App



Hello Kas,
Thanks for your splendid enthusiasm!  I like the "billcat edition"!
But there is just one little problem....have a look at the screenshots :D
....first is original joystick bt plus v1.1a, second is joystick bt commander v4.0b(billcat edition)
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 12, 2014, 10:08 pm
Quote
But there is just one little problem....have a look at the screenshots  :D


Oops... Looks pretty much the same  :smiley-red:
Seems I edited the wrong template
Let me have another try
Title: Re: Android Bluetooth joystick
Post by: thornlv on Jun 12, 2014, 10:27 pm
Hi Kas. Will try it out in about 3 days. Have work shifts for the while won't get time till then. Looking forward to it and will let you know how it goes.

Have a great weekend

Cheers, Vic
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 13, 2014, 12:04 pm
@billcat
Quote
But there is just one little problem....have a look at the screenshots  :D


Second try
Check your mail  ;)
Title: Re: Android Bluetooth joystick
Post by: john_lenfr on Jun 13, 2014, 02:43 pm

@john_lenfr
Quote
Ok, c'est bien l'appli avec le retour vidéo possible?

oops... désolé  :smiley-red:
The video App is not yet mainstream and will be available after Joystick BT Commander V5.0 release
Not too familiar with FPV equipment...
Video is acquired by any standalone IP camera, or any Android device with integrated camera + IP webcam App
Stream is sent via WiFi to the App through a router (for IP cameras) or directly (for Android cameras)
I use this mini router (http://forum.arduino.cc/index.php?topic=236401.msg1703997#msg1703997)
Did you already test Joystick BT Commander V4.0 ??

Ok, that's what I thought.
No I didn't test it because I'm just starting to use HC-05 modules.
I just found how to do the AT commands in Arduino Monitor
So I am at the beginning of the beginning  :smiley-mr-green:
Title: Re: Android Bluetooth joystick
Post by: billcat on Jun 14, 2014, 02:37 pm
Howdy Kas,
Great news.....second try's a charm, very nice.
many thanks!
  :D                                                               :D                                                           :D                                                       :D
Title: Re: Android Bluetooth joystick
Post by: joepro on Jun 14, 2014, 05:43 pm

Quote
Hello Kas,

First I would like to say thank you for the great piece of software you have written.  It has made implementing this type of controls into my project SO much easier.

I do have one question for you, but it would probably be better to give you a little background first...

I'm currently developing an autonomous mobile robot platform, with the UI to control it on an Android tablet.  I've developed most of the UI already for my device, and included a button that opens your Joystick BT Commander app directly from within my UI, for when the end user needs to manually control the robot.

However the Joystick BT Commnader app looks nothing like my UI design/theme, most notably you have a dark theme while my UI uses a "light" theme with a white background.

So my question for you is are you planning on implementing any sort of customization in this area into your app in the near future at all?  If not, is there some way that I can change the colors so our software would better compliment eachother?  I know I can go back and redesign my UI to match your app, but for my particular application (outdoors and/or in direct sunlight) a dark theme is a lot harder for the end user to see.

Thanks in advance for any assistance you can provide.  It is greatly appreciated.


Hi joepro
Thanks for the comments
Should be included in V5.0, to be posted within 4 weeks


Sounds good, I look forward to it.  Also, one other thing I noticed recently is that you have your app locked to Landscape.  Obviously by the way it is designed a landscape view is required.  Would it be possible for you to set it to sensorLandscape instead, that way it will automatically flip if the user turns their device upside down.

Once again, thank you for your fantastic software and the excellent support you provide.  Now if we could get all software developers to listen to their end users like this, the world would be a much better place. :-)
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 14, 2014, 07:06 pm
Quote
Would it be possible for you to set it to sensorLandscape instead, that way it will automatically flip if the user turns their device upside down

Thanks joepro for this suggestion, makes a lot of sense, will definitely be included in V5.0


Quote
However the Joystick BT Commander app looks nothing like my UI design/theme, most notably you have a dark theme while my UI uses a "light" theme with a white background.

Let me have the code snippet with your theme definition
Title: Version 5.0 coming soon
Post by: kas on Jun 14, 2014, 10:03 pm
Version 5.0 to be released

Early Warning

Backgroung:
Initial communication protocol was developped one year ago
At that time the App was simple (two buttons only, joystick values coded on a single Byte, no feedback communication from Arduino to Android)
Time has evolved, with added features, transmitted data amount has rapidly inflated

In some situations (RF noise environment) Arduino may receive erratic values and joystick values may be seen as button commands

Version 5.0 will feature a pure ASCII transmission protocol and definitely address this problem

This new version will be online next week
For those who want to anticipate and start modifying their code,
I will post the new communication protocol, together with the relevant demo sketch (AndroTest V2.0)
Title: Version 5.0 ** communication protocol **
Post by: kas on Jun 15, 2014, 05:05 pm
New communication protocol for Joystick BT Commander V5.x

Communication from Android to Arduino                   (or to any microcontroller)

- Joystick information:
Joystick data is transmitted as ASCII data, according to this data frame:
        <STX  "Joy_X + 200"  "Joy_Y + 200"  ETX>

with STX=0x2, ETX=0x3


This is the relevant Android (Java) code snippet from Joystick Bluetooth Commander:
Code: [Select]

   final int XvalB = Xval + 200;
   final int YvalB = Yval + 200;
   if((((Xant!=Xval) || (Yant!=Yval)) || (mTimeoutCounter>=mMaxTimeoutCount && mMaxTimeoutCount>-1)))   // joystick position changed, or timeout occurred
    String toSend = String.format("%c%d%d%c", STX, XvalB, YvalB, ETX);
    sendMessage(toSend);


So, for Xval=0 Yval=0:
 XvalB = YvalB = 200
 '2' is Ascii 32 hex (decimal 50)
 '0' is Ascii 30 hex (decimal 48)
Data frame:   <0x02 0x32 0x30 0x30 0x32 0x30 0x30 0x03>

for Xval=100 Yval=100:
 XvalB = YvalB = 300
 '3' is Ascii 33 hex (decimal 51)
 '0' is Ascii 30 hex (decimal 48)
Data frame:   <0x02 0x33 0x30 0x30 0x33 0x30 0x30 0x03>

The data frame is send via BlueTooth to the arduino board and decoded.
This is the Arduino code snippet from AndroTest V2.0:
Code: [Select]

void getJoystickState(byte data[8])    {
 int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain an Int from the ASCII representation
 int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
 joyX = joyX - 200;                                                  // Offset to avoid
 joyY = joyY - 200;                                                  // transmitting negative numbers
}



- Button information:
Each time an android button is pressed, the following data frame is transmitted
               <STX  buttonState  ETX>

buttonState is transmitted as a Byte value and reflects the state of the pushed button
Button #1:  ON: 'A'      OFF: 'B'
Button #2: ON: 'C'      OFF: 'D'
Button #3  ...

On the Arduino side, data frame is decoded in getButtonState()
Code: [Select]
void getButtonState(int bStatus)  {
 switch (bStatus) {
// -----------------  BUTTON #1  -----------------------
   case 'A':
     buttonStatus |= B000001;        // ON
     Serial.println("\n** Button_1: ON **");
     // your code...      
     break;
   case 'B':
     buttonStatus &= B111110;        // OFF
     Serial.println("\n** Button_1: OFF **");
     // your code...      
     break;

// -----------------  BUTTON #2  -----------------------
   case 'C':
     buttonStatus |= B000010;        // ON
     Serial.println("\n** Button_2: ON **");
     // your code...      
     break;
   case 'D':
     buttonStatus &= B111101;        // OFF
     Serial.println("\n** Button_2: OFF **");
     // your code...      
     break;

   ....
}



Communication back from Arduino to Android:
(same as V4.0)

Arduino code
Code: [Select]
void sendBlueToothData()  {

 ....

   mySerial.print((char)STX);                                             // Start of Transmission
   mySerial.print(getButtonStatusString());  mySerial.print((char)0x1);   // buttons status feedback
   mySerial.print(GetdataInt1());            mySerial.print((char)0x4);   // datafield #1
   mySerial.print(GetdataFloat2());          mySerial.print((char)0x5);   // datafield #2
   mySerial.print(displayStatus);                                         // datafield #3
   mySerial.print((char)ETX);                                             // End of Transmission
 
 ....  
}



Data frame transmitted back from Arduino to Android device:  (by default, every 1000ms)
< STX   Buttons state   0X01   DataField#1   0x04   DataField#2   0x05   DataField#3   ETX >  

example: < 0X02    001011    0X01    120.00    0x04   -4500   0x05   Motor enabled   0x03 >

Button state:
This is a six character string reflecting the Arduino state for buttons position
button #1,#2,#4: ON, all others: OFF   >>>  001011
This feedback avoid any discrepancy with the Android device button state
An Arduino Reset will reinitialize the Android buttons, Two way communication is mandatory for "clean" control
Button state string is created in the getButtonStatusString() function.

Code: [Select]
String getButtonStatusString()  {
 String bStatus = "";
 for(i=0; i<6; i++)  {
   if(buttonStatus & B100000 >>i)      bStatus += "1";
   else                                bStatus += "0";
 }
 return bStatus;
}



Datafields:
Data is transmitted as ASCII characters using Serial.print()
Numbers are printed using an ASCII character for each digit
120.00   >>>   0X31, 0X32, 0X30, 0X2E, 0X30, 0X30

So  < 0x02     001011      0x01      120.00     0x04      -4500      0x05     Motor enabled     0x03 >
is actually transmitted as
    < 0x02,   0x30,0x30,0x31,0x30,0x31,0x31,   0X01,   0x31,0x32,0x30,0x2E,0x30,0x30,  
       0x04,  0x2D,0x34,0x35,0x30,0x30,   0x05,   0x4D,0x6F,0x74,0x6F,0x72,0x20,0x65,
       0x6E,0x61,0x62,0x6C,0x65,0x64,  0x03 >

without commas and spaces

Should you have additional questions, let me know  ;)

Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Jun 15, 2014, 06:22 pm
will this protocol also be used in Total RC commander ?
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 15, 2014, 06:28 pm
Quote
will this protocol also be used in Total RC commander ?

It will

Joystick BT Commander & Total RC commander share the same Bluetooth engine
Total RC commander has WiFi live video atop
Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Jun 15, 2014, 06:54 pm
Great, thanks

just a few ideas that maybe can implemented in future releases.
1. Text overlay on the video feed, like a HUD. Instead of printing the adruino sent messages under the video screen  overlay them on the video feed.
2. Have an option to switch between the joystick style control and a four directional arrow control.

Any idea when Total RC commander will be available with the new protocol and a test sketch ?
Title: Version 5.0 ** demo sketch **
Post by: kas on Jun 15, 2014, 06:56 pm
This is AndroTest V2.0 demo sketch for Joystick BT Commander V5.x

modified variables
- STX
- ETX
- cmd[8]

modified functions:
- loop()
- getJoystickState()
- getButtonState()

Code: [Select]
#define VERSION     "\n\nAndroTest V2.0 - @kas2014\ndemo for V5.x App"

// V2.0  changed to pure ASCII Communication Protocol ** not backward compatible **
// V1.4  improved communication errors handling
// V1.3  renamed for publishing, posted on 09/05/2014
// V1.2  Text display   ** not backward compatible **
// V1.1  Integer display
// V1.0  6 buttons + 4 data char implemented

// Demo setup:
// Button #1 controls pin #13 LED
// Button #4 toggle datafield display rate
// Button #5 configured as "push" button (momentary)
// Other buttons display demo message

// Arduino pin#2 to TX BlueTooth module
// Arduino pin#3 to RX BlueTooth module
// make sure your BT board is set @57600 bps
// better remove SoftSerial for PWM based projects

// For Mega 2560:
// remove   #include "SoftwareSerial.h", SoftwareSerial mySerial(2,3);
// search/replace  mySerial  >> Serial1
// pin#18 to RX bluetooth module, pin#19 to TX bluetooth module

#include "SoftwareSerial.h"

#define    STX          0x02
#define    ETX          0x03
#define    ledPin       13
#define    SLOW         750                            // Datafields refresh rate (ms)
#define    FAST         250                             // Datafields refresh rate (ms)

SoftwareSerial mySerial(2,3);                           // BlueTooth module: pin#2=TX pin#3=RX
byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};                 // bytes received
byte buttonStatus = 0;                                  // first Byte sent to Android device
long previousMillis = 0;                                // will store last time Buttons status was updated
long sendInterval = SLOW;                               // interval between Buttons status transmission (milliseconds)
String displayStatus = "xxxx";                          // message to Android device

void setup()  {
 Serial.begin(57600);
 mySerial.begin(57600);                                // 57600 = max value for softserial
 pinMode(ledPin, OUTPUT);    
 Serial.println(VERSION);
 while(mySerial.available())  mySerial.read();         // empty RX buffer
}

void loop() {
 if(mySerial.available())  {                           // data received from smartphone
   delay(2);
   cmd[0] =  mySerial.read();  
   if(cmd[0] == STX)  {
     int i=1;      
     while(mySerial.available())  {
       delay(1);
       cmd[i] = mySerial.read();
       if(cmd[i]>127 || i>7)                 break;     // Communication error
       if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
       i++;
     }
     if     (i==2)          getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
     else if(i==7)          getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
   }
 }
 sendBlueToothData();
}

void sendBlueToothData()  {
 static long previousMillis = 0;                            
 long currentMillis = millis();
 if(currentMillis - previousMillis > sendInterval) {   // send data back to smartphone
   previousMillis = currentMillis;

// Data frame transmitted back from Arduino to Android device:
// < 0X02   Buttons state   0X01   DataField#1   0x04   DataField#2   0x05   DataField#3    0x03 >  
// < 0X02      "01011"      0X01     "120.00"    0x04     "-4500"     0x05  "Motor enabled" 0x03 >    // example

   mySerial.print((char)STX);                                             // Start of Transmission
   mySerial.print(getButtonStatusString());  mySerial.print((char)0x1);   // buttons status feedback
   mySerial.print(GetdataInt1());            mySerial.print((char)0x4);   // datafield #1
   mySerial.print(GetdataFloat2());          mySerial.print((char)0x5);   // datafield #2
   mySerial.print(displayStatus);                                         // datafield #3
   mySerial.print((char)ETX);                                             // End of Transmission
 }  
}

String getButtonStatusString()  {
 String bStatus = "";
 for(int i=0; i<6; i++)  {
   if(buttonStatus & (B100000 >>i))      bStatus += "1";
   else                                  bStatus += "0";
 }
 return bStatus;
}

int GetdataInt1()  {              // Data dummy values sent to Android device for demo purpose
 static int i= -30;              // Replace with your own code
 i ++;
 if(i >0)    i = -30;
 return i;  
}

float GetdataFloat2()  {           // Data dummy values sent to Android device for demo purpose
 static float i=50;               // Replace with your own code
 i-=.5;
 if(i <-50)    i = 50;
 return i;  
}

void getJoystickState(byte data[8])    {
 int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
 int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
 joyX = joyX - 200;                                                  // Offset to avoid
 joyY = joyY - 200;                                                  // transmitting negative numbers

 if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // commmunication error
 
// Your code here ...
   Serial.print("Joystick position:  ");
   Serial.print(joyX);  
   Serial.print(", ");  
   Serial.println(joyY);
}

void getButtonState(int bStatus)  {
 switch (bStatus) {
// -----------------  BUTTON #1  -----------------------
   case 'A':
     buttonStatus |= B000001;        // ON
     Serial.println("\n** Button_1: ON **");
     // your code...      
     displayStatus = "LED <ON>";
     Serial.println(displayStatus);
     digitalWrite(ledPin, HIGH);
     break;
   case 'B':
     buttonStatus &= B111110;        // OFF
     Serial.println("\n** Button_1: OFF **");
     // your code...      
     displayStatus = "LED <OFF>";
     Serial.println(displayStatus);
     digitalWrite(ledPin, LOW);
     break;

// -----------------  BUTTON #2  -----------------------
   case 'C':
     buttonStatus |= B000010;        // ON
     Serial.println("\n** Button_2: ON **");
     // your code...      
     displayStatus = "Button2 <ON>";
     Serial.println(displayStatus);
     break;
   case 'D':
     buttonStatus &= B111101;        // OFF
     Serial.println("\n** Button_2: OFF **");
     // your code...      
     displayStatus = "Button2 <OFF>";
     Serial.println(displayStatus);
     break;

// -----------------  BUTTON #3  -----------------------
   case 'E':
     buttonStatus |= B000100;        // ON
     Serial.println("\n** Button_3: ON **");
     // your code...      
     displayStatus = "Motor #1 enabled"; // Demo text message
     Serial.println(displayStatus);
     break;
   case 'F':
     buttonStatus &= B111011;      // OFF
     Serial.println("\n** Button_3: OFF **");
     // your code...      
     displayStatus = "Motor #1 stopped";
     Serial.println(displayStatus);
     break;

// -----------------  BUTTON #4  -----------------------
   case 'G':
     buttonStatus |= B001000;       // ON
     Serial.println("\n** Button_4: ON **");
     // your code...      
     displayStatus = "Datafield update <FAST>";
     Serial.println(displayStatus);
     sendInterval = FAST;
     break;
   case 'H':
     buttonStatus &= B110111;    // OFF
     Serial.println("\n** Button_4: OFF **");
     // your code...      
     displayStatus = "Datafield update <SLOW>";
     Serial.println(displayStatus);
     sendInterval = SLOW;
    break;

// -----------------  BUTTON #5  -----------------------
   case 'I':           // configured as momentary button
//      buttonStatus |= B010000;        // ON
     Serial.println("\n** Button_5: ++ pushed ++ **");
     // your code...      
     displayStatus = "Button5: <pushed>";
     break;
//   case 'J':
//     buttonStatus &= B101111;        // OFF
//     // your code...      
//     break;

// -----------------  BUTTON #6  -----------------------
   case 'K':
     buttonStatus |= B100000;        // ON
     Serial.println("\n** Button_6: ON **");
     // your code...      
      displayStatus = "Button6 <ON>"; // Demo text message
    break;
   case 'L':
     buttonStatus &= B011111;        // OFF
     Serial.println("\n** Button_6: OFF **");
     // your code...      
     displayStatus = "Button6 <OFF>";
     break;
 }
// ---------------------------------------------------------------
}



Title: Re: Android Bluetooth joystick
Post by: kas on Jun 16, 2014, 05:18 pm
@tolisn63
Quote
Great, thanks
just a few ideas that maybe can implemented in future releases.
1. Text overlay on the video feed, like a HUD. Instead of printing the arduino sent messages under the video screen  overlay them on the video feed.

Well... to keep it simple, I have Bluetooth and WiFi modules well apart
This is easier for maintenance and upgrade
Text overlay would create modules intricacy

Quote
2. Have an option to switch between the joystick style control and a four directional arrow control.
Nice suggestion
I will first implement the long awaited accelerometer control (tilting the Android device)

Quote
Any idea when Total RC commander will be available with the new protocol and a test sketch ?

Will wait for Joystick BT commander V5.0 feedback
Would say two or three weeks
Title: Re: Android Bluetooth joystick
Post by: thornlv on Jun 16, 2014, 06:21 pm
Hi Kas

Have tried the updated Andro_Pan_Tilt sketch but it did not work.
What happens is the servos centre and when I use the joystick I get a few lines of positions in serial monitor and then 'communication error' repeating lines. MyservoX changes to full 180 position  and stays there (motor whirring) whilst MyservoY does nothing.

I played with the delay settings in the void loop to no avail (same behavior) except delay of 1 stops the communication error but the servos do not respond.

My Phone is Sony experia, am using an arduino Uno and a HC-06 bluetooth module (Set to 57600 with your AT sketch)
BT TX to D0, Servos to 9 and 10 (BT RX not used ?)

Hope this helps
Title: Version 5.0 ** now available **
Post by: kas on Jun 16, 2014, 06:46 pm
Joystick Bluetooth Commander Version 5.0  has just been published on Google Play (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result)

Change log:
- improved communication protocol  see reply #252
- smoother Joystick behavior  (thanks Bob1943)
- automatically flip if the user turns device upside down  (thanks joepro)
- optimized layout  (thanks billcat)

Demo sketch: AndroTest V2.0       see reply #256

Please let me have feedback, including screenshots

Enjoy   ;)
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 16, 2014, 07:14 pm
@thornlv
Quote
Have tried the updated Andro_Pan_Tilt sketch but it did not work.
What happens is the servos centre and when I use the joystick I get a few lines of positions in serial monitor and then 'communication error' repeating lines. MyservoX changes to full 180 position  and stays there (motor whirring) whilst MyservoY does nothing.

Go to settings/About and confirm your actual App version
What is your Arduino board model ??
You don't need to connect motors before you get sensible readings on your Serial Monitor

Quote
BT TX to D0, Servos to 9 and 10 (BT RX not used ?)

Yes, no need to send data back to your phone
Title: Re: Android Bluetooth joystick
Post by: thornlv on Jun 16, 2014, 10:27 pm
Hi Kas
App is V4 and the board is a Uno v3

Hope this helps
Cheers, Vic
Title: Pan & Tilt demo
Post by: kas on Jun 17, 2014, 10:48 am
@thornlv
Sorry guy, I was too self confident in modifying the code and not testing it  :smiley-red:
I just modified my code (reply #354)
Now fully tested on Serial Monitor ;)

Please upgrade and use Joystick BT Commander V5.0
Title: Re: Android Bluetooth joystick
Post by: thornlv on Jun 17, 2014, 12:27 pm
Hi Kas.

Have briefly tried it and it works ok, will give a thorough test when I have finished my domestic duties today by order of her indoors  ;)

Cheers mate

Vic
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 17, 2014, 02:00 pm
Quote
Hi Kas.
Have briefly tried it and it works ok, will give a thorough test when I have finished my domestic duties today by order of her indoors   ;)

Cheers mate
Vic


Great  :)
Remember, you can adjust Zero position, max move and motors direction
When you have time, please post a video showing both App screen and moving gimball

Title: Re: Android Bluetooth joystick
Post by: thornlv on Jun 17, 2014, 09:01 pm
Hi Kas

Gave it a good going over, everything works ok. going to work out how to adjust maximum movement as I dont need full 180 deg field - at around 90deg for pan and 45 for tilt. Next will be to include an old HTC phone to act as a 'monitor' with V5 - because live view with a 300/600mm lens is a narrow field which makes it difficult to adjust position for the subject, I see the option of a 'wider angle' view on the smart phone will aid that much more quickly - I will try to show you what I mean when record a video of the intended set up.

Many thanks.#

Vic
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 21, 2014, 10:37 am
Quote
hi kas , i saw your nice app and i thought telling you a problem that  i have with my app.. well my hc-06 disconnects in really random times.. it might work for 10 minutes or more with no problem while on the other hand it might start disconnecting again and again without being able to understand why..
Any ideas why this might happening?

Thank you  :) :)


@zaxarias

Some shots in the dark
- Your board is resetting due to high load, use a separate power supply for Arduino
- intermittent contact within breadboard, move and secure components
- defective BT board, not an expensive item, try a spare one

Let us know the outcome
Title: Re: Android Bluetooth joystick
Post by: jaapdemaat on Jun 21, 2014, 08:35 pm
Hi All,
Ive been using this app (v5) for my remote controlled filling cabinet project. https://vimeo.com/98759560
Kas has been helping intensively both with customizing the app and the Arduino code.
Attached is the final code I used, incl distance sensor feedback & Battery level and lots more.

Hardware: Arduino mega, DC Motor Driver 2x 15A - Lite,  BT2S Bluetooth to Serial Slave, HC-SR04 Distance Sensors, Pride electric wheel chair, blood sweat and tears. You can find more making of videos on: https://vimeo.com/jaapdemaat/videos.

Title: Re: Android Bluetooth joystick
Post by: john_lenfr on Jun 22, 2014, 12:56 pm
Bonjour Kas, juste pour confirmer que l'appli fonctionne avec le programme exemple:
Quote
AndroTest V2.0 - @kas2014
demo for V5.x App


Et avec :
Quote
Samsung Galaxy Note 3
Android 4.4.2


Quote

HC 05 bluetooth module


Acheté ici:
http://www.dx.com/p/hc-05-wireless-bluetooth-serial-pass-through-module-w-backboard-green-blue-298911#.U6a0QPl_sjE


Je n'ai pas encore testé en détail (j'ai remarqué qu'il y a pleins d'options)mais je voulais te féliciter pour ton travail qui a l'air énorme!

Les seuls points négatifs que j'aurais à redire sont sur la communication de ton programme, mais je te rassure ce sont des points de détails comparé au reste de ton travail:
- Tu devrais éditer ton premier post pour mettre ton versionning en sens inverse: le plus récent en haut de la liste (on a plus l'habitude que ce soit dans ce sens et ça perturbe pour trouver la bonne info)
- Pour les renvois vers les posts des version etc fais juste un lien hypertext sur le post en question par exemple si tu parles de la réponse #256 tu la transforme en #256 (http://forum.arduino.cc/index.php?topic=173246.msg1766646#msg1766646) c'est de suite plus pratique.
- Pour le coté GooglePlay met un lien direct vers le programme exemple (fichier .ino) car sinon il faut venir sur ce post, chercher la dernière version, et ensuiite se rendre à la réponse #256 pour enfin faire un copier/coller du code: le nombre de manip est rebuttant et cela peut causer problème pour une personne qui s'y connait pas trop mais qui voudrait utiliser ton appli.

Encore une fois ce sont des critiques constructives pour que tu puisse faire partager cet excellente application à encore plus de monde!

;)
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 22, 2014, 01:00 pm
Quote
Hi All,
Ive been using this app (v5) for my remote controlled filling cabinet project. https://vimeo.com/98759560
Kas has been helping intensively both with customizing the app and the Arduino code.
Attached is the final code I used, incl distance sensor feedback & Battery level and lots more.

Hardware: Arduino mega, DC Motor Driver 2x 15A - Lite,  BT2S Bluetooth to Serial Slave, HC-SR04 Distance Sensors, Pride electric wheel chair, blood sweat and tears. You can find more making of videos on: https://vimeo.com/jaapdemaat/videos.



For info
Jaap is a senior graphic designer (http://www.studiojoepjacobs.co.uk/), based in Rotterdam and London
The Cabinet ("I Know What You Did Last Summer") is currently exhibited at the Royal College of Art (http://www.rca.ac.uk/news-and-events/events/show-rca-2014/), in London, up to June 27th
(http://i.imgur.com/iyrWjWu.jpg)

@Jaap,
Thanks again for your hospitality in London, I really enjoyed entering your universe for a while


Title: Re: Android Bluetooth joystick
Post by: john_lenfr on Jun 22, 2014, 03:23 pm
Hello Kas,

I made a first test with a turet of servos. I have a problem and servos are "ticking" even if there is no command.
The problem is more visible when I am in "FAST" mode (compare to the "SLOW" mode)

Because my english is very poor I made a video:
http://www.youtube.com/watch?v=bSABrto4lxg

Do you understand the problem? How can I do to solve it?

Thanks!

Par ailleurs tu m'avais demandé un imprim écran de l'appli, la voici en PJ.

Title: Re: Android Bluetooth joystick
Post by: kas on Jun 22, 2014, 05:58 pm
Quote
Hi All,
Ive been using this app (v5) for my remote controlled filling cabinet project. https://vimeo.com/98759560
Kas has been helping intensively both with customizing the app and the Arduino code.
Attached is the final code I used, incl distance sensor feedback & Battery level and lots more.

Hardware: Arduino mega, DC Motor Driver 2x 15A - Lite,  BT2S Bluetooth to Serial Slave, HC-SR04 Distance Sensors, Pride electric wheel chair, blood sweat and tears. You can find more making of videos on: https://vimeo.com/jaapdemaat/videos.



For info
Jaap is a senior graphic designer (http://www.studiojoepjacobs.co.uk/), based in Rotterdam and London
The Cabinet ("I Know What You Did Last Summer") is currently exhibited at the Royal College of Art (http://www.rca.ac.uk/news-and-events/events/show-rca-2014/), in London, up to June 27th
(http://i.imgur.com/iyrWjWu.jpg)

@Jaap,
Thanks again for your hospitality in London, I really enjoyed entering your universe for a while


Title: Re: Android Bluetooth joystick
Post by: kas on Jun 22, 2014, 06:08 pm
Quote
Je n'ai pas encore testé en détail (j'ai remarqué qu'il y a pleins d'options)mais je voulais te féliciter pour ton travail qui a l'air énorme!

Les seuls points négatifs que j'aurais à redire sont sur la communication de ton programme, mais je te rassure ce sont des points de détails comparé au reste de ton travail:
- Tu devrais éditer ton premier post pour mettre ton versionning en sens inverse: le plus récent en haut de la liste (on a plus l'habitude que ce soit dans ce sens et ça perturbe pour trouver la bonne info)
- Pour les renvois vers les posts des version etc fais juste un lien hypertext sur le post en question par exemple si tu parles de la réponse #256 tu la transforme en #256 c'est de suite plus pratique.
- Pour le coté GooglePlay met un lien direct vers le programme exemple (fichier .ino) car sinon il faut venir sur ce post, chercher la dernière version, et ensuiite se rendre à la réponse #256 pour enfin faire un copier/coller du code: le nombre de manip est rebuttant et cela peut causer problème pour une personne qui s'y connait pas trop mais qui voudrait utiliser ton appli.

Thanks  john_lenfr for the comments, feedback is always welcome
I will definitely add more links to reply #1 (http://forum.arduino.cc/index.php?topic=173246.msg1286706#msg1286706)  ;)


Quote
I have a problem and servos are "ticking" even if there is no command.

not normal behavior  :smiley-roll-blue: :smiley-roll-blue:
Possibly electric noise or MCU internal timers interaction
please post your full code, I will try it on my side

What happens if you comment
Code: [Select]
 sendBlueToothData();


Let me know

EDIT: which Arduino model are you using ??
Title: Re: Android Bluetooth joystick
Post by: john_lenfr on Jun 22, 2014, 06:23 pm

not normal behavior  :smiley-roll-blue: :smiley-roll-blue:
Possibly electric noise or MCU internal timers interaction
please post your full code, I will try it on my side

You wrote here (http://forum.arduino.cc/index.php?topic=173246.msg1307645#msg1307645) that Softserial doen'nt work with servo lib. It is always true?


Quote
What happens if you comment
Code: [Select]
 sendBlueToothData();

The problem is less visible but ticking  is always here :( (and data 3 is not updated on Android screen of course)
Quote

Let me know

Here is my starting skech I use attached.
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 22, 2014, 08:43 pm
Quote
You wrote here that Softserial doen'nt work with servo lib. It is always true?

Try
https://www.google.com/search?hl=en&as_q=%22SoftwareSerial%22+%22servo%22+%22library%22+arduino&as_epq=&as_oq=&as_eq=&as_nlo=&as_nhi=&lr=&cr=&as_qdr=all&as_sitesearch=&as_occt=any&safe=images&tbs=&as_filetype=&as_rights=&gws_rd=ssl
and see for yourself  ;)

I tried your sketch, removing Wire and snootor references; serial monitor readings are 100% stable
Please upload Pan & Tilt demo sketch at reply #242 (http://forum.arduino.cc/index.php?topic=173246.msg1763147#msg1763147)

//  Arduino pin #0 to TX BlueTooth module
// BT TX to be disconnected from D0 during sketch upload
// pinServo_X=9        pinServo_Y=10

Do not use SoftwareSerial for the moment, let me know how it works
Which Arduino board are you using ??

Title: Re: Android Bluetooth joystick
Post by: john_lenfr on Jun 22, 2014, 09:23 pm
Quote
Try
https://www.google.com/search?hl=en&as_q=%22SoftwareSerial%22+%22servo%22+%22library%22+arduino&as_epq=&as_oq=&as_eq=&as_nlo=&as_nhi=&lr=&cr=&as_qdr=all&as_sitesearch=&as_occt=any&safe=images&tbs=&as_filetype=&as_rights=&gws_rd=ssl
and see for yourself  ;)

What is the lib that I have to choose because the link is your google search?

Quote
I tried your sketch, removing Wire and snootor references; serial monitor readings are 100% stable
Please upload Pan & Tilt demo sketch at reply #242 (http://forum.arduino.cc/index.php?topic=173246.msg1763147#msg1763147)

Yes, I saw that values are OK and 100% stable.

Quote
//  Arduino pin #0 to TX BlueTooth module
// BT TX to be disconnected from D0 during sketch upload
// pinServo_X=9        pinServo_Y=10
Do not use SoftwareSerial for the moment, let me know how it works
Which Arduino board are you using ??

Tested your Pan&Tilt V3.6 there is no ticking, but when I test it servos are not staying in position (but I think it is because of the code):
http://www.youtube.com/watch?v=DBu2DoXk3hA

So, what is the last Softserial I have to choose to do the last test?

My board is an Uno, you can't see it on vids?  :smiley-mr-green:
Title: Re: Android Bluetooth joystick
Post by: john_lenfr on Jun 22, 2014, 09:25 pm
So now I will test the first program, but with 0 and 1 serial

EDIT: Ok I tested with Demo code AndroTest V2.0 and no ticking but same problem as the video on post above
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 23, 2014, 09:05 am
For the servo's test, please go to "settings/joystick properties" and uncheck "Auto return to center"

So, the servo's are jerking, but the values are stable in the serial monitor ??
Are the servo's jerking only near joystick limit positions (-100 or +100) ??

I remember having problems with digital servo's, some years ago  :smiley-roll:
some wouldn't accept the total 0 to 180° rotation range

Just to make sure, please modify code to limit range to 45 to 135°
Code: [Select]

 joyX = map(joyX, -100, 100, 135, 45);
 joyY = map(joyY, -100, 100, 45, 135);  



if it works, you may try
Code: [Select]

 joyX = map(joyX, -100, 100, 170, 10);  
 joyY = map(joyY, -100, 100, 10, 170);

Title: Re: Android Bluetooth joystick
Post by: john_lenfr on Jun 23, 2014, 12:22 pm
Ok I will test it soon as possible.

Many thanks for quick replies ;)
Title: SoftwareSerial limitations
Post by: kas on Jun 23, 2014, 02:14 pm
I just tried running two servo's using SoftwareSerial on pins #2 & #3, and also got the "Tick-Tick syndrom"
SoftwareSerial disables interrupts while sending a byte.
This interferes with the Servo library, which relies on timer interrupts

The hardware Serial port should always be used, if possible, before considering SoftwareSerial.
Additional readings (http://pharos.ece.utexas.edu/wiki/index.php/Resolving_the_Conflict_between_SoftwareSerial_and_Servo_on_the_Traxxas)

Possible options
- drop SoftwareSerial and use pins #0 and #1 (disconnect pins before uploading sketch)
- try using ServoTimer2 or AltSoftSerial libraries that use a different timer (not tested)
- get an Arduino Mega which has additional hardware serial ports


Title: I Know What You Did Last Summer
Post by: kas on Jun 23, 2014, 04:57 pm
Jaap, this is FilingCab V1.6
PWM frequency was boosted from 490Hz to 20KHz to get rid of hissing noise at low speed
Also the infamous SoftwareSerial library was dropped  ]:)

Serial:
- move pin #11  to  RX1 (pin #19)
- move pin #12  to  TX1 (pin #18)

PWM:
- move pin #5   to  pin #11
- move pin #6   to  pin #12

Smoother and quieter control

Happy driving, mind the stair  ;)


Title: Total RC commander V5.0
Post by: kas on Jun 25, 2014, 07:52 pm
@tolisn63
Quote
Quote
Any idea when Total RC commander will be available with the new protocol and a test sketch ?

Will wait for Joystick BT commander V5.0 feedback
Would say two or three weeks


The video App is now ready for test
Same demo sketch as Joystick BT commander V5.0

Check your mail and let me have your feedback  ;)
Title: Re: Android Bluetooth joystick
Post by: magicjackho on Jul 08, 2014, 05:29 am
I can't really get onto google play and download the app from China
can anybody send me the app to my email
or send me another link to download
thankyou very much!
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 08, 2014, 10:05 am
Quote
I can't really get onto google play and download the app from China
can anybody send me the app to my email (xxx-xxx@qq.com)
or send me another link to download
thank you very much!


Hi magicjackho, welcome to the Forum
Check your mail ;)

I sent you V5.2 to be published on Google Play within a few weeks
Should you need support, this is the place

Let me have a screenshot of the Application

@All     ** I NEED screenshots **
this my only way to optimize display layout for your specific device  :)

Personal advice:
To avoid spamming, I suggest you edit your message and remove your email info   ]:)

Title: Re: Android Bluetooth joystick
Post by: twm47099 on Jul 26, 2014, 07:10 pm
I've downloaded version 5 to my Samsung tablet 4.  I cannot find a way to get to a settings screen.  I have BT turned on, but I have not yet paired it to a device.  Does that make a difference?  How do I find a settings screen.

Thanks
Tom
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 27, 2014, 07:05 am
Hi Tom

Quote
I have BT turned on, but I have not yet paired it to a device. 
Does that make a difference?

No, you should access option screens w/o pairing

Quote
I've downloaded version 5 to my Samsung tablet 4. 
I cannot find a way to get to a settings screen.

Are you talking about this one (http://www.amazon.com/Samsung-Galaxy-Tab-7-Inch-White/dp/B00J8DL78O) ??

Let me know
Title: Re: Android Bluetooth joystick
Post by: twm47099 on Jul 27, 2014, 05:34 pm
Thanks for the quick response.

The tablet I have is the 8-inch version:
http://www.amazon.com/Samsung-Galaxy-Tab-8-Inch-White/dp/B00JKCH4V2/ref=sr_1_1?s=electronics&ie=UTF8&qid=1406474905&sr=1-1&keywords=Samsung+Galaxy+Tab+4+%288-Inch%2C+White%29 (http://www.amazon.com/Samsung-Galaxy-Tab-8-Inch-White/dp/B00JKCH4V2/ref=sr_1_1?s=electronics&ie=UTF8&qid=1406474905&sr=1-1&keywords=Samsung+Galaxy+Tab+4+%288-Inch%2C+White%29)

I can't find any active areas on the screen except for the joystick and 6 buttons.  There is also the pulldown notifications panel that is used to turn on the different table functions (wifi, location, bluetooh, etc).

Thanks
Tom
Title: Samsung Galaxy Tab 4 ** Menu button **
Post by: kas on Jul 27, 2014, 06:59 pm
Samsung has finally killed the dedicated menu button, replacing it with a task-switching key  :smiley-eek-blue:

Try pressing and holding this left button for a few seconds
Should bring the Option menu

Let me know if it works  ;)
Title: Re: Android Bluetooth joystick
Post by: twm47099 on Jul 27, 2014, 10:11 pm
Thanks that worked.  Where did you find that?

Tom
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 28, 2014, 08:08 am
Quote
Thanks that worked

Glad to help

Quote
Where did you find that?

I used a new service called "Search Engine"   ;)  ;)  ;)
Try it:
https://www.google.com/search?hl=en&as_q=%22menu+button%22+%22tab+4%22+samsung&as_epq=&as_oq=&as_eq=&as_nlo=&as_nhi=&lr=&cr=&as_qdr=all&as_sitesearch=&as_occt=any&safe=images&tbs=&as_filetype=&as_rights=&gws_rd=ssl#as_qdr=all&hl=en&lr&q=%22menu+button%22+%22galaxy+tab+4%22+youtube

Can you connect now to your Arduino ??



Title: Re: Android Bluetooth joystick
Post by: twm47099 on Jul 28, 2014, 02:29 pm
Duh!! Usually google is my friend, but sometimes I don't know what to ask.

I'm using a Propeller MCU.  I have C and Forth programs I wrote (using yours as a basis) for the previous protocol.  I've got to make a few changes for the new protocol. 

Thanks again,
Tom
Title: Re: Android Bluetooth joystick
Post by: kas on Jul 29, 2014, 08:10 am
Quote
I'm using a Propeller MCU.  I have C and Forth programs I wrote (using yours as a basis) for the previous protocol.  I've got to make a few changes for the new protocol. 


Tom,

I started learning MCU's using Basic Stamps, I would really appreciate to have AndroTest V2.0 demo sketch
ported to the Propeller environment and offered to the Parallax Community.

Keep us aware of your progress, be sure you will get full support for this task   :) :) :)

Title: ** Joystick Bluetooth Commander V5.2 **
Post by: kas on Aug 01, 2014, 05:44 pm
Joystick Bluetooth Commander Version 5.2  has just been published on Google Play
(https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result)

Change log
new features:
- Manual return to center Button is displayed when "Auto return to center" is unchecked (thanks Artouste)
- "automatically flip if device turned upside down" is now an option, to maintain compatibility with
    early Android versions  (thanks joepro)
- Additional on screen Option button for new devices w/o dedicated Menu button (thanks twm47099)

Fixes:
- Fixed possible racing conditions at App start up (flickering buttons)
- Various minor improvements

 Demo sketch:   AndroTest V2.0   (communication protocol unchanged)    see reply #256



 Total RC Commander (with live video display) is also available.    Demo (http://forum.arduino.cc/index.php?topic=236401.msg1699561#msg1699561)
(http://i.imgur.com/ylTIAWT.jpg)
Please contact me via PM

Enjoy  ;)



Title: Re: Android Bluetooth joystick
Post by: twm47099 on Aug 02, 2014, 02:31 am

Quote
I'm using a Propeller MCU.  I have C and Forth programs I wrote (using yours as a basis) for the previous protocol.  I've got to make a few changes for the new protocol. 


Tom,

I started learning MCU's using Basic Stamps, I would really appreciate to have AndroTest V2.0 demo sketch
ported to the Propeller environment and offered to the Parallax Community.

Keep us aware of your progress, be sure you will get full support for this task   :) :) :)




I've written a C program to use BT Commander with the Parallax Propeller ActivityBot.  So far I have the sections that (1) use a separate core to read the bluetooth data, translate the data to x & y (or button value) and transfer the results to the main core that continuously loops through the drive commands, (2) take the Joystick position and send drive commands to the bot, and (3) read the buttons -- I only have 2 buttons programmed so far, E-stop and Quit, but I intend to use the buttons to turn on an ultrasonic range finder and the Pixy color tracker.  I still have not gotten my head around the method for building the data frame for sending data to the android.  I want to use that to send range data from the UT range finder, but I'm trying to work out how I want to change numbers to ascii for the data frame.  Your sketch is a help, but the library functions are different so I try to port the concepts rather than the code.

Two questions -- 1. Does the data sent have to include values for all data fields?  Or can some be left out?
      2.  When the button status is sent to the android device, is it echoed back to the bot?

The code listing is at post 7 in the following thread:
http://forums.parallax.com/showthread.php/154687-EZ-Bluetooth-in-***C***-and-a-nice-App (http://forums.parallax.com/showthread.php/154687-EZ-Bluetooth-in-***C***-and-a-nice-App)

Tom

Title: Re: Android Bluetooth joystick
Post by: kas on Aug 02, 2014, 11:48 am
My suggestion:  Keep . It . Simple   ;)

Start with a program that parses data received from Android and just does that
It's final mission is to display (X,Y) joystick position and report button pushes
For data feedback to Android, just aknowledge button status on datafields phone screen.
You will find it much more confortable not to care about robot, motors and sensors at this development stage

Your PC screen should look pretty much like that:
(http://i.imgur.com/YAulg3u.png)


In a second step, you may add debug facilities to your program
You will then chase communication errors and possibly adjust timing and code to reduce them
- Joystick errors
- Buttons errors
- data frame errors
- total data frames received

(http://i.imgur.com/mIKMkEP.png)
One Joystick (trapped) error out of 17530 received frames, not bad with Bluetooth

This is my Print debug function that reports possible errors:
Code: [Select]
void printDebug(int nByte)  {
static int buttonErr=0, joyErr=0, frameErr=0;
static long frames=0;

 frames++;
 if(nByte==2)     {                                                                // button data   < STX X ETX >
   if(cmd[1]>64 && cmd[1]<77 && cmd[2]==ETX)  {
     Serial.print("buttonStatus: "); Serial.print(buttonStatus);
     Serial.print("  bin: ");        Serial.println(getButtonStatusString());    
     Serial.print("Button: ");
   }  else { buttonErr++;   Serial.print("** Button error **: "); }
 }

 else if(nByte==7)  {                                                             // Joystick data   < STX  XXX YYY ETX >
   boolean dataOK = cmd[1]>48 && cmd[1]<52 && cmd[2]>47 && cmd[2]<58 && cmd[3]>47 && cmd[3]<58
                 && cmd[4]>48 && cmd[4]<52 && cmd[5]>47 && cmd[5]<58 && cmd[6]>47 && cmd[6]<58
                 && cmd[7]==ETX;
   if(dataOK)           Serial.print("Joystick: ");                              // digits within range
   else                { joyErr++;   Serial.print("** Joystick error **: ");  }
 }

 else         { frameErr++; Serial.print("** data frame error **: "); }          // wrong Byte number
 
 Serial.print("< ");                                                             // print incoming Bytes
 for(int j =0; j<nByte+1; j++)   { Serial.print(cmd[j]); Serial.print(" "); }
 Serial.print(">  ");  

 Serial.print(buttonErr); Serial.print("-");                                     // print errors status
 Serial.print(joyErr);    Serial.print("-");  
 Serial.print(frameErr);  Serial.print("-");
 Serial.println(frames);
}



Finally, adapt a copy of your program to drive the ActivityBot



Quote
Two questions --
1. Does the data sent have to include values for all data fields?  Or can some be left out?

No, just send the delimiters:
- Standard frame:
Code: [Select]
< STX   Buttons state   0X01   DataField#1   0x04   DataField#2   0x05   DataField#3   ETX >  - DataField#2 and #3 omited:
Code: [Select]
< STX   Buttons state   0X01  DataField#1  0x04   0x05  ETX >  


Quote
2.  When the button status is sent to the android device, is it echoed back to the bot?

It was the case in V4, now fixed in V5
MCU feedback did generate a "onCheckedChanged" Android event that trigged a new button data frame to MCU
In some situation, data could flow back and forth and gererate buttons flickering
Now button info sent from Android to MCU is echoed back (Buttons state) by MCU to Android, that's it

Good luck   ;)



Title: Re: Android Bluetooth joystick
Post by: twm47099 on Aug 02, 2014, 08:46 pm
Thank s for the info.  I actually did use the approach you described.  First I just read the buttons & printed the value to make sure that the android would communicate.  Next I added code to differentiate joystick from button data.  Then I moved the reading of the data from andriod to a different core and printed the results from the main core.

That was where I found a problem.  When transferring data between cores the Propeller automatically syncs the transfer for 1 variable.  For transferring groups of related data (x & y from the same time) the programmer has to handle it.  When the program printed x & y it was taking x & y from separate sequential data sets.  So I added a couple of global variables 'okwrite' and 'okread' to keep things sync'd.

Once I did that, I added code to calculate the scaled motor wheel speeds and the method for adding the turn values, with a printout of x, y, base speed, turn values, and modified speed.  Once I got reasonable values, I added the actual drive commands, the E-stop command (I had included the quit code in the first button reading step.)

My next steps are tuning the drive speeds and x y to speed scaling, sending data to the android (which I'll do in one of the earlier / simpler code versions), and then running things like pixy and ping.

I am glad that you deleted the android echoing of the button status since it complicated the code.

Tom

Title: Re: Android Bluetooth joystick
Post by: twm47099 on Aug 02, 2014, 08:51 pm
One other thing, I haven't seen any button or joystick errors yet, but for a roaming robot they may start as distances increase.   So I will port your error checking code. 

Thanks for the example.
Tom
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 04, 2014, 07:34 am
Quote
That was where I found a problem.  When transferring data between cores the Propeller automatically syncs the transfer for 1 variable.  For transferring groups of related data (x & y from the same time) the programmer has to handle it.  When the program printed x & y it was taking x & y from separate sequential data sets.  So I added a couple of global variables 'okwrite' and 'okread' to keep things sync'd.


I have no experience with multicore MCU's, so I may be wrong  :smiley-roll-blue:
What about combining  X & Y data into a single integer variable before transferring to the main core:
Code: [Select]
int joyData = joyX << 8  +  joyY
then parse back this value ??


Quote
One other thing, I haven't seen any button or joystick errors yet,

You may experience transmission errors when you start sending back data to the Android device
Title: Re: Android Bluetooth joystick
Post by: twm47099 on Aug 04, 2014, 07:12 pm

Quote
That was where I found a problem.  When transferring data between cores the Propeller automatically syncs the transfer for 1 variable.  For transferring groups of related data (x & y from the same time) the programmer has to handle it.  When the program printed x & y it was taking x & y from separate sequential data sets.  So I added a couple of global variables 'okwrite' and 'okread' to keep things sync'd.


I have no experience with multicore MCU's, so I may be wrong  :smiley-roll-blue:
What about combining  X & Y data into a single integer variable before transferring to the main core:
Code: [Select]
int joyData = joyX << 8  +  joyY
then parse back this value ??


I originally tried something like that, but it didn't work -- possibly because it was 3AM when I tried it.  I did that with the Forth code I wrote for your earlier versions of the app.  Although the flags method is easy and it works, I'd rather do it in one transfer rather than 2, so I'm going to try again.

Tom
Title: Re: Android Bluetooth joystick
Post by: twm47099 on Aug 05, 2014, 04:14 am
I revised the code that transfers the x & y data between cores (and it works).

The core that receives the BT data does the following:

Code: [Select]
joydata = (x<<10) | y;   //  x & y range from 100 to 300,  joydata is a global integer

The core that uses the data parses joydata:

Code: [Select]
yval = (joydata & 511) - 200;      //   yval ranges from -100 to +100
xval = (joydata >> 10) - 200;     //   xval ranges from -100 to +100
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 05, 2014, 07:06 pm
Quote
I revised the code that transfers the x & y data between cores (and it works).


I tried your code and got wrong results

Code: [Select]
unsigned int joyData;
int joyX, joyY;

void setup()  {
 Serial.begin(57600);
 
 // twm47099 code
 joyX = 280;    // 280-200 = 80
 joyY = 260;    // 260-200 = 60
 
 joyData = (joyX<<10) | joyY;                    // encoding
 // --------------------------------
 joyY = (joyData & 511) - 200;                   // decoding
 joyX = (joyData >> 10) - 200;
 Serial.print(joyX);  Serial.print("\t");  Serial.println(joyY);  Serial.println();
 // >> printed result:   -176 60  (not OK) <<


 
 // kas code
 joyX = 280;    // 280-200 = 80
 joyY = 260;    // 260-200 = 60

 joyData = (joyX-100 <<8) | joyY-100;              // encoding
 // --------------------------------
 joyX = (joyData >>8) -100;                        // decoding
 joyY = (joyData & 0xFF) -100;
 Serial.print(joyX);  Serial.print("\t");  Serial.print(joyY);
 // >> printed result:   80 60  (OK) <<
}

void loop()  {}


Probably due to data type implementation difference in Arduino and Propeller   :smiley-roll-blue: :smiley-roll-blue:
Title: Re: Android Bluetooth joystick
Post by: twm47099 on Aug 06, 2014, 03:40 am
Kas,
Interesting results.  It must be due to different number formats, or maybe the declaration of an unsigned integer?

Propeller C uses 32 bit integers.  I chose not to subtract 100, just to save a step.

Here's the code I ran on the Prop using both your and my methods.  I did declare joydata as an integer.

Code: [Select]

#include "simpletools.h"                      // Include simple tools
int joydata;
int joyY;
int joyX;
int x;
int y;

int main()                                    // Main function
{
  joyX = 280;       // x = 280-200 = 80
  joyY = 260;       // y = 260 - 200 =60

  //  Tom's Method
  joydata = (joyX << 10) | joyY;
  printi ("joydata = %b    %d\n", joydata, joydata);
  y = (joydata & 511) -200;
  x = (joydata >> 10) -200;
printi ("x = %d     y = %d\n\n", x, y );
  // results copied below
  // joydata = 1000110000100000100    286980
// x = 80     y = 60

  // Kas Method
  joydata = (joyX -100 << 8) | joyY - 100;
  printi ("joydata = %b    %d\n", joydata, joydata);
  y = (joydata & 0xFF) - 100;
  x = (joydata >> 8) - 100;
  printi ("x = %d     y = %d\n\n", x, y );
  // results copied below
  // joydata = 1011010010100000    46240
  // x = 80     y = 60
}

Title: Re: Android Bluetooth joystick
Post by: twm47099 on Aug 06, 2014, 03:51 am
I tried it again declaring joydata as an unsigned integer, and I got the same results I got in the above post.

Tom
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 07, 2014, 08:05 am
Your binary format printout explains it all:
 // Propeller joydata = (280 << 10) | 260  =  100  01100001  00000100  =  286980    
 // Arduino joydata   = (180 <<  8 ) | 160    =            10110100   10100000   =    46240

All methods are OK using Arduino _long_ integers (32 bits)

16 bit Arduino _unsigned_ integer does overflow when shifted 10 times
as 286980  >  65535 (2^16 -1)

even 16 bit Arduino _signed_ integer does overflow when shifted 8 times
as 46240  >  32767 (2^15 - 1)

Quote
I tried it again declaring joydata as an unsigned integer, and I got the same results I got in the above post

Still more room, this is luxury  ;)
Title: Re: Android Bluetooth joystick
Post by: thornlv on Aug 24, 2014, 09:15 pm
Hi Kas

Been a while since replied - holidays et al.

Anyway have uploaded a vid on my youtube channel here http://youtu.be/9d16H1JVMLk (http://youtu.be/9d16H1JVMLk), as you can see it works but have a few issues with it.

Only works fully only if powered by USB for both servos and arduino, I have constructed a prototype shield which enables me to power them independently of each other, I can also jump power to servos form arduino uno power input (battery, USB).

If I power them independently, then the servos are erratic or go full 180 degs lock - not ideal as I wont have USB power in the field.

Have tried some similar ways of control of which independent power works ok - example here http://youtu.be/bnlbc1swaTU (http://youtu.be/bnlbc1swaTU).

have not played with the code to slow down movement or limit travel, need to resolve the power first.

Also as my HC06 has gone belly up, I bought another HC05 (CZ-HC-05 , gomcu) which works fine, albeit at 9600 baud. Cant seem to configure it with your HC-05 configurator - get comm error, so I have modified the sketch to 9600 - works fine apart from the power issue.

any thoughts
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 25, 2014, 06:06 pm
Hi Vic,

Quote
Only works fully only if powered by USB for both servos and arduino, I have constructed a prototype shield which enables me to power them independently of each other, I can also jump power to servos form arduino uno power input (battery, USB).

If I power them independently, then the servos are erratic or go full 180 degs lock - not ideal as I wont have USB power in the field.
Have tried some similar ways of control of which independent power works ok - example here


I don't see any reason why the two App's would behave differently  :smiley-sad-blue: :smiley-sad-blue:
I would have expected better results with separate power, as USB is 5 Volts by nature and servo's need 6 Volts
Are your servo's Analog or digital ??   the solution is probably here (http://forum.arduino.cc/index.php?PHPSESSID=egeiptihum54ctb9ru29b5hmf0&topic=173246.msg1776726#msg1776726)

Finally, please post the sketches for the two controllers

Title: Re: Android Bluetooth joystick
Post by: kas on Aug 26, 2014, 10:44 am
from Google Play:
Quote
Awesome I use this great app to control my arduino-based tank. The developer seems very willing to provide a support and updates. For example he compiled a special version for me, when I was having some problems with the official release. Thanks
Jakub Topi?


Thanks Jakub for this nice feedback, much appreciated   :)
Title: Re: Android Bluetooth joystick
Post by: thornlv on Aug 26, 2014, 10:41 pm
Hi Kas

Have been doing tests today and taking power readings, but to recap

Forget what I said about it being fine with the other app/controller, it suffers the same

When testing the setup using USB power, everything is fine - I took reading of the power at all points, have a steady 5v. Because it is only a mock setup, the servos move the gimbal head fine in each axis (pan/tilt), I have even edited your sketch to my preferred angles.

The 2 servos I am using are Futaba s3003 for pan (4.8 - 6v, 3.2/4.1kg torque) and a Goteck GS-5515MG for tilt(4.8-6v, 13.2/15kg torque), Both analog. The tilt needs a powerful servo as the s3003 just doesn't budge it at all. This setup works fine in Radio Control mode as each servo gets 6v from the RC Reciever - this is moving 6kg of camera/lens.

In mock up test, using USB power and camera/lens loaded - pan is fine. tilt is just about enough but cant go too far as it then needs a 'hand' back to zero, but at least it shows the potential i want.

Problems start when I want separate power for Arduino/BT and servos, cant use USB power in the field.
I will be using batteries, 4xAA 1.5v (6v) for Arduino/BT power and 5x 1.2V AA NiMH (6v, 2700 mAh) for the servos

In that setup, one of the servos locks at full 180, the other will be fine.

If I power the Ard/BT and servos with just the 4xAAs, no lock up, pan is fine, tilt is not locked but not enough power to move the camera/lens (see above, its ok with mock setup - no camera)

So this led me to measure the voltages at each point and discovered the voltage drops to 4.03v - bluetooth works/connects, pan works (does not need much torque, so the S3003 is probably given less torque than the specs), tilt just doesn't cut the mustard - this needs the torque (about 10kg I reckon)

Not sure what is happening here, does seem a power issue - as I said USB power fine, steady 5v at all points, battery 6v potential, but drops to just above 4v  :~

have included photos of BT module and my proto-shield (note also, this happens with breadboard tests making same circuits)

https://www.flickr.com/photos/birdincamera/15043545821/ (https://www.flickr.com/photos/birdincamera/15043545821/)
https://www.flickr.com/photos/birdincamera/14860030248/ (https://www.flickr.com/photos/birdincamera/14860030248/)

also, edited sketch using:

Code: [Select]
#define VERSION     "\n\nAndro_Pan&Tilt V3.6 - @kas2014\n** Stepper demo for V5.x App **"

// Controls two servo motors

// V3.6: Android BT Commander V5.X compatible, no button data management
// V3.0: Android BT Commander V3.X compatible, no button data management
// V2.5 can receive both Byte & Integer data
// V2.0: removed SoftwareSerial

// Android BT Commander settings:
// Options/Options for advanced users/Data Range        >>>  -100 to +100
// Options/Options for advanced users/Refresh interval  >>>  50ms

//  Arduino pin #0 to TX BlueTooth module
// BT TX to be disconnected from D0 during sketch upload

#include <Servo.h>

boolean    DEBUG =         true;

#define    pinServo_X     3              //Pan
#define    pinServo_Y     2              //Tilt
#define    STX            0x02
#define    ETX            0x03
#define    MIN_Y          45             // vertical move limitation
#define    MAX_Y          180
#define    ZERO_Y         60             // vertical offset

byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};
Servo myservoX;                         // create servo objects
Servo myservoY;

void setup()  {
 Serial.begin(9600);
 myservoX.attach(pinServo_X);  
 myservoY.attach(pinServo_Y);  
 if(DEBUG)    Serial.println(VERSION);
}

void loop() {
  if(Serial.available())  {                            // data received from smartphone
   delay(2);
   cmd[0] =  Serial.read();  
   if(cmd[0] == STX)  {
     int i=1;      
     while(Serial.available())  {
       delay(1);
       cmd[i] = Serial.read();
       if(cmd[i]>127 || i>7)                 break;     // Communication error
       if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
       i++;
     }
     if(i==7)     setServoPosition(cmd);
   }
 }
}

void setServoPosition(byte data[8])    {
 int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
 int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
 joyX = joyX - 200;                                                  // Offset to avoid
 joyY = joyY - 200;                                                  // transmitting negative numbers

 if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // commmunication error
 
 joyX = map(joyX, -100, 100, 125, 55);   //  << adjust to change motor direction Pan
 joyY = map(joyY, -100, 100, 75, 105);   //  << adjust to change motor direction Tilt

 joyY+=ZERO_Y;
 joyY = constrain(joyY, MIN_Y, MAX_Y);
 myservoX.write(joyX);
 myservoY.write(joyY);
 if(DEBUG)    {Serial.print(joyX); Serial.print(", "); Serial.println(joyY);}
}


I am wondering, have I got a duff UNO - or is the HC-05 hogging power.

anyones help would be appreciated
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 27, 2014, 11:18 am
Quote
Hi kas

Since the vacation season for me is nearly over I started to finish my custom made 4WD chassis using Dagu 75:1 motors and wheels.

The parts that I will use are:
1. USB RoboClaw 2x15A Brushed DC Motor Controller
2. APM2.6 autopilot      https://code.google.com/p/ardurover/wiki/ArduRover2Setup
3. An arduino (probably the mega2560)
4. 7.2V/8Ah NI-Mh battery
5. You application for setting the modes of the APM2.6, viewing the route using the IP camera and for manual controlling the rover.

Can you help me interface your application with the arduino and the APM2.6?
What I was thinking is have the application send command to the arduino and then the arduino send R/C compatible signals to the APM2.6 autopilot. The Autopilot will send control signal to the motor controller.

My goal is to have a waypoint following rover using the apm2.6 and also be able to control the rover in manual mode using your application.

let my hear your thoughts 



Hi tolisn63

Nice project   :P

Not too familiar with the ArduPilot Mega   :smiley-roll-blue:
I suspect APM2.6 (http://www.ardupilot.co.uk/) accepts only PPM (Pulsed Position Modulation) combined signal
You will need a PWM to PPM converter such as this one (http://www.ebay.com/itm/ATMEL-ATMEGA328P-AVR-PPM-Encoder-for-RC-Model-V1-0-Version-ge-/261440780853?pt=LH_DefaultDomain_0&hash=item3cdf15ba35) (6$ shipped).
Conversion could be made directly by Arduino, but requires interrupts and signal timing may become an issue, depending on other connected sensors

Keep us aware
Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Aug 27, 2014, 12:02 pm
Hi Kas

The apm auto pilot accepts both pwm(default setting) and ppm signals(using a jumper to invoke the mode) so there is no need for a converter.
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 27, 2014, 06:25 pm
Quote
The apm auto pilot accepts both pwm(default setting) and ppm signals(using a jumper to invoke the mode)

Beyond PWM data, what do you plan to send from BT Commander to APM  ??

How do you switch APM from autopilot to manual mode ??
Please post a link to the Operator's Manual
Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Aug 27, 2014, 10:04 pm
Hi Kas
please see my replies in red.

Quote
Beyond PWM data, what do you plan to send from BT Commander to APM  ??

Well, my goal is to use your app to steer the rover (via the apm) when in manual mode and also use the app to make the apm change modes.

Quote
How do you switch APM from autopilot to manual mode ??

Switching between modes is accomplished by changing pwm values on one channel. Thus when the pwm value is "A" the apm mode is "manual", when it is "B" the mode goes to "Auto" and so on.
Quote
Please post a link to the Operator's Manual

Unfortunately there is no user manual that can be downloaded, only online wikis depending on what type of vehicle you intend to use the APM on.
http://rover.ardupilot.com/wiki/table-of-contents/
http://plane.ardupilot.com/wiki/arduplane-setup/connecting-your-rc-gear/

keep the questions coming
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 28, 2014, 06:47 am
Quote
Switching between modes is accomplished by changing pwm values on one channel. Thus when the pwm
value is "A" the apm mode is "manual", when it is "B" the mode goes to "Auto" and so on.

What are the specific values for A & B ??
Can you point me to the wiki part where this is described in details

The objective is to create a third PWM output
If Button#1 == not pushed   then PWM = A  (manual mode, default)
If Button#1 == pushed           then PWM = B  (autopilot mode)
Korrect ??
Title: Re: Android Bluetooth joystick
Post by: woodygb on Aug 28, 2014, 03:19 pm
Quote
Problems start when I want separate power for Arduino/BT and servos, cant use USB power in the field.
I will be using batteries, 4xAA 1.5v (6v) for Arduino/BT power and 5x 1.2V AA NiMH (6v, 2700 mAh) for the servos

In that setup, one of the servos locks at full 180, the other will be fine.

If I power the Ard/BT and servos with just the 4xAAs, no lock up, pan is fine, tilt is not locked but not enough power to move the camera/lens (see above, its ok with mock setup - no camera)


This sounds like it might be just a simple wiring problem ... have you got both the battery pack GNDs linked?
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 28, 2014, 04:03 pm
Hi Vic,

Quote
Not sure what is happening here, does seem a power issue

Yes, highly probable
Check your ground connections as suggested by woodygb

Quote
When testing the setup using USB power, everything is fine

What is your actual USB 5V source ??   mAh available ??

Quote
So this led me to measure the voltages at each point and discovered the voltage drops to 4.03v

No drop when iddle ??
Is your battery pack brand new or used ??

According to Goteck GS-5515MG datasheet (4.8 & 6V):
(http://i.imgur.com/qOdfeuo.png)

2200mA at free run, means 5+ Amps at full load
This may be too much for a 2700mAh NiMH battery set
Try a 4000mAh+ battery pack

Any possibility to reduce required torque through better camera balance ??

Title: Re: Android Bluetooth joystick
Post by: thornlv on Aug 28, 2014, 05:54 pm
Hey, brilliant feed back - will check gnds etc - just undergoing testing with various power pack options - and remembered I have a 6000mAh power pack I use for emergency mobile phone/tablet, but it needs a full charge.

At moment its all a bit moot as my Nikon USB port has failed and needs a repair so wont be using the bt control tripod head until then   ---   :~ =( :( :smiley-sad-blue:
Title: Re: Android Bluetooth joystick
Post by: woodygb on Aug 28, 2014, 10:27 pm
I'm surprised that you couldn't give an immediate answer .... Oh well .

On the assumption that you have neglected to COMMON your GND's  ...do it ....and I suspect that your problem will go away.

http://electronics.stackexchange.com/questions/73503/multiple-voltage-sources-using-a-single-ground
Title: Re: Android Bluetooth joystick
Post by: thornlv on Aug 28, 2014, 11:24 pm
hi woody, this is just a quick look for me.

Quote
I'm surprised that you couldn't give an immediate answer .... Oh well


some clues. Wife, new washing machine, 3 days of washing needs to be done, out door window ledges need stripping, painted. big trip out tomorrow - get cameras charged, sandwiches made, hats coats boots ready, work out route to destination - dog needs walking etc etc - a husbands work is never done, no time for play. oh, and didn't really understand the question about grounds but your link is today's invaluable addition to my understanding on basic electronics so ta very much so when I get round to playing again will update - unless something else breaks. :P

Cheers
Vic
Title: Re: Android Bluetooth joystick
Post by: woodygb on Aug 28, 2014, 11:55 pm
Ah! .... OK... Vic.

The signal that you sent from the Arduino to the servo's needs to complete a return journey ...... it's return point of the loop is the  GND of the Arduino.

The normal return point of the signal entering the servo is the GND of the servo's battery pack.

So COMMON ( join ) the two battery pack GND's and the signal your sending to the servo's will not be forced to try and find an alternate  path.

If the signal couldn't find any route back ...E.G ...without the GND's being COMMONED ...something like a single servo would not work ... you however have two signal wires and I suspect that one of these ( probably the servo that goes hard over ) is being  used as a less than ideal route back to the Arduino's GND causing much wierdness.

Cheers Woody
Title: Re: Android Bluetooth joystick
Post by: thornlv on Aug 30, 2014, 01:21 pm
just had some time to play.

The issue was down to wiring, have tried a breadboard version of my circuit and then added a common ground back to the arduino for the servos (should I wire up as a 'starpointing' schematic ?).

as for power source for servos, I can now use 2700mAh NiMH batteries, when I used to use a RC transmitter, I knew I could get about 12+ hours. The servos will not be constantly moving, in fact repositioning would be very infrequent.

as for when I was testing the circuit for power I was using a PC usb port - about .5A

Balancing the camera/lens is quite easy. The gimbal head I am using takes very little effort in positioning - only needing a slight push with a finger whilst still remaining stable and without shake (can vary the amount of friction on both axis). The lens plate which attaches the camera/lens to the tripod head is marked for alignment, I have marked demarcation points for each lens combination so that whichever lens I use, i can quickly mount them and they will be balanced.

The heaviest setup I use needs a bigger servo for tilt than the pan. I could experiment to find what torque I need but this would mean buying more servos (even though some are cheap) but I already know that if the voltage drops below 5v the tilt servo may struggle. If use a lighter lens I would have plenty of torque (My current heaviest setup is 4kg, 9lbs)

I may in the future add a third servo for controlling zoom (my working lens is a fixed focal length prime). Now i have a stable circuit I will now play with angles and speeds.

I have also found a sketch to set the HC-05 - http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/?ALLSTEPS (http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/?ALLSTEPS)

Other thoughts I had, could there be a WiFi version, would/could I also need a version of the app that includes video feedback ?, battery charge indication.

Many thanks for the help, education.
Title: Re: Android Bluetooth joystick
Post by: woodygb on Aug 30, 2014, 06:22 pm
Happy to help.

Ignore the star pointing diagram.
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 31, 2014, 07:57 am
Quote
... display battery charge indication ...

easy  ;)
- enable Arduino >> Android communication (see AndroTest V2.0 demo sketch (http://forum.arduino.cc/index.php?topic=173246.msg1766646#msg1766646))
- bring a 4 Volts image of your battery level to Analog Input 0 using a resistive voltage divider (http://en.wikipedia.org/wiki/Voltage_divider)
- monitor A0 value every 1000ms
- send value to datafield#1
- if value < voltMin,  send  "** LOW Bat **"  message to datafield#3

Code: [Select]
void checkLowBat()  {                                            // check Low battery condition
 static long previousMillis = 0;                            
 long currentMillis = millis();
 if(currentMillis - previousMillis > checkLowBatInterval) {     // check every checkLowBatInterval milliseconds
   previousMillis = currentMillis;
   voltage = analogRead(Vpin) * K;                              // K: calculated according resistors values
   if(voltage < voltLimit)    displayStatus = "** LOW Bat **";  // send message to Android device
 }  
}

You can monitor both batteries, using A0 & A1



Quote
Other thoughts I had, could there be a WiFi version, would/could I also need a version of the app that includes video feedback ?

Should be possible
Total RC Commander (http://forum.arduino.cc/index.php?topic=173246.msg1702855#msg1702855) is a sister App that includes Video features through WiFi
(http://i.imgur.com/Ea7lXGt.png)
See the video in the Exhibition Section  (http://forum.arduino.cc/index.php?topic=236401.msg1699561#msg1699561)

Let me have more info about the video stream you want to display



Quote
I have also found a sketch to set the HC-05 - http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/?ALLSTEPS

Did you succeed in changing your BT card bps ??
The command line should be "at+uart=57600,0,0\r\n"

Title: Re: Android Bluetooth joystick
Post by: Olivier8604 on Aug 31, 2014, 08:10 am
i just want to say this is a good forum.etui galaxy tab 4 10.1 (http://www.etuigalaxytab4.com) housse galaxy tab 4 10.1 (http://www.etuigalaxytab4.com) etui samsung galaxy tab 4 10.1 (http://www.etuigalaxytab4.com)
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 31, 2014, 09:04 am
Quote
i just want to say this is a good forum  :) :)


Thanks  8)
Welcome to the Arduino Forum
Title: Re: Android Bluetooth joystick
Post by: thornlv on Aug 31, 2014, 12:02 pm
Just wanted to say this is NOT a good forum, much better than that - good is average.

With the HC05 configure sketch I was able to change its name, passcode and any baud rate I chose - however ending in ,0,0 did not work - AT+UART=57600 did.

Many thanks, now to walk the dog, pack clothes ready for a short break in Wales - will tinker more when I am back.

Cheers.

Vic
Title: Re: Android Bluetooth joystick
Post by: woodygb on Sep 04, 2014, 10:47 am


I'd suggest that you use a logic like this....to operate the motor switches from the X Y inputs and let the "autonomous" routine take care of itself.

NOTE:- I haven't bothered to check if the < >  are matched correctly to the motor directions

if JoyY  > 10 .... forward  .............( 10 used as an arbitrary  "deadband")
if JoyY  < -10 ..... backward

if JoyX  > 10 ..... turnright
if JoyX  < -10 ..... turnleft

else  ...  motorwiper()     ("autonomous" routine ?)

add in button press logic to suit yourself.... ON/OFF  ...Joystick input only ..  etc

http://arduino.cc/en/Reference/Return ...you seem to be using them without need.
Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Sep 05, 2014, 07:08 am
Hi Kas
I'm struggling to find information regarding the signals required but this is very slow. Other forums are not near as active as this one.
Anyway, this is what I found out so far.
In order to switch between the modes, the apm requires a signal that has one of the three values.
with a signal of 1200 it will go to Auto, 1500 it will go to LEARNING and 1800 it will go to Manual. This is one PWM output.

Another PWM output controls the add and delete waypoint (yet to determine the values)

Two more PWM channels are used for throttle and direction control (probably normal R/C PWM control values) .





Quote
Switching between modes is accomplished by changing pwm values on one channel. Thus when the pwm
value is "A" the apm mode is "manual", when it is "B" the mode goes to "Auto" and so on.

What are the specific values for A & B ??
Can you point me to the wiki part where this is described in details

The objective is to create a third PWM output
If Button#1 == not pushed   then PWM = A  (manual mode, default)
If Button#1 == pushed           then PWM = B  (autopilot mode)
Korrect ??

Title: Re: Android Bluetooth joystick
Post by: woodygb on Sep 05, 2014, 05:15 pm


I'm struggling to find information regarding the signals required but this is very slow. Other forums are not near as active as this one.
Anyway, this is what I found out so far.
In order to switch between the modes, the apm requires a signal that has one of the three values.
with a signal of 1200 it will go to Auto, 1500 it will go to LEARNING and 1800 it will go to Manual. This is one PWM output.

Another PWM output controls the add and delete waypoint (yet to determine the values)

Two more PWM channels are used for throttle and direction control (probably normal R/C PWM control values) .


I assume that you are aware of the std PWM signal range for R/C ?
Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Sep 05, 2014, 05:35 pm
Yes, I do know the std R/C operation range and that is why I assume the throttle and steering use this.
I'm not sure though of the values required for the waypoint manipulation. That is what I'm trying to find out.







I'm struggling to find information regarding the signals required but this is very slow. Other forums are not near as active as this one.
Anyway, this is what I found out so far.
In order to switch between the modes, the apm requires a signal that has one of the three values.
with a signal of 1200 it will go to Auto, 1500 it will go to LEARNING and 1800 it will go to Manual. This is one PWM output.

Another PWM output controls the add and delete waypoint (yet to determine the values)

Two more PWM channels are used for throttle and direction control (probably normal R/C PWM control values) .


I assume that you are aware of the std PWM signal range for R/C ?
Title: Re: Android Bluetooth joystick
Post by: woodygb on Sep 05, 2014, 05:56 pm
You could presume that the pulse used for the add/delete waypoint would be the normal signal output by the movement of a R/C transmitters toggle switch ...thus Low and High... 1200 - 1800.

Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Sep 05, 2014, 06:12 pm

You could presume that the pulse used for the add/delete waypoint would be the normal signal output by the movement of a R/C transmitters toggle switch ...thus Low and High... 1200 - 1800.





Well, the waypoint channel is controlled by one channel of the R/C receiver. This R/C receiver channel is controller by a two position switch on the R/C transmitter. What is the signal value for one position of the switch and what is the value for the other position, 1200 and 1800 ?.
Title: Re: Android Bluetooth joystick
Post by: woodygb on Sep 05, 2014, 06:25 pm
I'd need to actually read the values .... I can do this later if you wish ... but I'd say that it is a pretty safe bet that the signal is 1200 - 1800 ish .

The Ele , Aile , Rud & Throttle channels  ( joystick ) are certainly  1200 - 1500 - 1800 ish ..the ish  is to denote that there is always a slight variation from std.

Note that I have read the stick channel signals.... but never needed to read the Toggle switches
Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Sep 05, 2014, 06:30 pm

I'd need to actually read the values .... I can do this later if you wish ... but I'd say that it is a pretty safe bet that the signal is 1200 - 1800 ish .

The Ele , Aile , Rud & Throttle channels  ( joystick ) are certainly  1200 - 1500 - 1800 ish ..the ish  is to denote that there is always a slight variation from std.

Note that I have read the stick channel signals.... but never needed to read the Toggle switches


If you can do me this favour I'd really appreciate it. Please see the signal output for a 2 position toggle switch and a 3 position toggle switch if possible. Thanks for taking the time to reply.
Title: Re: Android Bluetooth joystick
Post by: woodygb on Sep 05, 2014, 08:19 pm
Here you go .... a screen shot of the outputs of 3 channels.

Note that neither of my two RC Transmitters have a 3 way switch ...and I used what was this Arduino's  read rudder channel pin .... thus originally 3 positions ... to read the 2 way gear switch.

Ele  is the Throttle and Aile is the Steering


(https://imagizer.imageshack.us/v2/257x351q90/r/903/FAU49t.jpg)


I might as well show the original screenshot before I deleted the center reading ...which is the "same" as one end of the scale.

(https://imagizer.imageshack.us/v2/257x351q90/r/908/8c2n3s.jpg)

The switch appears to have a 1100 - ( 1500) - 1900 signal range .... which is the "Norm" for  R/C .
Title: Re: Android Bluetooth joystick
Post by: tolisn63 on Sep 05, 2014, 08:33 pm
Thanks a million for this, it saved me a lot or time.
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 06, 2014, 10:56 am
@tolisn63
Buttons #1 (auto), #2 (manual) and #3 (learn) should be exclusive and configured as "radio buttons"
Assuming "auto" is the default mode, this is the way to go:
Code: [Select]
void getButtonState(int bStatus)  {
 switch (bStatus) {
// -----------------  BUTTON #1  -----------
   case 'A':
     buttonStatus |= B000001;    
     buttonStatus &= B111001;      // <<<<   radio button
     displayStatus = "<Manual>";
     myServo_Mode.writeMicroseconds(1800);
     break;
   case 'B':
     buttonStatus &= B111110;
     buttonStatus |= B000010;
     displayStatus = "<Auto>";
     myServo_Mode.writeMicroseconds(1200);
     break;

// -----------------  BUTTON #2  ----------
   case 'C':
     buttonStatus |= B000010;
     buttonStatus &= B111010;
     displayStatus = "<Auto>";
     myServo_Mode.writeMicroseconds(1200);
     break;
   case 'D':
     // no action
     break;

// -----------------  BUTTON #3  ----------
   case 'E':
     buttonStatus |= B000100;
     buttonStatus &= B111100;
     displayStatus = "<Learning>";
     myServo_Mode.writeMicroseconds(1500);
     break;
   case 'F':
     buttonStatus &= B111011;
     buttonStatus |= B000010;
     displayStatus = "<Auto>";
     myServo_Mode.writeMicroseconds(1200);
     break;

// -----------------  BUTTON #4  -----------------------
   case 'G':
   ...............


feel free to change buttons order


@woodygb
Thanks for your help  :)
Did you use BT Commander for a specific project ??
Let us have more info and photos
Title: Re: Android Bluetooth joystick
Post by: woodygb on Sep 06, 2014, 11:16 am
Hi Kas,

Yes ...I've used your Android App as the front end of a B.T. controlled wheelchair.

(http://www.wheelchairdriver.com/board/download/file.php?id=3262)
.

(http://www.wheelchairdriver.com/board/download/file.php?id=3261)
.

.
(http://www.wheelchairdriver.com/board/download/file.php?id=3266)


Thread here ...  http://www.wheelchairdriver.com/board/viewtopic.php?f=2&t=3790 (http://www.wheelchairdriver.com/board/viewtopic.php?f=2&t=3790) ... the last few pages http://www.wheelchairdriver.com/board/viewtopic.php?f=2&t=3790&start=380 (http://www.wheelchairdriver.com/board/viewtopic.php?f=2&t=3790&start=380)are about the B.T.

Cheers Woody
Title: Re: Android Bluetooth joystick
Post by: woodygb on Sep 06, 2014, 01:30 pm
Your seem to be using switches as the motor control...so ...you don't want "joystick" control ....just four compass points around the stick?

IF SO ... you could consider increasing the deadband out to around 90 ish  ...with the round joystick option selected.

This ... I THINK ...will give you four compass points on the extreme edge of the X,Y coordinates.

OR ...Consider a different App.
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 07, 2014, 08:14 am
Quote
Hi Kas,

Yes ...I've used your Android App as the front end of a B.T. controlled wheelchair.
Thread here ...  http://www.wheelchairdriver.com/board/viewtopic.php?f=2&t=3790 ... the last few pages http://www.wheelchairdriver.com/board/viewtopic.php?f=2&t=3790&start=380are about the B.T.

Cheers Woody



Interesting   :smiley-eek: :smiley-eek:
Feel free to propose any App modification

I have worked with a british artist on this project (http://forum.arduino.cc/index.php?topic=173246.msg1776002#msg1776002)
The robot was based on wheelchair motors, and fitted with proximity sonic sensors to avoid bumping on furniture/people

I also suggest using a simple "dead man" failsafe in your code, to stop the chair if BT signal is lost

Title: Re: Android Bluetooth joystick
Post by: woodygb on Sep 07, 2014, 10:01 am




Interesting   :smiley-eek: :smiley-eek:
Feel free to propose any App modification

I have worked with a british artist on this project (http://forum.arduino.cc/index.php?topic=173246.msg1776002#msg1776002)
The robot was based on wheelchair motors, and fitted with proximity sonic sensors to avoid bumping on furniture/people

I also suggest using a simple "dead man" failsafe in your code, to stop the chair if BT signal is lost




I've put in a Neutral command for that eventuality.

Code: [Select]
void checkDeadMan()  {                                                  // stop engines if signal is lost
  static long previousMillis = 0;                             
  long currentMillis = millis();
  if(currentMillis - previousMillis > deadManInterval) {                // send data to smartphone
    previousMillis = currentMillis;
    if(deadManTimeout)  {
      BT_Steering = Neutral;
      BT_Throttle = Neutral; //Failsafe signal
      Rapidity=0;  // Reset to "FAST" speed ...Allows joystick to be used as normal when BT connection isn't present.
      int joyX = 200;
      int joyY = 200;
      digitalWrite(ledPin,LOW);
Title: Re: Android Bluetooth joystick
Post by: woodygb on Sep 07, 2014, 10:17 am
janzluc14

You could try this approach for your "mower".

Note that my coding skills aren't that great and it will probably need debugging....and I haven't bothered with the buttons.

Quote
( anything < > 70.71 will give a quadrant )
...that should be plus 70.71 and minus 70.71 depending on the quadrant.

Code: [Select]

   if (joyY  > 90 ) //.... forward  .. SELECT "CIRCLE" ... then 90 ( anything < > 70.71 will give a quadrant ) is used as a "deadband" to give four activation compass points
     forward();
   
   if (joyY  < -90 ) //.... backward
     backward();
   
   if (joyX  > 90 ) // .... turnright
     turnright ();
   
   if (joyX < -90 ) //..... turnleft
     turnleft();
     
   else
     motorwiper();    
   
 }
 
 void getButtonState(int bStatus)  {
   switch (bStatus) {
     // -----------------  BUTTON #1  -----------------------
   case 'A':
     buttonStatus |= B000001;        // ON
     Serial.println("\n** Button_1: ON **");
     // your code...    
     displayStatus = "LED <ON>";
     Serial.println(displayStatus);
     digitalWrite(ledPin, HIGH);
 
     break;
   case 'B':
     buttonStatus &= B111110;        // OFF
     Serial.println("\n** Button_1: OFF **");
     // your code...      
     displayStatus = "LED <OFF>";
     Serial.println(displayStatus);
     digitalWrite(ledPin, LOW);
     break;
 
     // -----------------  BUTTON #2  -----------------------
   case 'C':
     buttonStatus |= B000010;        // ON
     Serial.println("\n** Button_2: ON **");
     // your code...      
     displayStatus = "Button2 <ON>";
     Serial.println(displayStatus);
     break;
   case 'D':
     buttonStatus &= B111101;        // OFF
     Serial.println("\n** Button_2: OFF **");
     // your code...      
     displayStatus = "Button2 <OFF>";
     Serial.println(displayStatus);
     break;
 
     // -----------------  BUTTON #3  -----------------------
   case 'E':
     buttonStatus |= B000100;        // ON
     Serial.println("\n** Button_3: ON **");
     // your code...  
     motorwiper();    
     displayStatus = "Motor #1 enabled"; // Demo text message
     Serial.println(displayStatus);
     break;
   case 'F':
     buttonStatus &= B111011;      // OFF
     Serial.println("\n** Button_3: OFF **");
     // your code...    
     halt();  
     displayStatus = "Motor #1 stopped";
     Serial.println(displayStatus);
     break;
 
     // -----------------  BUTTON #4  -----------------------
   case 'G':
     buttonStatus |= B001000;       // ON
     Serial.println("\n** Button_4: ON **");
     // your code...      
     displayStatus = "Datafield update <FAST>";
     Serial.println(displayStatus);
     sendInterval = FAST;
     break;
   case 'H':
     buttonStatus &= B110111;    // OFF
     Serial.println("\n** Button_4: OFF **");
     // your code...      
     displayStatus = "Datafield update <SLOW>";
     Serial.println(displayStatus);
     sendInterval = SLOW;
     break;
 
     // -----------------  BUTTON #5  -----------------------
   case 'I':           // configured as momentary button
     //      buttonStatus |= B010000;        // ON
     Serial.println("\n** Button_5: ++ pushed ++ **");
     // your code...      
     displayStatus = "Button5: <pushed>";
     break;
     //   case 'J':
     //     buttonStatus &= B101111;        // OFF
     //     // your code...      
     //     break;
 
     // -----------------  BUTTON #6  -----------------------
   case 'K':
     buttonStatus |= B100000;        // ON
     Serial.println("\n** Button_6: ON **");
     // your code...      
     displayStatus = "Button6 <ON>"; // Demo text message
     break;
   case 'L':
     buttonStatus &= B011111;        // OFF
     Serial.println("\n** Button_6: OFF **");
     // your code...      
     displayStatus = "Button6 <OFF>";
     break;
   }
   // ---------------------------------------------------------------
 }
 
 void motorwiper()
 {
 
   dist = digitalRead(switchPin);    //read the switch
 
   if(dist != object)
   {                         //if distance is not equal to object
     forward();               //then move forward
   }
   if(dist == object)
   {               //if distance is equal to object
     findroute();
   }
 
 }
 
 void forward()
 {                            // use combination which works for you
   digitalWrite(motor_pin1,LOW);
   digitalWrite(motor_pin2,HIGH);
   digitalWrite(motor_pin3,HIGH);
   digitalWrite(motor_pin4,LOW);
 }
 
 void findroute()
 {
   halt();                                             // stop
   backward();                                       //go backwards
   turnleft();
 
   /*lookleft();                                      //go to subroutine lookleft
    lookright();                                   //go to subroutine lookright
   
    if ( leftdist < rightdist )
    {
    turnleft();
    }
    else
    {
    turnright ();
    }*/
 
 }
 
 /*void lookleft() {
 /*myservo.write(150);
  delay(700);                                //wait for the servo to get there
  leftdist = analogRead(sensorpin);
  myservo.write(90);
  delay(700);                                 //wait for the servo to get there
 
 
 
  }
  */
 
 
 /*void lookright () {
 
  myservo.write(30);
  delay(700);                           //wait for the servo to get there
  rightdist = analogRead(sensorpin);
  myservo.write(90);                                  
  delay(700);                        //wait for the servo to get there
 
 
  digitalRead(switchPin) = HIGH;
  }*/
 
 void backward() {
   digitalWrite(motor_pin1,HIGH);
   digitalWrite(motor_pin2,LOW);
   digitalWrite(motor_pin3,LOW);
   digitalWrite(motor_pin4,HIGH);
   delay(1000);
   halt();
 
 }
 
 void halt ()
 {
   digitalWrite(motor_pin1,LOW);
   digitalWrite(motor_pin2,LOW);
   digitalWrite(motor_pin3,LOW);
   digitalWrite(motor_pin4,LOW);
   delay(500);                          //wait after stopping
 
 }
 
 
 void turnleft ()
 {
   digitalWrite(motor_pin1,HIGH);       //use the combination which works for you
   digitalWrite(motor_pin2,LOW);      //right motor rotates forward and left motor backward
   digitalWrite(motor_pin3,HIGH);
   digitalWrite(motor_pin4,LOW);
   delay(1000);                     // wait for the robot to make the turn
   halt();
 
 }
 
 void turnright ()
 {
   digitalWrite(motor_pin1,LOW);       //use the combination which works for you
   digitalWrite(motor_pin2,HIGH);    //left motor rotates forward and right motor backward
   digitalWrite(motor_pin3,LOW);
   digitalWrite(motor_pin4,HIGH);
   delay(1000);                              // wait for the robot to make the turn
   halt();
 
 }
Title: Re: Android Bluetooth joystick
Post by: woodygb on Sep 07, 2014, 12:29 pm
janzluc14
Have a look at your digitalRead logic questions and answers received ... or not ...  http://arduino.cc/en/Tutorial/DigitalReadSerial (http://arduino.cc/en/Tutorial/DigitalReadSerial)  see if you can sort it out.

I'd also suggest that you only need to find the ON / HIGH state... so... IF it's HIGH find route ELSE  forward.  

Code: [Select]
void motorwiper()
 {
 
   dist = digitalRead(switchPin);    //read the switch
 
   if(dist != object)
   {                         //if distance is not equal to object
     forward();               //then move forward
   }
   if(dist == object)
   {               //if distance is equal to object
     findroute();
   }
 
 }
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 11, 2014, 04:58 pm
Hi janzluc14,

As woodygb mentioned, your project belongs to the ON/OFF world, no joystick required
You may look for another App that will better fit your needs

Quote
sir their are times that when i put the joystick on forward and backward....the buttons will turn on automatically..is it because of the program???

Possible communication errors  :smiley-roll-blue: :smiley-roll-blue:
I understand your BT card is now set @57600bps
Please confirm that the basic demo sketch (http://forum.arduino.cc/index.php?topic=173246.msg1766646#msg1766646) is working OK

Also make sure that
- Refresh Interval is set to 50ms
-Timeout count is set to 10 intervals
Title: Re: Android Bluetooth joystick
Post by: woodygb on Sep 11, 2014, 08:17 pm
janzluc14

Try this for your "Joystick"

Code: [Select]
void joystick()
{
 if (jy > 71 ){ //.... forward  .. SELECT "CIRCLE" in the App ... then use +-71 ( anything < -70.71  &  > 70.71 will give a quadrant ) is used as a "deadband" to give four activation compass points    
   forward();
   Serial.println (" FORWARD");
 }  
 if (jy< -71 ){ //.... backward
   backward();
   Serial.println (" BACKWARD");
 }
 if (jx  > 71 ){ // .... turnright
   turnright();
   Serial.println (" TURN RIGHT");
 }
 if (jx< -71 ){ //..... turnleft
   turnleft();
   Serial.println (" TURN LEFT");
 }
 if  ((jx > -71&&jx <71) && (jy > -71&&jy <71)) {  
   halt();
   Serial.println (" HALT");    
 }
}



There is an issue with the Delay (500) on halt  .... see if your button problems disappear if you make it Delay (10)
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 11, 2014, 09:36 pm
Quote
There is an issue with the Delay (500) on halt  .... see if your button problems disappear if you make it Delay (10)

You are right, delay() create issues with Serial communication
RX buffer is probably overflowing and generating unpredictable errors

Thanks for bringing up this point  ;)
Title: Re: Android Bluetooth joystick
Post by: woodygb on Sep 14, 2014, 08:07 pm
janzluc14

This is your thesis not mine.

However...

You seem intent on checking  for two states  ... you only need to check for one ......if it isn't high then by default it must be the other state low.

if  pin is  high  ...find route ....else ....mow.


What function do you want to call at the end of the motorwiper()  ...  and why.

Define the why and then call the function because the condition has been met.

So you could go ...if pin high ....find route... else if  ( Define the why )  do this function..... else mow .


Write down what you'd like the mower to do .... and define some logic questions that will allow you to point to various functions depending on the answers.

E.G.  If button pressed ( ON ) ... then Manual mode ("joystick" only )  just  find the logic question/answer order that it is best to implement them in your motorwiper and other routines.


You are now completely on your own to do YOUR Thesis..

Regards Woody


EDIT.
I see that you've now deleted all your posts.
Title: Re: Android Bluetooth joystick
Post by: janzluc14 on Sep 15, 2014, 05:27 am
im just consulting sir....
yes sir kas...the program is all working...tnx...:)
Title: Re: Android Bluetooth joystick
Post by: janzluc14 on Sep 16, 2014, 07:12 am
yes sir i deleted it...:)...thanks for your help..
Title: Re: Android Bluetooth joystick
Post by: woodygb on Sep 21, 2014, 08:52 pm


@woodygb

Did you use BT Commander for a specific project ??
Let us have more info and photos



http://forum.arduino.cc/index.php?topic=173246.msg1870945#msg1870945 (http://forum.arduino.cc/index.php?topic=173246.msg1870945#msg1870945)


Hi Kas,

Here is a video of the interface being tested... not by me ... but by a wheelchair user.

http://www.youtube.com/watch?v=QLoXDDKCfC0 (http://www.youtube.com/watch?v=QLoXDDKCfC0)


Cheers  Woody
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 27, 2014, 10:03 pm
Hi Woody

Thanks for this video, I really appreciate your feedback  :)
Again, should you need any modification, just let me know

Title: Re: Android Bluetooth joystick
Post by: kas on Oct 08, 2014, 08:02 am
Quote
Postby Alexlebrit » 29 Sep 2014, 22:11  from wheelchairdriver.com

Out of interest does the app allow for control via tilting/rotating the handset, or
is it joystick control only?



Woody,

This option is relatively easy to include in Joystick BT Commander, for you to try
Let me kwow

Title: Re: Android Bluetooth joystick
Post by: kas on Oct 18, 2014, 07:04 am
For my new project (http://forum.arduino.cc/index.php?topic=271827), I am testing a robotic claw using Joystick BT Commander


Title: Re: Android Bluetooth joystick
Post by: testato on Oct 19, 2014, 12:33 pm
Is it Open Source ?
Is it on Github ?

Thanks
Title: Re: Android Bluetooth joystick
Post by: kas on Oct 20, 2014, 08:57 am
No (not yet)
For the BT engine, a good starting point is "Bluetooth chat"
The BluetoothChat sample can be found in your SDK directory (SDK 17 or lower)
Title: Re: Android Bluetooth joystick
Post by: cdb0ewm on Oct 21, 2014, 09:55 pm
This app is just what I'm looking for....but any chance of an IOS version

Thanks
Title: Re: Android Bluetooth joystick
Post by: woodygb on Oct 22, 2014, 12:24 am
Quote
Postby Alexlebrit » 29 Sep 2014, 22:11  from wheelchairdriver.com

Out of interest does the app allow for control via tilting/rotating the handset, or
 is it joystick control only?
Woody,

This option is relatively easy to include in Joystick BT Commander, for you to try
Let me kwow


I'll repost this over on the Wheelchairdriver forum.

Title: Re: Android Bluetooth joystick
Post by: kas on Oct 27, 2014, 10:56 pm
Quote
This app is just what I'm looking for....but any chance of an IOS version
Sorry, I know nothing about IOS   :-[
Best solution is to replace your phone    ;)
Title: Re: Android Bluetooth joystick
Post by: kas on Oct 28, 2014, 08:57 am
Quote
Options for advanced users
Auto connect at start up ticked
Refresh interval
25 milliseconds
Timeout count
Continually
Woody,
With this setting, you are sending a LOT of data in the air for no obvious reasons
Do you really need to resend same data 40 times per seconds if joystick has not changed position ??
Try 50ms/every 10 intervals, this will save resources on both phone and Arduino sides


Title: Re: Android Bluetooth joystick
Post by: woodygb on Nov 01, 2014, 04:49 pm
Woody,
With this setting, you are sending a LOT of data in the air for no obvious reasons
Do you really need to resend same data 40 times per seconds if joystick has not changed position ??
Try 50ms/every 10 intervals, this will save resources on both phone and Arduino sides



I really do not know if I need to ... it just seemed... at the time... to be sensible to have as much data flow as possible .... do you believe that 25ms will have any adverse effect?
Title: Re: Android Bluetooth joystick
Post by: kas on Nov 03, 2014, 07:13 am
Quote
do you believe that 25ms will have any adverse effect?
Yes
- sluggish reaction with old powerless smartphone
- transmission errors @9600bps (possible buffer overflow)
- >> smartphone battery drain <<

BTW how is the Arduino powered ??
You definitly can use the wheelchair battery (12V max)
Title: Re: Android Bluetooth joystick
Post by: woodygb on Nov 03, 2014, 06:28 pm
Thank you for the explanation ..I'll alter the instructions.

I'm using one of these Traco regulators to power the Arduino Pro Mini ATmega328P 5V etc .
Supply comes from the wheelchairs batteries 12v+12v= 24v.
(http://www.mathyvannisselroy.nl/7805%20and%20TSR%201-2450.jpg)

TRACO 5W Switching Regulator, 6.5 to 36V dc Input, 5V Output, 1A  TSR 1-2450
Title: Re: Android Bluetooth joystick
Post by: woodygb on Nov 11, 2014, 10:14 am
Hi Woody

Thanks for this video, I really appreciate your feedback  :)
Again, should you need any modification, just let me know


Hi Kaz

I have been asked about the possibility of a "slider" on the display .... which would be used as a variable adjustment to the chairs top speed... rather than the current button press selection of FULL Speed or 1/2 Speed.

Cheers Woody
Title: Re: Android Bluetooth joystick
Post by: cagiva on Nov 12, 2014, 01:38 am
For us was more relevant to move the pan/tilt autonomously.  Here you can see the result:

http://youtu.be/IpGD7KBM4zA
Title: Re: Android Bluetooth joystick
Post by: kas on Nov 12, 2014, 03:49 pm
Hi Woody,

This mod would need to modify communication protocol , and would break backward compatibility
As of today, the App has been downloaded 5650 times and I can't do that ...

Max speed should really be a discrete setting (Low/High)
If a user needs more choice, you can configure several buttons as "radio buttons"
and get Low/medium/High (3 settings) or even 25%/50%/75%/100% (4 settings)


Title: Re: Android Bluetooth joystick
Post by: woodygb on Nov 13, 2014, 10:04 am
No problem Kas ...thanks for the reply.

Hmmmm ... I could probably use 2 buttons and step up and down a predetermined selection of speed profiles.


EDIT

This seems to work fine.

Code: [Select]
case 'E':
   
   buttonPresses=(buttonPresses+1);// increment in the positive direction the buttonPresses variable

    if (buttonPresses > 5)// A stop for the max number of available function calls.
      buttonPresses = 5 ;       

case 'G':

    buttonPresses=(buttonPresses-1);// increment in the minus direction the buttonPresses variable
   
      if (buttonPresses < 1)//stop to prevent a number under 1.
        buttonPresses = 1;

==============================================

    if ((buttonPresses == 1)){ // or  2 , 3 , 4 , 5 etc

Title: Re: Android Bluetooth joystick
Post by: kas on Nov 13, 2014, 10:09 pm
Quote
For us was more relevant to move the pan/tilt autonomously.  Here you can see the result:
(http://i.imgur.com/JHLOKlj.png)

Video here (http://youtu.be/IpGD7KBM4zA)
Hi cagiva

Not directly related to RC control but very nice
Please let us have a link to your blog
Alternatively, feel free to describe your project here


Title: Re: Android Bluetooth joystick
Post by: kas on Nov 19, 2014, 10:55 am
 Hi Woody,

Based on your comments, I have developed an additional option within Joystick BT Commander:

(http://i.imgur.com/IhmiWvi.png)


This option allows to tune the joystick max value (chair's speed)

Should you be interested, let me have your email via PM
I will send you this new version for evaluation


Title: Re: Android Bluetooth joystick
Post by: woodygb on Nov 19, 2014, 01:54 pm
Thank you Kas ..
P.M. sent.
Title: Re: Android Bluetooth joystick
Post by: kas on Nov 20, 2014, 09:22 am
Check your mail   ;)
Title: Re: Android Bluetooth joystick
Post by: bonettil on Nov 21, 2014, 11:51 am
Hello,
Thank you Kas for your app, I'm making an app similar to yours.
I use mobile-anarchy-widgets, like you, but i dont want to when i touch part of widget the handler move to touched position, in your app this does not happen!!
Can you hepl me to solve this problem ?

Thankyou
Luca
Title: Re: Android Bluetooth joystick
Post by: kas on Nov 22, 2014, 08:50 pm
Quote
I dont want to when i touch part of widget the handler move to touched position, in your app this does not happen!!
This widget has some minor bugs, this is one of those

Fix is easy:
- get your touch position using ev.getX and ev.getY in onTouchEvent/ACTION_DOWN
- Introduce the corresponding offset in processMoveEvent


Title: Re: Android Bluetooth joystick
Post by: kas on Dec 10, 2014, 09:06 am
@all

I have started a new   exciting     project (http://forum.arduino.cc/index.php?topic=271827.0)    8)
and, from now on, I will be less active on this thread


Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 10, 2014, 05:59 pm
Hi Kas, or anyone,


Is there a step by step tutorial where I can first of all learn to use this app.  I know there's a lot of information on this but I haven't be able to find a step by step without having to jump around from what seems to be hundred of posts in this forum.

The first thing that I want to do is to simply use this app to do anything, blink and led, move a dc motor or what ever.

My first confusion is, do I need to combined sketches to lets say, to make a motor move, or an led blink?

The end result of my quest is to use the Joystick Bluetooth Commander App with Stepper Motors: 28BYJ-48 with ULN2003 and arduino uno.

So, if anyone knows where I can find a step by step tutorial please let me know.

Thanks.............Antonio
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 10, 2014, 09:52 pm
Hi Antonio,

Quote
Is there a step by step tutorial where I can first of all learn to use this app.
No, not yet...
You are welcome to create it once your App is up and running  ;)


Which hardware are you using??
- Android device (+ Android version)
- Arduino board
- BT card (HC05 or HC06)

A photo of your setup will definitly help

Carefully review those 10 questions and answer YES/NO
(If you don't understand a specific question, just tell it)

Android side (smartphone/tablet  screen):
1) go to Option/About and confirm that installed version is V5.2
2) can you move the joystick and display position at bottom left
3) is your BT card paired with your Android device
4) are you connected ("connected to: XXX", green text)

Arduino side:
5) are you using AndroTest V2.0 sketch
6) are Bluetooth TX connected to D2 and RX connected to D3
7) is your Bluetooth card already configured @57600 bps  (most are 9600bps by default)
8 ) is your Bluetooth card LED solid red or green  (blinking = not connected)
9) is your Arduino Serial monitor configured @57600 bps

Finally:
10)  your Arduino Serial Monitor should anycase display:
          AndroTest V2.0 - @kas2014
          demo for V5.X App
  does it ??

- any additional information ??


@All
Should you have any problems to run the App, please answer this questionnaire and post it



>> EDIT <<
Problem solved using a genuine Uno     :smiley-evil:  :smiley-evil:  :smiley-evil:
See reply #447




Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 11, 2014, 07:35 am
Hi Kas,

I'm running Android 4.2.1.
Arduino uno Rev 3
BT card - JY-MCU - HC06


Android side (smartphone/tablet  screen):
1) No, am working with 4.2.1 Samsung Victory
2)Yes, I can see the position display changing when I move the joystick
3) What do you mean paired?
4)Yes,

Arduino side:
5) Yes
6) Yes
7) no, don't know how.  I'll Google it.
8) Yes
9) Yes
10) Yes

Thanks.............I'll keep working on it.
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 11, 2014, 08:50 am
Quote
1) No, am working with 4.2.1 Samsung Victory
Sorry, I was expecting the App rev level
Within Joystick BT Commander, go to Option/about, should be 5.2


Quote
3) What do you mean paired?
The Bluetooth protocol does not involve a login for connection. To avoid abuse, only "trusted
devices" are accepted. The process of making a device known as "trusted" is called pairing:
On the first connect only, the user is asked whether the connecting device might be trusted.
Usually, the confirmation process requires a PIN to be entered.
Pairing is a general process between an Android phone and a specific BT card
It is done at the phone level, Total BT Commander is not involved in this process

Assuming you are connected, you BT card is definitely paired to your phone


Quote
7) no, don't know how.  I'll Google it
Have a look at Post #227
You will find usefull information and a utility for checking and setting  your JY-MCU HC06 card Baud rate


Sooo...
I assume
 - you are connected ("connected to: XXX", green text)
 - you can see the AndroTest V2.0 - @kas2014 welcome screen on your PC
 - you can't see the Joystick data on the Arduino Serial Monitor (any garbled characters??)

Please confirm App version and BT card baud rate


Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 11, 2014, 03:11 pm
Hi Kas,

I know very little about Android phones and WiFi ... so I've a question for you regarding the total rc commander version of your App .

Do you think that this product would be compatible with your App as it would make a neat remote camera for the wheelchair users that use my interface?

http://www.aliexpress.com/store/product/Mini-WiFi-Car-Rearview-Camera-Wireless-Back-Up-Reserve-170-Degree-Waterproof-Cam-Support-Android-System/138455_1727304917.html (http://www.aliexpress.com/store/product/Mini-WiFi-Car-Rearview-Camera-Wireless-Back-Up-Reserve-170-Degree-Waterproof-Cam-Support-Android-System/138455_1727304917.html)


Here's a similar product ..just seems to be a different camera.

http://www.amazon.co.uk/Blueskysea-Backup-Reversing-Camera-Android/dp/B00KIFJKKS  (http://www.amazon.co.uk/Blueskysea-Backup-Reversing-Camera-Android/dp/B00KIFJKKS)
which when you scroll down contains these instructions.

Quote
How to use the device ?
1. Install CarRMoniter to your Android device, and restart your device.
You can download the APK File from this link ,it is

http://www.sendspace.com/file/rbifoo (http://www.sendspace.com/file/rbifoo)

2. Open CarRMoniter, choose picture quality: normal and HD(We recommand Normal,it can save power)

3. Turn on your Android WIFI, search GLW-CAR-R signal and connect it, put in password
(find the password is 88888)

Will connection etc be as easy as simply following instruction 3 but with your App?

Cheers Woody
Title: Re: Will pay for help
Post by: AntonioLopez on Dec 11, 2014, 08:53 pm
Hi Kas,

It seems as though I'm able to pair up with the BT board, but I need to do some other things that are more complicated than I'm able to handle.  

Do you know of any one that I can pay to put something together for me?

Here's my hardware

1.BT Board - HC06
2.Arduino Uno
3 Stepper motor 28BYJ-48 with ULN2003

The project is to be able to control the stepper with your BT commander. AT this point I'm able to do it with a potentiometer but I don't want to be tethered to the Arduino.

Here's a little video I just shot. 

https://www.youtube.com/watch?v=WQE0EaavEio&feature=youtu.be



Thanks.........Antonio
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 11, 2014, 11:12 pm
Antonio,

I think that you might be missing some vital steps.

Have you uploaded a program/code to the Arduino? ...if so ..can you post it.

Cheers Woody
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 11, 2014, 11:40 pm
Antonio,

I've found another of your posts on the forum ... you need to integrate your stepper code into the Arduino code that Kas has provided for his App.



The Joystick swing values need to be used to replace the analogRead in the existing stepper code .

Code: [Select]

  PotVal = analogRead(POT);       // Potentiometer value range 0-1023

  PotVal= map(PotVal,0,1023,0,2047);      // Map pot range in the stepper range.
  PotVal= PotVal * 0.1 + LastPotVal * 0.9 ;  // Filtering to reduce noise.
  LastPotVal= PotVal;

 


Something like this.... which is a modified snippet of the BT  Joystick code.
NOTE:- This code is only a PART of what needs to be done.

Code: [Select]
void getJoystickState(byte data[8])    {
  int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
  int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
  joyX = joyX - 200;                                                  // Offset to avoid
  joyY = joyY - 200;                                                  // transmitting negative numbers

  if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)       return;   // commmunication error

   PotVal_A =  map (joyX,-100,100,0,2047);//  Map joyX range in the stepper range motor A
   PotVal_B =  map (joyY,-100,100,0,2047);//  Map joyY  range in the stepper range motor B

}


So ...just to be clear ...BOTH the Arduino code written for Kas's App AND the code that you currently have that works your stepper motor via a pot need to be combined.

Additional comments and links added to hopefully resolve any misunderstanding.

- AndroTest.ino demo sketch:             V2.0 (http://forum.arduino.cc/index.php?topic=173246.msg1766646#msg1766646)
THE ABOVE AndroTest.ino IS THE CODE THAT YOU MUST GET WORKING FIRST.

Also update your Android phone App to.
- Joystick bluetooth Commander:     V5.2 (https://play.google.com/store/apps/details?id=org.projectproto.btjoystick&feature=search_result)
Title: Re: Android Bluetooth joystick
Post by: Isaac96 on Dec 12, 2014, 12:54 am
@all, i am trying to hack a R/C car with a L293 controlling the back motor and a servo for steering.
I am going to use BT commander to control it. My code is attached.
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 12, 2014, 11:16 am
Hi Woody

Quote
I know very little about Android phones and WiFi ... so I've a question for you regarding the total rc commander version of your App
This is the dataflow diagram for Total BT Commander, as implemented for this RC tank (http://forum.arduino.cc/index.php?topic=236401.msg1699561#msg1699561) demo

(http://i.imgur.com/NF3VNr5.jpg)


Bluetooth:
Two way communication with the BT card, strickly identical to Joystick BT Commander

WiFi:
The video stream from the IP camera is sent to the home router, then to your Android device
This may not be convenient for outdoor activities ;)
For this reason, the tank has an onboard mini router


(http://i.imgur.com/StdxmNH.png)



A smartphone can also be used as an IP camera

(http://i.imgur.com/wIDhcBf.jpg)

WiFi tethering option allow direct connection with Total RC Commander, without any router



Now, to start connection from Total BT Commander, go to Options/Video properties/Camera feed URL

(http://i.imgur.com/9uxN3Su.png)

You should enter
- the IP camera address
- the Port to be used
- a command, specific to your IP camera
- some optional parameters (password ...)

For Wanscam IP cam: "http://192.168.1.10:99/videostream.cgi?user=admin1&pwd=&resolution=32&rate=0"
For the Moto G smartphone: "http://192.168.1.12:8080/videofeed"

To get Total RC Commander, look here (http://forum.arduino.cc/index.php?topic=173246.msg2105089#msg2105089)



Quote
Do you think that this product would be compatible with your App as it would make a neat remote camera for the wheelchair users that use my interface?
http://www.aliexpress.com/store/product/Mini-WiFi-Car-Rearview-Camera-Wireless-Back-Up-Reserve-170-Degree-Waterproof-Cam-Support-Android-System/138455_1727304917.html

This nice device is an IP camera with built-in router
It  should  work with Total BT Commander          **  EDIT: it doesn't so far  **



@Antonio
Please confirm App version and BT card baud rate
Keep-It-Stupid-Simple, forget steppers for the moment.
Can you see the Joystick data on the Arduino Serial Monitor using plain V2.0 sketch
Follow Woody's advices


Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 12, 2014, 12:44 pm
Quote
This nice device is an IP camera with built-in router
It  should  work with Total BT Commander
So ...suck it and see  :)
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 12, 2014, 08:45 pm
Woody ??  is that you ??    ;)

(http://i.imgur.com/rgz0dcY.jpg)
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 13, 2014, 03:21 am
Hi Kas and Woody,

This is the code that I'm uploading to the arduino, that is the right one right?  

As far as when I'm using the Joystick BT Commander goes, when I bring up the serial port, all I see is,

AndroTest V2.0 - @kas2014
demo for V5. x App



Down at the bottom I see,

Check mark on Autoscroll   Both NL & CR is selected  - 57600 baud is selected.



When I'm actually moving the joystick around, I see nothing else on the serial port.  How do I know that the Joystick BT Commander is communicating with the Arduino?  


Thanks......Antonio
Code: [Select]
#define VERSION     "\n\nAndroTest V2.0 - @kas2014\ndemo for V5.x App"

// V2.0  changed to pure ASCII Communication Protocol ** not backward compatible **
// V1.4  improved communication errors handling
// V1.3  renamed for publishing, posted on 09/05/2014
// V1.2  Text display   ** not backward compatible **
// V1.1  Integer display
// V1.0  6 buttons + 4 data char implemented

// Demo setup:
// Button #1 controls pin #13 LED
// Button #4 toggle datafield display rate
// Button #5 configured as "push" button (momentary)
// Other buttons display demo message

// Arduino pin#2 to TX BlueTooth module
// Arduino pin#3 to RX BlueTooth module
// make sure your BT board is set @57600 bps
// better remove SoftSerial for PWM based projects

// For Mega 2560:
// remove   #include "SoftwareSerial.h", SoftwareSerial mySerial(2,3);
// search/replace  mySerial  >> Serial1
// pin#18 to RX bluetooth module, pin#19 to TX bluetooth module

#include "SoftwareSerial.h"

#define    STX          0x02
#define    ETX          0x03
#define    ledPin       13
#define    SLOW         750                            // Datafields refresh rate (ms)
#define    FAST         250                             // Datafields refresh rate (ms)

SoftwareSerial mySerial(2,3);                           // BlueTooth module: pin#2=TX pin#3=RX
byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};                 // bytes received
byte buttonStatus = 0;                                  // first Byte sent to Android device
long previousMillis = 0;                                // will store last time Buttons status was updated
long sendInterval = SLOW;                               // interval between Buttons status transmission (milliseconds)
String displayStatus = "xxxx";                          // message to Android device

void setup()  {
 Serial.begin(57600);
 mySerial.begin(57600);                                // 57600 = max value for softserial
 pinMode(ledPin, OUTPUT);     
 Serial.println(VERSION);
 while(mySerial.available())  mySerial.read();         // empty RX buffer
}

void loop() {
 if(mySerial.available())  {                           // data received from smartphone
   delay(2);
   cmd[0] =  mySerial.read(); 
   if(cmd[0] == STX)  {
     int i=1;     
     while(mySerial.available())  {
       delay(1);
       cmd[i] = mySerial.read();
       if(cmd[i]>127 || i>7)                 break;     // Communication error
       if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
       i++;
     }
     if     (i==2)          getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
     else if(i==7)          getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
   }
 }
 sendBlueToothData();
}

void sendBlueToothData()  {
 static long previousMillis = 0;                             
 long currentMillis = millis();
 if(currentMillis - previousMillis > sendInterval) {   // send data back to smartphone
   previousMillis = currentMillis;

// Data frame transmitted back from Arduino to Android device:
// < 0X02   Buttons state   0X01   DataField#1   0x04   DataField#2   0x05   DataField#3    0x03 > 
// < 0X02      "01011"      0X01     "120.00"    0x04     "-4500"     0x05  "Motor enabled" 0x03 >    // example

   mySerial.print((char)STX);                                             // Start of Transmission
   mySerial.print(getButtonStatusString());  mySerial.print((char)0x1);   // buttons status feedback
   mySerial.print(GetdataInt1());            mySerial.print((char)0x4);   // datafield #1
   mySerial.print(GetdataFloat2());          mySerial.print((char)0x5);   // datafield #2
   mySerial.print(displayStatus);                                         // datafield #3
   mySerial.print((char)ETX);                                             // End of Transmission
 } 
}

String getButtonStatusString()  {
 String bStatus = "";
 for(int i=0; i<6; i++)  {
   if(buttonStatus & (B100000 >>i))      bStatus += "1";
   else                                  bStatus += "0";
 }
 return bStatus;
}

int GetdataInt1()  {              // Data dummy values sent to Android device for demo purpose
 static int i= -30;              // Replace with your own code
 i ++;
 if(i >0)    i = -30;
 return i; 
}

float GetdataFloat2()  {           // Data dummy values sent to Android device for demo purpose
 static float i=50;               // Replace with your own code
 i-=.5;
 if(i <-50)    i = 50;
 return i; 
}

void getJoystickState(byte data[8])    {
 int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
 int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
 joyX = joyX - 200;                                                  // Offset to avoid
 joyY = joyY - 200;                                                  // transmitting negative numbers

 if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // commmunication error
 
// Your code here ...
   Serial.print("Joystick position:  ");
   Serial.print(joyX); 
   Serial.print(", "); 
   Serial.println(joyY);
}

void getButtonState(int bStatus)  {
 switch (bStatus) {
// -----------------  BUTTON #1  -----------------------
   case 'A':
     buttonStatus |= B000001;        // ON
     Serial.println("\n** Button_1: ON **");
     // your code...     
     displayStatus = "LED <ON>";
     Serial.println(displayStatus);
     digitalWrite(ledPin, HIGH);
     break;
   case 'B':
     buttonStatus &= B111110;        // OFF
     Serial.println("\n** Button_1: OFF **");
     // your code...     
     displayStatus = "LED <OFF>";
     Serial.println(displayStatus);
     digitalWrite(ledPin, LOW);
     break;

// -----------------  BUTTON #2  -----------------------
   case 'C':
     buttonStatus |= B000010;        // ON
     Serial.println("\n** Button_2: ON **");
     // your code...     
     displayStatus = "Button2 <ON>";
     Serial.println(displayStatus);
     break;
   case 'D':
     buttonStatus &= B111101;        // OFF
     Serial.println("\n** Button_2: OFF **");
     // your code...     
     displayStatus = "Button2 <OFF>";
     Serial.println(displayStatus);
     break;

// -----------------  BUTTON #3  -----------------------
   case 'E':
     buttonStatus |= B000100;        // ON
     Serial.println("\n** Button_3: ON **");
     // your code...     
     displayStatus = "Motor #1 enabled"; // Demo text message
     Serial.println(displayStatus);
     break;
   case 'F':
     buttonStatus &= B111011;      // OFF
     Serial.println("\n** Button_3: OFF **");
     // your code...     
     displayStatus = "Motor #1 stopped";
     Serial.println(displayStatus);
     break;

// -----------------  BUTTON #4  -----------------------
   case 'G':
     buttonStatus |= B001000;       // ON
     Serial.println("\n** Button_4: ON **");
     // your code...     
     displayStatus = "Datafield update <FAST>";
     Serial.println(displayStatus);
     sendInterval = FAST;
     break;
   case 'H':
     buttonStatus &= B110111;    // OFF
     Serial.println("\n** Button_4: OFF **");
     // your code...     
     displayStatus = "Datafield update <SLOW>";
     Serial.println(displayStatus);
     sendInterval = SLOW;
    break;

// -----------------  BUTTON #5  -----------------------
   case 'I':           // configured as momentary button
//      buttonStatus |= B010000;        // ON
     Serial.println("\n** Button_5: ++ pushed ++ **");
     // your code...     
     displayStatus = "Button5: <pushed>";
     break;
//   case 'J':
//     buttonStatus &= B101111;        // OFF
//     // your code...     
//     break;

// -----------------  BUTTON #6  -----------------------
   case 'K':
     buttonStatus |= B100000;        // ON
     Serial.println("\n** Button_6: ON **");
     // your code...     
      displayStatus = "Button6 <ON>"; // Demo text message
    break;
   case 'L':
     buttonStatus &= B011111;        // OFF
     Serial.println("\n** Button_6: OFF **");
     // your code...     
     displayStatus = "Button6 <OFF>";
     break;
 }
// ---------------------------------------------------------------
}
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 13, 2014, 08:20 am
Antonio,

Again:   Please confirm App version and BT card baud rate

Based on your information, your RX/TX wires are probably inverted, try reversing D2 and D3


EDIT: Looking again at your video, I can see the datafields are updated according to V2 sketch code
The  Arduino >> Android  communication is OK

Try changing  mySerial.begin(57600) to  mySerial.begin(9600) or  mySerial.begin(19200)



EDIT2:
Quote
This is the code that I'm uploading to the arduino, that is the right one right?
Yes, assuming you didn't modify it

Quote
How do I know that the Joystick BT Commander is communicating with the Arduino?
Blinking TX led shows incoming data from Android (as labeled on _my_ board, with Serial Monitor enabled)

Carefully check your D2 connection (white cable)
Also disconnect all motor driver cables, just pure V2 code, to avoid possible interaction with Softserial

Let us have a new video, showing the new set up, including BT card and PC screen
We WILL make it out  ;)

Title: Re: Android Bluetooth joystick
Post by: kas on Dec 13, 2014, 11:13 am
@Woody,

I send you Total BT Commander V5.2, please check your mail
First, check the Bluetooth side, should work exactly as Joystick BT Commander

Let me have your IP camera model

Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 13, 2014, 12:23 pm
@Antonio

I have tried to combine your stepper prog with Kas's AndroTest V2.0... ONCE the AndroTest program and serial comms is sorted... then I'll post it for you and you can try it out.

@ Kas

APK received .... I'll need to purchase the back up camera first before I can play.


Quote
EDIT: Looking again at your video, I can see the datafields are updated according to V2 sketch code
The  Arduino >> Android  communication is OK
Isn't that proof of the myserial Blue Tooth baud rate being correct.... or am I once again missing something?
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 13, 2014, 02:37 pm
Quote
Isn't that proof of the myserial Blue Tooth baud rate being correct.... or am I once again missing something?
You are perfectly right  :-[
I edited my message
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 14, 2014, 01:49 am
Kas,

The originator of the request for a simple camera feed for his chair went ahead and bought the camera system...he emailed me this evening.

Quote
Woody I got the WiFi  back up camera working on my phone using CarMoniter.apk. It works really nice. This is the camera I got: http://www.dx.com/p/w-one-ip66-wireless-wi-fi-300kp-car-rearview-camera-system-for-andriod-black-310074#.VIzMtcYkCnA 

I got it off ebay though from a different seller and cheaper.


Could you get me the Total BT Commander apk so I could test it?

Thanks,
Pat Tallino
Beach Mobility Inc.
So I passed on the RC Commander App ( I owe you 2 more Euro's ) .

His reply came back an hour later...

Quote
Thanks, but no luck.  The CarMoniter app automatically finds the video signal when the phone is connected to the cameras WiFi router.
Total Rc Commander seems to need an ip address and port but I have no way of knowing that.
CarMoniter app download link below.

http://www.sendspace.com/file/rbifoo

Woody
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 14, 2014, 08:24 am
Quote
Thanks, but no luck.  The CarMoniter app automatically finds the video signal when the phone is connected to the cameras WiFi router.
Total Rc Commander seems to need an ip address and port but I have no way of knowing that.
Please confirm that  nothing   was entered in CarMoniter (user, password...), to obtain a video connection
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 14, 2014, 03:51 pm
Thanks Kas and Woody,

I'll be posting a new video later today, showing the sequence of events to make sure that isn't my problem.

I appreciate your help............Thanks..........Antonio
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 14, 2014, 04:43 pm
Please confirm that  nothing   was entered in CarMoniter (user, password...), to obtain a video connection
Kas ..here's a transcript of the conversion.

Quote
Hi Pat,

I've also been asked to confirm that once the Wifi  connection has been setup on the phone ...all you do is start the App and bingo a video appears?.

I assume that the Car monitor's WiFi shows up on the Android phone under Settings -WiFi- with the name GLW-CAR-R and simply requires a password to connect ?  
 
Note that we are asking questions blind and making assumptions ...so feel free to say "no no"  that's not how it works.... AND STEP ME THRU THE PROCESS.

Any chance of a scan of the relevant page from the manual?

Woody
Quote
Yes thats correct. If you start the app before you connect to WiFi, you have an option to choose "Normal" or "High" video quality.  But if the phone, Samsung Galaxy Note 4 in my case, is already connected to the WiFi, which is GLW-CAR-R0000795, then when you open the CarMoniter App, the video just starts automatically full screen like a backup moniter.  There are no options within the app for any setup
Hope this helps.

Woody


EDIT :- This seems to be the installation manual for the same backup camera but for a different supplier.

medias.pearl.fr/technique/notice/PX3745.pdf (http://medias.pearl.fr/technique/notice/PX3745.pdf)
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 14, 2014, 04:56 pm
Thanks Kas and Woody,

I'll be posting a new video later today, showing the sequence of events to make sure that isn't my problem.

I appreciate your help............Thanks..........Antonio
The communication TO the Android phone ( TX of Arduino to RX of Blue Tooth ) seems fine.

The problem appears to be one of Blue Tooth communication FROM the Android phone to the Arduino ( TX of Blue Tooth to RX of Arduino ).


This could just be a bad connection or wire as indicated by Kas ... or it's remotely possible that it is the UNO's pin... or a damaged Blue Tooth module.
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 14, 2014, 09:09 pm
Thanks Kas and Woody,

I'll be posting a new video later today, showing the sequence of events to make sure that isn't my problem.

I appreciate your help............Thanks..........Antonio
Here's a screen shot of the pot outputs after I've integrated the stepper App into the BT Commander.
The first column after the PotValA & B  swing from 0 - 2047 with 1023 as the center using the BT Joystick as an input.

(http://s5.postimg.org/6aa6axdzr/stepper_pot_values.jpg)
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 15, 2014, 01:11 am
Hi Woody, and Kass,

Wow, great work Woddy, that screen shot is amazing and proof that everything I'm doing is doing absolutely nothing.


Here's another short video showing you my sequence of events.

https://www.youtube.com/watch?v=JVjXsk76gw4&feature=youtu.be


I don't want to take up any more of your and Kass's time, so at this point, how do you feel about fixing this problem and I can pay you through Paypal, hopefully this isn't frowned upon on this site. 

I'm pretty burned out, this is the second bluetooth module that I've tried, and I've been to what seems a thousand - how to sites, so I  don't know what to say, except that I want to move forward.

Here's the code that I've been using with the potentiometer and the small stepper.
Code: [Select]
/*------------------------------------------------------
StepperPot_11
Arduining.com 13 APRIL 2013

A stepper motor follows a potentiometer on analog input 5.
A software low-pass filter is used to reduce the noise in the analog reading.
After 3 seconds of inactivity the motor coils are turned OFF to save energy.
The RED_LED is used to signal when the stepper is powered.

Hardware:
LaunchPad with MSP430G2553.
Driver: ULN2003A
Stepper Motor:  28BYJ48, 5VDC, step pangle 5.625 °
                Gear reduction 64:1
                No-load starting frequency:> = 500PPS (4 rpm)
                Coil resistance 60 Ohms.               
 -----------------------------------------------------*/

#include <Stepper.h>

// change this to the number of steps on your motor
#define  STEPSREV    2047    // 64(fullsteps) * 64 (reduction ratio)
#define  COIL1       11
#define  COIL2       9
#define  COIL3       10
#define  COIL4       8
#define  POT         0
#define  ENER        13
#define  TIMEOUT     3000    //Turns off after 3 secs of inactivity.

// create an instance of the stepper class, specifying
// the number of steps per revolution and pins atached to motor coils.
Stepper myStepper(STEPSREV, COIL1, COIL2, COIL3, COIL4);
int PotVal;
int LastPotVal= 0 ;          // To implement a software Low-Pass-Filter
int pos = 0;              // stepper position(0-4096)->(0-360°)
unsigned long stamp = 0;  // last move time stamped.

void setup()
{
  myStepper.setSpeed(4);  // set the motor speed to 4 RPM
  pinMode(ENER, OUTPUT);  // status led (coils energized).
//  Serial.begin(9600);   //for debuging.
}

void loop(){

  PotVal = analogRead(POT);       // Potentiometer value range 0-1023

  PotVal= map(PotVal,0,1023,0,2047);      // Map pot range in the stepper range.
  PotVal= PotVal * 0.1 + LastPotVal * 0.9 ;  // Filtering to reduce noise.
  LastPotVal= PotVal;

//  Serial.print(Val);              // For debuging.
//  Serial.print("   ");            //    "
//  Serial.println(pos);            //    "
//  delay(500);                     //    " 

  if(abs(PotVal - pos)> 4){              //if diference is greater than 4 steps.
      if((PotVal - pos)> 0){
          digitalWrite(ENER, HIGH);   //Motor energized.     
          myStepper.step(1);           // move one step to the right.
          pos++;
          }
      if((PotVal - pos)< 0){
          digitalWrite(ENER, HIGH);   //Motor energized.
          myStepper.step(-1);            // move one step to the left.
          pos--;
          }
      stamp = millis();               // stamp actual time.
      }
  else {     
      if((millis() - stamp) > TIMEOUT){   //Turn Off coils after TIMEOUT.
          digitalWrite(COIL1, LOW);
          digitalWrite(COIL2, LOW);
          digitalWrite(COIL3, LOW);
          digitalWrite(COIL4, LOW);
          digitalWrite(ENER, LOW);    //Motor de-energized.
          }   
      }

}


Thanks to the both of you again............Antonio
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 15, 2014, 07:39 am
Antonio,

For the moment
  Android >> Arduino   not OK
  Arduino >> Android   OK

Joystick BT Commander V4.x would create this exact situation 
Just to make sure, uninstall the App and reload from Google Play
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 15, 2014, 01:03 pm
Quote
I don't want to take up any more of your and Kass's time, so at this point, how do you feel about fixing this problem and I can pay you through Paypal, hopefully this isn't frowned upon on this site. 

I'm pretty burned out, this is the second bluetooth module that I've tried, and I've been to what seems a thousand - how to sites, so I  don't know what to say, except that I want to move forward.
I could easily program a pro mini and post it to you... BUT ..the fix is likely to be simple if you persevere with the guidance being provided.

Follow Kas's advice ...uninstall BT Commander from your phone & download the latest version of the App



If your interested in knowing what version of Kas's software your currently running go to the screen line that pops up at the bottom of the App with  Connect  Options  reset Opt  About and press About.

Mine says Joystick BT Commander V5.2
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 15, 2014, 08:45 pm
Hi Guys, and once again thanks for your help.


I reinstalled Commander to make sure and I do have V5.2 installed, problem is the same.

Later on today I'll setup the HC5 to see what happens, I didn't want to setup a voltage divider, that's why I bought an HC6.



 Woody, what do you mean, program a pro mini?

Thanks...........Antonio
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 15, 2014, 09:24 pm
http://arduino.cc/en/Main/ArduinoBoardProMini (http://arduino.cc/en/Main/ArduinoBoardProMini)


(http://www.wheelchairdriver.com/board/download/file.php?id=2841)

I'm fairly confident ... seeing as how you have managed to reprogram it ...that your Blue Tooth is working fine.

So....


I'm going to suggest that you move the connection from pin2 of the UNO to pin4

The SoftwareSerial mySerial(2,3);  in the program code will become SoftwareSerial mySerial(4,3);



Title: Re: Android Bluetooth joystick
Post by: kas on Dec 15, 2014, 10:53 pm
You may try this bare minimum sketch to test incoming data from your smartphone

Code: [Select]

#include "SoftwareSerial.h"

#define txPin 3
#define rxPin 2

SoftwareSerial mySerial(rxPin,txPin);

void setup()  {
  mySerial.begin(57600);
  Serial.begin(57600);
  Serial.println("Test Soft_Serial");
}

void loop() {
  if(mySerial.available())    Serial.print(mySerial.read());  
}


Bytes received by the Bluetooth card will be echoed to the Arduino Serial Monitor
Upload sketch, start and connect Joystick BT Commander

Should display series of numbers:
250545050525332505450505253325054505052533250545050525332505450505253325054505052533 ..................


As suggested by Woody, try changing rxPin to #4



Quote
how do you feel about fixing this problem and I can pay you through Paypal, hopefully this isn't frowned upon on this site
Please discuss this point via PM's.  Personally not interested   ;)

Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 16, 2014, 12:00 am
Hi Kas and Woody,

Kas, I just say your latest post, I try that code in a bit, meanwhile it take a look at my video.

https://www.youtube.com/watch?v=XWZ_Co76doM

It does seem to be working.


Woody, how do I contact you PM?
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 16, 2014, 12:04 am
Kas,

I just tried your code and the Commander is sending data to the arduino, GREAT, THANKS.
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 16, 2014, 12:35 am
click on my user name or avatar

page opens

bottom left

click on send PM
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 16, 2014, 01:03 am
Code is in 2 lumps as the forum complained about it's size.
2nd lump on next page.

Code: [Select]

#define VERSION     "\n\nAndroTest V2.0 - @kas2014\ndemo for V5.x App"
#include "SoftwareSerial.h"
#include <Stepper.h>

#define rxPin 2
#define txPin 3

// change this to the number of steps on your motor
#define  STEPSREV    2047    // 64(fullsteps) * 64 (reduction ratio)= 4096

#define  COIL1_A    11
#define  COIL2_A     9
#define  COIL3_A    10
#define  COIL4_A     8

#define  COIL1_B    4 // ???  PIN NUMBERS GUESSED
#define  COIL2_B    5
#define  COIL3_B    6
#define  COIL4_B    7

#define  ENER_A       13       //Motor A Status led
//#define  ENER_B       ?     //Motor B Status led do you wish a seperate one?

#define  TIMEOUT     3000    //Turns off after 3 secs of inactivity.

// create an instance of the stepper class, specifying
// the number of steps per revolution and pins atached to motor coils.
Stepper myStepperA(STEPSREV, COIL1_A, COIL2_A, COIL3_A, COIL4_A);
Stepper myStepperB(STEPSREV, COIL1_B, COIL2_B, COIL3_B, COIL4_B);
int PotValA;
int PotValB;
int pos_A = 1024;              // stepper A position(0-4096)->(0-360°) CENTERED
int pos_B = 1024;              // stepper B position (0-4096)->(0-360°)CENTERED
unsigned long stamp_A = 0;  // last A move time stamped.
unsigned long stamp_B = 0;  // last B move time stamped.
#define    STX          0x02
#define    ETX          0x03
//#define    ledPin       13
#define    SLOW         750                            // Datafields refresh rate (ms)
#define    FAST         250                             // Datafields refresh rate (ms)

SoftwareSerial mySerial(rxPin,txPin);  // BlueTooth module: pin#2=TX  pin#3=RX
byte cmd[8] = {
  0, 0, 0, 0, 0, 0, 0, 0};                 // bytes received
byte buttonStatus = 0;                                  // first Byte sent to Android device
long previousMillis = 0;                                // will store last time Buttons status was updated
long sendInterval = SLOW;                               // interval between Buttons status transmission (milliseconds)
String displayStatus = "xxxx";                          // message to Android device

void setup()  {
  Serial.begin(57600);
  mySerial.begin(57600);   // 57600 = max value for softserial
  pinMode(txPin, OUTPUT);
  pinMode(rxPin, INPUT);
  myStepperA.setSpeed(4);  // set the motor speed to 4 RPM
  myStepperB.setSpeed(4);  // set the motor speed to 4 RPM
  pinMode(ENER_A , OUTPUT);
  //  pinMode(ENER_B , OUTPUT);   
  Serial.println(VERSION);
  while(mySerial.available())  mySerial.read();         // empty RX buffer
}

void loop() {
  if(mySerial.available())  {                           // data received from smartphone
    delay(2);
    cmd[0] =  mySerial.read(); 
    if(cmd[0] == STX)  {
      int i=1;     
      while(mySerial.available())  {
        delay(1);
        cmd[i] = mySerial.read();
        if(cmd[i]>127 || i>7)                 break;     // Communication error
        if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
        i++;
      }
      if     (i==2)          getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
      else if(i==7)          getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
    }

    if(abs(PotValA - pos_A)> 4){  //if diference is greater than 4 steps.
      if((PotValA - pos_A)> 0){
        digitalWrite(ENER_A, HIGH);   //Motor ENER_Agized.     
        myStepperA.step(1);    // move one step to the right.
        pos_A++;
      }
      if((PotValA - pos_A)< 0){
        digitalWrite(ENER_A, HIGH);   //Motor ENER_Agized.
        myStepperA.step(-1);    // move one step to the left.
        pos_A--;
      }
      stamp_A = millis();  // stamp actual time. 
    }

    if(abs(PotValB - pos_B)> 4){ //if diference is greater than 4 steps.
      if((PotValB - pos_B)> 0){
        digitalWrite(ENER_A, HIGH);  //Motor ENER_Agized. ********   ENER_A led used ...change to ENER_B if required and define another led number
        myStepperB.step(1);  // move one step to the right.
        pos_B++;
      }
      if((PotValB - pos_B)< 0){
        digitalWrite(ENER_A, HIGH);   //Motor ENER_Agized.********  ENER_A led used ...change to ENER_B if required and define another led number
        myStepperB.step(-1);  // move one step to the left.
        pos_B--;
      }
      stamp_B = millis(); // stamp actual time.
    }
    else {     
      if((millis() - stamp_A) > TIMEOUT){   //Turn Off coils after TIMEOUT.
        digitalWrite(COIL1_A, LOW);
        digitalWrite(COIL2_A, LOW);
        digitalWrite(COIL3_A, LOW);
        digitalWrite(COIL4_A, LOW);
        digitalWrite(ENER_A, LOW); //Motor de-ENER_Agized.

        if((millis() - stamp_B) > TIMEOUT)//Turn Off coils after TIMEOUT.
          digitalWrite(COIL1_B, LOW);
        digitalWrite(COIL2_B, LOW);
        digitalWrite(COIL3_B, LOW);
        digitalWrite(COIL4_B, LOW);
        digitalWrite(ENER_A, LOW);//Motor de-ENER_Agized.Motor *********   ENER_A led used ...change to ENER_B if required and define another led number
      }

    }
  }

  sendBlueToothData();
}

void sendBlueToothData()  {
  static long previousMillis = 0;                             
  long currentMillis = millis();
  if(currentMillis - previousMillis > sendInterval) {   // send data back to smartphone
    previousMillis = currentMillis;

    // Data frame transmitted back from Arduino to Android device:
    // < 0X02   Buttons state   0X01   DataField#1   0x04   DataField#2   0x05   DataField#3    0x03 > 
    // < 0X02      "01011"      0X01     "120.00"    0x04     "-4500"     0x05  "Motor enabled" 0x03 >    // example

    mySerial.print((char)STX);                                             // Start of Transmission
    mySerial.print(getButtonStatusString()); 
    mySerial.print((char)0x1);   // buttons status feedback
    mySerial.print(GetdataInt1());           
    mySerial.print((char)0x4);   // datafield #1
    mySerial.print(GetdataFloat2());         
    mySerial.print((char)0x5);   // datafield #2
    mySerial.print(displayStatus);                                         // datafield #3
    mySerial.print((char)ETX);                                             // End of Transmission
  } 
}

String getButtonStatusString()  {
  String bStatus = "";
  for(int i=0; i<6; i++)  {
    if(buttonStatus & (B100000 >>i))      bStatus += "1";
    else                                  bStatus += "0";
  }
  return bStatus;
}

int GetdataInt1()  {   // Data dummy values sent to Android device for demo purpos_Ae
  static int i= -30;  // Replace with your own code
  i ++;
  if(i >0)    i = -30;
  return i; 
}

float GetdataFloat2()  { // Data dummy values sent to Android device for demo purpos_Ae
  static float i=50; // Replace with your own code
  i-=.5;
  if(i <-50)    i = 50;
  return i; 
}

void getJoystickState(byte data[8])    {
  int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
  int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
  joyX = joyX - 200;                                                  // Offset to avoid
  joyY = joyY - 200;                                                  // transmitting negative numbers

  if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)       return;   // commmunication error

  PotValA =  map (joyX,-100,100,0,2047);//  Map joyX range in the stepper range motor 1
  PotValB =  map (joyY,-100,100,0,2047);//  Map joyY  range in the stepper range motor 2



  Serial.print("PotValA");
  Serial.print("  :  ");
  Serial.print(PotValA);         
  Serial.print("  :  "); 
  Serial.print("pos_A");
  Serial.print("  :  ");
  Serial.print(pos_A);   
  Serial.print("  :  ");
  Serial.print("PotValB");
  Serial.print("  :  ");
  Serial.print(PotValB);
  Serial.print("  :  "); 
  Serial.print("pos_B");
  Serial.print("  :  ");
  Serial.println(pos_B);       
}


Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 16, 2014, 01:05 am
Take note of the coil pin numbers that I have used..check that they will match your setup.
Retain your pin 13 LED as it is in this code to indicate motor movement ... ON when the steppers are instructed to move and turns OFF when they are idle for 3 secs.

I'd suggest these settings for the Android phone
Go into in Options ...Joystick properties

The joystick behavior box should NOT be ticked.
& Joystick constraint should be BOX.


2nd lump of code....

Code: [Select]
void getButtonState(int bStatus)  {
  switch (bStatus) {
    // ----  BUTTON #1
  case 'A':
    buttonStatus |= B000001;        // ON
    Serial.println("\n** Button_1: ON **");
    // your code...     
    displayStatus = "LED <ON>";
    Serial.println(displayStatus);
    // digitalWrite(ledPin, HIGH);
    break;
  case 'B':
    buttonStatus &= B111110;        // OFF
    Serial.println("\n** Button_1: OFF **");
    // your code...     
    displayStatus = "LED <OFF>";
    Serial.println(displayStatus);
    // digitalWrite(ledPin, LOW);
    break;

    // ------  BUTTON #2 
  case 'C':
    buttonStatus |= B000010;        // ON
    Serial.println("\n** Button_2: ON **");
    // your code...     
    displayStatus = "Button2 <ON>";
    Serial.println(displayStatus);
    break;
  case 'D':
    buttonStatus &= B111101;        // OFF
    Serial.println("\n** Button_2: OFF **");
    // your code...     
    displayStatus = "Button2 <OFF>";
    Serial.println(displayStatus);
    break;

    // ------  BUTTON #3
  case 'E':
    buttonStatus |= B000100;        // ON
    Serial.println("\n** Button_3: ON **");
    // your code...     
    displayStatus = "Motor #1 enabled"; // Demo text message
    Serial.println(displayStatus);
    break;
  case 'F':
    buttonStatus &= B111011;      // OFF
    Serial.println("\n** Button_3: OFF **");
    // your code...     
    displayStatus = "Motor #1 stopped";
    Serial.println(displayStatus);
    break;

    // ---  BUTTON #4
  case 'G':
    buttonStatus |= B001000;       // ON
    Serial.println("\n** Button_4: ON **");
    // your code...     
    displayStatus = "Datafield update <FAST>";
    Serial.println(displayStatus);
    sendInterval = FAST;
    break;
  case 'H':
    buttonStatus &= B110111;    // OFF
    Serial.println("\n** Button_4: OFF **");
    // your code...     
    displayStatus = "Datafield update <SLOW>";
    Serial.println(displayStatus);
    sendInterval = SLOW;
    break;

    // ----  BUTTON #5
  case 'I':           // configured as momentary button
    //      buttonStatus |= B010000;        // ON
    Serial.println("\n** Button_5: ++ pushed ++ **");
    // your code...     
    displayStatus = "Button5: <pushed>";
    break;
    //   case 'J':
    //     buttonStatus &= B101111;        // OFF
    //     // your code...     
    //     break;

    // ----  BUTTON #6
  case 'K':
    buttonStatus |= B100000;        // ON
    Serial.println("\n** Button_6: ON **");
    // your code...     
    displayStatus = "Button6 <ON>"; // Demo text message
    break;
  case 'L':
    buttonStatus &= B011111;        // OFF
    Serial.println("\n** Button_6: OFF **");
    // your code...     
    displayStatus = "Button6 <OFF>";
    break;
  }
}









Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 16, 2014, 05:00 am
Thanks Woody, that was fast.

I've tried the code and for some reason the motor turns only one direction and after a while the motor turns off. 

I guess this is the code that is turning it off - #define  TIMEOUT     3000    //Turns off after 3 secs of inactivity.  I know that is in the code I sent you, but for some reason it's not turning back on when I move the pod.

I only hooked up one motor, I think thats why it's interpreted as inactivity.  Maybe?  I'll hook up the other motor to see what happens.

Thanks...........Antonio
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 16, 2014, 05:13 am
I've hooked up the second motor and change the pin numbers to match what I have as you said, both motors work, but they both turn in one direction regardless of what I'm doing on the BT commander. And then they turn off.

Thanks...........Antonio
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 16, 2014, 07:51 am
Quote
I just tried your code and the Commander is sending data to the arduino, GREAT, THANKS
So what ??

(http://i.imgur.com/ZktxOg3.png)

Why couldn't you see data in the Arduino serial monitor ??
Please explain, as it may be useful for the Community

The onboard TX led does reflect Serial activity (not mySerial), and will flash when data is sent to the Serial Monitor

Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 16, 2014, 09:08 am
Thanks Woody, that was fast.

I've tried the code and for some reason the motor turns only one direction and after a while the motor turns off. 

I guess this is the code that is turning it off - #define  TIMEOUT     3000    //Turns off after 3 secs of inactivity.  I know that is in the code I sent you, but for some reason it's not turning back on when I move the pod.

I only hooked up one motor, I think thats why it's interpreted as inactivity.  Maybe?  I'll hook up the other motor to see what happens.

Thanks...........Antonio
I ASSumed that you could also see activity on the PC monitor via the Serial port ...  it would seem that you cannot... therefore I believe that your original problem still exists.

The stepper code will ...I think .... without any input from the Android joystick ..cause the motors to simply settle @ a end position defined by PotVal 0 and Pos 1024.

So ... it's back to trying to figure out the underlying cause... and get some numbers scrolling on the screen.



Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 16, 2014, 10:29 am
I've modified the first lump of stepper code ...nothing that will fix the problem.... I've simply moved the serial print block up the code and added in a set start position for the stepper.

NOTE:- I never used or programmed steppers.

This should give you something to see on the screen.... but I suspect that it will be static.

However ...try it ...press the buttons on the phone and wiggle the stick..see if ANYTHING changes on the serial monitor screen.

Code: [Select]

  
#define VERSION     "\n\nAndroTest V2.0 - @kas2014\ndemo for V5.x App"
#include "SoftwareSerial.h"
#include <Stepper.h>

#define rxPin 2
#define txPin 3

// change this to the number of steps on your motor
#define  STEPSREV    2047    // 64(fullsteps) * 64 (reduction ratio)= 4096

#define  COIL1_A    11
#define  COIL2_A     9
#define  COIL3_A    10
#define  COIL4_A     8

#define  COIL1_B    4 // ???  PIN NUMBERS GUESSED
#define  COIL2_B    5
#define  COIL3_B    6
#define  COIL4_B    7

#define  ENER_A       13       //Motor A Status led
//#define  ENER_B       ?     //Motor B Status led do you wish a seperate one?

#define  TIMEOUT     3000    //Turns off after 3 secs of inactivity.

// create an instance of the stepper class, specifying
// the number of steps per revolution and pins atached to motor coils.
Stepper myStepperA(STEPSREV, COIL1_A, COIL2_A, COIL3_A, COIL4_A);
Stepper myStepperB(STEPSREV, COIL1_B, COIL2_B, COIL3_B, COIL4_B);
int PotValA;
int PotValB;
int pos_A = 1024;              // stepper A position(0-4096)->(0-360°) CENTERED
int pos_B = 1024;              // stepper B position (0-4096)->(0-360°)CENTERED
unsigned long stamp_A = 0;  // last A move time stamped.
unsigned long stamp_B = 0;  // last B move time stamped.
#define    STX          0x02
#define    ETX          0x03
//#define    ledPin       13
#define    SLOW         750                            // Datafields refresh rate (ms)
#define    FAST         250                             // Datafields refresh rate (ms)

SoftwareSerial mySerial(rxPin,txPin);  // BlueTooth module: pin#2=TX  pin#3=RX
byte cmd[8] = {
  0, 0, 0, 0, 0, 0, 0, 0};                 // bytes received
byte buttonStatus = 0;                                  // first Byte sent to Android device
long previousMillis = 0;                                // will store last time Buttons status was updated
long sendInterval = SLOW;                               // interval between Buttons status transmission (milliseconds)
String displayStatus = "xxxx";                          // message to Android device

void setup()  {
  PotValA = 1023;
  PotValB = 1023;
  Serial.begin(57600);
  mySerial.begin(57600);   // 57600 = max value for softserial
  pinMode(txPin, OUTPUT);
  pinMode(rxPin, INPUT);
  myStepperA.setSpeed(4);  // set the motor speed to 4 RPM
  myStepperB.setSpeed(4);  // set the motor speed to 4 RPM
  pinMode(ENER_A , OUTPUT);
  //  pinMode(ENER_B , OUTPUT);  
  Serial.println(VERSION);
  while(mySerial.available())  mySerial.read();         // empty RX buffer
}

void loop() {
  if(mySerial.available())  {                           // data received from smartphone
    delay(2);
    cmd[0] =  mySerial.read();  
    if(cmd[0] == STX)  {
      int i=1;      
      while(mySerial.available())  {
        delay(1);
        cmd[i] = mySerial.read();
        if(cmd[i]>127 || i>7)                 break;     // Communication error
        if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
        i++;
      }
      if     (i==2)          getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
      else if(i==7)          getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
    }

    if(abs(PotValA - pos_A)> 4){  //if diference is greater than 4 steps.
      if((PotValA - pos_A)> 0){
        digitalWrite(ENER_A, HIGH);   //Motor ENER_Agized.    
        myStepperA.step(1);    // move one step to the right.
        pos_A++;
      }
      if((PotValA - pos_A)< 0){
        digitalWrite(ENER_A, HIGH);   //Motor ENER_Agized.
        myStepperA.step(-1);    // move one step to the left.
        pos_A--;
      }
      stamp_A = millis();  // stamp actual time.  
    }

    if(abs(PotValB - pos_B)> 4){ //if diference is greater than 4 steps.
      if((PotValB - pos_B)> 0){
        digitalWrite(ENER_A, HIGH);  //Motor ENER_Agized. ********   ENER_A led used ...change to ENER_B if required and define another led number
        myStepperB.step(1);  // move one step to the right.
        pos_B++;
      }
      if((PotValB - pos_B)< 0){
        digitalWrite(ENER_A, HIGH);   //Motor ENER_Agized.********  ENER_A led used ...change to ENER_B if required and define another led number
        myStepperB.step(-1);  // move one step to the left.
        pos_B--;
      }
      stamp_B = millis(); // stamp actual time.
    }
    else {      
      if((millis() - stamp_A) > TIMEOUT){   //Turn Off coils after TIMEOUT.
        digitalWrite(COIL1_A, LOW);
        digitalWrite(COIL2_A, LOW);
        digitalWrite(COIL3_A, LOW);
        digitalWrite(COIL4_A, LOW);
        digitalWrite(ENER_A, LOW); //Motor de-ENER_Agized.

        if((millis() - stamp_B) > TIMEOUT)//Turn Off coils after TIMEOUT.
          digitalWrite(COIL1_B, LOW);
        digitalWrite(COIL2_B, LOW);
        digitalWrite(COIL3_B, LOW);
        digitalWrite(COIL4_B, LOW);
        digitalWrite(ENER_A, LOW);//Motor de-ENER_Agized.Motor *********   ENER_A led used ...change to ENER_B if required and define another led number
      }

    }
  }

  sendBlueToothData();
  
  Serial.print("PotValA");
  Serial.print("  :  ");
  Serial.print(PotValA);          
  Serial.print("  :  ");  
  Serial.print("pos_A");
  Serial.print("  :  ");
  Serial.print(pos_A);  
  Serial.print("  :  ");
  Serial.print("PotValB");
  Serial.print("  :  ");
  Serial.print(PotValB);
  Serial.print("  :  ");  
  Serial.print("pos_B");
  Serial.print("  :  ");
  Serial.println(pos_B);
}

void sendBlueToothData()  {
  static long previousMillis = 0;                            
  long currentMillis = millis();
  if(currentMillis - previousMillis > sendInterval) {   // send data back to smartphone
    previousMillis = currentMillis;

    // Data frame transmitted back from Arduino to Android device:
    // < 0X02   Buttons state   0X01   DataField#1   0x04   DataField#2   0x05   DataField#3    0x03 >  
    // < 0X02      "01011"      0X01     "120.00"    0x04     "-4500"     0x05  "Motor enabled" 0x03 >    // example

    mySerial.print((char)STX);                                             // Start of Transmission
    mySerial.print(getButtonStatusString());  
    mySerial.print((char)0x1);   // buttons status feedback
    mySerial.print(GetdataInt1());            
    mySerial.print((char)0x4);   // datafield #1
    mySerial.print(GetdataFloat2());          
    mySerial.print((char)0x5);   // datafield #2
    mySerial.print(displayStatus);                                         // datafield #3
    mySerial.print((char)ETX);                                             // End of Transmission
  }  
}

String getButtonStatusString()  {
  String bStatus = "";
  for(int i=0; i<6; i++)  {
    if(buttonStatus & (B100000 >>i))      bStatus += "1";
    else                                  bStatus += "0";
  }
  return bStatus;
}

int GetdataInt1()  {   // Data dummy values sent to Android device for demo purpos_Ae
  static int i= -30;  // Replace with your own code
  i ++;
  if(i >0)    i = -30;
  return i;  
}

float GetdataFloat2()  { // Data dummy values sent to Android device for demo purpos_Ae
  static float i=50; // Replace with your own code
  i-=.5;
  if(i <-50)    i = 50;
  return i;  
}

void getJoystickState(byte data[8])    {
  int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
  int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
  joyX = joyX - 200;                                                  // Offset to avoid
  joyY = joyY - 200;                                                  // transmitting negative numbers

  if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)       return;   // commmunication error

  PotValA =  map (joyX,-100,100,0,2047);//  Map joyX range in the stepper range motor 1
  PotValB =  map (joyY,-100,100,0,2047);//  Map joyY  range in the stepper range motor 2


      
}

Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 16, 2014, 03:41 pm
@ Kas.

Seeing as how getButtonState appears fine ..... would there be any reason that getButtonState would work ....but getJoystickState is blocked or not implemented?

 
Code: [Select]
if     (i==2)          getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
      else if(i==7)          getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >


Woody
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 16, 2014, 06:11 pm
Hi Kas,

I am seeing data now.  I've tried your code the one that you told should show a line of numbers on the serial monitor and I do see data on the serial monitor.  That video I shot before I tried your code.

Thanks

Woody,

The code with the changes that you posted above, won't compile, here's the error,
      'getButtonState' was not declared in this scope, 

Here's the line:
      if     (i==2)          getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >

I'm posting a video that I just shot with your previous code so you can see what the steppers are doing.

Thanks 
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 16, 2014, 06:23 pm
Quote
Hi Kas,
I am seeing data now.  I've tried you the do and I do see data on the serial monitor.  That video I shot before I tried your code.
Are you now seeing both Joystick AND button info's in serial monitor, using AndroTest V2.0  ??
What was wrong in your setup ??



Quote
@kas
Seeing as how getButtonState appears fine ..... would there be any reason that getButtonState would work ....but getJoystickState is blocked or not implemented?
Quick check:
Code: [Select]
     
Serial.print("i=");  Serial.println(i);         // <<--- debug
if     (i==2)        getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
else if(i==7)        getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 16, 2014, 07:16 pm
Hi Kas,

The code above won't compile, here's the error for this line
Serial.print("i=");  Serial.println(i);         // <<--- debug 

Error.
expected constructor, destructor, or type conversion before ."token

Sorry, I wish I knew how to fix it.
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 16, 2014, 07:35 pm
Kas,

Here's the video showing what I can see in the serial monitor.

https://www.youtube.com/watch?v=sDAlXYJT6wA&feature=youtu.be

Let me know what you think.

Thanks
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 16, 2014, 07:36 pm
Quote
The code above won't compile, here's the error for this line
Serial.print("i=");  Serial.println(i);         // <<--- debug 
This line is to be added to AndroTest V2.0   ;)

just before
Code: [Select]
if     (i==2)        getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
else if(i==7)        getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 16, 2014, 09:11 pm
Woody,

The code with the changes that you posted above, won't compile, here's the error,
      'getButtonState' was not declared in this scope, 

Here's the line:
      if     (i==2)          getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >

I'm posting a video that I just shot with your previous code so you can see what the steppers are doing.

Thanks 
I don't think you read my post correctly ....
Quote
I've modified the first lump of stepper code
.. this combined with the second lump that contains the  getButtonState routine will be the COMPLETE code.


2nd lump....
Code: [Select]
void getButtonState(int bStatus)  {
  switch (bStatus) {
    // ----  BUTTON #1
  case 'A':
    buttonStatus |= B000001;        // ON
    Serial.println("\n** Button_1: ON **");
    // your code...     
    displayStatus = "LED <ON>";
    Serial.println(displayStatus);
    // digitalWrite(ledPin, HIGH);
    break;
  case 'B':
    buttonStatus &= B111110;        // OFF
    Serial.println("\n** Button_1: OFF **");
    // your code...     
    displayStatus = "LED <OFF>";
    Serial.println(displayStatus);
    // digitalWrite(ledPin, LOW);
    break;

    // ------  BUTTON #2 
  case 'C':
    buttonStatus |= B000010;        // ON
    Serial.println("\n** Button_2: ON **");
    // your code...     
    displayStatus = "Button2 <ON>";
    Serial.println(displayStatus);
    break;
  case 'D':
    buttonStatus &= B111101;        // OFF
    Serial.println("\n** Button_2: OFF **");
    // your code...     
    displayStatus = "Button2 <OFF>";
    Serial.println(displayStatus);
    break;

    // ------  BUTTON #3
  case 'E':
    buttonStatus |= B000100;        // ON
    Serial.println("\n** Button_3: ON **");
    // your code...     
    displayStatus = "Motor #1 enabled"; // Demo text message
    Serial.println(displayStatus);
    break;
  case 'F':
    buttonStatus &= B111011;      // OFF
    Serial.println("\n** Button_3: OFF **");
    // your code...     
    displayStatus = "Motor #1 stopped";
    Serial.println(displayStatus);
    break;

    // ---  BUTTON #4
  case 'G':
    buttonStatus |= B001000;       // ON
    Serial.println("\n** Button_4: ON **");
    // your code...     
    displayStatus = "Datafield update <FAST>";
    Serial.println(displayStatus);
    sendInterval = FAST;
    break;
  case 'H':
    buttonStatus &= B110111;    // OFF
    Serial.println("\n** Button_4: OFF **");
    // your code...     
    displayStatus = "Datafield update <SLOW>";
    Serial.println(displayStatus);
    sendInterval = SLOW;
    break;

    // ----  BUTTON #5
  case 'I':           // configured as momentary button
    //      buttonStatus |= B010000;        // ON
    Serial.println("\n** Button_5: ++ pushed ++ **");
    // your code...     
    displayStatus = "Button5: <pushed>";
    break;
    //   case 'J':
    //     buttonStatus &= B101111;        // OFF
    //     // your code...     
    //     break;

    // ----  BUTTON #6
  case 'K':
    buttonStatus |= B100000;        // ON
    Serial.println("\n** Button_6: ON **");
    // your code...     
    displayStatus = "Button6 <ON>"; // Demo text message
    break;
  case 'L':
    buttonStatus &= B011111;        // OFF
    Serial.println("\n** Button_6: OFF **");
    // your code...     
    displayStatus = "Button6 <OFF>";
    break;
  }
}








Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 16, 2014, 10:00 pm
Antonio I think that the problem is nearly identified ...that doesn't however mean that the reason for the problem will be sorted.


Try inserting that extra line of code that Kas posted into the  AndroTest V2.0 ....in the position indicated.

THEN when you run the new modified code you should see i=7 ...which I believe gives a cue for reading the joystick value ...or ... when a button is pressed i=2 a cue that a button has been pressed go read it's value.






Title: Re: Android Bluetooth joystick
Post by: kas on Dec 16, 2014, 10:46 pm
Quote
Kas,

Here's the video showing what I can see in the serial monitor.
https://www.youtube.com/watch?v=sDAlXYJT6wA&feature=youtu.be
Let me know what you think.

Thanks
:smiley-eek:  :smiley-eek:
In this video datafields and button state are no more updated
Button #5 is configured as "push button" and should be reset by Arduino within 750 milliseconds
Is that the unmodified V2.0 sketch ??
Did you change the mySerial pins ??

Add the debug line to a fresh V2.0 and let us have the result


EDIT
Any possibility to test the App with another Android smartphone or tablet ??
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 16, 2014, 11:21 pm
Kas ... I've had the data field etc become just xxx ...and stay like that after reconnecting to the Blue Tooth....but only when I've been playing about uploading new code to the Arduino with the Joystick Commander App still ON ...turning the App OFF then ON again resolves this for me. 


Is it OK to remove the if(i==7) and just have else?
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 17, 2014, 01:04 am
Hi Kas, Woody,

Here's the video showing the this code


Code: [Select]
     
Serial.print("i=");  Serial.println(i);         // <<--- debug
if     (i==2)        getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
else if(i==7)        getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >


inserted just before  
Code: [Select]
if     (i==2)        getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
else if(i==7)        getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >


https://www.youtube.com/watch?v=5HIAY2zPf7I&feature=youtu.be



Let me know what's going on.............Thanks.........Antonio
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 17, 2014, 01:29 am
Well that seems to explain it!!..Your seeing i=2 for a button press which is CORRECT.

BUT i=5 is WRONG it should be i=7 ....if it isn't a 7 it'll never look down the code at the joystick input.

This isn't your fault Antonio...just an unexpected and unforeseen circumstance.

Kas probably won't be on till tomorrow ....he is the man that will know more ...in the mean time you could try changing that 7 in the line

else if(i==7)          getJoystickState(cmd);

to a 5 and see what happens...so it becomes.

 else if(i==5)          getJoystickState(cmd);

OR..just change it to my favorite option which is.

 else  getJoystickState(cmd);

which means that if the number isn't a 2 it WILL go down the code for any joystick values.

Woody


Goodnight ..it's 00.48am here in the U.K.  ZZZZzzzzzzzzzzzzzzzzzzzzzzz
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 17, 2014, 10:07 am
Quote
Is it OK to remove the if(i==7) and just have else?
No it won't work

i<>2 and i<>7 means "communication error"
You can't expect valid data out of bad data frames
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 17, 2014, 10:59 am
No it won't work

i<>2 and i<>7 means "communication error"
You can't expect valid data out of bad data frames
I realise that the joystick data read... if any ... by removing the if and i==7 may not be valid but it would give Antonio "hope" to see something being produced by the joystick .... even if it is WRONG.

But your right it may well be best to track down the real reason for the problem.

So.

Any idea of what the data problem is likely to be or the solution?

Do you suspect that it is simply the current Android phone being used that is at fault?

Cheers Woody
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 17, 2014, 11:41 am
@antonio

This is my personal V2 debug version, don't break it  ;)

You should see that type of info  on your Serial Monitor:

(http://i.imgur.com/41DBlEQ.png)

See reply #252 for data frame explanations
The last 3 numbers on the right are errors, sorted by categories

Please let us have a new video



@woody
Quote
Do you suspect that it is simply the current Android phone being used that is at fault?
Data transmission is not far from Black Magic  :smiley-evil:
very sensitive to timing issues that could be generated by an underpowed device

Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 17, 2014, 12:01 pm
Quote
@woody
Quote
Do you suspect that it is simply the current Android phone being used that is at fault?
Data transmission is not far from Black Magic  :smiley-evil:
very sensitive to timing issues that could be generated by an underpowed device
Uuummmm .... was that a yes ,no or maybe?  :o 
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 17, 2014, 01:17 pm
Quote
Uuummmm .... was that a yes ,no or maybe? 
Still hesitating for the moment  ;)
Dual-core 1.2 GHz should be plenty enough
Let's wait for Antonio's data frames
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 17, 2014, 05:57 pm
Kas,

I downloaded - AndroTest_V20_POSTED_DEBUG.ino from your post #425, this is the same one as before, I'm assuming, but I downloaded again to make sure and that is what you want me to try, correct?

Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 17, 2014, 06:37 pm
Kas and Woody,

Here's the video, towards the end of the video I zoom in while using the phone, at that point you'll be able to see the data up close.

https://www.youtube.com/watch?v=Hav3gtyR1UQ&feature=youtu.be

Now I'm assuming that I'm not the only guy that this is happening to?.....maybe?  However, I have been know to lose a bet on a one horse race.  Hopefully this is not the case here.




Thanks.............Let me know what's going on.
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 17, 2014, 07:18 pm
Thanks Antonio,

I now see what happens

Please go to setup and press "reset options"

also, In AndroTest_V20_POSTED_DEBUG.ino, within this code snipet:
Code: [Select]
     while(mySerial.available())  {
       delay(1);    //   <----------<<
       cmd[i] = mySerial.read();
       if(cmd[i]>127 || i>7)                 break;     // Communication error
       if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
       i++;
     }

try increasing delay
change
  delay(1);
to
  delay(2);
and see if errors are disappearing

 
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 17, 2014, 08:05 pm
Also, in the App, try Option >> advanced users >> refresh interval: 100 milliseconds
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 17, 2014, 10:16 pm
Code: [Select]
     while(mySerial.available())  {
       delay(1);
       cmd[i] = mySerial.read();
       if(cmd[i]>127 || i>7)                 break;     // Communication error
       if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
       i++;
     }

within AndroTest V2, this "while" loop does collect the incoming data frame and should succesfully exit when receiving an ETX (0x03) byte.
Error exit is triggered if received Byte is >127 or frame lenght is >8

As you see, for some reason, Arduino receives Bytes >127 (149, 144, 176 ...) and a Data frame error is generated.
(http://i.imgur.com/7nNxWKO.png)

Now... why and where are these Bytes generated  :smiley-roll:  :smiley-roll:  :smiley-roll:
- from the Android device
>> reset App options to factory default
>> increase delay(1)
>> set refresh interval to 100 milliseconds
>> test the App on another Android smartphone

- from the BT card 
>> change card baud rate (38400bps)
>> setup another card


Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 18, 2014, 01:03 am
Thanks Kas,

As of now,

I resat the app to factory default
increased delay to (2)
sat the refresh interval to 100 milliseconds

Nothing changes, all remains the same.


So, I'm trying to find someone with an android phone or tablet that I can use, so we'll see what  happens.

Thanks.........and talk to you later.
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 18, 2014, 03:24 pm
I tried to reproduce these errors without success   :-\  :-\

This is a call for witnesses
- buttons data display = OK
- joystick data display = not OK

Anyone ??


>> EDIT <<
Problem solved using a genuine Uno     :smiley-evil:  :smiley-evil:  :smiley-evil:
See reply #447


Antonio,

1) In loop() function, try commenting last line:
 sendBlueToothData();    ->    // sendBlueToothData();
 This will stop Arduino to Android communication and reduce Bluetooth traffic

2) Also for the good sake, confirm again your BT card baudrate

3) Finally let us know the outcome, using another phone/tablet
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 22, 2014, 05:36 pm
Kas,

Would this explain the problems?

http://forum.dev.arduino.cc/index.php?topic=140299.0 (http://forum.dev.arduino.cc/index.php?topic=140299.0)

I've sent Antonio this utility/program that I found sometime ago ...( it's mentioned in the link above )...to check and or set the Baud rate.

Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 22, 2014, 08:09 pm
Woody, Kas

Here's another video showing my latest attempt. 

https://www.youtube.com/watch?v=pcYE50oG6UE&feature=youtu.be

Refresh interval - set at 100 milliseconds




Thanks..............Let me know what you think.
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 22, 2014, 09:01 pm
Quote
Kas,
Would this explain the problems?
http://forum.dev.arduino.cc/index.php?topic=140299.0
Interesting comment in the thread you mentioned:
Quote
If I use the Hardware serial ports on the Mega, everything works perfectly, no odd bits  :smiley-eek:
Using SoftwareSerial it does not work on the Uno or Mega.
So I assume that the Bluetooth module is fine, but the SoftwareSerial has a problem
Antonio,
Please confirm you have a Mega Arduino available
This board has several hardware serial ports that may solve the problem
I will then prepare a V2.0 sketch for the Mega, for you to test
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 22, 2014, 09:12 pm
Note that Antonios video shows rubbish for the end of the name linvor.

Here's a pic of mine.

Title: Re: Android Bluetooth joystick
Post by: kas on Dec 22, 2014, 09:47 pm
Quote
Note that Antonios video shows rubbish for the end of the name linvor
Yes, seen that  ::)

The two remaining potential culprits are BT card and Softserial/Arduino board
Let's try a Mega board

Here is the code for the Mega

Attach pin#18 to RX bluetooth module and pin#19 to TX bluetooth module
Do not modify delay(1)
Reset options to factory setting in the App

Next stop: BT card ;)
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 23, 2014, 12:56 am
Here it is........

https://www.youtube.com/watch?v=mN3R-YLwtmY&feature=youtu.be

So what does this mean?



Thanks..............Antonio

Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 23, 2014, 01:42 am
I'm fairly sure that it means that the Uno has issues with the code. 

SoftwareSerial wasn't used in the Mega version as it has extra serial ports built in and everything seemed to work just fine.

Quote
The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18 (TX), Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX).
http://arduino.cc/en/Reference/softwareSerial (http://arduino.cc/en/Reference/softwareSerial)
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 23, 2014, 11:41 am
Great it finally works  :)  :)  :)  :)




Quote
Quote
Note that Antonios video shows rubbish for the end of the name linvor
Yes, seen that  ::)
Same beheaviour in AndroTest_V20_POSTED_DEBUG.ino
(http://i.imgur.com/HAFo9LM.jpg)

and in Antonio's video (https://www.youtube.com/watch?v=pcYE50oG6UE&feature=youtu.be) at 01:30
(http://i.imgur.com/ZQjWXsQ.jpg)
in both cases, 4 to 5 "good" Bytes, then rubbish
Thus this problem does not seem related to Android BT Joystick or AndroTest_V20



Quote
I'm fairly sure that it means that the Uno has issues with the code
Right, there is definitely something wrong between your clone Uno and the SoftSerial library
Please confirm you also tested the code with the genuine Uno

Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 23, 2014, 12:23 pm
Quote
Please confirm you also tested the code with the genuine Uno
Extract from Antonio's last email to me should answer that....

Quote
I had tried two different Unos and neither worked.  Maybe it's because they're not authentic Arduino Unos
I've sent him a revised Mega version for his steppers ...hopefully this will work.
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 23, 2014, 04:14 pm
@woody
Quote
I've sent him a revised Mega version for his steppers ...hopefully this will work
No real need for a Mega, you can still use the Uno w/o SoftSerial
Just connect to the normal Serial port (pin #0 & pin #1) for Bluetooth communication
Don't forget to disconnect pin #0 before uploading a new sketch to the board



@Antonio,
Tell us more about your project     a new photo gizmo ??   ;)  ;)

Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 23, 2014, 04:42 pm
Quote
No real need for a Mega, you can still use the Uno w/o SoftSerial
Just connect to the normal Serial port (pin #0 & pin #1) for Bluetooth communication
Don't forget to disconnect pin #0 before uploading a new sketch to the board
Let's try with something that definitely works first before stressing Antonio out with more instructions! :smiley-wink:
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 24, 2014, 09:54 pm
Hi Guys,

I've been real busy with relatives, I'll try an authentic Uno tomorrow and post a video.


Thanks.................Antonio
Title: Re: Android Bluetooth joystick
Post by: AntonioLopez on Dec 30, 2014, 06:31 am
Kas and Woody,

Here's another video showing the results of using an authentic Arduino uno.

https://www.youtube.com/watch?v=Ty8VpjdsmjI&feature=youtu.be



Let me know what you think........Thanks.............Antonio
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 30, 2014, 11:17 am
Hi Antonio,

It's definitely working using a genuine Uno     :smiley-evil:  :smiley-evil:  :smiley-evil:

The two clones you tested probably have inaccurate ceramic resonators
Please let me have a link to these two boards, I would like to clarify this matter

You may have good reasons to use stepper motors, did you consider servo motors ??
Have a look at thornlv project, starting at message #234


Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 30, 2014, 05:30 pm
Hi Kas,

One of the users of the wheelchair Blue Tooth device is having problems getting the APP to CONNECT to the Blue Tooth board.

It pairs fine via the tablet ..but refuses to connect via the App.

He is using a ....

Samsung Galaxy Tab 2 with 8GB internal RAM and a 32 GB external RAM; Model GT-P3100XXLD4; Android 4.03;

Any ideas?


Cheers Woody

Title: Re: Android Bluetooth joystick
Post by: kas on Dec 30, 2014, 07:03 pm
Hi Woody,

Quote
One of the users of the wheelchair Blue Tooth device is having problems getting the APP to CONNECT to the Blue Tooth board
"Auto connect at start up" should be unchecked for the very first connection.
First connection should be performed manually using the <Connect> menu item
Joystick BT Commander will then remember the BT card MAC address for futur Auto connections

Please ask user to <reset options> and try again

Let me know


Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 30, 2014, 08:09 pm
No joy Kas,


Quote
Done done and done.. still BT not connected... but as we had before it still pairs successfully under the Tablet settings.. I've tried all combinations.. It shows the Mac address no probs... but simply won't talk to it...

Phil and I have been trying various combinations all day.


Information that might help.

This App seems to connect fine .....

Quote
I've just loaded another App called USBJoyService... selected something called Moga Pro Bluetooth... and it has connected perfectly to it... my blue light is flashing like mental.... the problem is definitely with the Ardruino App's compatibility with Galxy Tab2  7" tablet....
With a bit of luck Phil can try a borrowed phone tomorrow.

Cheers Woody
(http://s2.postimg.org/870aanveh/Screenshot_2014_12_30_15_43_50_resized.png)
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 30, 2014, 09:38 pm
Quote
It shows the Mac address no probs... but simply won't talk to it...
Just to make it clear:
(http://i.imgur.com/Dclufjw.png)
The BT board name and MAC address do appear in BT Commander    >>correct??


The HC-06 BT board led should change from blinking to solid green when connected
but it does keep blinking    >>correct??


Quote
The problem is definitely with the Ardruino App's compatibility with Galxy Tab2  7" tablet....
Not sure  ::) ,  I personally use a Galaxy (Tab3)


Quote
With a bit of luck Phil can try a borrowed phone tomorrow
Let's see


Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 30, 2014, 10:06 pm
Quote
The HC-06 BT board led should change from blinking to solid green when connected
but it does keep blinking    >>correct??
If Phil connects to the BTchair bluetooth device via the USBJoyService and Moga Pro Bluetooth THEN he gets a blinking EXTERNAL Blue led that I use as an indication of connection .... it serves much the same purpose as the solid green on the actual board.

Note that I have modified your Arduino code with the addition of a time out failsafe for the Bluetooth.... this could be the reason for this BLUE led flashing on/off when using the above App.

I think that I lifted the failsafe code from one of the other projects.
snippet below
Code: [Select]
long deadManInterval = 110;                              // milisecs interval between
boolean deadManEnabled = true;                          // stop chair if BT com is lost
boolean deadManTimeout = false;   



Quote
The BT board name and MAC address do appear in BT Commander    >>correct??
Quote
Yes they do... it is BTchair and then a series of numbers...phil
Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 30, 2014, 10:30 pm
video of earlier attempt ... before posting the original question ... to PAIR via the App
https://www.youtube.com/watch?v=cvsqpx2JZ6k&feature=youtu.be (https://www.youtube.com/watch?v=cvsqpx2JZ6k&feature=youtu.be)

The green and red led's are direction indicators for forward/reverse &  left/right they also indicate a lack of BT signal by blinking.
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 31, 2014, 05:03 pm
Quote
video of earlier attempt ... before posting the original question ... to PAIR via the App
https://www.youtube.com/watch?v=cvsqpx2JZ6k&feature=youtu.be
:smiley-roll-blue:  :smiley-roll-blue:  :smiley-roll-blue:   I don't get it

Pairing should be done at the tablet level, not within App
A factory reset App shouldn't even try to connect at start up

This is a screenshot @00:22
(http://i.imgur.com/GkMiM0U.png)


For a new board
 - Pair from the Tablet
 - Launch the App
 - Menu > Connect
 - Select the right BT board (BTchair) within paired devices
 - App should display "connecting" and finally connect to the board

Please let me have a video showing this process

Title: Re: Android Bluetooth joystick
Post by: woodygb on Dec 31, 2014, 08:11 pm
Phil was getting desperate and trying every combination that he could.


I had previously sent this to him.

Quote
30 December 2014 16:14
To:
Subject: Re: Pictures of screenshots

 

The order seems wrong ...

PAIR device via TABLET

Do not CONNECT to device just PAIR

Start BT Commander App

tap the cog symbol top right

Connect   Options   reset Opt    About           appears on the bottom line

tap Connect

at this point my phone lists the paired BlueTooth devices. 

Select

BTchair ....there are no extra questions or requests
 
Title: Re: Android Bluetooth joystick
Post by: kas on Dec 31, 2014, 08:25 pm
OK, let's wait for the video

EDIT    make sure that:
- Option/Advanced users/Auto connect is unchecked
- the BT card is not already connected to another device


Happy New Year to you and to the Community  8)  8)




Title: Re: Android Bluetooth joystick
Post by: woodygb on Jan 02, 2015, 06:11 pm
A happy new year to you as well Kas.

UPDATE ...copy & paste

Quote
Hi Woody

I've just tried it with my son's Android Samsung Galaxy S5, which is running Android 4.4.4 KitKat, and it WORKS albeit very slowly (as in my chair drives only when on 100%, but that might be because I'm a bit heavy, but it works.. SO there must be an issue with my Android communication, whether it's the version of Blutooth or the version of Android which on mine is Android 4.0.3 Samsung Galaxy Tab 2 7.0...

Interesting lol

Happy New Year.

Phil

Woody
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 03, 2015, 01:21 pm
Quote
I've just tried it with my son's Android Samsung Galaxy S5, which is running Android 4.4.4 KitKat, and it WORKS albeit very slowly
Your task, I guess  ;)



Quote
SO there must be an issue with my Android communication, whether it's the version of Blutooth or the version of Android which on mine is Android 4.0.3 Samsung Galaxy Tab 2 7.0...
The App is compatible starting SDK 8 (Android 2.2 or higher)
Galaxy Tab2  7"  is OK

Please let me have the requested video, showing the connection process

Title: Re: Android Bluetooth joystick
Post by: woodygb on Jan 03, 2015, 08:35 pm
Quote
Your task, I guess  ;)
Yes ... It of course worked fine for me as I test every interface before posting them.:smiley-confuse:

I'm hoping it's the Advanced option settings , as the failsafe code requires that the Android device be set to CONTINOUS comms and MINIMUM timeout.

The chairs actual joystick input is coded to override the blue tooth and it works just fine.
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 03, 2015, 09:51 pm
Quote
long deadManInterval = 110;
Your Dead Man interval looks pretty short
You could try 250ms or even 500ms, and still be on the safe side


Quote
the failsafe code requires that the Android device be set to CONTINOUS comms and MINIMUM timeout
MINIMUM timeout=refresh interval 25ms ??
I advise not to use this extreme configuration combination
Depending on the Android hardware, you may experience communication errors

Title: Re: Android Bluetooth joystick
Post by: woodygb on Jan 04, 2015, 02:55 pm
Hi Kas.

As requested a video.

https://www.youtube.com/watch?v=P2EinIpXWrA&index=15&list=PL86DD36CCC47E6662 (https://www.youtube.com/watch?v=P2EinIpXWrA&index=15&list=PL86DD36CCC47E6662)
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 05, 2015, 08:08 am
I can't understand why the App requests pairing again, as the tablet is allready paired to the BT card


Please exit/relaunch App
Tap connect
is the BT card (BTchair) still registered as "paired" ??
Will the pairing screen still pop in when selecting BTchair ??


Last try: completely uninstall App and reload from Google Play

Title: Re: Android Bluetooth joystick
Post by: viperfan7 on Jan 19, 2015, 08:14 pm
Just wondering if there's anyway to get this working with something like the BLEBee which uses Bluetooth low energy. I'd be willing to try to get it working myself
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 21, 2015, 07:55 am
Quote
Just wondering if there's anyway to get this working with something like the BLEBee which uses Bluetooth low energy. I'd be willing to try to get it working myself
Hi viperfan7,

The App should connect to BLEBee provided your Android hardware is compatible with BT Low Energy
BLE is supported on Android v4.3 and higher

(http://i.imgur.com/J42A6l2.png)

Let us know the outcome ;)

Title: Re: Android Bluetooth joystick
Post by: viperfan7 on Jan 21, 2015, 09:05 pm
Running it with this module: https://www.dfrobot.com/index.php?route=product/product&product_id=1073

And it just doesn't seem to want to play nicely, it'll start the connection and scan, but never complete the connection (BT Connection failed) I've set up an app that does connect to it using their libraries, mind you, I really have no idea what I'm doing on the android side of things, but I have communication with my app, but nothing usable, seems to send random data unless I'm reading the serial data wrong.

Also, when trying to connect, I see no activity from the connection state light on the module
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 22, 2015, 07:08 am
Sorry, no experience with Bluetooth 4.0  :-\

Quote
I've set up an app that does connect to it using their libraries, mind you, I really have no idea what I'm doing on the android side of things, but I have communication with my app, but nothing usable, seems to send random data unless I'm reading the serial data wrong.
Try decreasing baudrate   AT+UART=57600<CR+LF>
You may also use transparent mode  AT+FSM=FSM_TRANS_USB_COM_BLE<CR+LF>   

Did you try using el cheapo JY-MCU HC-06 ??  they work right out of the box   

Title: Re: Android Bluetooth joystick
Post by: viperfan7 on Jan 22, 2015, 06:24 pm
THats what I was thinking, too, bringing down the baud rate, because I really don't need full bandwidth, and if this doesn't work, I'll just be grabbing a bluetoothbee, the longer range of BT4.0 is nice but not really needed on these kind of projects
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 23, 2015, 07:38 am
http://www.ebay.com/sch/i.html?_sop=15&_from=R40%7CR40%7CR40%7CR40%7CR40%7CR40&_sacat=0&_nkw=bluetooth+module+HC-06+-base+-ttl&rt=nc&_dmd=1&LH_BIN=1 (http://www.ebay.com/sch/i.html?_sop=15&_from=R40%7CR40%7CR40%7CR40%7CR40%7CR40&_sacat=0&_nkw=bluetooth+module+HC-06+-base+-ttl&rt=nc&_dmd=1&LH_BIN=1)
Four bucks, shipped  8)

Title: Re: Android Bluetooth joystick
Post by: viperfan7 on Jan 24, 2015, 02:20 am
Sadly, gotta go with xbee form factor, my board is just too cluttered, running a speaker, 2 ir leds and sensors, a button, and a ping module with servo
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 29, 2015, 08:35 am
@woodygb

Quote
SO there must be an issue with my Android communication, whether it's the version of Blutooth or the version of Android which on mine is Android 4.0.3 Samsung Galaxy Tab 2 7.0...
Did you solve the connection problem ??
Have a look at this new thread (http://forum.arduino.cc/index.php?topic=239738.0)  :smiley-neutral:

Title: Re: Android Bluetooth joystick
Post by: twm47099 on Jan 31, 2015, 12:19 am
Sadly, gotta go with xbee form factor, my board is just too cluttered, running a speaker, 2 ir leds and sensors, a button, and a ping module with servo
I've had success with using kas' app with this Xbee form factor BT module:

https://www.sparkfun.com/products/11601

Note that it defaults to 115200 baud, so you may have to command it to a lower baud depending on your microprocessor.

Tom
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 01, 2015, 05:58 pm
Hi Tom,

Nice to to see you again here  :)

Did you finally have your Propeller Bot up and running ??
Care to share photo's/video's ??

Title: Re: Android Bluetooth joystick
Post by: woodygb on Feb 01, 2015, 06:41 pm
@woodygb

Did you solve the connection problem ??
Have a look at this new thread (http://forum.arduino.cc/index.php?topic=239738.0)  :smiley-neutral:


Hi Kas,

I haven't heard from Phil ....it's entirely possible that he's back in Hospital. :(

Woody
Title: Re: Android Bluetooth joystick
Post by: twm47099 on Feb 03, 2015, 10:57 pm
Hi Tom,

Nice to to see you again here  :)

Did you finally have your Propeller Bot up and running ??
Care to share photo's/video's ??


Hi Kas,

I did get the Propeller ActivityBot up and running.  Unfortunately, I am a bit under the weather recovering from a gall bladder operation, so I can't get any photos or videos at this time.

I use your app to control different modes on the ActivityBot.  The mode when it starts is just joystick control (fwd, back, right, left speed up, and slow down.)  I use the buttons to change modes.  One mode adds a Ping distance sensor in a third core and just changes an RGB LED from green to yellow to red as I drive and the bot gets nearer or further from objects.  It was a very simple addition that I really used just to learn how to start and stop cores.  (BT commander software runs in its own core that I start at the beginning of the program and keep running to the end).

The other primary mode is to put the bot under control of the CMUCAM5 Pixy color identification and tracking camera.  I use the buttons to select/deselect this mode, set the pixy control mode (proportional or fixed rotation tracking), and to select the color to be tracked.  Other buttons provide emergency stop and program end.  All of modes and  conditions can be selected/changed real time (that's why BT commander software runs in is own core). 

I use Bot to android communication to clear the button lights at program start, to set/clear the button lights depending on what the program does (when I select Pixy mode- button 4 turns on, the program deselects Ping mode and turns off the button 3 light in the android device.)  The Bot to Android communication also updates the status regarding the Pixy command mode used and the color signature chosen to track.)

I've gotten sidetracked a bit because I wanted to use Pixy's SPI data interface mode to allow more colors to be tracked, but that meant I had to learn how to include an existing fast SPI driver that incorporates native Propeller code (SPIN and Assembly language) into C programs.  That led to developing a Propeller C SPI library function and writing library functions for a number of my SPI devices.  So I haven't had time to do much additional with the Bot.

One thing of interest is that one of the propeller experts has recently written Propeller SPIN code that uses  your app.  His post is here:

http://forums.parallax.com/showthread.php/159920-Android-Control-of-Propeller-using-Joystick-BT-Commander-App-Spin-Code

Tom


Title: Re: Android Bluetooth joystick
Post by: kas on Feb 05, 2015, 08:03 am
Hi Tom,

Thanks for the update, hope you will be fully recovered very soon   :)
Take care

Title: Re: Android Bluetooth joystick
Post by: lilo on Feb 20, 2015, 08:40 pm
hello, I can't find a version of the application "Total RC Commander" on Google Play. how do I get it please?
Title: Total RC Commander
Post by: kas on Feb 21, 2015, 08:09 pm
hello, I can't find a version of the application "Total RC Commander" on Google Play. how do I get it please?
I sell this App directly (2€ / 3$), payment via Paypal

Preriquisites:
 - to be familiar with Joystick BT Commander (same Bluetooth engine)
 - to be able to connect an IP camera on a PC
 - to be able to load an .apk file in an Android device

The App was tested using Wanscam, Foscam and Moto_G smartphone cameras

More info and demo here (http://forum.arduino.cc/index.php?topic=173246.msg1998617#msg1998617)

Let me have you email address via PM

Title: Re: Android Bluetooth joystick
Post by: kas on Feb 23, 2015, 08:32 am
Quote
hello, I can't find a version of the application "Total RC Commander" on Google Play. how do I get it please?
Check your mail  ;)

Title: Re: Android Bluetooth joystick
Post by: nick_b0y7 on Feb 24, 2015, 11:08 am
I wish to use your useful app Android bluetooth joystick (v5.2) for my project. Can you please send me source code of this app.
Title: Re: Android Bluetooth joystick
Post by: nick_b0y7 on Feb 24, 2015, 11:11 am
Can you please send me source code of Joystick Bluetooth Commander v5.2.
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 26, 2015, 07:16 am
Sorry nick_b0y7, the source code is not available for the moment
Android language allows you to call Joystick BT Commander from within your own App
JBTC becomes then just another activity for your App
Title: Re: Android Bluetooth joystick
Post by: SMadd on Mar 03, 2015, 03:13 pm
Has anyone used this app with the Sabertooth motor controllers?

http://www.dimensionengineering.com/products/sabertooth2x32


I am trying to determine how to integrate this app with the sabertooth libraries.
Title: Re: Android Bluetooth joystick
Post by: anthon33 on Mar 04, 2015, 07:12 pm
Is it possible to implement elementarny joystick to the following protocol
X
0xFD 0x02 0x00 0x52 0x43 0x0A data-low-byte data-high-byte crc-low-byte crc-high-byte
Y
0xFD 0x02 0x00 0x52 0x43 0x0B data-low-byte data-high-byte crc-low-byte crc-high-byte
Checksum
http://mbed.org/users/shimniok/code/AVC_2012/file/826c6171fc1b/MAVlink/include/checksum.h
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 05, 2015, 07:53 pm
Quote
Has anyone used this app with the Sabertooth motor controllers?
http://www.dimensionengineering.com/products/sabertooth2x32
I am trying to determine how to integrate this app with the sabertooth libraries.
Hi SMadd,
First, have a look here (http://forum.arduino.cc/index.php?topic=236401.msg1727328#msg1727328) and let us know if it helps



Quote
Is it possible to implement elementarny joystick to the following protocol
X
0xFD 0x02 0x00 0x52 0x43 0x0A data-low-byte data-high-byte crc-low-byte crc-high-byte
Y
0xFD 0x02 0x00 0x52 0x43 0x0B data-low-byte data-high-byte crc-low-byte crc-high-byte
Checksum
http://mbed.org/users/shimniok/code/AVC_2012/file/826c6171fc1b/MAVlink/include/checksum.h
To avoid potential problems, the communication protocol (http://forum.arduino.cc/index.php?topic=173246.msg1766491#msg1766491) is hardcoded in the App and cannot be changed easily

Title: Re: Android Bluetooth joystick
Post by: SMadd on Mar 06, 2015, 03:13 pm
Hi SMadd,
First, have a look here (http://forum.arduino.cc/index.php?topic=236401.msg1727328#msg1727328) and let us know if it helps

Kas, thanks for the reply.

I plan on using this to drive an old power chair base with dual motors.  I currently have it working using the serial commands with the "BlueStick" app which allows for simple arrow style commands (forward, backward, left, right).  I would like to use your app to allow traditional power chair control (tank style with joystick).

I will look at the code you suggested to see if I can adapt it to serial commands.

thanks again for your help.
Title: Re: Android Bluetooth joystick
Post by: khanzz17 on Mar 07, 2015, 03:39 pm
Hi everybody, I made a self balancing robot using the below code I just got it from net it uses nrf24L01 to control its movement but I want to control it with android using hc 06 what changes should i make in the code as i am no good in programming, can any body help me, please.




Code: [Select]

#include "Wire.h"
#include "SPI.h" 
#include "Mirf.h"
#include "nRF24L01.h"
#include "MirfHardwareSpiDriver.h"
#include "I2Cdev.h"
#include "MPU6050.h"

MPU6050 accelgyro;
int16_t ax, ay, az;
int16_t gx, gy, gz;

#define Gry_offset 0
#define Gyr_Gain 0.00763358 
#define Angle_offset 1.94
#define RMotor_offset 20
#define LMotor_offset 20
#define pi 3.14159

long data;
int x, y;
float kp, ki, kd;
float r_angle, f_angle, omega;
float Turn_Speed = 0, Turn_Speed_K = 0;
float Run_Speed = 0, Run_Speed_K = 0, Run_Speed_T = 0;
float LOutput,ROutput;

unsigned long preTime = 0;
float SampleTime = 0.08;
unsigned long lastTime;
float Input, Output;
float errSum, dErr, error, lastErr;
int timeChange;

int TN1=3;
int TN2=4;
int ENA=9;

int TN3=5;
int TN4=6;
int ENB=10;

void setup() {
  Wire.begin();
  accelgyro.initialize();
  pinMode(TN1,OUTPUT);
  pinMode(TN2,OUTPUT);
  pinMode(TN3,OUTPUT);
  pinMode(TN4,OUTPUT);
  pinMode(ENA,OUTPUT);
  pinMode(ENB,OUTPUT);
 
  Mirf.spi = &MirfHardwareSpi;   
  Mirf.init();
  Mirf.setRADDR((byte *)"serv1");
  Mirf.payload = sizeof(long);
  Mirf.config();
  Serial.begin(57600);
}

void loop() {
//Recive();
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
  r_angle = (atan2(ay, az) * 180 / pi + Angle_offset);
  omega =  Gyr_Gain * (gx +  Gry_offset);  Serial.print("  omega="); Serial.print(omega);
  if (abs(r_angle)<30){
    myPID();
    PWMControl();
  }
  else{
    analogWrite(ENA, 0);
    analogWrite(ENB, 0);
  }
}

/*void Recive(){
  if(!Mirf.isSending() && Mirf.dataReady()){
    Mirf.getData((byte *)&data);
    Mirf.rxFifoEmpty();
   
    x = data >> 16;
    y = data & 0x0000ffff;
   
    if(x >= 520){
      Run_Speed_K = map(x, 520, 1023, 0, 100);
      Run_Speed_K = Run_Speed_K / 50;
      Run_Speed = Run_Speed + Run_Speed_K;
    }
    else if(x <= 480){
      Run_Speed_K = map(x, 480, 0, 0, -100);
      Run_Speed_K = Run_Speed_K / 50;
      Run_Speed = Run_Speed + Run_Speed_K;
    }
    else{
      Run_Speed_K = 0;
    }
    if(y >= 520){
      Turn_Speed = map(y, 520, 1023, 0, 20);
    }
    else if(y <= 480){
      Turn_Speed = map(y,480,0,0,-20);
    }
    else{
      Turn_Speed = 0;
    }
  }
  else{
    x = y = 500;
  }
}*/

void myPID(){
  //kp = analogRead(A0)*0.1;  Serial.print("  kp=");Serial.print(kp);
  //kd = analogRead(A2)*1.0;  Serial.print("  kd=");Serial.print(kd);
  //ki = analogRead(A3)*0.001;  Serial.print("  ki=");Serial.print(ki);

  kp = 17.60;  Serial.print("  kp=");Serial.print(kp);
  kd = 959;  Serial.print("  kd=");Serial.print(kd);
  ki = 0.1;  Serial.print("  ki=");Serial.print(ki);
   
  unsigned long now = millis();
  float dt = (now - preTime) / 1000.0;
  preTime = now;
  float K = 0.8;
  float A = K / (K + dt);
  f_angle = A * (f_angle + omega * dt) + (1 - A) * r_angle;  Serial.print("  f_angle=");Serial.print(f_angle);
 
  timeChange = (now - lastTime);
  if(timeChange >= SampleTime){
    Input = f_angle;
    error = Input;
    errSum += error * timeChange;
    dErr = (error - lastErr) / timeChange;
    Output = kp * error + ki * errSum + kd * dErr;
    LOutput = Output + Run_Speed + Turn_Speed;  Serial.print("  LOutput=");Serial.print(LOutput);
    ROutput = Output + Run_Speed - Turn_Speed;  Serial.print("  ROutput=");Serial.println(ROutput);
    lastErr = error;
    lastTime = now;
  }
}

void PWMControl(){
  if(LOutput > 0){
    digitalWrite(TN1, HIGH);
    digitalWrite(TN2, LOW);
  }
  else if(LOutput < 0){
    digitalWrite(TN1, LOW);
    digitalWrite(TN2, HIGH);
  }
  else{
    digitalWrite(TN1, HIGH);
    digitalWrite(TN2, HIGH);
  }
  if(ROutput > 0){
    digitalWrite(TN3, HIGH);
    digitalWrite(TN4, LOW);
  }
  else if(ROutput < 0){   
    digitalWrite(TN3, LOW);
    digitalWrite(TN4, HIGH);
  }
  else{
    digitalWrite(TN3, HIGH);
    digitalWrite(TN4, HIGH);
  }
    analogWrite(ENA, min(255, abs(LOutput) + LMotor_offset));
    analogWrite(ENB, min(255, abs(ROutput) + RMotor_offset));
}
Title: Re: Android Bluetooth joystick
Post by: janzluc14 on Mar 08, 2015, 05:22 pm
hi sir kas....we finaly finish our thesis...thanks to your apps.:)

sir woodgy....thank for your help in our program...:)
https://www.youtube.com/watch?v=r8brZ3IItwE (https://www.youtube.com/watch?v=r8brZ3IItwE)
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 09, 2015, 12:03 pm
@khanzz17

Sorry, I just have no time to understand and modify your code.
Since my first Balancing Robot (http://forum.arduino.cc/index.php/topic,8871.0.html), I went full digital and installed a MPU6050 Acc/Gyro combo.
I also use a modified version of lauszus code (http://www.balanduino.net/), to include bluetooth control implementation

Joystick BT Commander offsets the "standing angle" setpoint:
angle = 0: the bot stands still
angle > 0: forward move
angle < 0: backward move

Should you need a copy of my code, just let me know

I have moved to other projects, lauszus (http://forum.arduino.cc/index.php?topic=58048.0) is the new guru for balancing bots, you can contact him on my behalf, he is a very helpfull guy

Oh, BTW, you won't get good results without motors encoders  ;)




@janzluc14

Thanks for this nice feedback, I wish you luck with your future job   :)  :)
Hope Woody is still following this thread



Title: Re: Android Bluetooth joystick
Post by: MRGSoft on Mar 18, 2015, 05:42 pm
Magnifica application, do I Might say that language is scheduled for Android ?.
Thank you very much, and a greeting.
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 18, 2015, 10:57 pm
Quote
Magnifica application
Thanks  :smiley-cool:

Quote
do I Might say that language is scheduled for Android ?
not sure to understand your question  ::)
please clarify

Title: Re: Android Bluetooth joystick
Post by: MRGSoft on Mar 19, 2015, 05:06 pm
Hello, sorry for my bad English.
Would want to know if this programmed Basic4Android, Eclipse, AppInventor ....
Thank you very much.
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 19, 2015, 07:51 pm
Quote
Would want to know if this programmed Basic4Android, Eclipse, AppInventor ....
Got it now :)       pure Java, within Eclipse (https://eclipse.org/) IDE
Title: Android Bluetooth joystick
Post by: nick_b0y7 on Mar 26, 2015, 12:38 pm
Hi,
  I wish to use your app. "Android Bluetooth Joystick V5.2" For my project.
     Can you please send me source code of your above app.
      Thank You,
Harish Sharma
email id. : harish_kr_sh@yahoo.co.in
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 27, 2015, 07:34 am
Same question, same answer, see reply #482
Title: Re: Android Bluetooth joystick
Post by: alexander1978 on Apr 26, 2015, 08:39 am
Why not  :)

This a screen shot of "Total RC Commander" V0.1B:
(http://i.imgur.com/1nFYamx.jpg)
The application is working but for the moment, the screen is optimized only for a 8" tablet
I suspect the application needs at least 7" to display the information correctly
sorry, no phones  :~ :~

Do you have a tablet ??
Please let me have size and resolution

Title: Re: Android Bluetooth joystick
Post by: kas on Apr 27, 2015, 05:29 pm
Time has passed  ::)

Total RC Commander V5.2 (http://forum.arduino.cc/index.php?topic=173246.msg2105089#msg2105089)  is now fully optimized for smartphone

(http://i.imgur.com/ylTIAWT.jpg)


I access it daily using my Motorola Moto G


Title: Re: Android Bluetooth joystick
Post by: vlad-sh on May 05, 2015, 07:08 am
Hi Kas,

Thank you for useful "Joystick BT Commander" application.
But is it possible to ask you to add option to switch from joystick to simple keys (left, right, forward, backward and stop)?

It could be like:

If "left" key is pressed - send x=-100,y=0
If "right" key is pressed - send x=100,y=0
If "forward" key is pressed - send x=0,y=100
If "backward" key is pressed - send x=0,y=-100
If "stop" key is pressed - send x=0,y=0


Picture is attached :).

(http://forum.arduino.cc/index.php?action=dlattach;topic=173246.0;attach=124875)

In another words, keys will be duplicate leftmost, rightmost, topmost and bottommost joystick's positions.
Title: Re: Android Bluetooth joystick
Post by: kas on May 05, 2015, 07:24 pm
Hi vlad-sh, welcome to the Forum

This is an analog joystick emulator App
I want to keep this 90KB App as compact and efficient as possible  ;)


A possible workaround is to modify AndroTest V2.0 (http://forum.arduino.cc/index.php?topic=173246.msg1766646#msg1766646)

Code: [Select]
// within getJoystickState:                                  ** not tested **

  if      ((joyY>50)  && (abs(joyX)<25))       {joyX=0; joyY=100;}
  else if ((joyY<-50) && (abs(joyX)<25))       {joyX=0; joyY=-100;}
  else if ((joyX>50)  && (abs(joyY)<25))       {joyX=100; joyY=0;}
  else if ((joyX<-50) && (abs(joyY)<25))       {joyX=-100; joyY=0;}
  else if ((abs(joyX)<25) && (abs(joyY)<25))   {joyX=0; joyY=0;}
  else                                         {joyX=JoyX_ant; joyY=JoyY_ant;}
  JoyX_ant = JoyX;
  JoyY_ant = JoyY;

Also uncheck Options / Joystick properties / Auto return to center

Let me know if it helps

Title: Celebration
Post by: kas on May 24, 2015, 10:44 pm
As of today, this thread has been viewed 100 000 times, with 500 responses
Joystick BT Commander has been downloaded 8100 times on Google Play

Thanks for your ongoing interest  8)  8)  8)

As a celebration, I will give away 10 copies of Total BT Commander (http://forum.arduino.cc/index.php?topic=173246.msg1998617#msg1998617)
Just contact me by email or PM

Finally, please post a photo/video showing your favorite Android controlled project



Title: Re: Android Bluetooth joystick
Post by: rth0 on May 30, 2015, 02:51 pm
Hi vlad-sh, welcome to the Forum

This is an analog joystick emulator App
I want to keep this 90KB App as compact and efficient as possible  ;)


A possible workaround is to modify AndroTest V2.0 (http://forum.arduino.cc/index.php?topic=173246.msg1766646#msg1766646)

Code: [Select]
// within getJoystickState:                                  ** not tested **

  if      ((joyY>50)  && (abs(joyX)<25))       {joyX=0; joyY=100;}
  else if ((joyY<-50) && (abs(joyX)<25))       {joyX=0; joyY=-100;}
  else if ((joyX>50)  && (abs(joyY)<25))       {joyX=100; joyY=0;}
  else if ((joyX<-50) && (abs(joyY)<25))       {joyX=-100; joyY=0;}
  else if ((abs(joyX)<25) && (abs(joyY)<25))   {joyX=0; joyY=0;}
  else                                         {joyX=JoyX_ant; joyY=JoyY_ant;}
  JoyX_ant = JoyX;
  JoyY_ant = JoyY;

Also uncheck Options / Joystick properties / Auto return to center

Let me know if it helps


Hi kas,

Thanks for this awesome work.

I think you might have misunderstood vlad-sh as I've recently run into a situation where I need  to control something with Joystick BT commander using keystroke. I use one of these old android phone with a fancy slide-out-full-querty-with-direction keyboard so I was also wondering if I could use they keypad to send frames to the arduino. Thus the full left-right-up-down (and possibly some combination).

I don't think that it'd be hard to implement such a feature? I would help implementing it if I can fork the project but since the source is not open, ... or if the project is available in the form of "importable" jar package then it would even be better.

Let me know your thought.
Cheers
Title: Re: Android Bluetooth joystick
Post by: kas on May 31, 2015, 10:35 pm
Hi rth0,

Sorry, for personal reasons, I won't release the code in a foreseable futur
You may check Google Play for similar Apps

Cheers


Title: Re: Android Bluetooth joystick
Post by: jak97100 on Jun 23, 2015, 06:56 pm
Hi Kas,

I am having trouble reading the values from the app to my computer through an HC-06 BT module attached to my uno. I used ur code but  it still didn't work. Please help asap! Thanks

-Jak
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 24, 2015, 06:31 am
Hi Jak, welcome to the Forum  :)

Which  Android device are you using (+ Android version)


Carefully review those 10 questions and answer YES/NO
(If you don't understand a specific item, just tell it)

Android side (smartphone/tablet  screen):
1) go to Option/About and confirm that JBTC App version is V5.2
2) can you move the joystick and display position at bottom left
3) is your BT card paired with your Android device
4) are you connected ("connected to: XXX", green text)

Arduino side:
5) are you using AndroTest V2.0 sketch
6) are Bluetooth TX connected to D2 and RX connected to D3
7) is your Bluetooth card already configured @57600 bps  (most are 9600bps by default)
8 ) is your Bluetooth card LED solid red or green  (blinking = not connected)
9) is your Arduino Serial monitor configured @57600 bps

Finally:
10)  your Arduino Serial Monitor should anycase display:
          AndroTest V2.0 - @kas2014
          demo for V5.X App
  does it ??

- any additional information ??

Title: Re: Android Bluetooth joystick
Post by: jak97100 on Jun 24, 2015, 06:39 am
Hi,

I have 5.2V, i can move the joystick and see the numbers change, BT is paired with my phone properly and does say connected to "JAK" (name of BT) in green

Arduino side:

i believe i am using the 5.2V sketch, tx to rx and rx to tx are connecte, my BT module is configured at 9600 but it wont allow me to change it for some reason in AT mode gives me error(0); my BT module only has a red light and it will blink every second rather than constantly when not connected. I tried changing the baud rate on the serial monitor but no results. And yes it does give me

"AndroTest V2.0 - @kas2014
          demo for V5.X App"

but nothing after that. Thanks
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 24, 2015, 07:29 am
Which  Android device are you using (+ Android version) ??
Is your Arduino board genuine Uno or clone


Quote
tx to rx and rx to tx are connected .... my BT module only has a red light
Just to make sure, try inverting Arduino D2 and D3 wires
Please let me have a link to your specific BT board


Finally try this bare minimum sketch to test incoming data from your smartphone

Code: [Select]

#include "SoftwareSerial.h"

SoftwareSerial mySerial(2, 3);

void setup()  {
  mySerial.begin(9600);       // assuming 9600bps BT card
  Serial.begin(57600);
  Serial.println("Test Soft_Serial");
}

void loop() {
  if(mySerial.available())    Serial.print(mySerial.read());  
}


Bytes received by the Bluetooth card will be echoed to the Arduino Serial Monitor

Should display series of numbers:
25054505052533250545050525332505450505253325054505052533250545050525 ..................


Title: Re: Android Bluetooth joystick
Post by: jak97100 on Jun 27, 2015, 10:37 pm
Hi there,

  Sorry for the late reply, I was really busy with family and things didnt find any time but I'm back to it again.

Here is the link to the BT board: http://www.canadarobotix.com/bluetooth/1258-hc-05-wireless-bluetooth-module

The code does work and gives me this as output on the Serial Monitor:
" Test Soft_Serial
2504848504848325048485048483250484850484832504848504848325048485048483250484850484"

Pin 2 goes to Tx of BT and pin 3 goes to Rx of BT.
Thanks!
Title: Re: Android Bluetooth joystick
Post by: jak97100 on Jun 27, 2015, 10:47 pm
Also,

after that test, i am able to change the baudrate of the BT to 57600 successfully. Before I was using the AT+UART7 command but that is for the HC-06 BT. Instead I used the AT+UART=57600,0,0 command and it worked properly. The code you provided for testing in your latest reply still works and gives those values.

Note: I thought my BT was HC-06 but its actually the HC-05.
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 28, 2015, 07:46 am
Quote
The code does work and gives me this as output on the Serial Monitor:
" Test Soft_Serial
2504848504848325048485048483250484850484832504848504848325048485048483250484850484"
So far so good  ;)
Communication is OK, probably a parsing problem

Please run the attached debugging sketch and post back the Serial Monitor output
(you need to be logged to see the file)

Which  tablet/smartphone are you using (+ Android version) ??
Is your Arduino board genuine Uno or clone ??



Title: Re: Android Bluetooth joystick
Post by: jak97100 on Jun 28, 2015, 08:16 am
Im using my phone, Nexus 5, has the 5.1.1 Android version. My arduino is an remeo V1.1 but acts like the uno.

Link: https://www.bananarobotics.com/shop/image/cache/data/sku/BR/0/1/0/2/2/BR010223-DFRobot-Romeo-All-In-One-Robot-Controller-V1.1-with-ATMega328p/DFRobot-Romeo-All-In-One-Robot-Controller-V1.1-top-600x600.jpg

Im trying the code and will post back. Thanks
Title: Re: Android Bluetooth joystick
Post by: jak97100 on Jun 28, 2015, 08:21 am
Good news, The values change with the Joystick!!!
Is there a simplified version of this code, Im just using the app to control a motor and servo with the joystick, for an RC car and I just need one way communication? Since you said this is the debug code. Thank You so muchhh!!!! :)

Here is some of the code from the serial:

"AndroTest V2.0 - @kas2014
demo for V5.X App (6 button version)
1   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
2   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
3   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
4   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
5   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
6   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
7   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
8   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
9   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
10   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
11   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
12   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
13   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
14   Joystick: < 2 50 48 50 50 48 48 3 >   0-0-0
15   Joystick: < 2 50 49 55 50 48 53 3 >   0-0-0
16   Joystick: < 2 50 51 53 50 48 55 3 >   0-0-0
17   Joystick: < 2 50 54 55 50 48 52 3 >   0-0-0
18   Joystick: < 2 50 56 54 50 48 51 3 >   0-0-0
19   Joystick: < 2 50 57 57 50 48 50 3 >   0-0-0
20   Joystick: < 2 50 57 57 50 48 49 3 >   0-0-0
21   Joystick: < 2 50 57 57 50 48 48 3 >   0-0-0
22   Joystick: < 2 50 57 57 49 57 55 3 >   0-0-0
23   Joystick: < 2 50 57 57 49 56 55 3 >   0-0-0
24   Joystick: < 2 50 57 49 49 54 50 3 >   0-0-0
25   Joystick: < 2 50 55 50 49 51 50 3 >   0-0-0
26   Joystick: < 2 50 51 55 49 49 49 3 >   0-0-0
27   Joystick: < 2 49 57 55 49 48 56 3 >   0-0-0
28   Joystick: < 2 49 53 55 49 49 57 3 >   0-0-0
29   Joystick: < 2 49 50 50 49 51 57 3 >   0-0-0
30   Joystick: < 2 49 48 56 49 54 53 3 >   0-0-0
31   Joystick: < 2 49 48 50 49 56 53 3 >   0-0-0
"

updates with the joystick movement, but i can barely tell cause the value range is from 40-60 im guessing?
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 28, 2015, 10:09 am
Quote
Im using my phone, Nexus 5, has the 5.1.1 Android version. My arduino is an remeo V1.1 but acts like the uno.
(http://i.imgur.com/PjlDhLN.jpg)
Nice board  :P




Quote
Here is some of the code from the serial:

"AndroTest V2.0 - @kas2014
demo for V5.X App (6 button version)
1   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
2   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
3   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
4   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
5   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
6   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
7   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
8   Joystick: < 2 50 48 48 50 48 48 3 >   0-0-0
  . . . . . . . .
:o  :o
Android/Arduino communication is strickly koscher (protocol (http://forum.arduino.cc/index.php?topic=173246.msg1766491#msg1766491))
I understand now you were not using the _original_ (http://forum.arduino.cc/index.php?topic=173246.msg1766646#msg1766646) AndroTest V2.0 demo sketch
Please run it and confirm you can display joystick position (-100 +100 range) within the Serial Monitor




Title: Re: Android Bluetooth joystick
Post by: jak97100 on Jun 28, 2015, 10:18 am
"AndroTest V2.0 - @kas2014
demo for V5.X App (6 button version)
Joystick position:  0, 0
Joystick position:  0, 0
Joystick position:  0, 0
Joystick position:  0, 0
Joystick position:  7, 1
Joystick position:  25, 10
Joystick position:  40, 31
Joystick position:  53, 57
Joystick position:  59, 79
Joystick position:  57, 81
Joystick position:  56, 82
"

Its working perfectly now :D Thank you so much! Yeah, I believe i was using the older version of your code and didnt have my BT at the correct baud rate. So to add in my own changes to the code, do i do it in the joystick function? Also, can I speed up the response time?
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 28, 2015, 10:38 am
Quote
Its working perfectly now
.    :)  :)  :)  :)  :)



Quote
to add in my own changes to the code, do i do it in the joystick function?
Yes, within getJoystickState()



Quote
Also, can I speed up the response time?
Not sure to understand, please elaborate





Title: Re: Android Bluetooth joystick
Post by: jak97100 on Jun 28, 2015, 10:44 am
So on the app with the code running on the uno, If I hold the joystick right let's say, on the serial monitor it will show me 99 I think and will show me 99 again for the next update and then 99 again for the next time it calculates it. But that update time is around 500ms or 250ms I think but is there a way to make it update faster let's maybe? Cause I'm gonna use the joystick for a DC motor, 6Amp motor and iif it has a small delay in communication between the joystick app and Arduino then it would be perfect! So is there a possible way? Thank you for ur help I appreciate this a lot! :)
Title: Re: Android Bluetooth joystick
Post by: kas on Jun 28, 2015, 11:14 am
Quote
But that update time is around 500ms or 250ms I think but is there a way to make it update faster let's maybe?
By default, data is updated 20 times per seconds (50ms) if joystick data has change
If joystick hasn't moved, data is updated every 10 intervals (500ms), to save phone battery

You can change this default behavior
Go to Option/advanced user,  'Refresh Interval '  and  'Timeout Count'
Adjust to taste  ;)


When ready, show us your new toy



Title: MQTT Commander
Post by: kas on Jul 28, 2015, 06:56 pm
This is my new App  :smiley-cool:  :smiley-cool:  :smiley-cool:

MQTT Commander can switch a light bulb or any appliance from anywhere in the world, using an Android smartphone

(http://i.imgur.com/5HylDWJ.png)

More infos in the home automation section (http://forum.arduino.cc/index.php?topic=338622.msg2334381#msg2334381)


Title: Re: Android Bluetooth joystick
Post by: woodygb on Jul 30, 2015, 10:48 am
I'll keep an eye on your progress Kas. :)
Title: MQTT Commander
Post by: kas on Jul 31, 2015, 06:49 am
I'll keep an eye on your progress Kas
Hi Woody, nice to see you again   ;)



Title: Re: Android Bluetooth joystick
Post by: shuvo915 on Sep 06, 2015, 08:26 pm
Hi, I am trying to use the app to control my arduino nano based robot.
I am having problems with the buttons and receiving feedback from the arduino. After the initial data sent by the arduino the app doesn't update. The buttons turn off and if enabled turns off again. On the arduino side i have checked that the data was being sent and received correctly as per described protocol. The arduino was saving button status correctly and sending them back at regular intervals (750ms).
But on the app the data fields were not being updated and the buttons were turning off.
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 07, 2015, 07:05 am
Hi shuvo915,

From your description, I understand that smartphone >> Arduino communication is OK
but Arduino >> smarphone communication is failing


Which  Android device are you using + Android version
Confirm BT Commander App version (Option/About...)

Is your Nano clone or genuine Arduino
What is your BT card baud rate

Please upload the _original_ (http://forum.arduino.cc/index.php?topic=173246.msg1766646#msg1766646) AndroTest V2.0 demo sketch in your Nano,
move joystick, press buttons, and let us have a Serial Monitor printout




Title: Re: Android Bluetooth joystick
Post by: scandermore on Sep 19, 2015, 07:28 pm
Hello Kas.

 I am building now my first robot and I am sure that your program will be very useful, as it is not only limited to move forward and backward, like most of the arduino be controllers I have seen in Google play. The explanations and the protocol are very straightforward and easy to understand. Thanks for all the job to the community.

 I would like to suggest only one thing, as I am planning to grow up my robot in short time: would it be possible to add another Joystick, to move another pair of axis? The typical use would be a camera with pan and tilt servos. The communication protocol should be modified, but I think it would be possible to add another type of message, to keep the compatibility.

 Thank you, and good luck with all your projects!

 Alex
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 21, 2015, 08:27 am
Quote
Hello Kas.
 I am building now my first robot and I am sure that your program will be very useful, as it is not only limited to move forward and backward, like most of the arduino be controllers I have seen in Google play. The explanations and the protocol are very straightforward and easy to understand. Thanks for all the job to the community.
Thanks Alex  8)


Quote
I would like to suggest only one thing, as I am planning to grow up my robot in short time: would it be possible to add another Joystick, to move another pair of axis? The typical use would be a camera with pan and tilt servos. The communication protocol should be modified, but I think it would be possible to add another type of message, to keep the compatibility.
As already mentioned, I want to keep the App as simple as possible
Sorry for that  ::)



@all
I am busy preparing  Joystick WiFi Commander, a Wifi enabled App for the new ESP8266 module.

(http://i.imgur.com/e0uGB3E.jpg)


This little board is available for 3 bucks shipped (http://www.ebay.com/sch/i.html?_from=R40&_sacat=0&_sop=15&_nkw=esp-01&rt=nc&_dmd=2)

Joystick WiFi Commander should behave as Joystick BT Commander, by just replacing the HC-O5 Bluetooth module by the ESP8266 WiFi board.
You will then be able to control you favorite bot from anywhere in the world  ;)  ;)  ;)


Title: Re: Android Bluetooth joystick
Post by: scandermore on Sep 21, 2015, 10:51 pm
 OK, thank you for your hard work. Maybe you could consider to add it in the future to the other app (the one that shows also the video. That would make sense, as then you could move the robot and the camera PAN and TILT :-)

 I will keep an eye to the wifi board and app. Just have to change all the mechanics of my robot, as I was using an old cybot, and the drivers and motors were not very good. Planning to do a balancing robot also, so I will be using your app to control both of them. Thank you!

 Alex
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 22, 2015, 11:54 am
Quote
OK, thank you for your hard work. Maybe you could consider to add it in the future to the other app (the one that shows also the video. That would make sense, as then you could move the robot and the camera PAN and TILT :-)
Total RC Commander (http://forum.arduino.cc/index.php?topic=173246.msg1998617#msg1998617)  can be modified to have buttons send move information to a Pan and Tilt camera
Buttons would move camera either by incremental steps or to a specific/predefined position

Would that be acceptable for your project ??

Title: Re: Android Bluetooth joystick
Post by: scandermore on Sep 22, 2015, 12:10 pm

 Yes, that would be possible. Though the camera movement would not have speed control, always max speed, and two buttons would be used for that, and not for robot options.

 IMHO, a good (alternative) layout would be camera image in center, two "joysticks", one each side (could be smaller, because for me, and having long fingers, the circle is a bit big), and the buttons at the top of the controllers. Just similar to a classic arcade bluetooth joystick.

 With this joystick you could also control robots that "need" two joypads, like hexapods, etc...

 But... these are only suggestions. You have done a great work, just trying to give some feedback.

 Alex
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 23, 2015, 09:45 am
I may end up creating the two joystick App, but for the moment I am busy developing  Joystick WiFi Commander

Let's try the "button" solution
Please let me have a link to your Pan & Tilt IP camera

Title: Re: Android Bluetooth joystick
Post by: scandermore on Sep 23, 2015, 09:53 am
 At the moment I don't have the camera yet. I amb only in "testing" process. Yesterday I was going to buy all the hardware I need (robot motors, gears, etc..) but there were some elements that were not in stock, so I have to wait.

 Also, I don't know if I will end developing the project with a new Arduino Yun I was gifted this week, so the camera decision will have to wait. The Yun allows you to install a simple USB camera, and I would have all the hardware in only one board. The one thing I am sure is that I will be moving the pan&tilt with a support and servos (http://www.robotshop.com/eu/en/dagu-mini-pan-and-tilt-kit.html), not a pan&tilt camera.

 I will show the project when I have something "decent" to show. Still work in progress...

 aLeX
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 24, 2015, 04:33 pm
Quote
The one thing I am sure is that I will be moving the pan&tilt with a support and servos, not a pan&tilt camera.
OK...
With a servo's pan & tilt support, you can use one App button to toggle Joystick duty from "robot move" to "camera move"

Good luck with your project

Title: Re: Android Bluetooth joystick
Post by: founddean on Jan 03, 2016, 06:18 pm
Hello
Our sumo club uses this app to control our robots and it works great.

We are looking to upgrade and start using BLUNO and Romeo all in one boards with built in BLE. (DFROBOT)

Is there any chance we can get a version that will work with those boards ?

I can't seem to get it to connect.

Thanks for all your hard work!!

Dean
Title: Re: Android Bluetooth joystick
Post by: Isaac96 on Jan 05, 2016, 04:38 pm
Your phone probably does not have BLE. Also, what pins are the Romeo BLE modules on? I assume you have paired already?
Title: Re: Android Bluetooth joystick
Post by: founddean on Jan 05, 2016, 07:17 pm
My phone connects seamlessly with the sample app they supply. The BLE is built into the board so I am unsure of what pins it uses.

Any help would be great!!
Title: Re: Android Bluetooth joystick
Post by: DuaneDegn on Jan 05, 2016, 08:44 pm
The BLE is built into the board so I am unsure of what pins it uses.
The seller didn't provide any documentation? That doesn't sound like DFROBOT.

Isn't this more of a BLUNO question than a Joystick BT Commander question?

Edit: I used the internet (http://www.dfrobot.com/index.php?route=product/product&product_id=1044#.VowdkPkrKJA) and found out (http://www.dfrobot.com/image/data/DFR0267/Bluno%20Sch.pdf) the BLUNO Bluetooth module uses digital pin #0 and #1 (which isn't surprising). They even provide some sample code (http://www.dfrobot.com/wiki/index.php/Bluno_SKU:DFR0267#Bluno_Basic_Demo).
Title: Re: Android Bluetooth joystick
Post by: founddean on Jan 06, 2016, 05:40 pm
YES DuaneDegn they provide sample code for Arduino and Android...I have it working...I was hoping to find an easy way to use Joystick BT commander with it...I don't understand BLE protocol so I cannot connect the two together. Our sumo club uses Joystick BT commander to control our bots...looking for an easier hardware soulution than hooking up an external  bluetooth module.   We would like to use the Romeo BLE mini all in one .

DFRobot has an iPhone/iPad app 'GoBle' but nothing for Android yet...

As I have no understanding of the difference between BLE and the older Bluetooth I don't know how much work would be involved adapting Joystick Bluetooth Commander to work.

Thanks,
Dean
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 06, 2016, 09:50 pm
Quote
Hello
Our sumo club uses this app to control our robots and it works great.
We are looking to upgrade and start using BLUNO and Romeo all in one boards with built in BLE. (DFROBOT)
Is there any chance we can get a version that will work with those boards ?
I can't seem to get it to connect.
Thanks for all your hard work!!

Dean
Hi Dean,
I am reviewing BLE spec's and will let you know the outcome
Correct me if I am wrong, but I don't see any real reason to use BLE  ::)



Quote
looking for an easier hardware solution than hooking up an external  bluetooth module.   
We would like to use the Romeo BLE mini all in one
Why don't you use a standard BT/Arduino combo board ??
I use this one (https://www.itead.cc/iteaduino-bt.html)
(http://i.imgur.com/DIFpAQg.png)



Quote
Our sumo club uses Joystick BT commander to control our bots
Let us have some photos  ;)



Title: Re: Android Bluetooth joystick
Post by: winchymatt on Jan 09, 2016, 05:16 pm
Hi, Great app. very useful! I see someone has asked for a two joystick version previously, this is something I would also be interested in. Alternatively I may be able to modify your existing app code, is this available / open source?

regards

matt.
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 12, 2016, 08:35 am
Quote
Hi, Great app. very useful!
Thanks matt  8)


Quote
I may be able to modify your existing app code, is this available / open source?
Joystick BT Commander is the base of Total BT Commander (paid App)
Sorry, source code is not available


Quote
I see someone has asked for a two joystick version previously, this is something I would also be interested in
I had additional development in head
- control by tilting the smartphone, using built in accelerometers
- dual joystick
So far, did not generate sufficient interest to justify the additional development time


Title: Re: Android Bluetooth joystick
Post by: kri5too on Jan 19, 2016, 07:02 pm
/ For Mega 2560:
// remove   #include "SoftwareSerial.h", SoftwareSerial mySerial(2,3);
// search/replace  mySerial  >> Serial1
// pin#18 to RX bluetooth module, pin#19 to TX bluetooth module

I did exactly the same but i wont get readings in serial monitor :(
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 19, 2016, 07:24 pm
/ For Mega 2560:
// remove   #include "SoftwareSerial.h", SoftwareSerial mySerial(2,3);
// search/replace  mySerial  >> Serial1
// pin#18 to RX bluetooth module, pin#19 to TX bluetooth module

I did exactly the same but i wont get readings in serial monitor :(

Hi kri5too, please post your code

Title: Re: Android Bluetooth joystick
Post by: kri5too on Jan 19, 2016, 07:33 pm
Code: [Select]
#define VERSION     "\n\nAndroTest V2.0 - @kas2014\ndemo for V5.x App"

// V2.0  changed to pure ASCII Communication Protocol ** not backward compatible **
// V1.4  improved communication errors handling
// V1.3  renamed for publishing, posted on 09/05/2014
// V1.2  Text display   ** not backward compatible **
// V1.1  Integer display
// V1.0  6 buttons + 4 data char implemented

// Demo setup:
// Button #1 controls pin #13 LED
// Button #4 toggle datafield display rate
// Button #5 configured as "push" button (momentary)
// Other buttons display demo message

// Arduino pin#2 to TX BlueTooth module
// Arduino pin#3 to RX BlueTooth module
// make sure your BT board is set @57600 bps
// better remove SoftSerial for PWM based projects

// For Mega 2560:
// remove   #include "SoftwareSerial.h", SoftwareSerial mySerial(2,3);
// search/replace  mySerial  >> Serial1
// pin#18 to RX bluetooth module, pin#19 to TX bluetooth module


#define    STX          0x02
#define    ETX          0x03
#define    ledPin       13
#define    SLOW         750                            // Datafields refresh rate (ms)
#define    FAST         250                             // Datafields refresh rate (ms)
                      // BlueTooth module: pin#2=TX pin#3=RX
byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};                 // bytes received
byte buttonStatus = 0;                                  // first Byte sent to Android device
long previousMillis = 0;                                // will store last time Buttons status was updated
long sendInterval = SLOW;                               // interval between Buttons status transmission (milliseconds)
String displayStatus = "xxxx";                          // message to Android device

void setup()  {
Serial.begin(57600);
Serial1.begin(57600);                                // 57600 = max value for softserial
pinMode(ledPin, OUTPUT);    
Serial.println(VERSION);
while(Serial1.available())  Serial1.read();         // empty RX buffer
}

void loop() {
if(Serial1.available())  {                           // data received from smartphone
  delay(2);
  cmd[0] =  Serial1.read();  
  if(cmd[0] == STX)  {
    int i=1;      
    while(Serial1.available())  {
      delay(1);
      cmd[i] = Serial1.read();
      if(cmd[i]>127 || i>7)                 break;     // Communication error
      if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
      i++;
    }
    if     (i==2)          getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
    else if(i==7)          getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
  }
}
sendBlueToothData();
}

void sendBlueToothData()  {
static long previousMillis = 0;                            
long currentMillis = millis();
if(currentMillis - previousMillis > sendInterval) {   // send data back to smartphone
  previousMillis = currentMillis;

// Data frame transmitted back from Arduino to Android device:
// < 0X02   Buttons state   0X01   DataField#1   0x04   DataField#2   0x05   DataField#3    0x03 >  
// < 0X02      "01011"      0X01     "120.00"    0x04     "-4500"     0x05  "Motor enabled" 0x03 >    // example

  Serial1.print((char)STX);                                             // Start of Transmission
  Serial1.print(getButtonStatusString());  Serial1.print((char)0x1);   // buttons status feedback
  Serial1.print(GetdataInt1());            Serial1.print((char)0x4);   // datafield #1
  Serial1.print(GetdataFloat2());          Serial1.print((char)0x5);   // datafield #2
  Serial1.print(displayStatus);                                         // datafield #3
  Serial1.print((char)ETX);                                             // End of Transmission
}  
}

String getButtonStatusString()  {
String bStatus = "";
for(int i=0; i<6; i++)  {
  if(buttonStatus & (B100000 >>i))      bStatus += "1";
  else                                  bStatus += "0";
}
return bStatus;
}

int GetdataInt1()  {              // Data dummy values sent to Android device for demo purpose
static int i= -30;              // Replace with your own code
i ++;
if(i >0)    i = -30;
return i;  
}

float GetdataFloat2()  {           // Data dummy values sent to Android device for demo purpose
static float i=50;               // Replace with your own code
i-=.5;
if(i <-50)    i = 50;
return i;  
}

void getJoystickState(byte data[8])    {
int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
joyX = joyX - 200;                                                  // Offset to avoid
joyY = joyY - 200;                                                  // transmitting negative numbers

if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // commmunication error

// Your code here ...
  Serial.print("Joystick position:  ");
  Serial.print(joyX);  
  Serial.print(", ");  
  Serial.println(joyY);
}

void getButtonState(int bStatus)  {
switch (bStatus) {
// -----------------  BUTTON #1  -----------------------
  case 'A':
    buttonStatus |= B000001;        // ON
    Serial.println("\n** Button_1: ON **");
    // your code...      
    displayStatus = "LED <ON>";
    Serial.println(displayStatus);
    digitalWrite(ledPin, HIGH);
    break;
  case 'B':
    buttonStatus &= B111110;        // OFF
    Serial.println("\n** Button_1: OFF **");
    // your code...      
    displayStatus = "LED <OFF>";
    Serial.println(displayStatus);
    digitalWrite(ledPin, LOW);
    break;

// -----------------  BUTTON #2  -----------------------
  case 'C':
    buttonStatus |= B000010;        // ON
    Serial.println("\n** Button_2: ON **");
    // your code...      
    displayStatus = "Button2 <ON>";
    Serial.println(displayStatus);
    break;
  case 'D':
    buttonStatus &= B111101;        // OFF
    Serial.println("\n** Button_2: OFF **");
    // your code...      
    displayStatus = "Button2 <OFF>";
    Serial.println(displayStatus);
    break;

// -----------------  BUTTON #3  -----------------------
  case 'E':
    buttonStatus |= B000100;        // ON
    Serial.println("\n** Button_3: ON **");
    // your code...      
    displayStatus = "Motor #1 enabled"; // Demo text message
    Serial.println(displayStatus);
    break;
  case 'F':
    buttonStatus &= B111011;      // OFF
    Serial.println("\n** Button_3: OFF **");
    // your code...      
    displayStatus = "Motor #1 stopped";
    Serial.println(displayStatus);
    break;

// -----------------  BUTTON #4  -----------------------
  case 'G':
    buttonStatus |= B001000;       // ON
    Serial.println("\n** Button_4: ON **");
    // your code...      
    displayStatus = "Datafield update <FAST>";
    Serial.println(displayStatus);
    sendInterval = FAST;
    break;
  case 'H':
    buttonStatus &= B110111;    // OFF
    Serial.println("\n** Button_4: OFF **");
    // your code...      
    displayStatus = "Datafield update <SLOW>";
    Serial.println(displayStatus);
    sendInterval = SLOW;
   break;

// -----------------  BUTTON #5  -----------------------
  case 'I':           // configured as momentary button
//      buttonStatus |= B010000;        // ON
    Serial.println("\n** Button_5: ++ pushed ++ **");
    // your code...      
    displayStatus = "Button5: <pushed>";
    break;
//   case 'J':
//     buttonStatus &= B101111;        // OFF
//     // your code...      
//     break;

// -----------------  BUTTON #6  -----------------------
  case 'K':
    buttonStatus |= B100000;        // ON
    Serial.println("\n** Button_6: ON **");
    // your code...      
     displayStatus = "Button6 <ON>"; // Demo text message
   break;
  case 'L':
    buttonStatus &= B011111;        // OFF
    Serial.println("\n** Button_6: OFF **");
    // your code...      
    displayStatus = "Button6 <OFF>";
    break;
}
// ---------------------------------------------------------------
}

Title: Re: Android Bluetooth joystick
Post by: kas on Jan 20, 2016, 08:19 am
Quote
Quote
I did exactly the same but i wont get readings in serial monitor :(
Can you display
  AndroTest V2.0 - @kas2014
  demo for V5.x App

on the Serial Monitor ??


Title: Re: Android Bluetooth joystick
Post by: kri5too on Jan 20, 2016, 08:30 am
Can you display
  AndroTest V2.0 - @kas2014
  demo for V5.x App

on the Serial Monitor ??



Yes, if i upload scketch and start serial monitor, then this text will show up.
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 20, 2016, 08:53 am
Quote
Yes, if i upload scketch and start serial monitor, then this text will show up
OK


Carefully review those 6 questions and answer YES/NO
(If you don't understand a specific item, just tell it)

Android side (smartphone/tablet):
1) go to Option/About and confirm that JBTC App version is V5.2
2) can you move the joystick and display position at bottom left
3) is your BT card already paired with your Android device
4) are you connected ("connected to: XXX", green text at bottom)

Arduino side:
5) is your Bluetooth card already configured @57600 bps  (most are 9600bps by default)
6) is your Bluetooth card LED solid red or green  (blinking = not connected)



Title: Re: Android Bluetooth joystick
Post by: kri5too on Jan 20, 2016, 09:50 am
OK


Carefully review those 6 questions and answer YES/NO
(If you don't understand a specific item, just tell it)

Android side (smartphone/tablet):
1) go to Option/About and confirm that JBTC App version is V5.2
2) can you move the joystick and display position at bottom left
3) is your BT card already paired with your Android device
4) are you connected ("connected to: XXX", green text at bottom)

Arduino side:
5) is your Bluetooth card already configured @57600 bps  (most are 9600bps by default)
6) is your Bluetooth card LED solid red or green  (blinking = not connected)

1.Yes
2.No
3.Yes
4.Yes
5.How to do this ?I think that is solution.
6.If i go home i will chek it.
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 20, 2016, 12:03 pm
Quote
2) can you move the joystick and display position at bottom left
2.No
::)  ::)  ::)
Data is just above "Connected to..."
(0,0) should change value according to joystick position
Should work even if not connected
Please confirm


Quote
5) is your Bluetooth card already configured @57600 bps  (most are 9600bps by default)
5.How to do this ?I think that is solution.
Is your BT board HC-05 or HC-06 ??
Let me have a link to your specific BT board

In your code, please change
Serial1.begin(57600);                                // 57600 = max value for softserial
to
Serial1.begin(9600);

and let me know the outcome

Title: Re: Android Bluetooth joystick
Post by: kri5too on Jan 20, 2016, 08:58 pm
I changed the Serial1.begin(57600)to 9600 and the joystick values became to serial monitor.
Everything was all right.
But when i writed my code, after that the joystick wont work :(
If i look to serial monitor i dont get joystick values from joystick posison in left. If joystick is right then i get the readings.
What i did wrong ?
Here is my code.. I just wanna run 2 dc motors according joystick position.

Quote
#define VERSION     "\n\nAndroTest V2.0 - @kas2014\ndemo for V5.x App"

// V2.0  changed to pure ASCII Communication Protocol ** not backward compatible **
// V1.4  improved communication errors handling
// V1.3  renamed for publishing, posted on 09/05/2014
// V1.2  Text display   ** not backward compatible **
// V1.1  Integer display
// V1.0  6 buttons + 4 data char implemented

// Demo setup:
// Button #1 controls pin #13 LED
// Button #4 toggle datafield display rate
// Button #5 configured as "push" button (momentary)
// Other buttons display demo message

// Arduino pin#2 to TX BlueTooth module
// Arduino pin#3 to RX BlueTooth module
// make sure your BT board is set @57600 bps
// better remove SoftSerial for PWM based projects

// For Mega 2560:
// remove   #include "SoftwareSerial.h", SoftwareSerial mySerial(2,3);
// search/replace  mySerial  >> Serial1
// pin#18 to RX bluetooth module, pin#19 to TX bluetooth module
#include <AFMotor.h>
AF_DCMotor motorV(3,MOTOR12_64KHZ); //vasak moto
AF_DCMotor motorP(4,MOTOR12_64KHZ); //parem moto
int motorSpeed;
int center;
#define    STX          0x02
#define    ETX          0x03
#define    ledPin       13
#define    SLOW         750                            // Datafields refresh rate (ms)
#define    FAST         250                             // Datafields refresh rate (ms)


everything between this is the same code you wrote.

void getJoystickState(byte data[8])    {
 int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
 int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
 center=joyX = joyX - 200;                                                  // Offset to avoid
 joyY = joyY - 200;                                                  // transmitting negative numbers

 if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // commmunication error
// Your code here ...
if (joyX>10){
motorSpeed = map(joyX, 0,100,0,255);
motorP.setSpeed(motorSpeed);
motorV.setSpeed(motorSpeed);
motorP.run(FORWARD);
motorV.run(FORWARD);

   Serial.print("Joystick position:  ");
   Serial.print(joyX);  
   Serial.print(", ");  
   Serial.println(joyY);
}}

and continues with your code.
Title: Re: Android Bluetooth joystick
Post by: kas on Jan 21, 2016, 09:00 pm
Quote
If i look to serial monitor i dont get joystick values from joystick posison in left. If joystick is right then i get the readings.
What i did wrong ?
Easy  ;)

change

if (joyX>10){
motorSpeed = map(joyX, 0,100,0,255);
motorP.setSpeed(motorSpeed);
motorV.setSpeed(motorSpeed);
motorP.run(FORWARD);
motorV.run(FORWARD);

   Serial.print("Joystick position:  ");       <--<<  Joystick position only printed if joyX >10 !!
   Serial.print(joyX);  
   Serial.print(", ");  
   Serial.println(joyY);
}}  
                                          

to


if (joyX>10){
motorSpeed = map(joyX, 0,100,0,255);
motorP.setSpeed(motorSpeed);
motorV.setSpeed(motorSpeed);
motorP.run(FORWARD);
motorV.run(FORWARD);
}

   Serial.print("Joystick position:  ");
   Serial.print(joyX);  
   Serial.print(", ");  
   Serial.println(joyY);
}





For better performances, you really need to set your BT board at 57600 bps
Is your board HC-05 or HC-06 ??
Let me have a link to your specific board


Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 02, 2016, 02:19 pm
KAS, awesome app it looks good on my Samsung S5 ! I am not a programmer  so please excuse the noobie questions. I did download your example sketch and got my Adruino uno to work with B1 lighting up my LED on pin 13 using a SH_BT_Board V1.3 HC-05 from ebay.  I am confused when ready this thread
if I need to have the servo libray or use the PID_v1.h ? Where do you find PID_v1.h as it isn't in the standard library .


My Scenario is :

I have a rover that has 2 dc motors connected to an esc
I want to control my rover with my android phone however can not find a suitable sketch or know how to modify an existing sketch to remove the Hbridge that others commonly use on the RC Car builds.

I have hc05 tx going to the rx on the uno and hc05 rx going to the tx on the uno . I notice in some of your example sketches you have the TX (hc-05) going to pin 2 and RX (hc-05) going to pin 3 ? Why not TX/RX pins on the UNO?

I would really like to see real time voltage and Mah but if I could get my rover working I would be really happy :)


Title: Re: Android Bluetooth joystick
Post by: kas on Feb 02, 2016, 07:22 pm
Quote
I have hc05 tx going to the rx on the uno and hc05 rx going to the tx on the uno . I notice in some of your example sketches you have the TX (hc-05) going to pin 2 and RX (hc-05) going to pin 3 ? Why not TX/RX pins on the UNO?
In order to display debug info in the Serial Monitor, we need a second Serial connection
 - hardware serial (DO/D1) to PC (debug)
 - software serial (D2/D3) to BT board

You can connect BT card to DO/D1, if debug info's are not required


Quote
I want to control my rover with my android phone however can not find a suitable sketch or know how to modify an existing sketch to remove the Hbridge that others commonly use on the RC Car builds.
Let's first check if the Android/BT card transmission is OK
Please download AndroTest V2.0 demo sketch (http://forum.arduino.cc/index.php?topic=173246.msg1766646#msg1766646) (with SoftSerial)
and confirm you can display Joystick position and buttons press on your Serial Monitor
Your PC screen should look pretty much like that:

(http://i.imgur.com/YAulg3u.png)

Let us know




Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 03, 2016, 12:59 am
I have good connection to APP , I used your demo sketch :)
Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 03, 2016, 02:09 pm
KAS,

Now that I have good connection to Joy Stick Commander App, what do you suggest my next step would be? Try and modify someone elses code and remove the Hbridge ? I know where I want to go but don't know how to get there. Thanks for all the help thus far.
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 03, 2016, 08:00 pm
Most ESC's are driven using a PWM servo signal

This code is the bare minimum for servo's control
As there is no feed back from Arduino to smartphone, DO1 (Arduino TX) is not used,
so you still can display debug info's on the serial monitor

Code: [Select]
#define VERSION     "\n\nAndro_Pan&Tilt V3.6 - @kas2014\n** servo's demo for V5.x App **"

// Controls two servo motors

// V3.6: Android BT Commander V5.X compatible, no button data management
// V3.0: Android BT Commander V3.X compatible, no button data management
// V2.5 can receive both Byte & Integer data
// V2.0: removed SoftwareSerial

// Android BT Commander settings:
// Options/Options for advanced users/Data Range        >>>  -100 to +100
// Options/Options for advanced users/Refresh interval  >>>  50ms

//  Arduino pin #0 to TX BlueTooth module
// BT TX to be disconnected from D0 during sketch upload

#include <Servo.h>

boolean    DEBUG =         true;

#define    pinServo_X     9             // <<  ServoX pin
#define    pinServo_Y     10           // <<  ServoY pin
#define    STX            0x02
#define    ETX            0x03
#define    MIN_Y          0  //45             // vertical move limitation,
#define    MAX_Y          180                 // adjust to needs
#define    ZERO_Y         -1  //60             // vertical zero offset

byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};
Servo myservoX;                         // create servo objects
Servo myservoY;

void setup()  {
  Serial.begin(57600);
  myservoX.attach(pinServo_X); 
  myservoY.attach(pinServo_Y); 
  if(DEBUG)    Serial.println(VERSION);
}

void loop() {
   if(Serial.available())  {                            // data received from smartphone
    delay(2);
    cmd[0] =  Serial.read(); 
    if(cmd[0] == STX)  {
      int i=1;     
      while(Serial.available())  {
        delay(1);
        cmd[i] = Serial.read();
        if(cmd[i]>127 || i>7)                 break;     // Communication error
        if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
        i++;
      }
      if(i==7)     setServoPosition(cmd);
    }
  }
}

void setServoPosition(byte data[8])    {
  int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
  int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
  joyX = joyX - 200;                                                  // Offset to avoid
  joyY = joyY - 200;                                                  // transmitting negative numbers

  if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // communication error
 
  joyX = map(joyX, -100, 100, 180, 0);   //  << adjust to change motor direction
  joyY = map(joyY, -100, 100, 0, 180);   //  <<

  joyY+=ZERO_Y;
  joyY = constrain(joyY, MIN_Y, MAX_Y);
  myservoX.write(joyX);
  myservoY.write(joyY);
  if(DEBUG)    {Serial.print(joyX); Serial.print(", "); Serial.println(joyY);}
}



Don't forget to disconnect BT TX from D0 during sketch upload

** EDIT: code was fixed as per below


Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 04, 2016, 04:06 am
I tried to upload the sketch but it has errors?


sketch_feb03a.ino: In function 'void setup()':
sketch_feb03a.ino:21:45: error: 'ServoX' was not declared in this scope
sketch_feb03a.ino:35:19: note: in expansion of macro 'pinServo_X'
sketch_feb03a.ino:22:44: error: 'ServoY' was not declared in this scope
sketch_feb03a.ino:36:19: note: in expansion of macro 'pinServo_Y'
Error compiling.
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 04, 2016, 06:52 am
Opps ...  sorry  :-*  :-*
ServoX pin and ServoX pin are just added comments


Please replace

#define    pinServo_X     9             <<  ServoX pin
#define    pinServo_Y     10           <<  ServoY pin

by

#define    pinServo_X     9            // <<  ServoX pin
#define    pinServo_Y     10           // <<  ServoY pin



Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 04, 2016, 04:09 pm
Thank you KAS, I test it with the LEDS and you can see they are changing pulse widths with stick movement however I am out of the pwn range on my ESC as you can see it just flashes (green LED on ESC should be solid) .

Maybe it should see throttle set to zero for 3 seconds, then send signal ? I am not sure if this ESC has a throttle protection built in ?

Excuse the wiring mess as it's in prototype stage.

https://youtu.be/DNMxmfj8cco

Thank you
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 04, 2016, 06:02 pm
Quote
Thank you KAS, I test it with the LEDS and you can see they are changing pulse widths with stick movement however I am out of the pwn range on my ESC as you can see it just flashes (green LED on ESC should be solid) .
According to Scorpion XL documentation:
Quote
These should be attached to your R/C receiver or signal
source just like a normal R/C servo.
Forget the bot for the moment
Please connect two servos and see if they are actuated
Also let me have a screenshot showing debug info's on Serial Monitor

BTW, this documentation is less than adequate :-\


EDIT: also google for robot "differential steering"

Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 04, 2016, 06:08 pm
The ESC Is connected I just have the LEDs connected also so you could see the pulses .

Let me grab some servos :)
Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 04, 2016, 06:27 pm
I just tested with servos and it works. It has to be something with esc then?
Is it safe to power my bread board with battery and also connect to Usb computer source for
serial monitor? I don't want to burn up anything.

Here is more info on the esc, however this is the 2.0 board though. I am still searching for more info.
http://www.robotpower.com/products/scorpion_XL_info.html

Here is the youtube video with servos.

https://youtu.be/IFoRBFMhhFw

Title: Re: Android Bluetooth joystick
Post by: kas on Feb 04, 2016, 08:15 pm
Quote
Is it safe to power my bread board with battery and also connect to Usb computer source for
serial monitor? I don't want to burn up anything.
Yes, grounds should be connected


Quote
I just tested with servos and it works. It has to be something with esc then?
According to doc: "Microcontrollers such as PIC, AVR, ARM, Arduino etc. can drive the Scorpion XL by using servo command outputs"
So, yes it has to be something with this specific ESC
Please get support from manufacturer

We will then address remaining aspects (differential steering, real time voltage and milli amps monitoring)

Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 04, 2016, 08:33 pm
KAS the ESC works perfect when you use traditional radio control , I am thinking it may need to see throttle position at 0 for x seconds before it will power the motors?

Here is me controlling the rover programmed to my radio

https://www.youtube.com/watch?v=RBomaEX9W1E
Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 04, 2016, 09:20 pm
Here is serial pic request, I am still researching on my ESC
Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 04, 2016, 09:58 pm
Kas , I owe you a beer for the help thus far . :)

It appears we need to cut the signal for 3-5 seconds or put throttle to 0 . If it see signal then the esc won't engage .

I hooked everything up and moved joy stick to back position on your app and it engaged.  Therefore I was able to drive rover forward and back for this video . When I tried to do same procedure and test again it would not engaged the esc ???

Here is video

https://youtu.be/ix-E1TvCHXY
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 05, 2016, 07:40 am
Quote
Here is me controlling the rover programmed to my radio
https://www.youtube.com/watch?v=RBomaEX9W1E
Nice and powerful bot
At which level is differential steering implemented ??


Quote
Here is serial pic request, I am still researching on my ESC
Perfect  ;)


Quote
It appears we need to cut the signal for 3-5 seconds or put throttle to 0 . If it see signal then the esc won't engage .
I hooked everything up and moved joy stick to back position on your app and it engaged.  Therefore I was able to drive rover forward and back for this video . When I tried to do same procedure and test again it would not engaged the esc
Sorry, can't help you for this specific ESC


I suggest you dedicate one App button for LOW speed mode  ;)



Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 05, 2016, 02:12 pm
On my RC radio differential steering in activated on initial start up, there is no delay as it reacts exactly to my stick movements.

Is there a way to write a section of code to send signal inputs to -100 or low position for X seconds ? I don't mind to use the button just to test this. I think it's very close but the pwm signal seems to be out of range
for the ESC, I will keep test further as I really want this to work.

Here is a PDF of more information that I am reading now.

http://www.robotpower.com/downloads/RobotPower_Scorpion_XL_quickstart.pdf

Thanks KAS   
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 05, 2016, 04:28 pm
Quote
Is there a way to write a section of code to send signal inputs to -100 or low position for X seconds ? I don't mind to use the button just to test this.
Change your setServoPosition function for this one:

Code: [Select]
void setServoPosition(byte data[8])    {   // differential steering version
  int servo_L, servo_R;
  int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
  int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
  joyX = joyX - 200;                                                  // Offset to avoid
  joyY = joyY - 200;                                                  // transmitting negative numbers

  if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // communication error

  if(joyY >-10)  {                                                    // differential steering
    servo_L = (joyY - (3*joyX)/4);
    servo_R = (joyY + (3*joyX)/4);
  }  else  {
    servo_L = (joyY + (3*joyX)/4);
    servo_R = (joyY - (3*joyX)/4);
  }
 
  servo_L = map(servo_L, -100, 100, 180, 0);   //  << adjust to change motor direction XXX
  servo_R = map(servo_R, -100, 100, 0, 180);   //  <<
  servo_L = constrain(servo_L, 0, 180);
  servo_R = constrain(servo_R, 0, 180);

  myservoX.write(servo_L);
  myservoY.write(servo_R);
  if(DEBUG)    {Serial.print(joyX); Serial.print(", "); Serial.println(joyY);}
}


This version implements differential steering
By moving joystick "full south", you will send 'low' to both motors
Should you post a new video, please move joystick slowly  ;)

Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 05, 2016, 06:21 pm
I really wish I understood the code that you give me, thanks for your patience. I will try it asap and slow my stick movements on next video :)

Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 06, 2016, 04:01 am
kas, I have good news I got rover working. I calibrated ESC and now it's working fine.
I do have a video but its not very good. Rover is very difficult to control as Left and Right Stick movements
cause the rover to go forward or backwards and up/down movements cause it to turn.

I tried to capture this on video but it was difficult by myself. I also need to dial in some expo as it's very sensitive before it gets full power.

Thank you sir.

Video

https://youtu.be/50HhGHvt52E
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 06, 2016, 07:41 am
Quote
I do have a video but its not very good. Rover is very difficult to control as Left and Right Stick movements cause the rover to go forward or backwards and up/down movements cause it to turn.
As mentioned in the code, adjust motors direction

Depending on your motor connections, you probably have to change
  servo_L = map(servo_L, -100, 100, 180, 0);       //  << adjust to change motor direction XXX
  servo_R = map(servo_R, -100, 100, 0, 180);

to
  servo_L = map(servo_L, -100, 100, 0, 180);       //  << adjust to change motor direction XXX
  servo_R = map(servo_R, -100, 100, 0, 180);



During testing, you may change
  myservoX.write(servo_L);
  myservoY.write(servo_R);

to
  myservoX.write(servo_L /2);
  myservoY.write(servo_R /2);


Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 07, 2016, 12:26 am
I found out I have to calibrate the esc every time  I make changes to the pwn signal.  After a couple more hours of messing it I now have a drivable unit . I can't thank you enough Kas . :)

Here is a video , it's not very good as it's hard to drive and video . I will have my wife help me tomorrow .

How can I display mAh and voltage ? The other things I'm curious about as if signal is weak or missing then it will act as dead man switch to motors .

Also can I insert code from example ino file for the button commands to actual a servo ?


Video
https://youtu.be/MdcPS_c69Is


Thanks ,
FullSpool
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 07, 2016, 12:21 pm
Quote
Here is a video
Seems we are on the right track  ;)


Quote
How can I display mAh and voltage ? The other things I'm curious about as if signal is weak or missing then it will act as dead man switch to motors .
Let's start by the Dead Man implementation
Which safety level do you require ??
 - moderate: boot will stop if signal is lost and immediately restart when signal is back
 - high: needs Arduino reboot to restart motion

Let me have a copy of your actual working sketch
We need to work on the very same code

Is there mV and mA outputs on your driver board ??


Quote
Also can I insert code from example ino file for the button commands to actual a servo ?
Please elaborate


Out of curiosity, where are you based in this Global Village ?


Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 07, 2016, 04:58 pm
Kas,

This sketch is working really well but I have expo jumper installed on the ESC . If not, it's to sensitive with the joy stick commander app. I am in the USA , if you want exact location I can PM you .

I have no pins assigned on my UNO yet for mA or voltage read out. I am powering my rover with
a 3s lipo (4.1v x 3= 12.3 v fully charged) so I assume I will need to solder in a jumper off the main feed and tie it into an analog pin on the uno? or tie into the balance port  on the Lipo battery itself? I can't use the 5v out pin on the uno as it wont show me true voltage as I am powering it with more then 5v.

I just need moderate dead mans kill switch.

I would also like button 1 to tie into pin 8 on the uno, when button 1 is pushed a new servo will sweep 90 degrees, when button 1 is pressed again it will move back to original state.

Code: [Select]

#define VERSION     "\n\nAndro_Pan&Tilt V3.6 - @kas2014\n** servo's demo for V5.x App **"

// Controls two servo motors

// V3.6: Android BT Commander V5.X compatible, no button data management
// V3.0: Android BT Commander V3.X compatible, no button data management
// V2.5 can receive both Byte & Integer data
// V2.0: removed SoftwareSerial

// Android BT Commander settings:
// Options/Options for advanced users/Data Range        >>>  -100 to +100
// Options/Options for advanced users/Refresh interval  >>>  50ms

//  Arduino pin #0 to TX BlueTooth module
// BT TX to be disconnected from D0 during sketch upload

#include <Servo.h>

boolean    DEBUG =         true;

#define    pinServo_X     9            //<<  ServoX pin
#define    pinServo_Y     10           //<<  ServoY pin
#define    STX            0x02
#define    ETX            0x03
#define    MIN_Y          0  //45             // vertical move limitation,
#define    MAX_Y          180                 // adjust to needs
#define    ZERO_Y         -1  //60             // vertical zero offset

byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};
Servo myservoX;                         // create servo objects
Servo myservoY;

void setup()  {
 Serial.begin(57600);
 myservoX.attach(pinServo_X);  
 myservoY.attach(pinServo_Y);  
 if(DEBUG)    Serial.println(VERSION);
}

void loop() {
  if(Serial.available())  {                            // data received from smartphone
   delay(2);
   cmd[0] =  Serial.read();  
   if(cmd[0] == STX)  {
     int i=1;      
     while(Serial.available())  {
       delay(1);
       cmd[i] = Serial.read();
       if(cmd[i]>127 || i>7)                 break;     // Communication error
       if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
       i++;
     }
     if(i==7)     setServoPosition(cmd);
   }
 }
}

void setServoPosition(byte data[8])    {   // differential steering version
 int servo_L, servo_R;
 int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
 int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
 joyX = joyX - 200;                                                  // Offset to avoid
 joyY = joyY - 200;                                                  // transmitting negative numbers

 if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // communication error

 if(joyY >-10)  {                                                    // differential steering
   servo_L = (joyY - (3*joyX)/4);
   servo_R = (joyY + (3*joyX)/4);
 }  else  {
   servo_L = (joyY + (3*joyX)/4);
   servo_R = (joyY - (3*joyX)/4);
 }
 
 servo_L = map(servo_L, -100, 100, 0, 180);   //  << adjust to change motor direction XXX
 servo_R = map(servo_R, -100, 100, 0, 180);   //  <<
 servo_L = constrain(servo_L, 0, 180);
 servo_R = constrain(servo_R, 0, 180);

 myservoX.write(servo_L/2);
 myservoY.write(servo_R/2);
 if(DEBUG)    {Serial.print(joyX); Serial.print(", "); Serial.println(joyY);}

}

Title: Re: Android Bluetooth joystick
Post by: kas on Feb 08, 2016, 08:32 am
Quote
This sketch is working really well but I have expo jumper installed on the ESC . If not, it's to sensitive with the joy stick commander app
Is it OK with the expo jumper ??
The signal can also be tuned within the Arduino code


Quote
I am powering my rover with a 3s lipo (4.1v x 3= 12.3 v fully charged) so I assume I will need to solder in a jumper off the main feed and tie it into an analog pin on the uno?
Don't do that  :smiley-eek:    you will fry your Uno
Analog pins accept no more than 5 Volts, you need a voltage divider


Back to full blown code, with feedback to smartphone
This is AndroTest_Servo_fullspool V1.1, with Dead Man implementation

Code: [Select]
#define VERSION     "\n\nAndroTest_Servo_fullspool V1.x - @kas2016\ndemo for servo's"

// V1.1  added Dead Man feature
// V1.0  Basic implementattion

// Android BT Commander settings:
// Options/Options for advanced users/Data Range        >>>  -100 to +100
// Options/Options for advanced users/Refresh interval  >>>  50ms

//  Arduino pin #0 to TX BlueTooth module
// BT TX to be disconnected from D0 during sketch upload

#include <Servo.h>

#define    pinServo_X     9            //<<  ServoX pin
#define    pinServo_Y     10           //<<  ServoY pin
#define    STX            0x02
#define    ETX            0x03
#define    ledPin         13

Servo myservoX;                                         // create servo objects
Servo myservoY;
byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};                 // bytes received
byte buttonStatus = 0;                                  // first Byte sent to Android device
long previousMillis = 0;                                // will store last time Buttons status was updated
long sendInterval = 750;                                // interval between Buttons status transmission (milliseconds)
long deadManInterval = 1100;                            // interval between Dead Man checks (milliseconds)
boolean deadManTimeout = false;                         // dead man flag
String displayStatus = "xxxx";                          // message to Android device
int servo_L, servo_R = 90;                              // servo's positioning values

void setup()  {
  Serial.begin(57600);
  myservoX.attach(pinServo_X); 
  myservoY.attach(pinServo_Y); 
  pinMode(ledPin, OUTPUT);     
  while(Serial.available())  Serial.read();          // empty RX buffer
}

void loop() {
  if(Serial.available())  {                              // data received from smartphone
    deadManTimeout = false;                              // reset Dead Man
    delay(2);
    cmd[0] =  Serial.read(); 
    if(cmd[0] == STX)  {
      int i=1;     
      while(Serial.available())  {
        delay(1);
        cmd[i] = Serial.read();
        if(cmd[i]>127 || i>7)                 break;     // Communication error
        if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
        i++;
      }
      if     (i==2)          getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
      else if(i==7)          getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
    }
  }
  sendBlueToothData();
  checkDeadMan();
  motorsControl();
}

void checkDeadMan()  {                                                  // stop engines if signal is lost
  static long previousMillis = 0;                             
  long currentMillis = millis();
  if(currentMillis - previousMillis > deadManInterval) {                // check is performed every deadManInterval ms
    previousMillis = currentMillis;
    if(deadManTimeout)  {
      myservoX.write(90);                                               // stop motors
      myservoY.write(90);
    }
    deadManTimeout = true;
  } 
}

void motorsControl()  {
  myservoX.write(servo_L/2);
  myservoY.write(servo_R/2);
}

void sendBlueToothData()  {
  static long previousMillis = 0;                             
  long currentMillis = millis();
  if(currentMillis - previousMillis > sendInterval) {   // send data back to smartphone
    previousMillis = currentMillis;

// Data frame transmitted back from Arduino to Android device:
// < 0X02   Buttons state   0X01   DataField#1   0x04   DataField#2   0x05   DataField#3    0x03 > 
// < 0X02      "01011"      0X01     "120.00"    0x04     "-4500"     0x05  "Motor enabled" 0x03 >    // example

    Serial.print((char)STX);                                             // Start of Transmission
    Serial.print(getButtonStatusString());  Serial.print((char)0x1);     // buttons status feedback
    Serial.print(GetdataInt1());            Serial.print((char)0x4);     // datafield #1
    Serial.print(GetdataFloat2());          Serial.print((char)0x5);     // datafield #2
    Serial.print(displayStatus);                                         // datafield #3
    Serial.print((char)ETX);                                             // End of Transmission
  } 
}

String getButtonStatusString()  {
  String bStatus = "";
  for(int i=0; i<6; i++)  {
    if(buttonStatus & (B100000 >>i))      bStatus += "1";
    else                                  bStatus += "0";
  }
  return bStatus;
}

int GetdataInt1()  {              // Data dummy values sent to Android device for demo purpose
  static int i= -30;              // Replace with your own code
  i ++;
  if(i >0)    i = -30;
  return i; 
}

float GetdataFloat2()  {           // Data dummy values sent to Android device for demo purpose
  static float i=50;               // Replace with your own code
  i-=.5;
  if(i <-50)    i = 50;
  return i; 
}

void getJoystickState(byte data[8])    {
  int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
  int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
  joyX = joyX - 200;                                                  // Offset to avoid
  joyY = joyY - 200;                                                  // transmitting negative numbers

  if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // communication error

  if(joyY >-10)  {                                                    // differential steering
    servo_L = (joyY - (3*joyX)/4);
    servo_R = (joyY + (3*joyX)/4);
  }  else  {
    servo_L = (joyY + (3*joyX)/4);
    servo_R = (joyY - (3*joyX)/4);
  }
 
  servo_L = map(servo_L, -100, 100, 0, 180);   //         << adjust to change motor direction
  servo_R = map(servo_R, -100, 100, 0, 180);
  servo_L = constrain(servo_L, 0, 180);
  servo_R = constrain(servo_R, 0, 180);
}

void getButtonState(int bStatus)  {
  switch (bStatus) {
// -----------------  BUTTON #1  -----------------------
    case 'A':
      buttonStatus |= B000001;        // ON
      displayStatus = "LED <ON>";
      digitalWrite(ledPin, HIGH);
      break;
    case 'B':
      buttonStatus &= B111110;        // OFF
      displayStatus = "LED <OFF>";
      digitalWrite(ledPin, LOW);
      break;

// -----------------  BUTTON #2  -----------------------
    case 'C':
      buttonStatus |= B000010;        // ON
      displayStatus = "Button2 <ON>";
      break;
    case 'D':
      buttonStatus &= B111101;        // OFF
      displayStatus = "Button2 <OFF>";
      break;

// -----------------  BUTTON #3  -----------------------
    case 'E':
      buttonStatus |= B000100;        // ON
      displayStatus = "Button3 <ON>";
      break;
    case 'F':
      buttonStatus &= B111011;      // OFF
      displayStatus = "Button3 <OFF>";
      break;

// -----------------  BUTTON #4  -----------------------
    case 'G':
      buttonStatus |= B001000;       // ON
      displayStatus = "Button4 <ON>";
      break;
    case 'H':
      buttonStatus &= B110111;    // OFF
      displayStatus = "Button4 <OFF>";
     break;

// -----------------  BUTTON #5  -----------------------
    case 'I':                   // configured as momentary button
      displayStatus = "Button5: <pushed>";
      break;

// -----------------  BUTTON #6  -----------------------
    case 'K':
      buttonStatus |= B100000;        // ON
      displayStatus = "Button6 <ON>"; // Demo text message
      break;
    case 'L':
      buttonStatus &= B011111;        // OFF
      displayStatus = "Button6 <OFF>";
      break;
  }
// ---------------------------------------------------------------
}

I have no possibilities to test the code for the moment, but at least, it compiles  ;)


Make me a favor, edit your last post and embed your code as such
  [c ode] ... code... [/c ode]     (ommit the two spaces)
or use the </> button at the top left of the "Post reply" dialog
Post will be more legible



Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 08, 2016, 02:16 pm
Is it OK with the expo jumper ??
The signal can also be tuned within the Arduino code

Don't do that  :smiley-eek:    you will fry your Uno
Analog pins accept no more than 5 Volts, you need a voltage divider

Make me a favor, edit your last post and embed your code as such
  [c ode] ... code... [/c ode]     (ommit the two spaces)
or use the </> button at the top left of the "Post reply" dialog
Post will be more legible

So I can keep tuning the signal by adjusting this part of the code correct?
 myservoX.write(servo_L/2);
 myservoY.write(servo_R/2);

If I do a voltage divider will it only show the 5v on the telemetry? Or give me my actual 12v reading?

I fixed the post, thanks for the feed back. I will work on it more today.



Title: Re: Android Bluetooth joystick
Post by: kas on Feb 08, 2016, 05:57 pm
Quote
So I can keep tuning the signal by adjusting this part of the code correct?
 myservoX.write(servo_L/2);
 myservoY.write(servo_R/2);
Yes, you can use any mathematical function (linear or non linear)


Quote
If I do a voltage divider will it only show the 5v on the telemetry? Or give me my actual 12v reading
You will read actual battery voltage
Be prepared to have 1/4W resistors:
 1X  4.7K  +  1X  10K
or
 3X  4.7K

For Amp you will need a 5A Current Sensor Module ACS712 such as this one (http://www.ebay.com/itm/5A-range-Current-Sensor-Module-ACS712-Module-Arduino-module-NEW-/281683077478?hash=item41959ea966:g:aAoAAOSwgkRVSKxv)  (2 bucks, shipped)

(http://i.imgur.com/wUKHcUv.jpg)
Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 09, 2016, 03:08 am
Thank you Kas , I will get the parts ordered and research the voltage divider .

I tried the new code , when I press button 1 it lights up the LED however when I connect a servo to pin 13 it just twitches.

https://youtu.be/TyLJ8wD9v-o

Next I tested Deadman , whenever signal is lost the motors keep turning in the last known position .

https://youtu.be/mXp7KRq7sPA

I am not sure how to fix it ?

On a side note I made some new axles as my aluminum axles bend to easy . These are made from drill stock so should be much stronger .

(http://i244.photobucket.com/albums/gg13/99si_2007/20160208_195901_zpsmxg3nplt.jpg)
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 09, 2016, 10:47 am
Quote
I tried the new code , when I press button 1 it lights up the LED however when I connect a servo to pin 13 it just twitches.
Next I tested Deadman , whenever signal is lost the motors keep turning in the last known position .
I am not sure how to fix it ?
This is AndroTest_Servo_fullspool Version 1.2
// V1.2  added 3rd servo control, fixed Dead Man
Code is attached, you need to be logged to access it
Make sure to connect the AUX servo to pin #8
What is it used for ??

I also noticed on your video that your smartphone don't get any feedback from Arduino
Please connect BT board RX pin to Arduino pin #1
On your smartphone Datafield #1 and #2 will (should) display demo changing numbers
Datafield #3 will display AUX servo and buttons status


Quote
These are made from drill stock so should be much stronger
At least they won't bend anymore  ;)


Again, if you make any change to the code, please send me a copy
We really need to stay synchronized

Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 09, 2016, 02:33 pm
Kas,

I tested the servo with button 1 and it works now however the dead man test goes from last known for a second or 2 then motors go wide open until signal is restored .  The reason I want to move servo arm is for my locking mechanism .


I will test further , the code is attached.
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 09, 2016, 02:48 pm
Please replace

    if(deadManTimeout)  {
      servo_L = 0;                                               // stop motors
      servo_R = 0;
     }

by

    if(deadManTimeout)  {
      servo_L = 90;                                               // stop motors
      servo_R = 90;
     }

Can you see changing values in App's datafields ??

Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 10, 2016, 03:17 am
That fixed it however there is a 2 second delay from last known position till the motors quit.

Controls are getting really smooth , led lights up and servo actuates as it should for now.
I am really happy how this is progressing . I can't wait till my telemetry parts come in.

New video
https://youtu.be/7s2JOm0RWqg
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 10, 2016, 10:50 am
Quote
That fixed it however there is a 2 second delay from last known position till the motors quit
Want a fast Dead Man ??

replace
  long deadManInterval = 1100;                            // interval between Dead Man checks (milliseconds)
by
  long deadManInterval = 550;                             // interval between Dead Man checks (milliseconds)

Want it faster ?? just let me know  ;)



Quote
I am really happy how this is progressing . I can't wait till my telemetry parts come in
Let me know the actual resistors values as soon as you receive them
You can get them right away at your local RadioShack


Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 10, 2016, 05:51 pm
My local radio shack only had 4.7k 1/2 watt resistors so I will be using 3 of those .

Would it be better to use a zener diode since my voltage may change ? (Not now but may in future)
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 10, 2016, 09:00 pm
Résistors are OK

Let me know if 1 second signal drop is OK for Dead Man safety, and please let me have a copy of the modified code
Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 11, 2016, 03:06 am
The deadman works perfect, thanks :)

Code is attached.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 12, 2016, 03:02 am
Here is a new video .
https://youtu.be/WUH83wnfXeg
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 12, 2016, 03:13 pm
Quote
The deadman works perfect, thanks :)
finally  ;)



Battery monitoring

Please make sure you understand what you are doing, both on the hard and software sides
You may google for  "voltage divider" "arduino"

solder the three 4.7K resistors in series
connect both ends to battery <+> and <->
connect analog input A0 as per drawing

                 4.7K         4.7K          4.7K
<+> ----/\/\/\---/\/\/\-|-/\/\/\---- <->
                                              |
                                            A0

Before actually connecting to Arduino board, check voltage with a DVM
should read 4 to 4.5 Volts (not 8 to 9V  :smiley-eek: )
I don't know your setup, if you have more than one power supply, make sure that grounds are connected

Upload and run AndroTest_Servo_fullspool V1.3
Battery level should be displayed with two decimal digits in DataField #1
Let me have a video including phone screen


Title: Re: Android Bluetooth joystick
Post by: odin25 on Feb 12, 2016, 06:13 pm
hi... i am new .... i have 1 arduino uno ent 1 motor shield adafruit motor / stepper /servo shield... ent 1 adafruit servo shield...
   how to conect the shield adafruit whith rover 5  robot platform? sory for the bad english i am greek ent i don know veri good english... pliz foto how conect the shield whith rover  ent how conect the ultra sonic sensor whith arduino?


imail:
pantelis4ever1@hotmail.com
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 12, 2016, 08:03 pm
Sorry odin25, I have no experience with those shields.
May be somebody will jump in for additional information
I suggest to raise the question on the Adafruit website
Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 13, 2016, 06:36 am
finally  ;)



Battery monitoring

Please make sure you understand what you are doing, both on the hard and software sides
You may google for  "voltage divider" "arduino"

solder the three 4.7K resistors in series
connect both ends to battery <+> and <->
connect analog input A0 as per drawing

                 4.7K         4.7K          4.7K
<+> ----/\/\/\---/\/\/\-|-/\/\/\---- <->
                                              |
                                            A0

Before actually connecting to Arduino board, check voltage with a DVM
should read 4 to 4.5 Volts (not 8 to 9V  :smiley-eek: )
I don't know your setup, if you have more than one power supply, make sure that grounds are connected

Upload and run AndroTest_Servo_fullspool V1.3
Battery level should be displayed with two decimal digits in DataField #1
Let me have a video including phone screen



Thank you for the suggestions, I understand the hardware side no problem it's the software side that confuses me. :)

I built the circuit and at 11.7 Vin I get 3.8Vout , on full charge lipo I get 12.3 Vin and 4.1 Vout so we are with in range for a 3S Lipo battery. I will load the sketch and make a video tomorrow but in the mean time can you explain to me how it's working in the program? I don't understand the formula.
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 13, 2016, 08:30 am
Quote
but in the mean time can you explain to me how it's working in the program? I don't understand the formula.
for 0 Volt, analogRead(Vpin) value is 0
for 5 Volts,  analogRead(Vpin) value is 1024
If you measure a 0 to 5V voltage (no Voltage divider)

voltage = 5 * analogRead(Vpin)/1024



for 12V, Voltage divider divides value by 3   (4.7/9.4+4.7)
so we need to adjust back the value (multiply by 3) to obtain real voltage

voltage = analogRead(Vpin) * (5.0/1024) *3 = analogRead(Vpin) * 0.0146484375


Google will explain it in better English than I can do  ;)


Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 14, 2016, 01:02 am
Thank you I will continue my research . :)

On a side note , I made a new video showing the real time voltage display. I will do further testing tonight and tomorrow but everything looks good so far .

Excuse the wiring mess .

 https://youtu.be/F8BKWDSwAM4

Title: Re: Android Bluetooth joystick
Post by: kas on Feb 14, 2016, 10:14 pm
Quote
https://youtu.be/F8BKWDSwAM4 (https://youtu.be/F8BKWDSwAM4)
Looks prefect  :)


Don't forget you can customize buttons and datafields captions in the option menu
You can also hide unsused buttons for a cleaner screen


What about using button #2 for
 - Normal: half speed
 - Turbo: full speed


Let me know when you receive the current sensor



Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 15, 2016, 12:41 am
That sounds like an excellent idea for button #2 ! I will adjust the app to remove buttons soon, Im spending more time reading then seeing what the app is capable of :)

Is the app open source ? I didnt see an apk posted anywhere. It would cool if we could adjust background graphics and move the data fields around.

Thank you for helping me kas, I am very grateful and have learned so much.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 15, 2016, 02:20 am
This is very crude but something like this . I can make a better one in photoshop if needed . :)

(http://i244.photobucket.com/albums/gg13/99si_2007/PSMix_2016-02-14-19-13-17_zpsfpiqnbf5.png)
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 15, 2016, 03:53 pm
Quote
That sounds like an excellent idea for button #2 !
// V1.4  added Turbo function (Button #2)

fullspool, I sent you a PM

Title: Re: Android Bluetooth joystick
Post by: kas on Feb 15, 2016, 07:00 pm
Quote
Is the app open source ?
Joystick BT Commander (free App) is the base of Total RC Commander (http://forum.arduino.cc/index.php?topic=173246.msg1998617#msg1998617) (paid App)
The App is not open source for the moment

Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 15, 2016, 08:03 pm
Joystick BT Commander (free App) is the base of Total RC Commander (http://forum.arduino.cc/index.php?topic=173246.msg1998617#msg1998617) (paid App)
The App is not open source for the moment


Please let me know when you make it open source as I'd love to learn from it .

I noticed when I power up the ardiuno board the AUX servo twitches 1 time . Do you know what causes this ?

Title: Re: Android Bluetooth joystick
Post by: kas on Feb 18, 2016, 02:44 pm
Quote
I noticed when I power up the arduino board the AUX servo twitches 1 time . Do you know what causes this ?
Most hobby servo's have this problem
Have a look here (http://forum.arduino.cc/index.php?topic=121554.msg914500#msg914500)
Quote
Well it's not because of anything your are doing or not doing. Here is the problem, typical hobby servos are designed such that anytime they are powered up they need to be receiving a continuous and valid position control pulse. A servo that has DC power on but no position control pulse being received, is in a undefined state and no assumptions can or should be made as to what behavior the servo should exhibit while you either hold down reset switch. Once you send a valid servo.write command to the servo, the servo library code automatically keeps sending that same position output command at a standard servo update rate, around every 20ms ...
 If it important to try and eliminate this behavior then you need to think about about possible solutions. One possible method might be to have the power wired to your servo be controlled on and off by your sketch via an output pin controlling a relay which would then route power on or off to the servo. That way your servo can be set-up in software first and then turn on the digital output to switch power to the servo.
In setup, try moving myservoA.write(90); just below myservoA.attach(pinServo_A);
You may also drop myservoA.write(90);, but it may not be safe

Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 24, 2016, 03:13 am
Most hobby servo's have this problem
Have a look here (http://forum.arduino.cc/index.php?topic=121554.msg914500#msg914500)
In setup, try moving myservoA.write(90); just below myservoA.attach(pinServo_A);
You may also drop myservoA.write(90);, but it may not be safe


I tried moving the coding around and also deleting myservoA.write(90) , none of the options worked . :(
I also tried the turbo button but when I hit button 2 the rover just takes off by its self with no stick movement. Is this how you design the program? or should I be expecting something different? I am learning more and more everyday. I am glad there are people like you to help out us dreamers. :)

Thank you for the suggestions.
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 24, 2016, 08:11 pm
Quote
I tried moving the coding around and also deleting myservoA.write(90) , none of the options worked
no surprise, please remove modifications


Quote
I also tried the turbo button but when I hit button 2 the rover just takes off by its self with no stick movement. Is this how you design the program? or should I be expecting something different?
:o  :o  :o  (surprised)
No, rover shouldn't move when stick is 0.0
I double checked code, everything seems OK

Please check again on your side
also confirm that datafield #3 does display "Turbo <ON>" when pressing button #2
EDIT: also check ESC calibration (zero fine tuning)


Quote
I am glad there are people like you to help out us dreamers. :)
Thanks  8)


Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 26, 2016, 07:50 pm
I will test everything again and do another ESC calibrate. Yes, you do see the Turbo on/off when you press button 2 on the data field 3 entry.  I will make another video and show you what it's doing.

FYI , I finally got my current sensor in from China. I got the 30 amp one (ACS712) off ebay because I plan on making a larger bot once I get my smaller one working correctly.

Thanks kas,

Justin
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 27, 2016, 08:22 am
Quote
FYI , I finally got my current sensor in from China. I got the 30 amp one (ACS712) off ebay because I plan on making a larger bot once I get my smaller one working correctly.
For an additional two bucks, you should also purchase the 5000mA sensor  ;)
Measuring 2 amps within a 30 amps range will result in poor accuracy/resolution and generate noisy readings

Do you require assistance for interfacing this second sensor ??

Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 27, 2016, 01:38 pm
For an additional two bucks, you should also purchase the 5000mA sensor  ;)
Measuring 2 amps within a 30 amps range will result in poor accuracy/resolution and generate noisy readings

Do you require assistance for interfacing this second sensor ??


It was only 1.98 shipped , I don't know how they offer them so cheap as shipping in the USA along would be more then that .

If you had time to help on the program that would be awesome. I am sorry I didn't know about the noise issue.

Will it show real time mAh use and go back to zero with no throttle input or will it count and store the mAhs that have been used ?
Thanks ,
Justin
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 28, 2016, 07:54 am
Quote
It was only 1.98 shipped , I don't know how they offer them so cheap as shipping in the USA along would be more then that .
Agreed  ::)


Quote
Measuring 2 amps within a 30 amps range will result in poor accuracy/resolution and generate noisy readings
The module can measure positive and negative Amps, so the range is actually 60 Amps
We will interface the 30 amps module, but please also purchase the 5 amp board

30 Amp boards have different mV/A analog output according to manufacturer,
please let me have a link to your specific item


Quote
Will it show real time mAh use and go back to zero with no throttle input or will it count and store the mAhs that have been used ?
It will show real time mA (milli Amps) and go back to zero
You can then set up an over current alarm cut off
Useful to detect stalling and avoid burning motors

You can access mAH (milli Amp.hour) by integrating mA over time
This will put additional load on the 328P processor
To follow battery level, most people just monitor mV


Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 28, 2016, 03:48 pm
I will purchase the 5 amp board but it will probably take another month to get here .

The board I got is

 http://pages.ebay.com/link/?nav=item.view&id=161942411886&alt=web

Thanks for the additional info , with the over current alarm I might have a 12 volt buzzer in the parts pin somewhere we can experiment with.

Thanks,

Justin
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 29, 2016, 11:16 am
Amp's monitoring

Connect AC714 current sensor as such, using A1 :

(http://i.imgur.com/LfEr1pF.png)

Quote
with the over current alarm I might have a 12 volt buzzer in the parts pin somewhere we can experiment with
For faster protection I suggest direct motors cut off by code rather than ringing a bell  ;)

Again, don't expect much from a 30A sensor


// V1.5:  added Amp's monitoring


Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 29, 2016, 02:31 pm
For faster protection I suggest direct motors cut off by code rather than ringing a bell  ;)

That sounds great, I will download and try the new code out tonight. So if motors stalled out at 10 amps would you have the code kill the motors if it seen 10 amps for X milliseconds?

Thanks!
Title: Re: Android Bluetooth joystick
Post by: kas on Feb 29, 2016, 05:58 pm
Quote
So if motors stalled out at 10 amps would you have the code kill the motors if it seen 10 amps for X milliseconds?
Yes, that's exactly the story
Try manually stalling the two motors and let me know the corresponding Amp value

Title: Re: Android Bluetooth joystick
Post by: fullspool on Feb 29, 2016, 08:36 pm
Yes, that's exactly the story
Try manually stalling the two motors and let me know the corresponding Amp value


I will get those values tonight hopefully, I have to do damage control as I hooked up the AMP meter as the diagram showed it blew up and caught fire haha  . I have to do damage control now but I don't think it ruined my uno or hc-05.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 01, 2016, 03:13 pm
I should have looked at the data sheet first , looks like it can only handle 5V and I put 12v to it . Oops
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 01, 2016, 03:21 pm
Quote
I should have looked at the data sheet first , looks like it can only handle 5V and I put 12v to it
That's too bad   :smiley-sad-blue:
Most sensors are 3.3V or 5V

Time to get the 5A item  ;)

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 01, 2016, 03:39 pm
That's too bad   :smiley-sad-blue:
Most sensors are 3.3V or 5V

Time to get the 5A item  ;)


My main source is 12v that supplies my motors , I ordered the 5 amp already but it still can not handle my supplied voltage.
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 01, 2016, 06:06 pm
Quote
My main source is 12v that supplies my motors , I ordered the 5 amp already but it still can not handle my supplied voltage.
::)  ::)  ::)
Why don't you get the 5V supply voltage from the Arduino board ??
12V on the "measuring side" is OK

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 01, 2016, 06:23 pm
::)  ::)  ::)
Why don't you get the 5V supply voltage from the Arduino board ??
12V on the "measuring side" is OK


That's how I had it hooked up and it smoked the chip . I didn't think the measuring side could handle 12v is why it blew ????

The led on the amp meter lite up just fine showing it had 5v and ground. I then plugged in the 12v battery to feed my esc and then smoke / fire started .

Title: Re: Android Bluetooth joystick
Post by: rakohr on Mar 01, 2016, 10:12 pm

can you told me which BT moduls are working. I have HM11 modules. They don´t will work.

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 02, 2016, 01:49 am
We use hc05.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 02, 2016, 03:49 am
Yes, that's exactly the story
Try manually stalling the two motors and let me know the corresponding Amp value


I stalled the motors and my fluke meter reads 23 amps.
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 02, 2016, 07:41 am
Quote
That's how I had it hooked up and it smoked the chip . I didn't think the measuring side could handle 12v is why it blew ????
The led on the amp meter lite up just fine showing it had 5v and ground. I then plugged in the 12v battery to feed my esc and then smoke / fire started .
The measuring side definitely can handdle 12V

Two possibilities:
 - wrong connection (parallel vs serie) on the measuring side       <---<<
 - deffective item


Quote
I stalled the motors and my fluke meter reads 23 amps.
The 30A gizmo may be a good option  ;)

Title: Re: Android Bluetooth joystick
Post by: kas on Mar 02, 2016, 07:52 am
Quote
can you told me which BT moduls are working. I have HM11 modules. They don´t will work.
HM-11 is a BLE (Low Energy) Bluetooth board, not compatible with Joystick BT Commander
as mentioned by fullspool, use an HC-05 (or HC-06) board
Very cheap on eBay

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 02, 2016, 05:26 pm
The measuring side definitely can handdle 12V

Two possibilities:
 - wrong connection (parallel vs serie) on the measuring side       <---<<
 - deffective item

The 30A gizmo may be a good option  ;)


I solder lead from negative plug from 12v battery to plug on amp meter and solder lead from positive plug from 12v battery to plug on amp meter . Or should I just tap in to positive side on battery and left negative alone ?
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 02, 2016, 05:39 pm
Quote
I solder lead from negative plug from 12v battery to plug on amp meter and solder lead from positive plug from 12v battery to plug on amp meter . Or should I just tap in to positive side on battery and left negative alone ?
:o  :o
It an Amp meter, not a Volt meter
Should be a serial connection with the load (motors ...)
Look again at message #605


Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 02, 2016, 06:17 pm
:o  :o
It an Amp meter, not a Volt meter
Should be a serial connection with the load (motors ...)
Look again at message #605



I guess I was confused since the diagram shows the negative wire from battery source going to the amp meters terminal.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 04, 2016, 04:51 am
Here is the video of the turbo button not working correctly.  I don't know how to fix it ?

https://youtu.be/j7t_jwKomcA
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 04, 2016, 09:28 am
Quote
Here is the video of the turbo button not working correctly.  I don't know how to fix it ?
Got it
Once again, I forgot that with ESC's, neutral position is myservo.write(90), not myservo.write(0)
Try this one   :-[

// V1.6  fixed Turbo

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 04, 2016, 02:23 pm
Got it
Once again, I forgot that, with ESC's, neutral position is myservo.write(90), not myservo.write(0)
Try this one   :-[

// V1.6  fixed Turbo


I loaded the code and soon as I added power the motors started wide open, I would have to pull the joy stick all the way back for them to stop, release the joy stick and it goes back to wide open. I didn't have time to calibrate the ESC this morning before work but I will do that tonight and report back as I am not sure if it's an ESC calibration problem now.

Thanks,
Justin
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 04, 2016, 05:50 pm
Quote
I didn't have time to calibrate the ESC this morning before work but I will do that tonight
Please describe calibration procedure or let me have a link to it

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 04, 2016, 05:56 pm
Please describe calibration procedure or let me have a link to it


Radio Calibration
Different radio systems have slightly different center points and travel ranges. To adjust
the Scorpion XL to your radio a jumper is located on the ENC header on the circuit board
to activate the radio calibration function. To calibrate the Scorpion XL to your radio
systems set all your trims to center and place a jumper on the two pins indicated in the
image above. The Status LED will blink rapidly during calibration. Move the radio
controls to their full extent several times. When finished center the controls and remove
the jumper. The Scorpion XL is now calibrated and the radio information stored in non-
volatile memory. You can verify proper calibration by observing the motor LEDs. Both
should be off with the controls centered. We recommend you disconnect any motors
from the Scorpion XL during calibration.

http://www.robotmarketplace.com/products/0-SCORP-XL.html
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 04, 2016, 08:25 pm
Quote
Move the radio controls to their full extent several times. When finished center the controls and remove the jumper.
To get full extent, make sure to enable Turbo mode before performing calibration
(Button #2 <ON>)

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 05, 2016, 01:42 am
To get full extent, make sure to enable Turbo mode before performing calibration
(Button #2 <ON>)


I tried re-calibrating and everything works until you hit the turbo button. When I go to accelerate to full stick movement the rover freaks out and then goes wide open forward then backwards when you have forward stick position.
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 05, 2016, 07:53 am
I suspect calibration was performed in Turbo 0FF mode

1) With Turbo enabled, if you just move joystick North/South, only within the -50/+50 range
    Does it get crazy ??


2) As a test, try changing
    case 'C':
      buttonStatus |= B000010;        // ON
      turbo = 1;
to:
    case 'C':
      buttonStatus |= B000010;        // ON
      turbo = 4;

Hitting button #2 will actually slow down bot

Let me know the outcome


Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 05, 2016, 02:40 pm
The calibration was actually done with it on and with turbo button off as I tried every combination I could think of.  I still didn't get the result we were looking for . Let me make the changes to the code , thanks kas your intellect is mind blowing.
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 10, 2016, 05:32 pm
Rather than using....

  joyX = joyX/turbo;                                                  // turbo (button #2)
  joyY = joyY/turbo;



Would it not be better to redefine the map and constrain depending on wether Turbo mode is ON/OFF?

Perhaps something like this ....

if(joyY >-10)  {                                                    // differential steering
    servo_L = (joyY - (3*joyX)/4);
    servo_R = (joyY + (3*joyX)/4);
  }
  else
  {
    servo_L = (joyY + (3*joyX)/4);
    servo_R = (joyY - (3*joyX)/4);
  }
  if ( turbo == 1 ) { // FULL SPEED
  servo_L = map(servo_L, -100, 100, 0, 180);   //         << adjust to change motor direction
  servo_R = map(servo_R, -100, 100, 0, 180);
  servo_L = constrain(servo_L, 0, 180);
  servo_R = constrain(servo_R, 0, 180);
  }
  else // HALF SPEED
  { 
  servo_L = map(servo_L, -100, 100, 45, 135);   //         << adjust to change motor direction
  servo_R = map(servo_R, -100, 100, 45, 135);
  servo_L = constrain(servo_L, 45, 135);
  servo_R = constrain(servo_R, 45, 135);
}
}
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 10, 2016, 09:23 pm
Quote
Would it not be better to redefine the map and constrain depending on wether Turbo mode is ON/OFF?
Hi Woody   ;)

This code implementation should deliver identical values
Did I miss something ??



@fullspool
Did you try changing the code as per my last message ??

Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 10, 2016, 10:59 pm
Hi Kas,

I'm unsure if anything is wrong with your code ... dividing the X,Y values by 2 ...making them -50 /50 rather than -100/100 should work and give the same results as my rather longer method .

I'd need to program an Arduino and monitor the outputs to be sure.
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 12, 2016, 11:54 am
Well I've programmed and run both versions ... no appreciable difference other than the Turbo OFF values for servo L/R mix @ 100 / 100 +-  are  101/168 for Kas's version and 101/135 for mine ... and no out of range / weird numbers for the servo values.

I altered the code so that the servo values would display on the phone.

Code: [Select]
mySerial.print((char)STX);                                             // Start of Transmission
    mySerial.print(getButtonStatusString());  mySerial.print((char)0x1);     // buttons status feedback
    mySerial.print(servo_R);               mySerial.print((char)0x4);     // datafield #1 = battery level
    mySerial.print(servo_L);                 mySerial.print((char)0x5);     // datafield #2 = milli Amps
    mySerial.print(displayStatus);                                         // datafield #3 = status display
    mySerial.print((char)ETX);                                             // End of Transmission
  }
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 12, 2016, 09:06 pm
Thanks for the test,
obviously the variation is coming from the differential steering calculation

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 15, 2016, 01:24 am
@fullspool
Did you try changing the code as per my last message ??


I haven't had any success with the turbo button working correctly, when I change the values to 4 and re-calibrate the ESC the bot still freaks out when I try to use the turbo function. The video is uploading on youtube. It reflects the unmodified 1.6 code.

The problem is when it reads (0,82ish) it goes from forward to reverse.

On a side note, I got the AMP installed and working. Is there a way for it to read and transfer the data? It seems to lag a bit.

edit: video link
https://www.youtube.com/watch?v=aRiParYii1o&feature=em-upload_owner
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 15, 2016, 10:27 am
Quote
The problem is when it reads (0,82ish) it goes from forward to reverse
Same effect with (0,-82) ??


Quote
On a side note, I got the AMP installed and working. Is there a way for it to read and transfer the data? It seems to lag a bit.
V1.6 send Amp values every 750ms
To make it faster replace
 long sendInterval = 750;                            // interval between Buttons status transmission (milliseconds)
with
  long sendInterval = 500;                            // interval between Buttons status transmission (milliseconds)



EDIT:
Quote
when I change the values to 4 and re-calibrate the ESC the bot still freaks out when I try to use the turbo function
With turbo = 4, Button #2 <ON> is now a low speed mode
ESC should be calibrated with Button #2 OFF
(calibration using fastest position)
Please confirm

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 15, 2016, 01:16 pm
Same effect with (0,-82) ??
from 0,-82ish is the bot functions correctly, it's whenever the stick is pushed further forward
the bot will jerk and go into the reverse. If you watch the ESC in the video you can see a green led light
indicating forward position then when it goes past the -82ish mark it jumps straight in to reverse and you
see the red led light on the esc.


V1.6 send Amp values every 750ms
To make it faster replace
 long sendInterval = 750;                            // interval between Buttons status transmission (milliseconds)
with
  long sendInterval = 500;                            // interval between Buttons status transmission (milliseconds)
Thank you so much, I will try this.

EDIT:With turbo = 4, Button #2 <ON> is now a low speed mode
ESC should be calibrated with Button #2 OFF
(calibration using fastest position)
Please confirm

I've tried this and the bot moves slowly forward and backwards (with button 2 off and  ALOT slower with button 2 on) and then jumps forward to reverse when you put the joy stick in each of the quadrants.

Thanks,
Justin
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 15, 2016, 08:49 pm
I've looked back up the the thread and noticed that your using a Scorpion XL .
http://www.robotpower.com/downloads/RobotPower_Scorpion_XL_quickstart.pdf  (http://www.robotpower.com/downloads/RobotPower_Scorpion_XL_quickstart.pdf)

I'm assuming that you have the jumpers set on option 4 = TANK steering and NOT option 1 = MIX?
You'd get some weird things happening with 2 mixes!

I would however think that it would be much easier to allow the Scorpion to mix the signal and do away with the mix algo in the Arduino program.



Note that TURBO MODE is simply FULL SPEED whilst NO TURBO is 1/2 speed.

Title: Re: Android Bluetooth joystick
Post by: albertak on Mar 16, 2016, 01:54 am
thanks guys<a onclick="_gaq.push(['_trackEvent', 'Outgoing', '.', '']);" rel="nofollow" href="http://golkala.com" target="_blank">http://golkala.com</a>i used the informations
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 17, 2016, 01:32 pm
I've looked back up the the thread and noticed that your using a Scorpion XL .
http://www.robotpower.com/downloads/RobotPower_Scorpion_XL_quickstart.pdf  (http://www.robotpower.com/downloads/RobotPower_Scorpion_XL_quickstart.pdf)

I'm assuming that you have the jumpers set on option 4 = TANK steering and NOT option 1 = MIX?
You'd get some weird things happening with 2 mixes!

I would however think that it would be much easier to allow the Scorpion to mix the signal and do away with the mix algo in the Arduino program.



Note that TURBO MODE is simply FULL SPEED whilst NO TURBO is 1/2 speed.


Yes sir, my jumpers are configured in the option 4 for tank mode as I haven't changed the jumpers since we started this project. I am going to revert to a previous program that didn't have the turbo function to try and see if everything still works as it should.
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 17, 2016, 04:15 pm
Quote
I am going to revert to a previous program that didn't have the turbo function to try and see if everything still works as it should
Test this one
// V1.6A Test, no turbo

Output:
-100  0  +100    >>>   0  90  180

EDIT:    Datafields #1 & #2  will display servo_L  &  servo_R values

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 18, 2016, 03:22 am
I tried that code and it produced same results. Something has went wrong after version 1.3 as I uploaded this code attached and re-calibrated my ESC and everything wrong perfectly however it does not have the amp monitoring feature or turbo.

Thanks,
Justin
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 18, 2016, 04:03 am
On a side note I built a larger radio control bot with sabertooth 2x60  and it works perfect with traditional radio control but I tried to hook the uno,  hc05,  and Bluetooth app and I only get forward movement  ???

Here it is under radio control guidance,  it's alot of fun .

http://youtu.be/gKVBrUyCepA
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 18, 2016, 10:26 am
@Kas ..some thoughts.

I think that 0-180 is simply out of the normal radio control pulse range ..
Quote
The pulse nominally ranges from 1.0 ms to 2.0 ms with 1.5 ms always being center off
.. however...
Quote
The servo.cpp library contains the "default" us values as "default min is 544, max is 2400" .
.
As coded the NO Turbo function ( 1/2 write range value ) will be in range ....but out of range in TURBO .



So I think that rather than servo.write ( angle )  the code should use servo.writeMicroseconds(xxxx)....or reduce the angle range from 0-180 to 30-150.

Edit :- The stand alone servo which has a normal swing angle of 120 degrees seems to happily accept this extended range...but the Scorpion XL controller probably has a set acceptable range of 0.74ms to 2.24ms .

The value of 0.74ms to 2.24ms was gleaned from the web as the min/max  range limit for a Spektrum Transmitter/Receiver.
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 18, 2016, 11:38 am
Quote
I think that 0-180 is simply out of the normal radio control pulse range
 ..As coded the NO Turbo function ( 1/2 write value ) will be in range ....but out of range in TURBO .
Good point  :)


EDIT
Quote
Something has went wrong after version 1.3
V1.3:  (shouldn't work... but it does  :o )     EDIT2  ** see below **
 myservoX.write(servo_L/turbo);
 myservoY.write(servo_R/turbo);

V1.6:  (doesn't work... but it should   :smiley-evil: )
 joyX = joyX/turbo;
 joyY = joyY/turbo;


@fullspool,
please reload V1.6A,
calibrate,
test range by moving Joystick only North/South
let us know the exact normal working range (Datafields display)

Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 18, 2016, 12:23 pm
Probably not relevant ..but
v1.3 say's

Quote
void motorsControl()  {
  myservoX.write(servo_L/2);
  myservoY.write(servo_R/2);
NOT

Quote
myservoX.write(servo_L/turbo);
  myservoY.write(servo_R/turbo);
This would 1/2 the X, Y mix value or would the code 1/2 the 0-90-180 values ?
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 18, 2016, 01:11 pm
Probably not relevant ..but
v1.3 say's

❝void motorsControl()  {
  myservoX.write(servo_L/2);
  myservoY.write(servo_R/2);
NOT
❝myservoX.write(servo_L/turbo);
  myservoY.write(servo_R/turbo);

This would 1/2 the X, Y mix value ?
Sorry, I was comparing with V1.4 :-*

So, the asumption is definitely that the Scorpion ESC doesn't accept the full 0 - 180° range
Let's wait for fullspool results

We WILL make it out  ;)



Title: Re: Android Bluetooth joystick
Post by: kas on Mar 18, 2016, 01:26 pm
@woodygb

❝void motorsControl()  {
    myservoX.write(servo_L/2);
    myservoY.write(servo_R/2);

was wrong coding
When joystick is iddle
  joyX = joyY = 0
  servo_L = servo_R = 90

Sent command is
  myservoX.write(45);
  myservoY.write(45);
Which is 'backward'  NOT  'stop'
This was probably corrected by calibrating the ESC

I did address this bug in V1.4

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 18, 2016, 01:34 pm
EDIT
V1.3:  (shouldn't work... but it does  :o )     EDIT2  ** see below **
 myservoX.write(servo_L/turbo);
 myservoY.write(servo_R/turbo);

V1.6:  (doesn't work... but it should   :smiley-evil: )
 joyX = joyX/turbo;
 joyY = joyY/turbo;


@fullspool,
please reload V1.6A,
calibrate,
test range by moving Joystick only North/South
let us know the exact normal working range (Datafields display)

I uploaded the code again and it produced same results, the bot went into full reverse around the 162ish mark in the data fields. Uploaded v1.3, re-calibrated and it worked perfect, LOL im confused.

Thanks for the help guys, I really appreciate it.

Video:
https://youtu.be/7XDa-ClUwrI
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 18, 2016, 02:05 pm
Quote
the bot went into full reverse around the 162ish mark in the data fields
This one should be OK   ;)


// V1.6B Test, MAX_ANGLE output limit (no turbo)

Please calibrate after loading

EDIT: should work for forward motion, not backward (yet)
EDIT2: modified (forward + backward motion)
Let me know


Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 18, 2016, 02:23 pm
@Kas .

That code may well be a work around to THIS controllers problem but I doubt that it will apply to other makes/models of R/C motor controllers.

Why not just follow standard R/C signal range protocol and restrict the angle and thus the ms value ?



  joyX = joyX/turbo;                                                  // turbo (button #2)
  joyY = joyY/turbo;

  if(joyY >-10))  {  // divide minus 10 by turbo?        // differential steering
    servo_L = (joyY - (3*joyX)/4);
    servo_R = (joyY + (3*joyX)/4);
  }  else  {
    servo_L = (joyY + (3*joyX)/4);
    servo_R = (joyY - (3*joyX)/4);
  }
 
  servo_L = map(servo_L, -100, 100, 30, 150);   //         << adjust to change motor direction
  servo_R = map(servo_R, -100, 100, 30, 150);
  servo_L = constrain(servo_L, 30, 150);
  servo_R = constrain(servo_R, 30, 150);

Title: Re: Android Bluetooth joystick
Post by: kas on Mar 18, 2016, 02:58 pm
Quote
That code may well be a work around to THIS controllers problem but I doubt that it will apply to other makes/models of R/C motor controllers
Fixed values would restrict range for 0/180 servo's and possibly some calibration-less drivers

    #define    LIMIT_ANGLE    20                            // Max range, adjust to your specific controller/servo

is easy to adjust value for a specific device
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 18, 2016, 07:27 pm
This one should be OK   ;)


// V1.6B Test, MAX_ANGLE output limit (no turbo)

Please calibrate after loading

EDIT: should work for forward motion, not backward (yet)
EDIT2: modified (forward + backward motion)
Let me know



I tested this code and it works just like v1.3 did with out any issues. I suppose this ESC doesn't like ranges past 160?
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 18, 2016, 09:18 pm
This post is only to give my view point.

Web quote..

Quote
The pulse itself most often ranges from 1 ms to 2 ms, with ~1.5 ms being the neutral position.  For servos with larger ranges, you might see pulses between 0.5 and 2.5 ms (neutral will still be around 1.5 ms).
https://github.com/esp8266/Arduino/blob/master/libraries/Servo/src/Servo.h

The Arduino servo angle  0-90-180 equates to 544- ( 1500 ) -2400ms signal range which is a 900 ish swing.

A 1100 - ( 1500 ) - 1900ms signal range ...  a 400 swing ... is the "Norm" for  many R/C Transmitter /Receiver combos including those owned by me.
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 18, 2016, 10:50 pm
Quote
I tested this code and it works just like v1.3 did with out any issues.
Finally   ;D  ;D  ;D


Quote
I suppose this ESC doesn't like ranges past 160?
Yes, thanks woodygb for this bright idea


// V1.7  added adjustable output limit   (with turbo enabled)

EDIT: Calibration should be made in turbo mode (Button #2 <ON>)


Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 19, 2016, 04:03 am
Great news , the bot preform perfectly! I do have a question though, how do I get the voltage and Amp display back in the data fields?

Thanks for your guys hard work!

Justin
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 19, 2016, 07:23 am
Quote
I do have a question though, how do I get the voltage and Amp display back in the data fields?
Just change
//    Serial.print(voltage, 2);               Serial.print((char)0x4);         // datafield #1 = battery level
//    Serial.print(milliAmp);                 Serial.print((char)0x5);         // datafield #2 = milli Amps
        Serial.print(servo_L);                  Serial.print((char)0x4);
        Serial.print(servo_R);                  Serial.print((char)0x5);

to
        Serial.print(voltage, 2);                Serial.print((char)0x4);         // datafield #1 = battery level
        Serial.print(milliAmp);                  Serial.print((char)0x5);         // datafield #2 = milli Amps
//    Serial.print(servo_L);                   Serial.print((char)0x4);
//    Serial.print(servo_R);                   Serial.print((char)0x5);

fullspool, I think it's now time to carefully read and understand the code  ::)


Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 20, 2016, 02:59 am
fullspool, I think it's now time to carefully read and understand the code  ::)

Thank you for all your help , I am doing my best to understand it but it's more advanced then I am at this point . I've read the code multiple times and picking up on a few things.

FYI I put a couple batteries through the bot and it's performing awesome.
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 20, 2016, 07:13 am
Quote
FYI I put a couple batteries through the bot and it's performing awesome.
8)


Quote
I am doing my best to understand it but it's more advanced then I am at this point . I've read the code multiple times and picking up on a few things.
My personal advice: don't cut corners, we all started by blinking a led and replicating the sketch examples   ;)


Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 20, 2016, 02:38 pm
8)

My personal advice: don't cut corners, we all started by blinking a led and replicating the sketch examples   ;)

100% agree ,I bought another uno to experiment with, I didn't want to take a chance of ruining the progress we've made thus far .

I am going to try the v1.7 code on a sabertooth esc today to see if the ranges are similar to the scrop XL.
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 20, 2016, 10:06 pm
IF you get probs with the Sabretooth I'd suggests going with...

Quote
#define    LIMIT_ANGLE    40                           // Max range, adjust to your specific controller/servo
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 20, 2016, 11:08 pm
IF you get probs with the Sabretooth I'd suggests going with...

I just tested it and was going to make this change . I am glad you confirmed my findings as in turbo mode in full stick movement in the reverse position it acts similar to what the XL did but in full forward position it's fine ???
What is also puzzling the differential steering doesnt work but does fine with traditional rc ?

Here is a video with code v1.7.

https://youtu.be/DWe2SYxBIic
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 21, 2016, 03:02 am
Switch 4 DOWN and 6 UP appears... I think .. to be the correct setting for use with the Arduino prog v1.7
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 21, 2016, 03:15 am
Switch 4 DOWN and 6 UP appears... I think .. to be the correct setting for use with the Arduino prog v1.7
I did this and it appears to work right for one motor only . The other motor doesn't turn .

I have 1 down , 2 up , 3 up , 4 down , 5 down , 6 up.
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 21, 2016, 09:48 am
Which Sabretooth model do you have?

https://www.dimensionengineering.com/datasheets/Sabertooth2X25QuickStart.pdf

Quote
Microcontroller pulses, independent
linear control: An R/C servo signal is
connected to terminals S1 and S2. A
1000us - 2000us pulse controls speed
and direction. 1500us is stop.
That appears to be 2,3 and 5 ON

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 21, 2016, 12:52 pm
Which Sabretooth model do you have?

https://www.dimensionengineering.com/datasheets/Sabertooth2X25QuickStart.pdf

That appears to be 2,3 and 5 ON


I have the sabertooth 2x60 , I will try that combination. I ran through the wizard settings and either 1 side would work correctly or but wheels would turn like in the video I posted. I will try this again on lunch break.

Thanks,
Justin
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 21, 2016, 03:15 pm
Wasn't entirely sure which model ...Try 1 down , 2 down , 3 down , 4 down , 5 down , 6 up.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 21, 2016, 06:15 pm
It does nothing on these settings .
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 22, 2016, 04:42 am
I tried several other dip options and neither were successful.  I emailed dim. Eng. To see If they had any suggestions.  It's either turning the starboard side correctly and port side doing nothing or both port and starboard side turn identical. 

@kas do you have any idea why the sabertooth is performing this way?
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 23, 2016, 09:38 am
Fullspool....Do you have R/C gear...If so ...I'd use it to check that both channels of the Sabretooth actually work.

I say this because your description of the Sabretooth's behavior seems to point towards a dead channel input.
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 23, 2016, 11:28 am
Quote
@kas do you have any idea why the sabertooth is performing this way?
Not really  ::)
Let's wait for dimension engineering response


@woodygb
Allthough we could switch Sabertooth to Analog control mode, use two Arduino PWM outputs and filter to get a true 0-5v continuous voltage,
I do consider this solution as subpar


Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 23, 2016, 12:34 pm
Fullspool....Do you have R/C gear...If so ...I'd use it to check that both channels of the Sabretooth actually work.

I say this because your description of the Sabretooth's behavior seems to point towards a dead channel input.
It works perfect on traditional rc gear, thats the confusing part. https://youtu.be/gKVBrUyCepA

Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 23, 2016, 01:29 pm
I'd suggest getting the dip switch settings correct for non mixed tank steering with the R/C gear.

Then altering the Arduino program to have the LIMIT_ANGLE =50 so that the Arduino's signal output matches that of a std R/C setup.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 23, 2016, 08:32 pm
Not really  ::)
Let's wait for dimension engineering response





This is what they said :


So this uses Arduino's servo library. You likely won't need our libraries. You will set Sabertooth DIPs to RC/microcontroller mode, and connect signals to S1/S2. I'm not sure if everything will run smooth as is- you may have to do some tweaking. I can tell you the Sabertooth tends to works best in this mode using a servo range of 40-140, with 90 being "stop."
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 23, 2016, 08:56 pm
Use LIMIT_ANGLE =50  as per woodygb advice

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 24, 2016, 04:16 am
Use LIMIT_ANGLE =50  as per woodygb advice


I've already did this yesterday and nothing new happened.

Edit :

I do have an update though and finally getting some where . I reset the board,  loaded 1.7 code with limit at 50 , check all connections and now it's kinda working .

Here is what's happening :

1 off, 2 and 3 on, 4 off, 5 on, 6 off
Motors are slowly turning at idle and stick movement is 90 degrees off. So if i turn the phone portrait I can move forward and backward correctly but left and right are backwards .

Title: Re: Android Bluetooth joystick
Post by: kas on Mar 24, 2016, 06:51 am
Quote
stick movement is 90 degrees off
swap pinServo_X  (D9)  and  pinServo_Y  (D10)  wires


Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 24, 2016, 09:46 am
Quote
1 off, 2 and 3 on, 4 off, 5 on, 6 off
Motors are slowly turning at idle and stick movement is 90 degrees off
The Arduino servo library is NOT an exact match for the R/C signal format ....SERVO 90 or OFF/Neutral/Idle is actually equiv to a signal value of 1471 rather than the standard neutral value of 1500 ...hence your getting the motors slowly turning.

Solution ... Turn ON Autocalibrate.

EDIT ...Or I suppose that you could redefine neutral in the Arduino prog as a servo value of 92.8.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 24, 2016, 01:28 pm
swap pinServo_X  (D9)  and  pinServo_Y  (D10)  wires



I tried this but it just rotated the stick movement another 90 degrees so left and right movements caused it to go forwards and backwards so I put it back to how I had it .

If I put the DIP to 1 down and the other 5 up my wheels don't turn at center stick movement but the sticks are 45 degrees off and left / right are mirrored again .

Thanks guys ,
Justin
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 24, 2016, 01:47 pm
The Arduino servo library is NOT an exact match for the R/C signal format ....SERVO 90 or OFF/Neutral/Idle is actually equiv to a signal value of 1471 rather than the standard neutral value of 1500 ...hence your getting the motors slowly turning.

Solution ... Turn ON Autocalibrate.

EDIT ...Or I suppose that you could redefine neutral in the Arduino prog as a servo value of 92.8.
Thank you for the suggestions, I will try this . Where did you get the value of 92.8 ?

Here is a video

https://youtu.be/UtN7EWkzLMs
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 24, 2016, 02:03 pm
Try inverting one motor power supply polarity

Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 24, 2016, 03:31 pm
Thank you for the suggestions, I will try this . Where did you get the value of 92.8 ?


Ummm lets check.

Quote
The servo.cpp library contains the "default" us values as "default min is 544, max is 2400" .
..so

The range of 544 to 2400 is  0  to 180 in the servo library  a bit of math gives us the single unit signal value of 10.31.

(90*10.31)+544 = 1471.9 a difference of  28.1 to the 1500 norm.

so we need 28.1/10.31= 2.72 more than servo 90  that would make 1500 neutral = servo 92.72  .

I think .......

Here's a link to much the same conclusion about the servo 90 value it includes a solution.
http://makezine.com/2014/04/23/arduinos-servo-library-angles-microseconds-and-optional-command-parameters/ (http://makezine.com/2014/04/23/arduinos-servo-library-angles-microseconds-and-optional-command-parameters/)


@Kas ...It would seem that the approach to use is to define the servo attach range... eg.

Quote
myservoA.attach(pinServo_A, 1000, 2000); 
  myservoX.attach(pinServo_X, 1000, 2000); 
  myservoY.attach(pinServo_Y);
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 24, 2016, 04:04 pm
Quote
Here's a link to much the same conclusion about the servo 90 value.
http://makezine.com/2014/04/23/arduinos-servo-library-angles-microseconds-and-optional-command-parameters/
Interesting readings
Based on this document, do you suggest to replace

  myservoX.attach(pinServo_X); 
  myservoY.attach(pinServo_Y);
 
by

  myservoX.attach(pinServo_X, 1000, 2000); 
  myservoY.attach(pinServo_Y, 1000, 2000); 


Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 24, 2016, 04:06 pm
Kas ..you posted whilst I was editing!!! :)

Yes ...I think it would be best to make the range match standard R/C protocol.

So the changes would be ...

Quote
myservoX.attach(pinServo_X, 1000, 2000); 
  myservoY.attach(pinServo_Y, 1000, 2000); 
and


 
Quote
servo_L = map(servo_L, -100, 100, 1000, 2000);   //         << adjust to change motor direction
  servo_R = map(servo_R, -100, 100, 1000, 2000);
  servo_L = constrain(servo_L, 1000, 2000);
  servo_R = constrain(servo_R, 1000, 2000);
Yes?
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 24, 2016, 05:00 pm
Quote
So the changes would be ...

❝myservoX.attach(pinServo_X, 1000, 2000); 
  myservoY.attach(pinServo_Y, 1000, 2000); 
Yes


Quote
and

 ❝servo_L = map(servo_L, -100, 100, 1000, 2000);   //         << adjust to change motor direction
  servo_R = map(servo_R, -100, 100, 1000, 2000);
  servo_L = constrain(servo_L, 1000, 2000);
  servo_R = constrain(servo_R, 1000, 2000);

Yes?
No
The remaining code still "speaks" degrees   ;)

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 25, 2016, 12:58 am
Ummm lets check.
..so

The range of 544 to 2400 is  0  to 180 in the servo library  a bit of math gives us the single unit signal value of 10.31.

(90*10.31)+544 = 1471.9 a difference of  28.1 to the 1500 norm.

so we need 28.1/10.31= 2.72 more than servo 90  that would make 1500 neutral = servo 92.72  .

I think .......

Here's a link to much the same conclusion about the servo 90 value it includes a solution.
http://makezine.com/2014/04/23/arduinos-servo-library-angles-microseconds-and-optional-command-parameters/ (http://makezine.com/2014/04/23/arduinos-servo-library-angles-microseconds-and-optional-command-parameters/)


@Kas ...It would seem that the approach to use is to define the servo attach range... eg.

Ahhh gotcha thank you for taking the time to explain it to me, I just read that blog. I am going to have to read it 5-6 more times for it to fully sink in . I still need to test this and see if it works, I would just have to change :

int servo_L, servo_R = 90;                              // servo's positioning values

to

int servo_L, servo_R = 92.72;                              // servo's positioning values

Is this correct?


@kas I changed the polarity of one motor and its working perfect now. Thank you for the suggestion.

I also adjusted to code to read :

  myservoX.attach(pinServo_X, 1000, 2000); 
  myservoY.attach(pinServo_Y, 1000, 2000); 

It fixed my motors from turning at center stick position however my top speed of the wheel chair is down
drastically compared to before. So It might be best to remove this range and adjust the servo position?


Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 25, 2016, 01:37 am
 
Quote
myservoX.attach(pinServo_X, 1000, 2000); // R/C norm range 
  myservoY.attach(pinServo_Y, 1000, 2000);  
Using the above code solves the problem of the slightly off neutral value of 1472 ... as 1500 is now slap in the middle...half way between 1000 and 2000. .. and 90 degrees is also halfway between 0 and 180 degrees.

So ...
Quote
int servo_L, servo_R = 90;
can stay as it is.

The code mod also does away with the need for the LIMIT_ANGLE as you have defined the range and in doing so have set a NEW number for the servo angle values.

Thus ...
servo_R/L @ 0=1000 , servo_R/L @ 90 = 1500  &  servo_R/L @ 180 = 2000 which matches R/C norm.

This means that can now use the original code.


Quote
servo_L = map(servo_L, -100, 100, 0, 180);   //         << adjust to change motor direction
  servo_R = map(servo_R, -100, 100, 0, 180);
  servo_L = constrain(servo_L, 0, 180);
  servo_R = constrain(servo_R, 0, 180);
I hope that makes sense.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 25, 2016, 03:24 am
Using the above code solves the problem of the slightly off neutral value of 1472 ... as 1500 is now slap in the middle...half way between 1000 and 2000. .. and 90 degrees is also halfway between 0 and 180 degrees.

So ... can stay as it is.

The code mod also does away with the need for the LIMIT_ANGLE as you have defined the range and in doing so have set a NEW number for the servo angle values.

Thus ...
servo_R/L @ 0=1000 , servo_R/L @ 90 = 1500  &  servo_R/L @ 180 = 2000 which matches R/C norm.

This means that can now use the original code.


I hope that makes sense.
I tried making these changes using the same DIP settings and BOT just freaks out, motors start turning, stopping, slowly turning, then back wide open, pauses for a minute and repeats LOL

I tried to revert back to my old code that was working now it's acting silly and unstable, I am really confused now as it worked fine but top speed was alot slower .

I thought maybe I screwed up my sabertooth so I hooked it back up to my radio control and everything worked perfect. I thought I was really making progress now I just screwed it up.

Here was a video from earlier, don't know why it doesn't work now.  :(

https://youtu.be/K78tliDVAWs

I attached the last working code, even though it doesnt work now??
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 25, 2016, 12:17 pm
Have you perhaps still got the Sabertooth in mix mode?

The SLOW problem that you previously encountered was simply the result of the change to myservo.
 
Quote
myservoX.attach(pinServo_X, 1000, 2000); 
  myservoY.attach(pinServo_Y, 1000, 2000);
and retaining 
Quote
#define    LIMIT_ANGLE    50                            // Max range
Making it ZERO would have given back the full speed range.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 25, 2016, 01:11 pm
Have you perhaps still got the Sabertooth in mix mode?

The SLOW problem that you previously encountered was simply the result of the change to myservo.
   


and retaining   


Making it ZERO would have given back the full speed range.
I was using 1 off, 2/3  on, 4 off, 5 on, 6 off >????
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 25, 2016, 02:08 pm
I checked your V1.8, it should work as before  ::)

- double check bot for wrong or loose connections
- make sure all grounds are connected
- disconnect battery(ies) for 5 minutes and try again


Quote
I was using 1 off, 2/3  on, 4 off, 5 on, 6 off
What is the purpose of switch 3 ??
If not used, keep it OFF just in case


EDIT
from your message #677:
Quote
Edit :
I do have an update though and finally getting some where . I reset the board,  loaded 1.7 code with limit at 50 , check all connections and now it's kinda working .
What was the problem at that time ??


Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 25, 2016, 03:22 pm
To muddy the waters even more ...
You tried at least once with dip switch 6 ON.
Which should have been ..... according to the instruction pdf ...Autocalibration mode.
I wonder if the Sabertooth did actually Autocalibrate and if it has possibly RETAINED the now erroneous  setting ?
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 26, 2016, 04:42 am
Woody and kas first off I want to apologize for the time you guys wasted to help me chase a problem that didn't need to exist .  Somehow I manage to place a lead from  the 5V pin from uno into my breadboard positive bus bar . I suppose the 5V from uno and the 6v battery both being tied into the positive bus bar was causing my hc05 to freak out ?

@Woody,  I set the limit angle to 0 and now I have full range and with the wiring correction it's working great .

@kas do you have a suggestion for amp sensor for these wheel chair motors ?
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 26, 2016, 07:55 am
Quote
Somehow I manage to place a lead from  the 5V pin from uno into my breadboard positive bus bar . I suppose the 5V from uno and the 6v battery both being tied into the positive bus bar was causing my hc05 to freak out ?
:o  :o
Happy guy, you didn't fry your BT card



Quote
@kas do you have a suggestion for amp sensor for these wheel chair motors ?
It's now time for you to describe your electrical setup, a drawing or a photo will help.
Woody is the expert for wheel chairs, most of them appear to be powered by two 12Volts batteries, please confirm

Remember you don't need a specific battery for the Arduino supply, as it can be powered from 12 volts  (NOT 24V  :smiley-evil: ).

Any need for battery Voltage monitoring ??


Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 26, 2016, 10:14 am
Wheelchairs are indeed 24v .

I use these sensors on my Robot Wars bot and use them in conjunction with a Roboteq and some script.
https://www.facebook.com/TeamKaPow/ (https://www.facebook.com/TeamKaPow/)

(http://i232.photobucket.com/albums/ee47/mickey231bhq/eBay_Temp/hcsm_diag_zpscb80447a.jpg)

http://www.ebay.co.uk/itm/111689533182?_trksid=p2060353.m1438.l2649&var=410695568918&ssPageName=STRK%3AMEBIDX%3AIT (http://www.ebay.co.uk/itm/111689533182?_trksid=p2060353.m1438.l2649&var=410695568918&ssPageName=STRK%3AMEBIDX%3AIT)

Pick the 100 amp bi-directional.

NOTE:- The analog voltage output from the sensor is a nice 0-5v and a standard R/C servo plug fits straight on the pins ... the Arduino headers will solder on directly ...  BUT the POS & NEG pins of the sensors are reversed compared to a Futaba R/C servo plug so you'll need to lift the tags and swap wires to get a colour polarity match.

(http://www.helifreak.com/attachment.php?attachmentid=571027&d=1424530129).
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 26, 2016, 01:44 pm
:o  :o
Happy guy, you didn't fry your BT card


It's now time for you to describe your electrical setup, a drawing or a photo will help.
Woody is the expert for wheel chairs, most of them appear to be powered by two 12Volts batteries, please confirm

Remember you don't need a specific battery for the Arduino supply, as it can be powered from 12 volts  (NOT 24V  :smiley-evil: ).

Any need for battery Voltage monitoring ??



Yes it is a 24 v system ,  I am power over a 6v battery for simply sake for now as I have everything mounted to a tray so it makes it easier to run back and forth from the garage to the computer . The sabertooth also has a BEC but I haven't used it yet .

The larger bot will need voltage monitoring and amps,  I am building this one as a TUG so it can help me move things around the house easier.

Will a simply voltage divider work like on the smaller BOT ?

@woody , thank you for the link . I will order that now.  Do you have a gear reduction drive on your BOTS?

Thanks guys
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 26, 2016, 08:14 pm
Quote
Will a simply voltage divider work like on the smaller BOT ?
Yes, let me have a proposal for the resistors values and the checkBat() formula   ;)

Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 26, 2016, 09:50 pm
The bot has a single stage gear reduction of 6-1 ...the most that can be obtained in one stage...two stages would be better to give 15 or 20-1 ratio....but I haven't got the space with this design.

I'd not use the built in BEC  .... instead I recommend a UBEC or SBEC.

E.G.

http://www.ebay.co.uk/itm/Turnigy-5A-8-40v-switching-BEC-SBEC-UBEC-Plane-Heli-UK-Seller-Fast-Dispatch-/131194157989?hash=item1e8bc7fba5:g:0AMAAOxyOlhS-7Ri (http://www.ebay.co.uk/itm/Turnigy-5A-8-40v-switching-BEC-SBEC-UBEC-Plane-Heli-UK-Seller-Fast-Dispatch-/131194157989?hash=item1e8bc7fba5:g:0AMAAOxyOlhS-7Ri)
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 27, 2016, 06:42 am
That is awesome , I am trying to source a good 20mm sprocket for the jack shaft . I was thinking about going 6 to 1 when I build my new frame . Have you measured the pulling force of your bot at 6 to 1 ?  How bad did your top speed suffer ?

I used the BEC on the sabertooth and it worked awesome on the radio control gear but on the uno the starboard wheel spins for 1 second then stops and when bluetooth connects it works.  So I need to figure out away to fix that issue or power the uno first then power the motors .
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 27, 2016, 12:15 pm
Quote
I am trying to source a good 20mm sprocket for the jack shaft . I was thinking about going 6 to 1 when I build my new frame . Have you measured the pulling force of your bot at 6 to 1 ?  How bad did your top speed suffer ?
I have in the distant past attempted to measure the pulling force ..but the math approach gives good approx results.

Note that getting an exact answer to your needs requires a fair bit of math and much more info on your setup....e.g.  motor specs .

MUCH SIMPLIFIED EXAMPLE.

Pulling power.

MASS in Kg's bearing down on each drive wheel x the Friction Coefficient of the tire.

On asphalt you get a Friction Coefficient of around 0.9 .

So ignoring other factors like rolling resistance etc ....50kg mass bearing down on each wheel  50 x 0.9 x 2 drive wheels.

A possible 90 kg of pulling force before breaking traction...assuming that your drive setup can supply sufficient torque & determining that requires motor and controller specs plus more math.

MASS that you could pull.

If your loading a trolley or trailer to go behind the bot then you could probably pull a fair bit of mass as you only need to contend with a Rolling Resistance Coefficient of around 0.1 ..so you could ...in this very simplified example ...pull 900 kg on the flat.

My advice ...just go with the standard wheelchair base and existing gearbox ratio unless you have hills/slopes to overcome.


Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 28, 2016, 04:51 am
Thank you Woody, I went out and tested how much mass I could move on a level surface and the wheel chair base moved 1856lbs . I was quite impressed but I am going to design a new frame in inventor , lower the CG, and add a drive reduction to see what I can really get out of it (hope I don't stall the motors.) I ordered the AMP sensor you posted from ebay, it's on the slow boat so im sure I will get it next month. How are you turning on your  BOT ? I am thinking about a Pin /FLAG switch with a relay as I need a safer and better way to turn this thing on.


@kas, do you think the coding you did for the AMP sensor I currently have will be the same for the 100 amp bi-directional ? I was also testing some fail safe measures on the current code and when I disconnect the battery powering the  Uno , 1 wheel will continue to spin and the other one will stop?  However if I turn off Bluetooth on my mobile both wheels will stop like its suppose to , is there a way to fix this? Or just hope I never have a dead battery or failed connector ? :)
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 28, 2016, 10:03 am
My math calc wasn't far out ...I did base it on my existing knowledge of wheelchairs ... 900kg=  1984.158lbs

Note that you cannot do anything about Friction Coefficient of your tires ...so to get increased pulling power you WILL need to increase the mass of the base as well as changing the gear ratio.


I'd suggest a 20mm taperlock for your gear ratio conversion.
http://www.bearingboys.co.uk/1008-20_Taper_Bush__Dunlop_-2203-p (http://www.bearingboys.co.uk/1008-20_Taper_Bush__Dunlop_-2203-p)
http://www.bearingboys.co.uk/41-15_Roller_Chain_Sprocket-6144-p (http://www.bearingboys.co.uk/41-15_Roller_Chain_Sprocket-6144-p)

My bot uses a removable link for powering up and the R/C receiver I use outputs NULL or nothing on signal loss from the transmitter.
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 28, 2016, 05:36 pm
Quote
I was also testing some fail safe measures on the current code and when I disconnect the battery powering the  Uno , 1 wheel will continue to spin and the other one will stop?  However if I turn off Bluetooth on my mobile both wheels will stop like its suppose to , is there a way to fix this? Or just hope I never have a dead battery or failed connector ?
- the hard way: control a relay from an Arduino output
 - the easy way: power the Arduino from one motor battery, as suggested.
   A depleted battery will still have enough juice for the micro controller

In both ways, a failed connection will still lead to unpredicable results  ;)

EDIT: Also seems there is a Failsafe feature within the Sabertooth device



Quote
do you think the coding you did for the AMP sensor I currently have will be the same for the 100 amp bi-directional ?
No!! please do the math, a (rather) easy task
Hint: the +-100A sensor sensitivity is 20mV/amp

Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 28, 2016, 09:50 pm
The sensor reads 2.5v center= zero amps .... and swings either side of that depending on motor direction.

So the range is I believe 2500/100= 25 mV per Amp.

Simply read the analog output voltage from the sensor with a spare Arduino pin and apply some programming math.

http://www.arduino.cc/en/Tutorial/ReadAnalogVoltage
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 28, 2016, 10:11 pm
From the datasheet:

(http://i.imgur.com/yp8aXkf.jpg)

Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 28, 2016, 11:57 pm
I stand corrected...20mV/A :-[

(http://i232.photobucket.com/albums/ee47/mickey231bhq/eBay_Temp/hcsm_table-800x203_zpsd1db491d.jpg)
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 29, 2016, 02:32 am
- the hard way: control a relay from an Arduino output
 - the easy way: power the Arduino from one motor battery, as suggested.
   A depleted battery will still have enough juice for the micro controller

In both ways, a failed connection will still lead to unpredicable results  ;)

EDIT: Also seems there is a Failsafe feature within the Sabertooth device


No!! please do the math, a (rather) easy task
Hint: the +-100A sensor sensitivity is 20mV/amp


How sensitive is the UNO board to voltage? a full 12v battery might see 12.6 to 12.8volts , should I step it down or roll with it?

What I was thinking is pin/flag switch to control power to the board, I would just break the ground with my pin/flag switch. Once connections has been established I would have Button 3 send signal on an digital channel from UNO to a relay . This would make sure connection was established via bluetooth app before any power gets to the motors. I think I have a 25 amp solid state relay I can experiment with.

Thank you for your input regarding the current sensor, let me study this and I will report back my findings.
 
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 29, 2016, 04:42 am
Yes, let me have a proposal for the resistors values and the checkBat() formula   ;)


kas , if my source is 24 v could I use a 39k and 10k resister to get my voltage around 4.89v?

so would it read:
 
voltage = analogRead(Vpin) * (5.0/1024) *2 = analogRead(Vpin) * 0.0146484375    ?
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 29, 2016, 10:28 am
BTW ...The voltage of a lead acid battery... when in use / under load... tells you nothing about it's ACTUAL state of charge.

http://modernsurvivalblog.com/alternative-energy/battery-state-of-charge-chart/ (http://modernsurvivalblog.com/alternative-energy/battery-state-of-charge-chart/)


http://www.smartgauge.co.uk/technical1.html#peukert_brief (http://www.smartgauge.co.uk/technical1.html#peukert_brief)
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 29, 2016, 10:53 am
Quote
kas , if my source is 24 v could I use a 39k and 10k resister to get my voltage around 4.89v?
With this setup, a fresh battery (12.8V) will generate 5.22V, and will probably fry the Analog Input
Try again  ;)

Title: Re: Android Bluetooth joystick
Post by: kas on Mar 29, 2016, 05:31 pm
Quote
How sensitive is the UNO board to voltage? a full 12v battery might see 12.6 to 12.8volts , should I step it down or roll with it?
The Uno will survive to anything below 20 Volts

Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 29, 2016, 05:37 pm
With this setup, a fresh battery (12.8V) will generate 5.22V, and will probably fry the Analog Input
Try again  ;)


What about a 40k and 6.8 k ?
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 29, 2016, 05:50 pm
Quote
What about a 40k and 6.8 k ?
OK!
what about the math ??

Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 29, 2016, 07:15 pm
Note that a battery JUST coming off the charger could initially be close to 14v.
I'd err on the side of caution and go with 15v per battery ..it also makes the resistor divider calc easier.

Your voltage divider is unlikely to be precise ...so you will either need to finesse the Arduino voltage measurement formula to get the displayed reading match that of a multi meter attached to the batteries.... OR you could ... if your careful... use a multi turn pot as your resistor divider ....and use that to get the Android display voltage to match the ACTUAL measured voltage of the batteries.

I use trim pots like this ....

http://www.ebay.co.uk/itm/5-Pack-3296-Multiturn-Variable-Resistors-Potentiometer-Preset-Trimmer-Pot-/121694846730?var=420697006427&hash=item1c5593ff0a:m:mc3DUYg7CR3yBagFIcQPjqw (http://www.ebay.co.uk/itm/5-Pack-3296-Multiturn-Variable-Resistors-Potentiometer-Preset-Trimmer-Pot-/121694846730?var=420697006427&hash=item1c5593ff0a:m:mc3DUYg7CR3yBagFIcQPjqw)
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 29, 2016, 07:34 pm
OK!
what about the math ??


Well if I use 30v as woody suggested we could use a 40k resistor and a 6k resistor to give us around 3.9v.  I suppose the formula would read:

 voltage = analogRead(Vpin) * 0.00976525;                     
  // battery voltage:(5.0/1024.0)*((40+6)/23)=0.00976525 V per ADC count


@woody I will look into those pots . I'm going to measure the actual voltage and see how it compares to my fluke meter . If it's out substantially I will make an adjustment, my main concern is a quick reference to avoid damage to the batteries.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 30, 2016, 03:59 am
Well I was experimenting with the uno and relays and got the B1 button to turn on the relay which then allows current to flow to the motors .

I need to adjust the code so I have a Button 3 control this as B1 has another purpose . I will probably just reorganize the layout at some point .

I'm using a fan for a demo but the motors will be hooked in line with the relay .

https://youtu.be/EvAueKsMQos

Edit:

I added some coding to the program and now Button 3 should initiate my relay control from pin 12. I haven't tested it yet but it compiled with out any errors so I will test this out to make sure it works as it should .

@ Kas does this look right?

#define    pinServo_A     8            //<<  ServoA pin (AUX)
#define    pinServo_X     9            //<<  ServoX pin
#define    pinServo_Y     10           //<<  ServoY pin
#define    STX            0x02
#define    ETX            0x03
#define    Relay          12                           // used for motor relay
#define    ledPin         13                           // lights up with servo movement
#define    Vpin           A0                            // battery monitoring analog pin
#define    Apin           A1                            // battery monitoring analog pin
#define    MVperAMP       66                            // The 30A module delivers 66mV/A;
#define    VSoffset       2500                          // 2.5V >> 0 Amp
#define    LIMIT_ANGLE    0                            // Max range set to 20 for SCROP XL


Servo myservoA;       
Servo myservoX;                                         // create servo objects
Servo myservoY;

byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};                 // bytes received
byte buttonStatus = 0;                                  // first Byte sent to Android device
long previousMillis = 0;                                // will store last time Buttons status was updated
long sendInterval = 750;                                // interval between Buttons status transmission (milliseconds)
long deadManInterval = 550;                             // interval between Dead Man checks (milliseconds)
boolean deadManTimeout = false;                         // dead man flag
String displayStatus = "xxxx";                          // message to Android device
int servo_L, servo_R = 90;                              // servo's positioning values
float voltage = 0.0;                                    // battery voltage in mV
int milliAmp = 0;                                       // milli Amp
int turbo = 2;                                          // tank max speed (2: slow, 1: fast)

void setup()  {
  Serial.begin(57600);
  myservoA.attach(pinServo_A); 
  myservoX.attach(pinServo_X,1000,2000); 
  myservoY.attach(pinServo_Y,1000,2000);
  pinMode(ledPin, OUTPUT); 
  pinMode(Relay, OUTPUT);     
  while(Serial.available())  Serial.read();          // empty RX buffer
  myservoA.write(90);
}



// -----------------  BUTTON #3  -----------------------
    case 'E':
      buttonStatus |= B000100;        // ON
      displayStatus = "Motors <ON>";
      digitalWrite(Relay, HIGH);
      break;
    case 'F':
      buttonStatus &= B111011;      // OFF
      displayStatus = "Motors <OFF>";
      digitalWrite(Relay, LOW);
      break;
 
Title: Re: Android Bluetooth joystick
Post by: kas on Mar 30, 2016, 07:43 am
Quote
I'm using a fan for a demo but the motors will be hooked in line with the relay .
https://youtu.be/EvAueKsMQos
The relay is LOW level input isn't it ??



Quote
@ Kas does this look right?
So far so good   :)

Although not mandatory, I would personally add
   digitalWrite(Relay, LOW);
after
   pinMode(Relay, OUTPUT);
     
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 30, 2016, 01:15 pm
 I think that your going to need 2 relays.
A 5V and a second... worked by the 5v relay ...rated @24v & 60 -100 Amp to supply/cut power to the Sabertooth.

OR ...

You could perhaps consider a 5v double throw relay that cuts the servo signals to the Sabretooth and rely on the built in failsafe ..switch 6...to stop the bot
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 30, 2016, 02:29 pm
The relay is LOW level input isn't it ??


So far so good   :)

Although not mandatory, I would personally add
   digitalWrite(Relay, LOW);
after
   pinMode(Relay, OUTPUT);
     
I am not sure I know enough to answer this correctly. I don't know how to turn on pins in the uno except by high/low . I checked this with my multimeter and it seems to work? I am all up for a better suggestion , I will make that change you depicted also, thank you.

@Woody Can I not just use my switch to power the uno? 12 volts coming to a switch, then switch to Vin on the uno? This would power my uno and then I connect via bluetooth to turn on my relay with button 3 from digital pin 12? The arduino program has deadman cut that works perfectly (thanks kas) and the sabertooth also has fail safe built in that works great also as i've tested both.
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 30, 2016, 03:33 pm
What EXACTLY is your relay turning ON?
A previous post
Quote
the motors will be hooked in line with the relay .
..seems to suggest the motor POWER wires.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 30, 2016, 04:04 pm
What EXACTLY is your relay turning ON?
A previous post ..seems to suggest the motor POWER wires.
The relay will allow current to flow to the motors . I have a switch that turns on the uno.
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 30, 2016, 09:23 pm
OK...So how much current?

We are going somewhere with these questions....
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 30, 2016, 10:39 pm
OK...So how much current?

We are going somewhere with these questions....
I would assume 100 amps as I stalled these out around 120 amps and I know I want be pulling that much current as I don't want to damage my esc .
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 30, 2016, 11:08 pm
OK.... you need a solenoid rated @ 100 amps.
You will not find a 5v relay capable of 100 amps...so you'll need to use a 5v relay to work a second solenoid with 2 contacts ( both rated for 100 amps ) one for each motor.

YES?

Hence my statement ..
Quote
I think that your going to need 2 relays.
A 5V and a second... worked by the 5v relay ...rated @24v & 60 -100 Amp
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 31, 2016, 02:40 am
OK.... you need a solenoid rated @ 100 amps.
You will not find a 5v relay capable of 100 amps...so you'll need to use a 5v relay to work a second solenoid with 2 contacts ( both rated for 100 amps ) one for each motor.

YES?

Hence my statement ..
Ahhh I see where you're going with this , do you have any recommendations?  

I am using a solid state relay now but it's only good for 25 amps.

https://youtu.be/1l6cuMIYea4

Edit:

I've done some searching on ebay for cheap relays and I think I can make it work . Here is my diagram let me know if you can think of a cheaper or better alternative ?

ebay link :

http://www.ebay.com/itm/Car-Auto-DC-12V-100A-Relay-4-Pin-RL180-Heavy-Duty-Install-Amp-Style-Split-/291693322253?hash=item43ea46e00d:g:wS4AAOSwll1WzqzQ

Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 31, 2016, 10:31 am
YUCK!..... To your Diagram!
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 31, 2016, 10:50 am
Personally I'd ALWAYS go with disconnecting the power at the battery supply to the ESC...( the ESC can then be be disconnected in the case of catastrophic failure ) ...I'd use a UBEC connected straight to the 24v battery to power the Arduino.

Cheap DC/DC  100A SSR's are available.

http://www.ebay.com/itm/100A-Solid-State-Relay-SSR-DC-In-DC-Out-/351040791984?hash=item51bba965b0:g:dO0AAOSwDk5UB2l~ (http://www.ebay.com/itm/100A-Solid-State-Relay-SSR-DC-In-DC-Out-/351040791984?hash=item51bba965b0:g:dO0AAOSwDk5UB2l~)
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 31, 2016, 02:29 pm
I've heard mixed reviews on SSR , so I don't know if it's the best route ?

Do you use a 5v relay to turn on a 24v 100 amp solenoid?  I'm having trouble finding a suitable solenoid.

I have some BEC / ubec here at the house from some uav projects I can use .

Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 31, 2016, 03:48 pm
http://www.ebay.com/itm/White-Rodgers-WR-124-114111-DC-Power-Solenoid-24V-Isolated-Coil-100Amp-/191837256339?hash=item2caa643a93:g:5XgAAOSwpDdVX3gv&vxp=mtr (http://www.ebay.com/itm/White-Rodgers-WR-124-114111-DC-Power-Solenoid-24V-Isolated-Coil-100Amp-/191837256339?hash=item2caa643a93:g:5XgAAOSwpDdVX3gv&vxp=mtr)

Your SSR should be more than capable of operating a solenoid...I just use a RC switch.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Mar 31, 2016, 06:24 pm
http://www.ebay.com/itm/White-Rodgers-WR-124-114111-DC-Power-Solenoid-24V-Isolated-Coil-100Amp-/191837256339?hash=item2caa643a93:g:5XgAAOSwpDdVX3gv&vxp=mtr (http://www.ebay.com/itm/White-Rodgers-WR-124-114111-DC-Power-Solenoid-24V-Isolated-Coil-100Amp-/191837256339?hash=item2caa643a93:g:5XgAAOSwpDdVX3gv&vxp=mtr)

Your SSR should be more than capable of operating a solenoid...I just use a RC switch.
Okay,  I found this one . It seems to be similar but cheaper . I talked to him and I can get it for 25 shipped . If not I will order what you posted.

http://pages.ebay.com/link/?nav=item.view&id=191068307775&alt=web
Title: Re: Android Bluetooth joystick
Post by: woodygb on Mar 31, 2016, 10:46 pm
Fine ...just replace the two 12v motor relays in my drawing with the one 24v solenoid and use it to connect/disconnect the battery feed to the ESC.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Apr 05, 2016, 02:32 am
Fine ...just replace the two 12v motor relays in my drawing with the one 24v solenoid and use it to connect/disconnect the battery feed to the ESC.
I found a good deal on a 100 amp SSR , I added a heat sink and it worked great for 20 mins  but I think it's toast as it no longer allows current to flow through and it appear to bottle neck the power to the motors as it wasn't as powerful as before . I'm ordering the solonoid and going to trigger it with a 5v relay.  Thanks for the help.

No!! please do the math, a (rather) easy task
Hint: the +-100A sensor sensitivity is 20mV/amp


@ Kas, can you check my formulas?

void checkAmp()   {
//   int mV = (analogRead(Apin) / 1024.0) * 5000;
//   milliAmp = ((mV - VSoffset) / MVperAMP) * 1000;

 milliAmp = 73.982 * analogRead(Apin) - 124755.859;             // (analogRead(Apin) * 4882.8125)/20 - 2500000/20

using a 40k and 6k resistor for voltage divider :

voltage = analogRead(Vpin) * 0.00976525;                      
 // battery voltage:(5.0/1024.0)*((40+6)/23)=0.00976525 V per ADC count
Title: Re: Android Bluetooth joystick
Post by: kas on Apr 05, 2016, 04:54 pm
Quote
@ Kas, can you check my formulas?
 milliAmp = 73.982 * analogRead(Apin) - 124755.859;
Not quite  ;)
for 512 ADC counts, you get   73.982 * 512 -124755.859 = 86877 milliAmps
should be zero

The formula should give:
     0 Amp:            (2500mV)                                               1024/2 = 512 ADC counts
 100 Amps:           (2500 + (100*20) = 4500mV)           1024*(4500/5000) = 922 ADC counts
-100 Amps :          (2500 - (100*20) =  500mV)            1024*(500/5000)  = 102 ADC counts

Title: Re: Android Bluetooth joystick
Post by: fullspool on Apr 07, 2016, 04:33 am
Not quite  ;)
for 512 ADC counts, you get   73.982 * 512 -124755.859 = 86877 milliAmps
should be zero

The formula should give:
     0 Amp:            (2500mV)                                               1024/2 = 512 ADC counts
 100 Amps:           (2500 + (100*20) = 4500mV)           1024*(4500/5000) = 922 ADC counts
-100 Amps :          (2500 - (100*20) =  500mV)            1024*(500/5000)  = 102 ADC counts


Im not sure I fully understand on what the actual equation shall be. At 512 ADC my formula should read
milliAmp = 243.664 * analogRead(Apin) - 124755.859;    // (analogRead(Apin) * 4882.8125)/20 - 2500000/2

Then as amps increase (or decreases) it multiplies it by that variable ? Is this correct ?


what about my voltage telemetry formula? Did it appear to be correct? I can't test it until my resistors get here to confirm so I am only speculating.
Title: Re: Android Bluetooth joystick
Post by: kas on Apr 07, 2016, 11:31 am
Quote
Im not sure I fully understand on what the actual equation shall be. At 512 ADC my formula should read
milliAmp = 243.664 * analogRead(Apin) - 124755.859;    // (analogRead(Apin) * 4882.8125)/20 - 2500000/2

Then as amps increase (or decreases) it multiplies it by that variable ? Is this correct ?

what about my voltage telemetry formula? Did it appear to be correct? I can't test it until my resistors get here to confirm so I am only speculating.
Here are the formulae

Amp:
//   int mV = (analogRead(Apin) / 1024.0) * 5000;
//   milliAmp = ((mV - VSoffset) / MVperAMP) * 1000;
milliAmp = 244.14062 * analogRead(Apin) - 125000.0;       // (analogRead(Apin) * 4882.8125)/20 - 2500000/20

Volts:
using a 40k and 6k resistor for voltage divider :
voltage = analogRead(Vpin) * 0.037434895833;             // (5.0/1024.0)*((40+6)/6) = 0.037434895833 V per ADC count


Before connecting sensors to your Analog Inputs pins, check with your DVM
 -Amp sensor should supply 2500 mV when no current
 -voltage divider should output 3130mV for a 24.0V input



Title: Re: Android Bluetooth joystick
Post by: fullspool on Apr 08, 2016, 05:20 am
Here are the formulae

Amp:
//   int mV = (analogRead(Apin) / 1024.0) * 5000;
//   milliAmp = ((mV - VSoffset) / MVperAMP) * 1000;
milliAmp = 244.14062 * analogRead(Apin) - 125000.0;       // (analogRead(Apin) * 4882.8125)/20 - 2500000/20

Volts:
using a 40k and 6k resistor for voltage divider :
voltage = analogRead(Vpin) * 0.037434895833;             // (5.0/1024.0)*((40+6)/6) = 0.037434895833 V per ADC count


Before connecting sensors to your Analog Inputs pins, check with your DVM
 -Amp sensor should supply 2500 mV when no current
 -voltage divider should output 3130mV for a 24.0V input




I'm not sure where I messed up , let me study this more . Thank you for the help and I will test it further with my dmm.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Apr 10, 2016, 08:46 pm
Before connecting sensors to your Analog Inputs pins, check with your DVM
 -Amp sensor should supply 2500 mV when no current
 -voltage divider should output 3130mV for a 24.0V input




Kas, for the amp sensor I am getting 1600mv with no current passing through the sensor.
Title: Re: Android Bluetooth joystick
Post by: woodygb on Apr 10, 2016, 09:59 pm
The voltage.... as measured by your DVM .... that is being supplied to the Amp sensor is ?
Title: Re: Android Bluetooth joystick
Post by: fullspool on Apr 10, 2016, 11:47 pm
The voltage.... as measured by your DVM .... that is being supplied to the Amp sensor is ?
Measuring from ground and "OUT" on the amp sensor I get 1600mv , this is with no current flowing through the sensor.
Title: Re: Android Bluetooth joystick
Post by: woodygb on Apr 11, 2016, 09:00 pm
That is not what I asked.
Quote
The voltage.... as measured by your DVM .... that is being supplied to the Amp sensor is ?
So ..is the INPUT voltage actually 5v  or is it perchance 3.3v ?
Title: Re: Android Bluetooth joystick
Post by: fullspool on Apr 12, 2016, 02:32 am
That is not what I asked.
So ..is the INPUT voltage actually 5v  or is it perchance 3.3v ?
I am sorry, I misunderstood you. I was using a 5v power supply and it wasn't powerful enough so it was reading 3.6v input to amp sensor. I changed power supply and now I am getting 2590 mv from OUT to GND so everything is good. :)
Title: Re: Android Bluetooth joystick
Post by: rxget on Apr 23, 2016, 06:46 pm
Hello Kas,
I'm glad I found your software because of its user friendliness. However I have a small issue. I tried connecting a servo motor to it and added the following code:

 HorizontalServoPosition  = map(joyX, -99, 99, ServoH_Min , ServoH_Max);
 HorizontalServo.write(HorizontalServoPosition);

The servo does what it is supposed to do but it flickers continuously. Meaning it moves a little and comes back. Can you please suggest me a remedy? 
Title: Re: Android Bluetooth joystick
Post by: kas on Apr 25, 2016, 09:56 pm
Quote
The servo does what it is supposed to do but it flickers continuously. Meaning it moves a little and comes back. Can you please suggest me a remedy?
Hi rxget
 
Possibly a power supply problem
Please describe how you power both Arduino and servo

Title: Re: Android Bluetooth joystick
Post by: rxget on Apr 27, 2016, 03:18 pm
Hi rxget
 
Possibly a power supply problem
Please describe how you power both Arduino and servo


Well I tried different types of power supply methods. Mostly arduino and the servo have separate 5V power with common Ground trough a breadboard. I don't think its a power supply problem since I tried with a micro servo too and it does the same thing. I want to say that the flicker it's repetitive and constant as such the loop part of the code.   
Title: Re: Android Bluetooth joystick
Post by: kas on Apr 27, 2016, 10:03 pm
Please attach your Arduino sketch to your next post

Title: Re: Android Bluetooth joystick
Post by: Lila on Apr 28, 2016, 07:01 pm
Hello Kas,

I'm trying to replicate this project for an assignment in school. The goal it to make a remote controlled, two motor car. The original plan was to control the car with the gyroscope in my phone. I'm using an Arduino 101, Moto G 2, and an HC-06 bluetooth chip. I've wired the bluetooth chip to the arduino, downloaded your code onto the board and your app onto the phone, but cannot get the chip and phone to "connect." The phone has been able to pair with the chip, but whenever I try to connect from your app, the "connection fails." I have a limited understanding of how your code and bluetooth in general works. Do you have any ideas on what my problem could be?
Title: Re: Android Bluetooth joystick
Post by: woodygb on Apr 28, 2016, 07:14 pm
Quote
is your Bluetooth card already configured @57600 bps  (most are 9600bps by default)
BT INO (http://forum.arduino.cc/index.php?action=dlattach;topic=173246.0;attach=106796)
Title: Re: Android Bluetooth joystick
Post by: kas on Apr 29, 2016, 06:26 pm
Quote
is your Bluetooth card already configured @57600 bps  (most are 9600bps by default)
Woody, as far as I know, the Serial speed setting is not relevant for the radio link between Android device and BT card
It only applies to the serial link with the microcontroller
Actually, you can connect the card using any bps setting


@Lila
Create a clean test environment:
 - disconnect RX & TX from BT board, just keep 3.3V and Ground
 - reset the App (Preferences > reset Opt.)
 - restart App

Press Connect and make sure to choose the right BT board
The led should stop blinking
If unsure, try all devices in the list

EDIT: make sure it is not a Low Energy BT board
They look pretty much the same


Title: Re: Android Bluetooth joystick
Post by: kas on Aug 07, 2016, 09:24 am
Quote
❝Hi,
I really really like your work.  

I have three vehicles using your RC Commander and now want to convert some of them to the TOTAL RC Commander.
I will be happy to send you $9.00 (USD) for one copy of the TOTAL RC Commander (assuming that it could be used eventually on all three vehicles.
I have installed IP cameras to a PC and to an automobile.  I am a bit familiar with Android phones.  I am somewhat comfortable with the RC Commander and bluetooth.

My eMail (and PayPal) address is NCxxx@HotMail.com

Thanks.
Hi Bob,
check your mail   ;)

Title: Re: Android Bluetooth joystick
Post by: Juris3D on Aug 09, 2016, 09:45 am
Hello! Even I am electronics hobbyist for decades, but only recently I did "catch RC virus" :) Well, probably partially because now I have a son 4 yrs old, so we can already share interests :)
So, I am collecting projects, Android applications, to see what would be good for me to experiment. This joystick looks good! After a quick look-around, I have a question. In apk options I am not finding PWM range settings (to limit max speed of motors when joystick is in some max position). I am yet to be looking into INO files of available projects (i am bad at programming from scratch, only can modify), but should max PWM be hard-coded at Arduino side (not very comfy)? OR am I missing something here :)   ?
Thanks in advance!
Thanks for this project in any case!
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 11, 2016, 11:34 am
Hello! Even I am electronics hobbyist for decades, but only recently I did "catch RC virus" :) Well, probably partially because now I have a son 4 yrs old, so we can already share interests :)
So, I am collecting projects, Android applications, to see what would be good for me to experiment. This joystick looks good! After a quick look-around, I have a question. In apk options I am not finding PWM range settings (to limit max speed of motors when joystick is in some max position). I am yet to be looking into INO files of available projects (i am bad at programming from scratch, only can modify), but should max PWM be hard-coded at Arduino side (not very comfy)? OR am I missing something here :)   ?
Thanks in advance!
Thanks for this project in any case!
Hi Juris3D,

Thanks for the kind words
You may be missing something  ;)  please google for PWM arduino

analogWrite() function send a modulated signal with a defined duty cycle
  analogWrite(pin, 0)       0% duty cycle     0 Volt output
  analogWrite(pin, 191)     75% duty cycle 
  analogWrite(pin, 255)   100% duty cycle   5 Volts output

So, no PWM settings in Joystick BT Commander
Within your Arduino sketch, you may adjust max motor speed by clamping analogWrite value using constrain() or scale it using map()

Driving servo motors is another story


Title: Re: Android Bluetooth joystick
Post by: Juris3D on Aug 12, 2016, 03:42 pm
Thank You for answer!
Well, one reason why I was asking about setting PWM limits from Android side, is because there are several projects that have that feature. I can quickly name two (maybe there are more): "Szabo RC Car" (not in Google store, found in Instructables) and "Arduino Joystick Controller" by Andi.Co.
It is nice feature to be able set maximum speed lower than value 255, maybe it can be implemented here too. I could even imagine presets like "gears" buttons, that can be configured each to particular maximum speed.
Title: Re: Android Bluetooth joystick
Post by: kas on Aug 13, 2016, 07:20 am
This feature was once built in, and deprecated with V4.0 release
I like the K.I.S.S approach and hate bloated software  ;)

Joystick BT Commander currently outputs a solid  [-100 +100] signal for each axis
These values reflect JOYSTICK position
Values customisation is definitly a user responsibility and should be implemented within Arduino sketch

It is dead easy to create "gear buttons" for LOW/HIGH max speed
Should you need sample code, just let me know


Title: Re: Android Bluetooth joystick
Post by: pedrobrio on Aug 20, 2016, 10:19 am
Sorry I am trying to test your app  AndroTest V2.0 with Arduino UNO and Android Nexus 4 (joystick commander)

I am not receiving any STX in cmd[0] , ony 0 and 224.

Could you help  :(

I solved the issue just changing Serial1.begin(9600); I have a bluethooth HC-06

With that everything works like a charm :=)


Title: Re: Android Bluetooth joystick
Post by: kas on Aug 22, 2016, 06:47 pm
I solved the issue just changing Serial1.begin(9600); I have a bluethooth HC-06
With that everything works like a charm :=)
Hi pedrobrio

Glad it works  ;)

To avoid any potential communication errors, I strongly suggest to revert to Serial1.begin(57600)
and set your HC-06 BT card to 57600 bps
Should you need any help, let us know



Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 02, 2016, 09:21 am
Hello to developer and all hobbyists here. I bought tank chassis and also I am getting that "Total RC" APK with camera support. I would be very thankful for some basic INO file that goes with current APK version, for driving 2-motor vehicle (tank). As for hardware, I have Arduinos (nano, uno, pro micro), bluetooth module HC-05, and several kinds of typical motor drivers (L298, L293).
Oh, and especially awesome would be, if there are some framework for "gears" buttons, discussed a little before. By that I mean couple buttons that can set maximum speed of wehicle.
Big Thanks in advance!
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 03, 2016, 10:30 am
Hi Juris,

First make sure you read the Android controlled RC tank with on-board Video (http://forum.arduino.cc/index.php?topic=236401.msg1699561#msg1699561) thread

(http://i.imgur.com/mwX2hOH.jpg)
See it in action: >> video << (http://youtu.be/ebHebDfhkuM)

and fullspool experience (http://forum.arduino.cc/index.php?topic=173246.msg2594735#msg2594735)



Let's check that your hardware is up and running
This basic code will move your tank forward/backward, without RC control:
Code: [Select]
// ***********************************************************************
// *   TankControl   V0.1                                    @kas 2016   *
// *   Code for driving a generic tank with two motors and L298 driver   *
// ***********************************************************************

// Rev history
// V0.1  Basic moves, no RC control


#define   DIR_L     5        // direction control for left motor
#define   PWM_L     6        // PWM control for left motor
#define   DIR_R     8        // direction control for right motor
#define   PWM_R     9        // PWM control for right motor

void setup()  {
  pinMode(PWM_L, OUTPUT);
  pinMode(PWM_R, OUTPUT);
  pinMode(DIR_L, OUTPUT);
  pinMode(DIR_R, OUTPUT);
}

void loop() {
  forward(100);             // forward low speed
  delay(1000);   
  forward(255);             // forward full speed
  delay(1000);   
  stopped();                // stop
  delay(1000);
  backward(100);            // backward low speed
  delay(1000);   
  backward(255);            // backward full speed
  delay(1000);   
  stopped();                // stop
  delay(2000);   
}

void forward(int pwmValue)    {
  digitalWrite(DIR_L, HIGH);
  digitalWrite(DIR_R, HIGH);
  analogWrite(PWM_L, pwmValue);
  analogWrite(PWM_R, pwmValue);
}

void backward(int pwmValue)   {
  digitalWrite(DIR_L, LOW);
  digitalWrite(DIR_R, LOW);
  analogWrite(PWM_L, pwmValue);
  analogWrite(PWM_R, pwmValue);
}

void stopped()   {
  analogWrite(PWM_L, 0);
  analogWrite(PWM_R, 0);
}

For next sketches, the roadmap is
- basic RC control
- differential drive
- normal/turbo speed ("gear" buttons)
- battery voltage display
- battery current monitoring
- who knows...   ;)

EDIT: depending on your motors setup, you may have to invert DIR_R pin level in forward() and backward() functions.

Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 05, 2016, 02:52 pm
Thank You for help! I will tell my progress here, it may be not very fast from my side - have several things going on, commonly called "Real Life (TM)"...  ;-D
But I am not totally blank, already made some "proof of concept", got tank chassis working from very simple Android apk "Robo RC" (just two speed sliders there, nothing else), so I know that all parts are working together.
Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 06, 2016, 08:54 am
I checked this initial tank control sketch, and it didn't really work well. Back and Forward speeds were different, one of directions were acting wrong. I investigated Arduino code from project "Robo RC", and realized we are driving L298 wrong here. Thing is, one of two inputs has to be set LOW and other one feeded with PWM, but - for oposite direction roles are changed: now -second- input has to be set LOW, and now PWM we feed to first input. I modified sketch. Changed pin names that are consistent with markings on typical L298 modules (IN1, IN2, IN3, IN4, with added "L" and "R" to easier "reading").
Changed "stopping" too. Now it works fine.
Arduino code (still without remote control, tank movies slow forward, stop, faster forward, stop, slow backward, stop, faster backward, stop. Repeat):

Code: [Select]
// ***********************************************************************
// *   TankControl   V0.2                                    @kas 2016   *
// *   Code for driving a generic tank with two motors and L298 driver   *
// ***********************************************************************

// Rev history
// V0.2  Basic moves, no RC control

//#define   DIR_L     5        // direction control for left motor
//#define   PWM_L     6        // PWM control for left motor
//#define   DIR_R     8        // direction control for right motor
//#define   PWM_R     9        // PWM control for right motor

#define   IN1_L     3        // direction control for left motor
#define   IN2_L     5        // PWM control for left motor
#define   IN3_R     6        // direction control for right motor
#define   IN4_R     9        // PWM control for right motor

void setup()  {
  pinMode(IN1_L, OUTPUT);
  pinMode(IN2_L, OUTPUT);
  pinMode(IN3_R, OUTPUT);
  pinMode(IN4_R, OUTPUT);
}

void loop() {
  delay(4000);
  forward(88);             // forward low speed
  delay(2000);   
    stopped();                // stop
  delay(2000);
  forward(177);             // forward higher speed (full - 255)
  delay(2000);   
  stopped();                // stop
  delay(2000);
  backward(88);            // backward low speed
  delay(2000);   
    stopped();                // stop
  delay(2000);
  backward(177);            // backward higher speed (full - 255)
  delay(2000);   
    stopped();                // stop
  delay(4000);   
}

void forward(int pwmValue)    {
  digitalWrite(IN1_L, LOW);
  digitalWrite(IN3_R, LOW);
  analogWrite(IN2_L, pwmValue);
  analogWrite(IN4_R, pwmValue);
}

void backward(int pwmValue)   {
  digitalWrite(IN2_L, LOW);
  digitalWrite(IN4_R, LOW);
  analogWrite(IN1_L, pwmValue);
  analogWrite(IN3_R, pwmValue);
}

void stopped()   {
  digitalWrite(IN1_L, LOW);
  digitalWrite(IN3_R, LOW);
  digitalWrite(IN2_L, LOW);
  digitalWrite(IN4_R, LOW);
}


P.S.: I changed pin definitions just because to be the same as from "Robo RC" project.
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 06, 2016, 07:37 pm
Sorry, I should have googled for this specific driver

The Robo RC (http://www.fadvisor.net/blog/2015/03/roborc/) setup may work...  ::)  (and it apparently does  ;) )

PWM signals should normally be fed to ENA (motorA) and ENB (motorB)
Please look here
 (https://tronixlabs.com.au/news/tutorial-l298n-dual-motor-controller-module-2a-and-arduino/)
The Robo RC only use 2 pins per motor, while the "normal" setup uses 3 pins

I will prepare the RC version code based on your modified sketch


Title: Re: Android Bluetooth joystick
Post by: kas on Sep 06, 2016, 08:40 pm
Here it is:
Code: [Select]

// ***********************************************************************
// *   TankControl   V0.3                                    @kas 2016   *
// *   Code for driving a generic tank with two motors and L298 driver   *
// ***********************************************************************

// Rev history
// V0.3  Basic moves (FW/BW only), with RC control, no buttons, no feedback
// V0.2  Basic moves, no RC control

// Arduino pin#0 to TX BlueTooth module
// Arduino pin#1 to RX BlueTooth module
// -->> remove pin#0 connection before downloading the sketch <<--
// make sure your BT board is set @57600 bps

#define   IN1_L     3        // direction control for left motor
#define   IN2_L     5        // PWM control for left motor
#define   IN3_R     6        // direction control for right motor
#define   IN4_R     9        // PWM control for right motor

#define    STX          0x02
#define    ETX          0x03

byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};                 // bytes received

void setup()  {
  pinMode(IN1_L, OUTPUT);
  pinMode(IN2_L, OUTPUT);
  pinMode(IN3_R, OUTPUT);
  pinMode(IN4_R, OUTPUT);
  Serial.begin(57600);         //  XXXXXXX   change to actual BT card baud rate   XXXXXXXXXXXXXXX
  while(Serial.available())  Serial.read();           // empty RX buffer
}

void loop() {
  if(Serial.available())  {                           // data received from smartphone
    delay(2);
    cmd[0] =  Serial.read(); 
    if(cmd[0] == STX)  {
      int i=1;     
      while(Serial.available())  {
        delay(1);
        cmd[i] = Serial.read();
        if(cmd[i]>127 || i>7)                 break;     // Communication error
        if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
        i++;
      }
      if(i==7)          getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
    }
  }
}

void getJoystickState(byte data[8])    {
  int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
  int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
  joyX = joyX - 200;                                                  // Offset to avoid
  joyY = joyY - 200;                                                  // transmitting negative numbers

  if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // commmunication error

  map(joyY,-100,100,-255,255);
 
  if(joyY>10)           forward(joyY);
  else if(joyY<-10)     backward(-joyY);
  else                  stopped();
}
 
void forward(int pwmValue)    {
  digitalWrite(IN1_L, LOW);
  digitalWrite(IN3_R, LOW);
  analogWrite(IN2_L, pwmValue);
  analogWrite(IN4_R, pwmValue);
}

void backward(int pwmValue)   {
  digitalWrite(IN2_L, LOW);
  digitalWrite(IN4_R, LOW);
  analogWrite(IN1_L, pwmValue);
  analogWrite(IN3_R, pwmValue);
}

void stopped()   {
  digitalWrite(IN1_L, LOW);
  digitalWrite(IN3_R, LOW);
  digitalWrite(IN2_L, LOW);
  digitalWrite(IN4_R, LOW);
}

Forward/Backward only, no buttons, no feedback
Purpose is to check BT communication
Set Serial.begin() to actual BT card baud rate

Quote
For next sketches, the roadmap is
- basic RC control
- differential drive
- normal/turbo speed ("gear" buttons)
- battery voltage display
- battery current monitoring
- who knows...   ;)
more:
 - Dead Man (https://en.wikipedia.org/wiki/Dead_man%27s_switch) feature (Bluetooth out of range)
 - lights ON/OFF


Disclaimer:
I currently have no way to check this code, it  _should_  work...
at least it compiles  ;)


Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 06, 2016, 10:07 pm
// V0.3  Basic moves (FW/BW only), with RC control, no buttons, no feedback
I currently have no way to check this code, it  _should_  work...
at least it compiles  ;)

I confirm, that this test sketch V0.3 is working. Forward and backward is working from "Total RC Commander" joystick, with proportional speed.

PWM signals should normally be fed to ENA (motorA) and ENB (motorB)
The Robo RC only use 2 pins per motor, while the "normal" setup uses 3 pins

Yes, I am aware, that "proper" implementation would be IN1/IN2 - HIGH/LOW - LOW/HIGH, and PWM feed to "EN". But since this simplified 2-pin solution works, there is a reason (besides Arduino ports economy) to keep it for tests: there are other "fancy" motor drivers around that has only 2 pins for input. Probably this simplified solution will fit for them too, and - I will be able to check it actually! Just today I got "assortment" of motor drivers modules from China, I think 3 different kinds. Will post here as soon as I try them.

For next sketches, the roadmap is ....
I could suggest some future feature: "shift", or "mode" switch, and it would change commander apk joystick control from tank driving, to camera pan/tilt (and back, obviously). I am "borrowing" that idea from apk "Arduino Joystick Controller"
https://play.google.com/store/apps/details?id=com.andico.control.joystick&hl=en
Title: Version 0.4
Post by: kas on Sep 07, 2016, 10:50 am
Quote
I confirm, that this test sketch V0.3 is working. Forward and backward is working from "Total RC Commander" joystick, with proportional speed
Perfect
Next step: differential stirring for left and right turns (V0.4)

Code: [Select]

// ***********************************************************************
// *   TankControl   V0.4                                    @kas 2016   *
// *   Code for driving a generic tank with two motors and L298 driver   *
// ***********************************************************************

// Rev history
// V0.4  Differential drive (FW/BW/left/right)
// V0.3  Basic moves (FW/BW only), with RC control, no buttons, no feedback
// V0.2  Basic moves, no RC control

#define   IN1_L     3        // direction control for left motor
#define   IN2_L     5        // PWM control for left motor
#define   IN3_R     6        // direction control for right motor
#define   IN4_R     9        // PWM control for right motor

#define    STX          0x02
#define    ETX          0x03

byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};                 // bytes received

void setup()  {
  pinMode(IN1_L, OUTPUT);
  pinMode(IN2_L, OUTPUT);
  pinMode(IN3_R, OUTPUT);
  pinMode(IN4_R, OUTPUT);
  Serial.begin(57600);         //  XXXXXXX   change to actual BT card baud rate   XXXXXXXXXXXXXXX
  while(Serial.available())  Serial.read();           // empty RX buffer
}

void loop() {
  if(Serial.available())  {                           // data received from smartphone
    delay(2);
    cmd[0] =  Serial.read(); 
    if(cmd[0] == STX)  {
      int i=1;     
      while(Serial.available())  {
        delay(1);
        cmd[i] = Serial.read();
        if(cmd[i]>127 || i>7)                 break;     // Communication error
        if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
        i++;
      }
      if(i==7)          getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
    }
  }
}

void getJoystickState(byte data[8])    {
  int pwm_L, pwm_R;
  int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
  int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
  joyX = joyX - 200;                                                  // Offset to avoid
  joyY = joyY - 200;                                                  // transmitting negative numbers
  if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // commmunication error

  if(joyY >-10)  {                                                    // differential steering
    pwm_L = (joyY - (3*joyX)/4);
    pwm_R = (joyY + (3*joyX)/4);
  }  else  {
    pwm_L = (joyY + (3*joyX)/4);
    pwm_R = (joyY - (3*joyX)/4);
  }
  pwm_L = map(pwm_L, -100, 100, -255, 255);
  pwm_R = map(pwm_R, -100, 100, -255, 255);
  pwm_L = constrain(pwm_L, -255, 255);
  pwm_R = constrain(pwm_R, -255, 255);

  motorControl_Left(pwm_L);
  motorControl_Right(pwm_R);
}
 
void motorControl_Left(int pwmValue)  {
  if(pwmValue >=0) {                                                // forward
    digitalWrite(IN1_L, LOW);
    analogWrite (IN2_L, pwmValue);
  }  else  {                                                        // backward
    digitalWrite(IN1_L, -pwmValue);
    analogWrite (IN2_L, LOW);
  }
}

void motorControl_Right(int pwmValue)  {
  if(pwmValue >=0) {                                                // forward
    digitalWrite(IN3_R, LOW);
    analogWrite(IN4_R, pwmValue);
  }  else  {                                                        // backward
    digitalWrite(IN3_R, -pwmValue);
    analogWrite(IN4_R, LOW);
  }
}

void stopped()   {
  digitalWrite(IN1_L, LOW);
  digitalWrite(IN3_R, LOW);
  digitalWrite(IN2_L, LOW);
  digitalWrite(IN4_R, LOW);
}




Quote
I could suggest some future feature: "shift", or "mode" switch, and it would change commander apk joystick control from tank driving, to camera pan/tilt
You got it   :smiley-evil:
Quote
For next sketches, the roadmap is
- basic RC control
- differential drive
- normal/turbo speed ("gear" buttons)
- battery voltage display
- battery current monitoring (stalled motors detection)
- Dead Man feature (Bluetooth out of range)
- lights ON/OFF
- who knows...   ;)
more:
 - mode switch for camera pan/tilt



For improved reliability, please set your BT card @57600 bps


Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 07, 2016, 10:49 pm
Next step: differential steering for left and right turns (V0.4)
Hello, and thanks for new version to try, and to learn! ;-)
Code was working, but it was acting weird (very fast) in "back hemisphere" of joystick movements. Forward, Forward-Right, Forward-Left was working perfectly. Then I found a problem in code: in "backward" operations there was digitalWrite for PWM value, and analogWrite for LOW/HIGH values. That needed to be swapped, of course (analog for PWM, digital for LOW/HIGH). Now all joystick movements are perfect. Here is corrected version, let's call it "V0.41" :-)
Code: [Select]

// ***********************************************************************
// *   TankControl   V0.41                                   @kas 2016   *
// *   Code for driving a generic tank with two motors and L298 driver   *
// ***********************************************************************

// Rev history
// V0.41  Differential drive (FW/BW/left/right)
// V0.3  Basic moves (FW/BW only), with RC control, no buttons, no feedback
// V0.2  Basic moves, no RC control

#define   IN1_L     3        // direction control for left motor
#define   IN2_L     5        // PWM control for left motor
#define   IN3_R     6        // direction control for right motor
#define   IN4_R     9        // PWM control for right motor

#define    STX          0x02
#define    ETX          0x03

byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};                 // bytes received

void setup()  {
  pinMode(IN1_L, OUTPUT);
  pinMode(IN2_L, OUTPUT);
  pinMode(IN3_R, OUTPUT);
  pinMode(IN4_R, OUTPUT);
//  Serial.begin(57600);         //  XXXXXXX   change to actual BT card baud rate   XXXXXXXXXXXXXXX
Serial.begin(9600);
  while(Serial.available())  Serial.read();           // empty RX buffer
}

void loop() {
  if(Serial.available())  {                           // data received from smartphone
    delay(2);
    cmd[0] =  Serial.read();
    if(cmd[0] == STX)  {
      int i=1;     
      while(Serial.available())  {
        delay(1);
        cmd[i] = Serial.read();
        if(cmd[i]>127 || i>7)                 break;     // Communication error
        if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
        i++;
      }
      if(i==7)          getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
    }
  }
}

void getJoystickState(byte data[8])    {
  int pwm_L, pwm_R;
  int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
  int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
  joyX = joyX - 200;                                                  // Offset to avoid
  joyY = joyY - 200;                                                  // transmitting negative numbers
  if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // commmunication error

  if(joyY >-10)  {                                                    // differential steering
    pwm_L = (joyY - (3*joyX)/4);
    pwm_R = (joyY + (3*joyX)/4);
  }  else  {
    pwm_L = (joyY + (3*joyX)/4);
    pwm_R = (joyY - (3*joyX)/4);
  }
  pwm_L = map(pwm_L, -100, 100, -255, 255);
  pwm_R = map(pwm_R, -100, 100, -255, 255);
  pwm_L = constrain(pwm_L, -255, 255);
  pwm_R = constrain(pwm_R, -255, 255);

  motorControl_Left(pwm_L);
  motorControl_Right(pwm_R);
}
 
void motorControl_Left(int pwmValue)  {
  if(pwmValue >=0) {                                                // forward
    digitalWrite(IN1_L, LOW);
    analogWrite (IN2_L, pwmValue);
  }  else  {                                                        // backward
    analogWrite(IN1_L, -pwmValue);
    digitalWrite (IN2_L, LOW);
  }
}

void motorControl_Right(int pwmValue)  {
  if(pwmValue >=0) {                                                // forward
    digitalWrite(IN3_R, LOW);
    analogWrite(IN4_R, pwmValue);
  }  else  {                                                        // backward
    analogWrite(IN3_R, -pwmValue);
    digitalWrite(IN4_R, LOW);
  }
}

void stopped()   {
  digitalWrite(IN1_L, LOW);
  digitalWrite(IN3_R, LOW);
  digitalWrite(IN2_L, LOW);
  digitalWrite(IN4_R, LOW);
}
Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 08, 2016, 08:52 am
Off topic: does anyone tried little physical joysticks, that you stick to touchscreen, in place where virtual joystick on the screen is? Are they working at all? If yes, is it better experience than touch (which does not give you sense, in what relative position your finger/joystick is)?
If not, maybe somewhere in the future there could be DIY physical joystick for tank control, similar to this:
(DIY BT controller transmitter at the end of article)

https://sites.google.com/site/bluetoothrccar/home/6-Joystick-Control
Title: Version 0.5 (1/2)
Post by: kas on Sep 09, 2016, 11:24 am
Quote
Then I found a problem in code: in "backward" operations there was digitalWrite for PWM value, and analogWrite for LOW/HIGH values. That needed to be swapped, of course (analog for PWM, digital for LOW/HIGH). Now all joystick movements are perfect
Nice catch
I can't test the code, those copy/paste errors are really difficult to chase   ::)

TankControl V0.5:
Two way communication between Android device and Arduino
Buttons now are enabled
For this demo
- App datafield #1 & #2 display moving numbers, generated by Arduino
- datafield #3 displays buttons status
- button #5 is configured as push/momentary button
Code: [Select]
// ***********************************************************************
// *   TankControl   V0.5                                    @kas 2016   *
// *   Code for driving a generic tank with two motors and L298 driver   *
// ***********************************************************************

// Rev history
// V0.5  Buttons and two way communication
// V0.41 Differential drive (FW/BW/left/right)
// V0.3  Basic moves (FW/BW only), with RC control, no buttons, no feedback
// V0.2  Basic moves, no RC control

// Demo setup:
// Button #5 configured as "push" button (momentary)
// Other buttons display demo message in datafield #3
// Datafields show arbitrary moving numbers

// Arduino pin#0 to TX BlueTooth module
// Arduino pin#1 to RX BlueTooth module
// -->> remove pin#0 connection before downloading the sketch <<--
// make sure your BT board is set @57600 bps

#define   IN1_L           3                             // direction/PWM control for left motor
#define   IN2_L           5                             // direction/PWM control for left motor
#define   IN3_R           6                             // direction/PWM control for right motor
#define   IN4_R           9                             // direction/PWM control for right motor
#define    STX          0x02
#define    ETX          0x03

byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};                 // bytes received
byte buttonStatus = 0;                                  // first Byte sent to Android device
long sendInterval = 600;                                // interval between Buttons status transmission (milliseconds)
String displayStatus = "xxxx";                          // message to Android device

void setup()  {
  pinMode(IN1_L, OUTPUT);
  pinMode(IN2_L, OUTPUT);
  pinMode(IN3_R, OUTPUT);
  pinMode(IN4_R, OUTPUT);
//Serial.begin(57600);        //  XXXXXXX   change to actual BT card baud rate   XXXXXXXXXXXXXXX
  Serial.begin(9600);
  while(Serial.available())  Serial.read();           // empty RX buffer
}

void loop() {
  if(Serial.available())  {                           // data received from smartphone
    delay(2);
    cmd[0] =  Serial.read();  
    if(cmd[0] == STX)  {
      int i=1;      
      while(Serial.available())  {
        delay(1);
        cmd[i] = Serial.read();
        if(cmd[i]>127 || i>7)                 break;     // Communication error
        if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
        i++;
      }
      if     (i==2)          getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
      else if(i==7)          getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
    }
  }
}

void sendBlueToothData()  {
  static long previousMillis = 0;                            
  long currentMillis = millis();
  if(currentMillis - previousMillis > sendInterval) {   // send data back to smartphone
    previousMillis = currentMillis;

// Data frame transmitted back from Arduino to Android device:
// < 0X02   Buttons state   0X01   DataField#1   0x04   DataField#2   0x05   DataField#3    0x03 >  
// < 0X02      "01011"      0X01     "120.00"    0x04     "-4500"     0x05  "Motor enabled" 0x03 >    // data example

    Serial.print((char)STX);                                             // Start of Transmission
    Serial.print(getButtonStatusString());  Serial.print((char)0x1);     // buttons status feedback
    Serial.print(GetdataInt1());            Serial.print((char)0x4);     // datafield #1
    Serial.print(GetdataFloat2());          Serial.print((char)0x5);     // datafield #2
    Serial.print(displayStatus);                                         // datafield #3
    Serial.print((char)ETX);                                             // End of Transmission
  }  
}

String getButtonStatusString()  {
  String bStatus = "";
  for(int i=0; i<6; i++)  {
    if(buttonStatus & (B100000 >>i))      bStatus += "1";
    else                                  bStatus += "0";
  }
  return bStatus;
}

int GetdataInt1()  {              // Data dummy values sent to Android device for demo purpose
  static int i= -30;              // Replace with your own code
  i ++;
  if(i >0)    i = -30;
  return i;  
}

float GetdataFloat2()  {           // Data dummy values sent to Android device for demo purpose
  static float i=50;               // Replace with your own code
  i-=.5;
  if(i <-50)    i = 50;
  return i;  
}

void getJoystickState(byte data[8])    {
  int pwm_L, pwm_R;
  int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
  int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
  joyX = joyX - 200;                                                  // Offset to avoid
  joyY = joyY - 200;                                                  // transmitting negative numbers
  if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // commmunication error
  
  if(joyY >-10)  {                                                    // differential steering
    pwm_L = (joyY - (3*joyX)/4);
    pwm_R = (joyY + (3*joyX)/4);
  }  else  {
    pwm_L = (joyY + (3*joyX)/4);
    pwm_R = (joyY - (3*joyX)/4);
  }
  pwm_L = map(pwm_L, -100, 100, -255, 255);
  pwm_R = map(pwm_R, -100, 100, -255, 255);
  pwm_L = constrain(pwm_L, -255, 255);
  pwm_R = constrain(pwm_R, -255, 255);

  motorControl_Left(pwm_L);
  motorControl_Right(pwm_R);
}

void motorControl_Left(int pwmValue)  {
  if(pwmValue >=0) {                                                // forward
    digitalWrite(IN1_L, LOW);
    analogWrite (IN2_L, pwmValue);
  }  else  {                                                        // backward
    analogWrite (IN1_L, -pwmValue);
    digitalWrite(IN2_L, LOW);
  }
}

void motorControl_Right(int pwmValue)  {
  if(pwmValue >=0) {                                                // forward
    digitalWrite(IN3_R, LOW);
    analogWrite (IN4_R, pwmValue);
  }  else  {                                                        // backward
    analogWrite (IN3_R, -pwmValue);
    digitalWrite(IN4_R, LOW);
  }
}

void stopped()   {                                                  // not used
  digitalWrite(IN1_L, LOW);
  digitalWrite(IN3_R, LOW);
  digitalWrite(IN2_L, LOW);
  digitalWrite(IN4_R, LOW);
}

void getButtonState(int bStatus)  {
  switch (bStatus) {
// -----------------  BUTTON #1  -----------------------
    case 'A':
      buttonStatus |= B000001;        // ON
      // your code...      
      displayStatus = "Button1 <ON>"; // Demo text message
      break;
    case 'B':
      buttonStatus &= B111110;        // OFF
      // your code...      
      displayStatus = "Button2 <OFF>"; // Demo text message
      break;
** see next message


The message exceeds the maximum allowed length (9000 characters)
** see next message

Please adjust your BT card baudrate to 57600


Title: Version 0.5 (2/2)
Post by: kas on Sep 09, 2016, 11:28 am

The message exceeds the maximum allowed length (9000 characters)
TankControl   V0.5       part 2


Code: [Select]
// -----------------  BUTTON #2  -----------------------
    case 'C':
      buttonStatus |= B000010;        // ON
      // your code...     
      displayStatus = "Button2 <ON>"; // Demo text message
      break;
    case 'D':
      buttonStatus &= B111101;        // OFF
      // your code...     
      displayStatus = "Button2 <OFF>"; // Demo text message
      break;

// -----------------  BUTTON #3  -----------------------
    case 'E':
      buttonStatus |= B000100;        // ON
      // your code...     
      displayStatus = "button3 <ON>"; // Demo text message
      break;
    case 'F':
      buttonStatus &= B111011;      // OFF
      // your code...     
      displayStatus = "button3 <OFF>";
      break;

// -----------------  BUTTON #4  -----------------------
    case 'G':
      buttonStatus |= B001000;       // ON
      // your code...     
      displayStatus = "button4 <ON>"; // Demo text message
      break;
    case 'H':
      buttonStatus &= B110111;    // OFF
      // your code...     
      displayStatus = "button4 <OFF>"; // Demo text message
     break;

// -----------------  BUTTON #5  -----------------------
    case 'I':           // configured as momentary button
//      buttonStatus |= B010000;        // ON
      // your code...     
      displayStatus = "Button5: <pushed>"; // Demo text message
      break;
//   case 'J':
//     buttonStatus &= B101111;        // OFF
//     // your code...     
//     break;

// -----------------  BUTTON #6  -----------------------
    case 'K':
      buttonStatus |= B100000;        // ON
      // your code...     
       displayStatus = "Button6 <ON>"; // Demo text message
     break;
    case 'L':
      buttonStatus &= B011111;        // OFF
      // your code...     
      displayStatus = "Button6 <OFF>"; // Demo text message
      break;
  }
// -----------------------------------------------------
}
Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 09, 2016, 11:55 pm
Trying sketch V0.5, tank control is still working, but nothing happens on data fields ("xxx" displayed). Now trying to understand code and trying to guess what is wrong.
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 10, 2016, 08:55 am
Quote
Trying sketch V0.5, tank control is still working, but nothing happens on data fields ("xxx" displayed)
Easy  :-*
Within loop() the sendBlueToothData() function is never called

At the end of loop(), please replace

     if     (i==2)          getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
     else if(i==7)          getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
   }
 }
}


by


     if     (i==2)          getButtonState(cmd[1]);    // 3 Bytes  ex: < STX "C" ETX >
     else if(i==7)          getJoystickState(cmd);     // 6 Bytes  ex: < STX "200" "180" ETX >
   }
 }
 sendBlueToothData();
}


Let me know the outcome


Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 10, 2016, 03:52 pm
Easy  :-*
Within loop() the sendBlueToothData() function is never called
.......
Let me know the outcome
Thank You for this correction, now data is being sent from Tank to Phone just fine. Two datafields shows those demo number counters, third field tells about button presses.
Btw, there was cosmetic syntaxis error in "Button1 <OFF>" (was "Button2" written, but that's not important.
Tested with both "Joy RC Commander" and "Total RC Commander", all fine so far (except there is no "Button5" in "TC" to test).
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 10, 2016, 04:03 pm
Quote
Tested with both "Joy RC Commander" and "Total RC Commander", all fine so far (except there is no "Button5" in "TC" to test)
Go to Options/Buttons Properties/Buttons to display
and help yourself

Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 10, 2016, 04:44 pm
Go to Options/Buttons Properties/Buttons to display
and help yourself
Hehe, stupid me! :)
Thanks. I guess, I was too distracted. Or, too sleepy :)
Speaking of Android apk, I think it would be nice it would turn off Bluetooth on program exit. Or, maybe have that as an "Advanced option".
Title: Version 0.6
Post by: kas on Sep 12, 2016, 08:57 am
TankControl V0.6:
Turbo mode enabled on Button#1 (gearbox)


Should you modify the code , please post back a copy
 ** reminder **  Please adjust your BT card baudrate to 57600 

Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 13, 2016, 10:24 pm
TankControl V0.6:
Turbo mode enabled on Button#1 (gearbox)
New V.6 tested, and it is working very well, Button1 changes "gear", when "ON" - maximum speed is higher. Hey, I didn't know my tank chassis can jump! :D  Now I know.
For me, values both Turbo ON and OFF are just fine, did not edit anything.
When tank was on V.5, I did quite extended "field testing" outside (before that only little room driving), and I must say, after very little practice, this control feels fine and natural. I have been driving with two sliders control before, and I was thinking, theoretically, that 2-slider control should be best for tank, but it's not, actually. I like joystick more.
So, once again, thanks for this code! :-)
I wonder, what's next? I would vote for headlights On/Off and floodlight On/Off. Then some night driving outside!  ;-)

** reminder **  Please adjust your BT card baudrate to 57600 
Yes, since version V.5 I have changed my BT module baudrate to 57600.
Title: Version V07
Post by: kas on Sep 15, 2016, 09:01 pm
TankControl   V0.7
Led ON/OFF on button#2

Asumption: You have a "main stream" Arduino board with built in led attached to D13

Change #define ledPin 13 to your chosen headlights pin
Should you need high power don't forget to add the requested transistor


(https://s16.postimg.org/6zx5t6r8l/power_transistor.jpg)


Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 15, 2016, 11:35 pm
TankControl   V0.7
Led ON/OFF on button#2
Asumption: You have a "main stream" Arduino board with built in led attached to D13

Hello, and Thanks again! I just did a quick check (quick, because it is really late night here), and new option, LED On/Off is working. In my case it was Arduino Nano onboard LED (D13).
Now I guess I can clone relevant pieces of code and make several On/Off commands, if needed. That I will try next night, I guess.
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 16, 2016, 07:27 am
Quote
Now I guess I can clone relevant pieces of code and make several On/Off commands
Let me have your V0.71 version once modifications are made

Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 17, 2016, 04:55 pm
Let me have your V0.71 version once modifications are made


Here it is, version V0.71, with two switchable ON/OFF lights (or whatever you want there).

Headlights:             ON/OFF on button#2 - output pin D13 (and onboard Arduino LED);
Spotlight (Projector): ON/OFF on button#3 - output pin D12.

Code is tested and it is working.
Hardware idea: for powerful night driving spotlight I will probably use some ready made bike light with its own batteries (put a transistor+relay to switch on), so it won't be depleting tank battery.
"Headlights" will be just some white LEDs in front of tank platform.
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 18, 2016, 09:10 pm
Quote
for powerful night driving spotlight I will probably use some ready made bike light with its own batteries (put a transistor+relay to switch on)
With Total RC Commander, you may also use IR ligths combined with an IP camera. I use a Wanscam JW0004 with integrated IR leds.
The stealth robot will move in total darkness while delivering a clear picture to the android smarphone  8)

Title: Re: Android Bluetooth joystick
Post by: fullspool on Sep 20, 2016, 03:22 am
@kas I am having issues with my robot. It seems to work fine unless you hit the buttons for function controls.  If you notice in this video you see button 1 is selected and the red led is on . Than it behaves erratically like it loses signal and than restarts ??? Ive tried everything that I could think of and came up no where so I figure I would consult the Oracle  :)

https://youtu.be/OxgERMBoeEM
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 20, 2016, 08:37 am
Quote
@kas I am having issues with my robot. It seems to work fine unless you hit the buttons for function controls.  If you notice in this video you see button 1 is selected and the red led is on . Than it behaves erratically like it loses signal and than restarts
Hi fullspool  :)

 - possible EMF interference
 - processor brown out  <<<

what is button #1 supposed to actuate ??

Title: Re: Android Bluetooth joystick
Post by: fullspool on Sep 20, 2016, 05:26 pm
Hi fullspool  :)

 - possible EMF interference
 - processor brown out  <<<

what is button #1 supposed to actuate ??


it operates a servo , however it is disconnect now as i thought it might be causing an issue so the led is in its place so you could easier see the issue I am having.  Should I get a new uno or hc-05 ?

I am using latest app and samsung s7 .
Title: Re: Android Bluetooth joystick
Post by: fullspool on Sep 21, 2016, 01:59 am
I did some more testing on my smaller robot using a different uno board but same hc-05 and its performing the same way.  I suppose my hc-05 has gone bad ?
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 21, 2016, 08:35 am
I did some more testing on my smaller robot using a different uno board but same hc-05 and its performing the same way.  I suppose my hc-05 has gone bad ?
What happens when you just test a plain UNO + HC-05 on a table with  _nothing_ attached  ??

Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 26, 2016, 10:57 am
You got it   :smiley-evil: more:
 - mode switch for camera pan/tilt

Hello! Any chance on new "Tank control lessons", with that pan/tilt control, or something? :)
No rush, I am just curious, and thanks for everything coded so far.
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 26, 2016, 09:39 pm
Hi juris3D

Did you already connect your IP camera to Total RC Commander ??


Quote
Any chance on new "Tank control lessons", with that pan/tilt control, or something? :)
OK   ;)
How do you want your pan/tilt control cooked ?  using one or two servo's ?

Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 26, 2016, 11:37 pm
Did you already connect your IP camera to Total RC Commander ??
How do you want your pan/tilt control cooked ?  using one or two servo's ?


I am fighting with camera right now... But I will win!!  :D
(EDIT: camera EDIMAX feed is working with native Android apk EdiView, and from PC web browser, but I am not sure how to feed cameras username and password for RC Total Commander for now. It is late night, will continue tomorrow.)
As for pan/tilt, it will be two servos config. Left/Right and Up/Down. Not assembled yet, but I can test with servos.
Title: TankControl V0.8
Post by: kas on Sep 29, 2016, 11:40 am
TankControl   V0.8

Button #3 now toggles joystick between  motor control  and  Pan/Tilt control, for camera or other devices
Vertical servo travel and offset are fully adjustable (MIN_Y, MAX_Y & ZERO_Y)

Don't forget to rename buttons according to their specific tasks (Options/Buttons properties/Buttons labels/...)

Enjoy  ;)


Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 29, 2016, 07:28 pm
Thank You for new version! Will try tonight or next days.
I am wondering, what would be best guess how to feed in commandline my camera's username and password? If I simply enter IP address in browser, it asks user/pssw, and then all is fine (see picture).
Link in browwser shows this:
http://10.0.0.45/live.asp?r=20130724
I had some experiments, looking at examples in Internet, how login and password is added to link, but did not succeed yet (Total RC Commander says "error 401: remove camera User Access Control".
I would appreciate some good suggestions here. Thanks!
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 29, 2016, 08:11 pm
Quote
I am wondering, what would be best guess how to feed in commandline my camera's username and password?
Did you try removing password (blank entry) within your IP camera ??

Title: Re: Android Bluetooth joystick
Post by: kas on Sep 29, 2016, 09:01 pm
Also let me have the exact model and possibly a link to your IP camera

Title: Re: Android Bluetooth joystick
Post by: Juris3D on Sep 29, 2016, 09:36 pm
Did you try removing password (blank entry) within your IP camera ??

No I did not, I don't want to have camera without a password.
Model is this:
EDIMAX IC-3115W
www.tesco.com.tr/admin/pages/files/IC-3115W%20User%20Manual.pdf
http://www.edimax.com/edimax/merchandise/merchandise_detail/data/edimax/global/home_network_cameras_indoor_fixed/ic-3115w

by the way, I appologize in advance, if I missed something obvious, probably even written somewhere. I just haven't had much free time, so I asked in advance to more experienced Author who probably knows that without looking anywhere :) :)
UPDATE:
link that works in android VLC player is:
http://IPADDRESS/mjpg/video.mjpg
but the same string does not show picture in RC TC.
Title: Re: Android Bluetooth joystick
Post by: kas on Sep 29, 2016, 10:21 pm
My best guesses:

http://login:password@10.0.0.45/mjpg/video.mjpg
http://login:password@10.0.0.45/mjpg/1/video.mjpg

If you drop login and password from your camera setup
http://10.0.0.45/mjpg/video.mjpg
http://10.0.0.45/mjpg/1/video.mjpg

You may also try adding Port info
10.0.0.45:80

Let me know what you tried



Title: Re: Android Bluetooth joystick
Post by: fullspool on Oct 01, 2016, 01:40 am
What happens when you just test a plain UNO + HC-05 on a table with  _nothing_ attached  ??


If I load a hc05 setup sketch I can send AT commands through the serial monitor.

I tried 2 different hc05 and 2 different uno and they are all behaving the same.

During testing it almost seems the buttons commands time out. So if b1 to light up an led , b2 for turbo , and b3 turns my motors on they all kick off after x amount of time but with no buttons selected the rover behaves normal.
Title: Re: Android Bluetooth joystick
Post by: kas on Oct 01, 2016, 07:48 am
Quote
During testing it almost seems the buttons commands time out. So if b1 to light up an led , b2 for turbo , and b3 turns my motors on they all kick off after x amount of time but with no buttons selected the rover behaves normal.
Humm... something is wrong   ::)
Please post a copy of your current rover Arduino sketch

Title: Re: Android Bluetooth joystick
Post by: kas on Oct 02, 2016, 09:49 pm
Quote
link that works in android VLC player is:
http://IPADDRESS/mjpg/video.mjpg
but the same string does not show picture in RC TC.
Does VLC ask for User/Password ??

Title: Re: Android Bluetooth joystick
Post by: Juris3D on Oct 02, 2016, 11:50 pm
Does VLC ask for User/Password ??
Hello! I got camera picture in "Total RC Commander" now :)
For now, I allowed anonymous access to camera, and just in case reinstalled "Commander". Now I got picture, so, basically all is fine now. I will eventually experiment with user/passw for camera, now that I really know it is working at all.
Pan/Tilt servos cod not tested yet, need a bit more free time.
Title: Re: Android Bluetooth joystick
Post by: kas on Oct 03, 2016, 07:40 am
Quote
Hello! I got camera picture in "Total RC Commander" now :)
So finally, which magic formula did you enter in Total RC Commander (http://forum.arduino.cc/index.php?topic=173246.msg1998617#msg1998617) to access video stream ??

Title: Re: Android Bluetooth joystick
Post by: Juris3D on Oct 03, 2016, 09:55 am
So finally, which magic formula did you enter in Total RC Commander to access video stream ??

I am entering the same as in VLC player:
http://IPADDRESS/mjpg/video.mjpg
Without password for now, will experiment with that another time.
But, the thing is, I am pretty sure I already tried that line many times before, and it did not work in "Commander". I uninstalled (with cleaning data) Commander, re-installed - now it is working.
Maybe the fact, that now I have VLC in my Android system somehow is doing the trick? I don't know.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Nov 12, 2016, 05:21 am
Humm... something is wrong   ::)
Please post a copy of your current rover Arduino sketch


Here you go, I don't understand whats going on. Tried new HC05 and different UNO but still acts up.

Title: Re: Android Bluetooth joystick
Post by: woodygb on Nov 14, 2016, 01:42 pm
I have mine setup with shorter intervals than yours ...might be worth giving them a whirl.


long sendInterval = 250;                               
long deadManInterval = 110;
Title: Re: Android Bluetooth joystick
Post by: kas on Nov 14, 2016, 02:58 pm
@fullspool
I uploaded AndroTest_Servo_fullspool_V1.9.ino on an Arduino/HC-05 combo board, and all is OK
Button are activated/deactivated on my Moto-G without a glitch

You definitally have a hardware problem
 - ground not connected
 - loose wire connections
 - processor brownout
 - EMF interferences (relay & motors)

@woodygb
Woody, I am a software guy  ::) , will you please take the lead and keep on sorting this situation ??

Title: Re: Android Bluetooth joystick
Post by: woodygb on Nov 15, 2016, 05:09 pm
I can try.
Title: Re: Android Bluetooth joystick
Post by: fullspool on Nov 16, 2016, 04:01 am
I will rewire the circuit again and test it. Its frustrated me to a point I had to take a break from it. It all seems to work fine but when I use rapid stick movement in turbo mode it seems to freak out and reset itself. Maybe I am over amping the board ???

I have a VD , amp sensor , 2 signal wires to my motor, 1 to LED, and 1 to a servo .
Title: Re: Android Bluetooth joystick
Post by: geeameal on Nov 17, 2016, 05:48 pm
hey, i tried using the code Andro_Pan&Tilt V3.1 (See my attachment) and i'm using the latest version of your app (i guess it is version 5.2). Well, I can't seem to make it work.
I connected BT Tx to Arduino D0
Servos to pin 9 & 10

Is there something wrong with that?
 
Title: Re: Android Bluetooth joystick
Post by: woodygb on Nov 18, 2016, 02:19 pm
I'd suggest modifying this sketch.
http://forum.arduino.cc/index.php?topic=173246.msg1766646#msg1766646

Have you also reprogrammed your blue tooth modules baud rate?






Title: Re: Android Bluetooth joystick
Post by: Shadowbuddy518 on Nov 18, 2016, 09:48 pm
Im using MEGA 2560 clone with the MEGA sensor shield V2.0 clone.
Bluetooth HC-06 Clone.

Im very new to writing code, could you point me to the correct downloads to get this app working with servos? I'd also like to connect the bluetooth to the (RX,0 and TX,1) on the sensor shield, so I can save my other pins for servos, can this be done?
Title: Re: Android Bluetooth joystick
Post by: geeameal on Nov 21, 2016, 02:09 pm
hey @kas, i was wondering if you can send me the .ino code for your project Arduino robot controlled via Android smartphone https://www.youtube.com/watch?v=-jaszg2t2TY.
And also can you teach me how to wire the parts altogether?