11 years, 1 month ago.

Help with my code?

Hi, I am an old programmer just trying to learn C, and get a start on an application. In my code below, I obviously have problems in C. I am trying to send out the x y and Z outputs of the accelerometer to the terminal.

  1. include "mbed.h"
  2. include "MMA8451Q.h"
  3. define MMA8451_I2C_ADDRESS (0x1d<<1)

Serial pc(USBTX, USBRX); tx, rx

int main(void) {

float XaccO;

float YaccO;

float ZaccO;

MMA8451Q acc(PTE25, PTE24, MMA8451_I2C_ADDRESS);

PwmOut rled(LED_RED);

PwmOut gled(LED_GREEN);

PwmOut bled(LED_BLUE);

pc.printf("Hello World!\n \n");

while (true) {

rled = 1.0 - abs(acc.getAccX());

gled = 1.0 - abs(acc.getAccY());

bled = 1.0 - abs(acc.getAccZ());

wait(1);

XaccO = 1.0 - abs(acc.getAccX());

YaccO = 1.0 - abs(acc.getAccY());

ZaccO = 1.0 - abs(acc.getAccZ());

pc.printf(Xacc0);

pc.printf("\n");

pc.printf(YaccO);

pc.printf("\n");

pc.printf(ZaccO);

pc.printf("\n");

pc.printf("\n");

}

2 Answers

11 years, 1 month ago.

Tom, just looks like a missing closing brace at the end. There's an opening brace at int main(void), and another at while(true), so you need two at the end, there's only one. Assume you're using a KL25Z board. The stock example for using the accelerometer is at http://mbed.org/users/mbed_official/code/FRDM_MMA8451Q/docs/70775be9f474/main_8cpp_source.html so you're really only trying to put in a printf. Note though that in cloning the code used to set up the RGB LED, you've also copied the bits subtracting it from one and doing an absolute to get rid of the sign - no need, these are only there to get a value suitable for the LED. Really could just take the stock example code and add in pc.printf("X=%f, Y=%f, Z=%f\n", acc.getAccX(), acc.getAccY(), acc.getAccZ());

Accepted Answer
11 years, 1 month ago.

Please use <<code>> and <</code>> around your code for better readability. And it helps to tell which error you get.

However for sure your printfs are a problem. What you need to do is: pc.printf("%f\n",Xacc0);, or even something like: pc.printf("X-accel = %f\n", Xacc0); %f tell the compiler the next argument should be a float, and the ascii value should be printed there. You can also do that with several arguments at the same time, such as: pc.printf("Acceleration: %f - %f - %f\n", Xacc0, Yacc0, Zacc0);