Main Content

Communicate with Arduino Server Using Serial Blocks

This example shows how to use the Serial Configuration, Serial Receive, and Serial Send blocks to communicate with an Arduino®. In this example, you send a read command to an Arduino Uno using the Serial Send block. The Arduino sends back the signal read from its analog pins to the Serial Receive block.

Setup

Plug in an Arduino Uno to your computer and load the following program using the Arduino IDE. Configure the code to use your port settings.

//Delay (ms) between consecutive scans in streaming mode
int interScanDelay = 20;
int inputPin1 = A2;
int sensorValue1 = 0;
int inputPin2 = A3;
int sensorValue2 = 0;
int inByte = 0;

void setup() {
Serial.begin(9600);
}

void loop() {
    if (Serial.available() > 0) {
        inByte = Serial.read();
        switch (inByte) {
            case '2':
                //Read and send sensor values from Arduino board
                sensorValue1 = analogRead(inputPin1);
                Serial.write(sensorValue1);
                sensorValue2 = analogRead(inputPin2);
                Serial.write(sensorValue2);
                delay(interScanDelay);
            break;
            default:
            break;
          }
     }
}

The INO file is also included in this example.

On-Demand Read from Server

This model uses the Serial Send block to send a command to the Arduino to return some data. The Serial Receive block reads the returned data.

Use the following command to open the model.

open_system('demoinstrsl_Serial_read_binary');

Use the following command to close the model.

close_system('demoinstrsl_Serial_read_binary');

Results

The INO program is configured to read values from the analog pins (A2 an A3) on the Arduino. The output that you see in the model depends on the type of sensor attached to the analog pins of your Arduino.

See Also

| |