В этом примере показано, как включить обратные вызовы для чтения синусоидальных данных из Arduino ® Uno с помощью tcpserver интерфейс. Arduino настроен как клиент TCP/IP и подключается к серверу TCP/IP, созданному в MATLAB ® с помощьюtcpserver.
Подключите Arduino Uno к компьютеру. Выполните эти шаги, чтобы соединить Щит Сети W5100 Ethernet с Uno Ардуино и с Вашим сетевым маршрутизатором или сетевым адаптером на компьютере.
Установите Ethernet Shield на Arduino Uno.

Используйте кабель RJ45 для подключения Arduino Ethernet Shield к одному из следующих устройств:
Сетевой маршрутизатор, обеспечивающий подключение компьютера к Интернету.
Сетевой адаптер на компьютере.

Определите IP-адрес маршрутизатора или сетевого адаптера, к которому подключен Arduino Ethernet Shield. Укажите этот IP-адрес в программе Arduino в разделе Программа загрузки в Arduino Uno. Этот IP-адрес также используется в качестве входного аргумента для tcpserver в разделе Создание сервера.
Загрузите следующую программу на Arduino Uno с помощью Arduino IDE. Эта программа записывает 250 плавающих значений синусоидальной волны.
/*
TCPIPClient
Write sine wave data values to the tcpserver object created in MATLAB.
*/
#include <SPI.h>
#include <Ethernet.h>
// Specify the MAC address printed on the Ethernet shield.
// If no MAC address is printed, then use the address shown below.
byte mac[] = {0xDE,0xAD,0xBE,0xEF,0xFE,0xED};
// Specify the server IP address that is used to create the tcpserver object in MATLAB.
// This is the IP address of the router or network adapter that the Arduino Ethernet Shield is connected to.
// In this example, 192.168.1.81 is the IP address for the server.
IPAddress server(192,168,1,81);
// Set the static IP address for the Arduino Ethernet Shield to act as a TCP/IP client.
// Choose an IP address that is in the same subnet or private network as the server IP address.
// In this example, 192.168.1.177 is the IP address for the Arduino Ethernet Shield. It is in the same subnet as the server IP address.
IPAddress ip(192,168,1,177);
IPAddress myDns(192,168,1,1);
// Ethernet client library.
EthernetClient client;
// Command sent by the server.
byte command;
// Sine wave data buffer.
float sineWaveBuffer[250];
// The setup routine runs once when you press reset.
void setup()
{
// Initialize serial communication.
Serial.begin(9600);
while (!Serial)
{
; // Wait for serial port to connect.
}
Ethernet.begin(mac,ip,myDns);
Serial.print("Manually assigned the following IP address to the Arduino:");
Serial.println();
Serial.println(Ethernet.localIP());
// Check for Ethernet hardware.
if (Ethernet.hardwareStatus() == EthernetNoHardware)
{
Serial.println("Ethernet shield was not found.");
}
// Check for Ethernet cable connection.
if (Ethernet.linkStatus() == LinkOFF)
{
Serial.println("Ethernet cable is not connected.");
}
Serial.print("Attempting connection to ");
Serial.print(server);
Serial.println("...");
// Attempt to connect to the server running at IP address 192.168.1.81 and port 5000.
if (client.connect(server,5000))
{
Serial.print("Connected to server running at ");
Serial.println(client.remoteIP());
}
else
{
Serial.println("Connection to server failed.");
}
// Store sine wave data as 250 float values.
for (int j = 0;j < 250;j++)
{
sineWaveBuffer[j] = sin(j*50.0/360.0);
}
}
// Main processing loop
void loop()
{
// Block until data is sent by server.
if (client.available() > 0)
{
// Read the command sent by the server.
command = client.read();
// Print the command sent by the server.
Serial.println("The server sent the following command:");
Serial.println(command);
if (client.connected() && command == 1)
{
// Write sine wave data to the server.
client.write((const uint8_t *) & sineWaveBuffer, sizeof(sineWaveBuffer));
}
}
}
Создать tcpserver с использованием IP-адреса маршрутизатора или сетевого адаптера.
В этом примере IP-адрес: 192.168.1.81 и номер порта: 5000. Этот IP-адрес должен совпадать с IP-адресом, указанным в программе Arduino.
server = tcpserver("192.168.1.81",5000)server =
TCPServer with properties:
ServerAddress: "192.168.1.81"
ServerPort: 5000
Connected: 0
ClientAddress: ""
ClientPort: []
NumBytesAvailable: 0
Show all properties, functions
tcpserver Объект для получения данныхУстановите ConnectionChangedFcn свойство для @requestDataCommand. Функция обратного вызова requestDataCommand запускается при подключении Arduino к tcpserver объект.
server.ConnectionChangedFcn = @requestDataCommand;
Создание функции обратного вызова requestDataCommand который отправляет значение uint8 1 в качестве команды для запроса Arduino на отправку данных.
function requestDataCommand(src,~) if src.Connected % Display the server object to see that Arduino client has connected to it. disp("The Connected and ClientAddress properties of the tcpserver object show that the Arduino is connected.") disp(src) % Request the Arduino to send data. disp("Send the command: 1") write(src,1,"uint8"); end end
Установите BytesAvailableFcnMode свойство to "byte", BytesAvailableFcn свойство для @readArduinoData, и BytesAvailableFcnCount свойство 1000.
configureCallback(server,"byte",1000,@readArduinoData);Функция обратного вызова readArduinoData запускается, когда 250 точек данных с плавающей синусоидальной частотой (1000 байт) доступны для чтения из Arduino.
Создание функции обратного вызова readArduinoData считывает 250 точек данных синусоидальной волны и строит график результата.
function readArduinoData(src,~) % Read the sine wave data sent to the tcpserver object. src.UserData = read(src,src.BytesAvailableFcnCount/4,'single'); % Plot the data. plot(src.UserData) % Clear any other remaining data sent by the Arduino. flush(src); end