1. Given number is:
unsigned int code =200100;
Let us note that the entered number is always stored in memory locations as 'natural binary'. Accordingly, 200100 will be saved as: 0011 0000 1101 1010 0100 (0x30DA4 in hex base). It is larger than 16-bit; so, the int type variable code will not hold the number. We need to declare it as:
unsigned long int code = 200100; //long type variable hold 32-bit data
==> unsigned long code = 200100; // 0x30DA4; int is understood.
2. Now, decide as to which representation (200100 or 0x30DA4) to send to the destination using UART Port. Let us agree that we want to send this image 200100; where, every digit will be sent in its 8-bit ASCII format according to following Table (Fig-1). The code is:
Serial.print(code, DEC); //0x32, 0x30, 0x30, 0x31, 0x30, 0x30 reach at receiver
Figure-1:
3. At the receiver, let us collect the ASCII represented codes and convert them back to this image 200100 and the decimal represented literal number: 200100.
4. Codes:
Transmit Codes:(tested)
#include<SoftwareSerial.h>
SoftwareSerial SUART(6, 7); //SRX = DPin-6, STX = Dpin-7
unsigned long code = 200100; //0x030DA4
void setup()
{
Serial.begin(9600);
SUART.begin(9600);
}
void loop()
{
Serial.println(code, DEC);
SUART.print(code, DEC); //
delay(1000);
}
Receive Codes:(tested)
#include<SoftwareSerial.h>
SoftwareSerial SUART(6, 7); //SRX = DPin-6, STX = Dpin-7
char code[7]="";
void setup()
{
Serial.begin(9600);
SUART.begin(9600);
}
void loop()
{
byte n = SUART.available();
if ( n == 6)
{
for (int i = 0; i < 6; i++)
{
code[i] = SUART.read();
}
code[6] = '\0';
Serial.println(code);
unsigned long code1 = atol(code);
Serial.println(code1, DEC);
memset(code, 0, 7);
}
}
5. //-------------Sending 200100 (0x030DA4) as binary number-------------
**(1)**TX Codes
#include<SoftwareSerial.h>
SoftwareSerial SUART(6, 7); //SRX = DPin-6, STX = Dpin-7
unsigned long code = 200100; //0x030DA4
union ////Convert the given number into bytes using the following union structure.
{
unsigned long x;
byte myData[4];
}data;
void setup()
{
Serial.begin(9600);
SUART.begin(9600);
data.x = 200100;
}
void loop()
{
Serial.println(data.x, DEC);
SUART.write(data.myData, sizeof(data.myData));
delay(1000);
}
(2)RX Codes:
#include<SoftwareSerial.h>
SoftwareSerial SUART(6, 7); //SRX = DPin-6, STX = Dpin-7
union
{
unsigned long x;
byte myData[4];
}data;
void setup()
{
Serial.begin(9600);
SUART.begin(9600);
}
void loop()
{
byte n = SUART.available();
if ( n == 4)
{
for (int i = 0; i < 4; i++)
{
data.myData[i] = SUART.read();
}
Serial.println(data.x, DEC);
}
}
6. //------- sending float x = 12.73 using UART Port-------------------------------------------
The steps very similar to that of sending/receiving integer numbers shown above except that you have to use atof() function.