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

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

Идентифицируйте IP-адрес маршрутизатора или сетевого адаптера, к которому подключен Arduino Ethernet Shield. Укажите этот IP-адрес в программе Arduino в разделе Load Program на 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-адрес должен быть таким же, как и в программе 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 свойство для "byte", the 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