I am new to Arduino programming. I have successfully been able to send one piece of data from Simulink to Arduino (Mega 2560) and store it in a variable called "voltage". Now, I want to send more than one piece of information and store it in a different variable, for instance, "current". Attached is the code to receive and store data from Simulink in a variable "voltage" in Arduino.
#include <SoftwareSerial.h>
//Variables
int character_location;
const int buffer_size=16; //buffer size and buffer used to recieve the
byte buf[buffer_size]; //data from Simulink
float output;
float output_current;
#define RX 10
#define TX 11
int voltage = 1;
int current = 1;
SoftwareSerial esp8mod(RX,TX);
union BytetoFloat //byte to float
{
byte b[16]; //size of 16 bytes
float fval;
} uni; //name of the defined union to be used
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
esp8mod.begin(115200);
}
void loop() {
// send data only when receive data, when in the serial port:
while (Serial.available()==0)
{
}
if (Serial.available()>0) {
voltage = readFromSimulink();
delay(0.001);
writeToMatlab(voltage);
}
}
float readFromSimulink() //gets numbers from data type as a float
{
character_location = Serial.readBytesUntil('\r\n', buf, buffer_size);
for (int i=0; i<buffer_size; i++) //go through each element until you looked through all the bytes in the buffer
//i++ means increment i each time
{
uni.b[i] = buf[i]; //store in b from union the item in buffer located i
}
output = uni.fval; //store in fval which was defined in union uni
return output;
}
void writeToSimulink (float number)
{
byte *uni = (byte *) &number; //the * means the address of the variable
//uni. The & is used to declare a pointer, I want
//to access the number's memory address.
Serial.write(uni,4); //write to ther serial port the union value
}
void writeToMatlab (float number)
{
byte *uni = (byte *) &number;
Serial.write(uni,4);
}