Go Down

Topic: Can't send integers correctly over Serial (Read 30306 times) previous topic - next topic

mesh

You might be able to use a union to easily rebuild the int.

See the arduino code in this post:

http://www.mikechambers.com/blog/2010/08/01/sending-multibyte-numbers-from-actionscript-to-arduino/

mike chambers

Electricaero87

Okay, I'll take a look at the Union stuff and see if that helps at all. I had a feeling that doing it the way I did would cause issues later on. I was just happy that I sent 16 bits!

I do have a question about the ASCII conversion though. I've tried using that but I couldn't get it too work. I know the function is itoa() or atoi() depending which way you want to go. But I'm not sure how to use it. Can anyone point me in a good direction with this? Thanks!!

AWOL

Quote
I know the function is itoa() or atoi()

"itoa" makes an ASCII string (correctly null terminated) from an integer, BUT "atoi" needs a correctly terminated string to work.

Electricaero87

Okay so looked into the unions and they seem to be a good way of doing this. I wrote a code based off of site that mesh provided. However when I try to send 12.141422271728516 through the Serial Port I get 0.0000000 on the other end. I have my Razor IMU connected to the Serail1 port on my Seeeduino Mega (and I did dial down the voltage to 3.3 volts) and display the values through the Serial Monitor.

Here is the send code (uploaded to my Razor IMU):
Code: [Select]
union u_tag {
 byte b[4];
 float f;
} u;

float test = 12.141422271728516;

void setup()
{
 Serial.begin(9600);
 
 u.f = test;
}

void loop()
{
 Serial.write(u.b,4);
 delayMicroseconds(random(1000));
}


And here is the receive code:
Code: [Select]
union u_tag {
 byte b[4];
 float f;
} u;

float rec=1.23456;

void setup()
{
 Serial.begin(9600);
 Serial1.begin(9600);
}
void loop()
{
 while(Serial1.available()<4)
 {
   delayMicroseconds(1);
 }
 if(Serial1.available()>=4)
 {
   for(int i=0; i<4; i++)
   {
     u.b[i]=Serial1.read();
   }
 }
 rec=u.f;
 
 Serial.write(u.b, 4);
 Serial.println(u.f, DEC);
 delay(1000);
}


Can anyone spot what is causing 0.00000000 to be displayed on the Serial Monitor? Thank you in advance for any help provided!!!

Go Up