5 years, 11 months ago.

How to control the servo using the accelerometer values?

Hi, I am trying to control the servo by tilting the microbit left or right. I've got the accelerometer values but I'm not sure how to fit it to the code to control the servo.

I think I need to scale the accelerometer values to the servo motor but I'm not sure how to do that either. The servo motor that i'm using is Hitec HSR5995TG. Thanks.

This is my code so far.

  1. include "MicroBit.h"
  2. include <stdlib.h>
  3. include <stdio.h>
  4. include <string.h>
  5. include <string>
  1. define SERVO_POSITION_CENTRE 93
  2. define SERVO_POSITION_MAX 128
  3. define SERVO_POSITION_MIN 54

using namespace std; Serial pc(USBTX, USBRX);

MicroBit uBit;

Scales the given value that is in the -1024 to 1024 range int a value between 0 and 4.

int pixel_from_g(int value) { int x = 0;

if (value > -750) x++; if (value > -250) x++; if (value > 250) x++; if (value > 750) x++;

return x; }

void onData(MicroBitEvent) { ManagedString b = uBit.radio.datagram.recv(); int num = atoi(b.toCharArray()); char seps[] = ","; char *token1; char *token2;

token1 = strtok( (char*)b.toCharArray(), seps ); pc.printf("x = %s\r\n", token1); token2 = strtok( NULL, seps ); pc.printf("y = %s\r\n", token2);

int acc_x = atoi(token1); int acc_y = atoi(token2); int x = pixel_from_g(acc_x); int y = pixel_from_g(acc_y); uBit.display.image.clear(); uBit.display.image.setPixelValue(x, y, 255);

}

int main() { Initialise the micro:bit runtime. uBit.init(); uBit.messageBus.listen(MICROBIT_ID_RADIO, MICROBIT_RADIO_EVT_DATAGRAM, onData); uBit.radio.enable();

uBit.io.P0.setServoPulseUs(20);

while(1) { uBit.sleep(1000); } }

Please edit to use

<<code>>
Your code
<</code>>

So that the formatting is correctly displayed.

posted by Andy A 24 May 2018
Be the first to answer this question.