battle programmers alliance
Would you like to react to this message? Create an account in a few clicks or log in to continue.


battle programming a forum for elite programmers with extreme will power to sharpen theire skills
 
HomeSearchRegisterLog in
Post new topic   Reply to topic
 

 gyro upgrade

Go down 
AuthorMessage
Moti Barski
super
super
Moti Barski

Posts : 445
Join date : 2011-08-02

gyro upgrade Empty
PostSubject: gyro upgrade   gyro upgrade EmptyWed Dec 18, 2019 7:44 am

added ability to get gyro input (DiDirty skill uses it)

add <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
to the manifest.xml file above <application

add interface (kotlin):
Code:
interface AccelerometerListener {

    fun onAccelerationChanged(x: Float, y: Float, z: Float)

    fun onShake(force: Float)
}

add a class named AccelerometerManager.kt (kotlin)

Code:

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.widget.Toast

object AccelerometerManager {

    private var context: Context? = null
    /**
    * Accuracy configuration
    */
    private var threshold = 15.0f
    private var interval = 200

    private var sensor: Sensor? = null
    private var sensorManager: SensorManager? = null
    // you could use an OrientationListener array instead
    // if you plans to use more than one listener
    private var listener: AccelerometerListener? = null

    /**
    * indicates whether or not Accelerometer Sensor is supported
    */
    private var supported: Boolean? = null
    /**
    * indicates whether or not Accelerometer Sensor is running
    */
    /**
    * Returns true if the manager is listening to orientation changes
    */
    var isListening = false
        private set

    private val sensorEventListener = object : SensorEventListener {

        private var now: Long = 0
        private var timeDiff: Long = 0
        private var lastUpdate: Long = 0
        private var lastShake: Long = 0

        private var x = 0f
        private var y = 0f
        private var z = 0f
        private var lastX = 0f
        private var lastY = 0f
        private var lastZ = 0f
        private var force = 0f

        override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}

        override fun onSensorChanged(event: SensorEvent) {
            // use the event timestamp as reference
            // so the manager precision won't depends
            // on the AccelerometerListener implementation
            // processing time
            now = event.timestamp

            x = event.values[0]
            y = event.values[1]
            z = event.values[2]

            // if not interesting in shake events
            // just remove the whole if then else block
            if (lastUpdate == 0L) {
                lastUpdate = now
                lastShake = now
                lastX = x
                lastY = y
                lastZ = z
                Toast.makeText(context, "No Motion detected", Toast.LENGTH_SHORT).show()

            } else {
                timeDiff = now - lastUpdate

                if (timeDiff > 0) {

                    force = Math.abs(x + y + z - lastX - lastY - lastZ)

                    if (java.lang.Float.compare(force, threshold) > 0) {

                        if (now - lastShake >= interval) {
                            // trigger shake event
                            listener!!.onShake(force)
                        } else {
                            Toast.makeText(
                                context, "No Motion detected",
                                Toast.LENGTH_SHORT
                            ).show()

                        }
                        lastShake = now
                    }
                    lastX = x
                    lastY = y
                    lastZ = z
                    lastUpdate = now
                } else {
                    Toast.makeText(context, "No Motion detected", Toast.LENGTH_SHORT).show()
                }
            }
            // trigger change event
            listener!!.onAccelerationChanged(x, y, z)
        }
    }

    /**
    * Unregisters listeners
    */
    fun stopListening() {
        isListening = false
        try {
            if (sensorManager != null && sensorEventListener != null) {
                sensorManager!!.unregisterListener(sensorEventListener)
            }
        } catch (e: Exception) {
        }

    }

    /**
    * Returns true if at least one Accelerometer sensor is available
    */
    fun isSupported(cntxt: Context): Boolean {
        context = cntxt
        if (supported == null) {
            if (context != null) {

                sensorManager = context!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager

                // Get all sensors in device
                val sensors = sensorManager!!.getSensorList(
                    Sensor.TYPE_ACCELEROMETER
                )

                supported = sensors.size > 0
            } else {
                supported = java.lang.Boolean.FALSE
            }
        }
        return supported!!
    }

    /**
    * Configure the listener for shaking
    *
    * @param threshold minimum acceleration variation for considering shaking
    * @param interval minimum interval between to shake events
    */
    fun configure(threshold: Int, interval: Int) {
        AccelerometerManager.threshold = threshold.toFloat()
        AccelerometerManager.interval = interval
    }

    /**
    * Registers a listener and start listening
    *
    * @param accelerometerListener callback for accelerometer events
    */
    fun startListening(accelerometerListener: AccelerometerListener) {

        sensorManager = context!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager

        // Take all sensors in device
        val sensors = sensorManager!!.getSensorList(
            Sensor.TYPE_ACCELEROMETER
        )

        if (sensors.size > 0) {

            sensor = sensors[0]

            // Register Accelerometer Listener
            isListening = sensorManager!!.registerListener(
                sensorEventListener, sensor,
                SensorManager.SENSOR_DELAY_GAME
            )

            listener = accelerometerListener
        }
    }

    /**
    * Configures threshold and interval
    * And registers a listener and start listening
    *
    * @param accelerometerListener callback for accelerometer events
    * @param threshold minimum acceleration variation for considering shaking
    * @param interval minimum interval between to shake events
    */
    fun startListening(accelerometerListener: AccelerometerListener, threshold: Int, interval: Int) {
        configure(threshold, interval)
        startListening(accelerometerListener)
    }
}

see next post for the main activity.
all said files in the app,java, first package folder


_________________
MB over and out emp it up
Back to top Go down
Moti Barski
super
super
Moti Barski

Posts : 445
Join date : 2011-08-02

gyro upgrade Empty
PostSubject: Re: gyro upgrade   gyro upgrade EmptyWed Dec 18, 2019 7:45 am

main activity.kt :

added JikanMon.kt time gate.

this class stabilizes the gyro input, so it filters out an input overload by violent shakes. only up to 1 input per x seconds

Code:
package com.yotamarker.lgkotlin1

class JikanMon {
    private val playGround = PlayGround()
    private var x = -1
    private var timePause = 3
    val isBlocked:Boolean
        get() {
            val nowSeconds = playGround.getSecondsAsInt()
            if ((x < 0 || nowSeconds > x) || (x > 60 && nowSeconds > (x - 60)))
            {
                x = -1
                return false
            }
            return true
        }
    fun block() {
        this.x = playGround.getSecondsAsInt() + timePause
    }
    fun setTimePause(timePause:Int) {
        if ((timePause > 0) && (timePause < 30))
        {
            this.timePause = timePause
        }
    }
}

emp it up

Code:
package com.yotamarker.lgkotlin1

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.MediaPlayer
import android.os.BatteryManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.text.TextUtils.substring
import android.util.Log
import android.view.View
import android.view.Window
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*
import java.nio.file.Files.size
import java.util.*
import kotlin.math.absoluteValue


class MainActivity : AppCompatActivity(), TextToSpeech.OnInitListener, AccelerometerListener{
    private var tts: TextToSpeech? = null
    var chii = Chobit()
    var toggleTic = false
    var gyroX = 0.0f; var gyroY = 0.0f;var gyroCounter = 0;var gyroGate = JikanMon()
    //var spoke = false
    var mbTTS = TTSVoice(this)
    private val mBatInfoReceiver = object : BroadcastReceiver() {
        override fun onReceive(ctxt: Context, intent: Intent) {
            val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
            val b8TRiStr = chii.doIt("","$level charge","")
            mbTTS.voiceIt(b8TRiStr)
            //voiceIt(b8TRiStr)
            if (b8TRiStr != ""){editText.setText(b8TRiStr)}
            //editText.setText(chii.doIt("","$level charge",""))
            //txtBox.setText("$level% $b8TRcounter")
            val status: Int = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
            val isCharging: Boolean = status == BatteryManager.BATTERY_STATUS_CHARGING
                    || status == BatteryManager.BATTERY_STATUS_FULL

            val chargePlug: Int = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
            val usbCharge: Boolean = chargePlug == BatteryManager.BATTERY_PLUGGED_USB
            val acCharge: Boolean = chargePlug == BatteryManager.BATTERY_PLUGGED_AC
            //txtBox.setText("$usbCharge")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tts = TextToSpeech(this, this)
        supportActionBar?.hide()
        this.registerReceiver(this.mBatInfoReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        var count = 0
        val t = object:Thread() {
            public override fun run() {
                while ((!isInterrupted()))
                {
                    try
                    {
                        Thread.sleep(4000)
                        runOnUiThread(object:Runnable {
                            public override fun run() {
                                if (toggleTic){
                                    count++
                                    mbTTS.voiceIt(count.toString())}
                            }
                        })
                    }
                    catch (e:InterruptedException) {
                        e.printStackTrace()
                    }
                }
            }
        }
        t.start()
        imageView2.setOnLongClickListener {

            toggleTic = !toggleTic
            if (toggleTic){imageView2.setImageResource(R.drawable.brainpic)}
            else{imageView2.setImageResource(R.drawable.yggdrasil)}
            true
        }
    }
    fun clrText(view: View){
        editText.setText("")
    }
    fun engage(view: View){
        var resultStr = chii.doIt(editText.text.toString(),"","")
        editText.setText("")
        mbTTS.voiceIt(resultStr)
        if (mbTTS.TTS){speakOut(resultStr)}
        face(chii.getEmot())
    }
    override fun onInit(status: Int) {

        if (status == TextToSpeech.SUCCESS) {
            // set US English as language for tts
            val result = tts!!.setLanguage(Locale.US)

            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS","The Language specified is not supported!")
            } else {
                //buttonSpeak!!.isEnabled = true
            }

        } else {
            Log.e("TTS", "Initilization Failed!")
        }

    }
    private fun speakOut(leftOver:String) {
        tts!!.speak(leftOver, TextToSpeech.QUEUE_FLUSH, null,"")
    }
    private fun face(face:String) {
        when (face) {
            "speaking" -> imageView.setImageResource(R.drawable.sugoikibun)

            else -> {imageView.setImageResource(R.drawable.waa)}
        }
    }
    public override fun onDestroy() {
        // Shutdown TTS
        if (tts != null) {
            tts!!.stop()
            tts!!.shutdown()
        }
        super.onDestroy()
        if (AccelerometerManager.isListening)
        {
            AccelerometerManager.stopListening()
            Toast.makeText(this, "onDestroy Accelerometer Stopped", Toast.LENGTH_SHORT).show()
        }
    }
    override fun onShake(force:Float) {
        Toast.makeText(this, "Motion detected", Toast.LENGTH_SHORT).show()
    }
    override fun onAccelerationChanged(x:Float, y:Float, z:Float) {
        // *add gyroy below
        if((gyroX - x) > 2 && !gyroGate.isBlocked){
            gyroCounter++
            gyroGate.block()
            Toast.makeText(this, "moved $gyroCounter", Toast.LENGTH_SHORT).show()
            // out put uses this 4 lines :
            var resultStr = chii.doIt("","shake","")
            editText.setText("")
            mbTTS.voiceIt(resultStr)
            if (mbTTS.TTS){speakOut(resultStr)}
            face(chii.getEmot())
             }
        else{}
        gyroX=x;gyroY=y;
    }
    override protected fun onResume() {
        super.onResume()
        if (AccelerometerManager.isSupported(this))
        {
            AccelerometerManager.startListening(this)
        }
    }
    override fun onStop() {
        super.onStop()
        //Check device supported Accelerometer senssor or not
        if (AccelerometerManager.isListening)
        {
            //Start Accelerometer Listening
            AccelerometerManager.stopListening()
            Toast.makeText(this, "onStop Accelerometer Stopped", Toast.LENGTH_SHORT).show()
        }
    }
}

the functions handling movement input :
onShake(force:Float)
*onAccelerationChanged which has room for alg improvements ATM (the inside of the function)

rain

_________________
MB over and out emp it up
Back to top Go down
 
gyro upgrade
Back to top 
Page 1 of 1

Permissions in this forum:You can reply to topics in this forum
battle programmers alliance :: battle programming alliance :: the LivinGrimoire-
Post new topic   Reply to topicJump to: