Applying the accelerometer sensor to my toy car

I was able to control a handmade toy car using my android app.

The controls I made are for manual drive, that is, I touch the buttons to move the car by sending a char to the arduino.

Now I want to take it to the next level and use the accelerometer sensor. I managed to get the readings of the x, y, z axis when I tilt my cell phone, but I don't know what to do next.

I came across two options:

  • Should I send accelerometer values ​​to arduino and let the arduino decide the speed (via PWM) and which motor to start.
  • Use android studio to compare axis values, for example, if x-axis is greater than 5, the app will send a character to arduino, which will make the car move forward at the desired speed. Here is the code I used to get the values, in the end I tried to send the character "F" to the arduino to move the car forward, but nothing happened. I know there is no problem in submitting the code, because I used the same thing in manual operation (using buttons).

Code

@Override
public void onSensorChanged(SensorEvent sensorEvent) {

    TextView tvX= (TextView)findViewById(R.id.x_axis);
    TextView tvY= (TextView)findViewById(R.id.y_axis);
    TextView tvZ= (TextView)findViewById(R.id.z_axis);

    Sensor mySensor = sensorEvent.sensor;
    if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        float x = sensorEvent.values[0];
        float y = sensorEvent.values[1];
        float z = sensorEvent.values[2];
        last_x = x;
        last_y = y;
        last_z = z;

        tvX.setText(Float.toString(last_x));
        tvY.setText(Float.toString(last_y));
        tvZ.setText(Float.toString(last_z));

        if(last_x > 5f){
            if(btSocket!=null){
                try
                {
                    btSocket.getOutputStream().write("F".toString().getBytes());
                }
                catch (IOException e)
                {
                    msg("Error");
                }
            }
        }
    }
}

      

+3


source to share





All Articles