Arduino Yun architecture for Wi-Fi connectivity, Arduino Yun Wi-Fi, Bridge library, Linux network configuration

Automatically Connect with Wifi SSID using Arduino YUN

2.5K Views
40
700
60
25
60
PCBWay

Hello friends! In this tutorial, we will configure an Arduino Yún to connect to a known Wi-Fi network and understand how it should recover when that network temporarily disappears. We will separate one-time configuration from ordinary connection monitoring so that the board does not repeatedly restart its own network.

The original Yún combines an ATmega32U4 with an Atheros AR9331 running a Linux-based system. The Linux side manages Wi-Fi, while an Arduino sketch can communicate with it through the Bridge library. That arrangement is different from an ordinary sketch controlling a Wi-Fi shield directly.

We will first save the intended network profile, then inspect connection status from the Arduino side. Along the way, we will correct several misunderstandings in the earlier example, including the difference between scanning for networks, joining a configured SSID and proving that an application server is reachable.

Arduino Yun architecture for Wi-Fi connectivity, Arduino Yun Wi-Fi, Bridge library, Linux network configuration
Figure: Arduino Yun architecture for Wi-Fi connectivity.

Understand Which Processor Controls Wi-Fi

The ATmega32U4 runs the Arduino sketch and handles the microcontroller I/O. The AR9331 runs the Linux networking environment. Arduino's original Yún introduction explains the division between the AVR and Linux processors and the Bridge connection between them.

The Wi-Fi and Ethernet interfaces belong to the Linux side. The USB host interface also belongs to that side; it is not the ATmega32U4's native USB connection used for the Arduino programming and serial interface. Keeping these two USB roles distinct helps when deciding which processor can access a device.

Linux is a separate operating-system environment on this board. It should not be described as the operating system normally used by Apple computers. For this project, its relevant role is managing network configuration and running processes requested through Bridge.

If you need a board introduction, begin with getting started with Arduino Yún. Also identify whether you have the original Yún, a Yún Rev2 or a Yún Shield, because setup instructions and installed firmware can differ.

Arduino Yun Bridge communication between AVR and Linux processors, Arduino Yun Wi-Fi, Bridge library, Linux network configuration
Figure: Arduino Yun Bridge communication between AVR and Linux processors.

What Automatic Connection Actually Means

A configured Wi-Fi client remembers the intended SSID and authentication settings. Its networking software attempts to associate with that network when it is available. This is different from selecting an arbitrary nearby network merely because its signal appears in a scan.

Scanning discovers advertised networks. Authentication establishes whether the client has the required credentials. Association establishes the wireless link, and IP configuration supplies the addressing needed for communication. An application request then tests a higher layer still.

StageWhat success establishesWhat it does not establish
SSID appears in a scanThe network can be observedThe password is correct
Wireless associationThe client joined an access pointA usable IP address was obtained
IP configurationThe interface has addressingThe intended server is responding
Successful application requestThat request reached its serviceEvery future request will succeed

The earlier sketch printed Connected after launching a script. That only showed that execution reached a print statement. A process being launched, or even returning successfully, is not the same as confirming association, DHCP completion and application connectivity.

Prepare the Board and Development Environment

Select the board package and target appropriate to your Yún in the Arduino IDE. Use a compatible Bridge library. The old statement that only Arduino IDE 1.5.5 could compile Yún sketches was a historical setup instruction, not a permanent version requirement.

Start with a reliable USB connection for programming and diagnostics. Network changes can disconnect a Wi-Fi programming session, so keep a local management route available while configuring the board. Verify that the Linux side has finished booting before interpreting an unavailable Bridge service as a radio failure.

Record the installed firmware version and its supported wireless configuration method. The general OpenWrt configuration concepts remain useful, but modern examples may use interface names or utilities that do not exist on an older Yún image.

Save the Known Wi-Fi Network Once

Use the board's configuration panel or the appropriate first-configuration example to select your own network and enter its credentials. Arduino's Yún Rev2 documentation identifies its web panel and YunFirstConfig workflow; use the corresponding instructions for the hardware and firmware you have.

  1. Open the board's configuration interface through its current management connection.
  2. Select client or station operation for joining an existing access point.
  3. Choose the intended SSID, preserving its exact spelling and capitalization.
  4. Select an authentication method supported by both the board and access point.
  5. Enter the network password through the configuration interface.
  6. Save and apply the configuration.
  7. Allow time for wireless association and IP address assignment.
  8. Confirm the resulting address and management access before proceeding.

Do not weaken the router's security simply to force compatibility with an old image. Identify the board's supported configuration and use a suitable network arrangement. The purpose is to join a network you control or are authorized to use, not to select whichever nearby SSID is easiest to connect to.

Once saved, the profile belongs to the Linux networking configuration. It should not need to be rewritten from the AVR every twenty seconds. Repeated commits can cause unnecessary storage writes, while repeated network restarts interrupt otherwise healthy communication.

Understand UCI before editing it directly

OpenWrt uses UCI configuration sections to describe wireless devices and interfaces. Its wireless configuration reference distinguishes the radio device from a wireless interface. A station interface is not necessarily the first anonymous section in every installation.

The old script assumed wireless.@wifi-iface[0] and modified network.lan without first identifying the active configuration. On another image, that can alter the wrong interface or disrupt the management connection. Inspect the actual board configuration before adapting any command-line example.

If you already manage the board through its Linux shell, the following read-only queries can help identify the first wireless section. They do not display the stored key or change the network. Repeat with the appropriate section index only when your configuration contains additional interfaces.

uci -q get wireless.@wifi-iface[0].mode
uci -q get wireless.@wifi-iface[0].ssid
uci -q get wireless.@wifi-iface[0].network

The network association returned by the last query identifies a logical network section, which may differ from the kernel device name. Names such as lan, wan and wlan0 describe different concepts and should not be substituted for one another without checking.

Monitor Linux Network Status from an Arduino Sketch

After the saved connection works, use Bridge to observe it. The sketch below requests status from the Linux ifstatus utility and forwards its output to the USB Serial Monitor. It performs a diagnostic query rather than restarting Wi-Fi.

First confirm that /sbin/ifstatus exists on your installed firmware and determine the logical network name associated with your station interface. Replace the example name below accordingly. If the utility is absent, use that firmware's supported status command rather than repeatedly launching a nonexistent program.

#include <Bridge.h>
#include <Process.h>

const char networkName[] = "lan"; // Replace after inspecting your board.
const unsigned long checkIntervalMs = 30000UL;
Process statusProcess;
unsigned long lastStarted = 0;
bool queryActive = false;
bool firstQuery = true;

void setup() {
  Serial.begin(9600);
  Bridge.begin();
  Serial.println("Bridge ready; network status is checked separately.");
}

void loop() {
  if (queryActive) {
    while (statusProcess.available()) {
      Serial.write(statusProcess.read());
    }
    if (!statusProcess.running()) {
      while (statusProcess.available()) {
        Serial.write(statusProcess.read());
      }
      Serial.print("Status command exit code: ");
      Serial.println(statusProcess.exitValue());
      statusProcess.close();
      queryActive = false;
    }
  }

  const unsigned long now = millis();
  if (!queryActive &&
      (firstQuery || now - lastStarted >= checkIntervalMs)) {
    firstQuery = false;
    lastStarted = now;
    statusProcess.begin("/sbin/ifstatus");
    statusProcess.addParameter(networkName);
    statusProcess.runAsynchronously();
    queryActive = bool(statusProcess);
    if (!queryActive) Serial.println("Could not start status command");
  }
}

The Bridge library's Process interface provides asynchronous execution, status and output access. Here, the sketch waits for one query to finish before launching another. It does not accumulate an unlimited number of background processes when the Linux side responds slowly.

Read the returned status according to your firmware's output format. An interface marked up with an assigned address is useful evidence, but it still does not establish that a remote application service is reachable. The printed process exit code describes the status command, not a universal Internet-connectivity result.

This diagnostic sketch intentionally avoids storing the Wi-Fi password in the AVR program or printing it over serial. It also avoids constructing a shell script by concatenating an SSID and password. Characters such as spaces, quotes and dollar signs can change the meaning of an incorrectly quoted shell command.

Why Repeated Network Restarts Are a Poor Reconnection Strategy

The earlier loop rewrote a script, committed settings and restarted networking repeatedly. That can interrupt association or DHCP before either has time to finish. A board may appear unable to remain connected because the recovery code keeps tearing down its own connection.

Configuration and recovery should have different responsibilities. Configuration changes a persistent profile when the user intends to change networks. Ordinary recovery first allows the Linux network manager and wireless client to use that existing profile.

If a connection remains unavailable, collect evidence before escalating. A missing access point, wrong credentials, unavailable DHCP server and unreachable application server require different responses. Restarting the radio cannot fix every one of them.

Archived Arduino Yun Wi-Fi configuration flowchart, Arduino Yun Wi-Fi, Bridge library, Linux network configuration
Figure: Archived Arduino Yun Wi-Fi configuration flowchart.

The archived flowchart shows the earlier setup-and-repeat approach. Use it as historical context for the original article. The revised flow is: configure once, observe status, retry the application when appropriate and escalate only after a defined persistent failure.

Design a Bounded Recovery Policy

A practical application can maintain states such as starting, waiting for network, online and waiting to retry. Each state should have a clear entry condition and a time limit where appropriate. Avoid using one Connected flag to represent every layer of the system.

For an illustrative retry schedule, wait 5 seconds after the first application failure, then 10, 20 and 40 seconds, with a maximum interval of 60 seconds. This reduces repeated requests during a longer outage. Add a small randomized component when many devices might reconnect together.

Reset the retry schedule after sustained success rather than after merely launching another request. Otherwise, a device that never completes useful communication can repeatedly return to its fastest retry interval.

If an interface restart is eventually justified, target the known interface using the supported procedure for that firmware. Rate-limit the action and record its reason. Do not repeatedly restart all networking because one external server is unavailable.

Preserve measurements during an outage

Automatic reconnection does not automatically prevent data loss. If your sketch samples a sensor while the network is unavailable, decide whether to buffer, summarize or discard those samples. The available memory and the value of the data determine the appropriate policy.

For example, a 32-byte record collected once per second requires 115,200 bytes for one hour, before file-system or message overhead. That exceeds the small AVR's internal RAM budget. A longer buffer belongs in suitable Linux-side storage or another storage device, with a defined capacity and retention policy.

Attach sequence numbers or timestamps to uploaded records. After a reconnect, the server can distinguish a delayed record from a new one and detect duplicates if a previously submitted request is retried.

Test Disconnection and Recovery Deliberately

  1. Confirm a normal connection and a successful request to the intended service.
  2. Temporarily disable the test access point and observe the board's state.
  3. Keep the outage long enough to exercise the retry schedule.
  4. Restore the access point without resetting the Yún.
  5. Observe association, address assignment and application recovery separately.
  6. Repeat with the application server unavailable while Wi-Fi remains working.
  7. Restart the board and confirm that its saved network profile remains available.

The second failure case is important. If Wi-Fi and IP addressing are healthy but the server is down, a well-designed application should retry its service request rather than continually reset the radio. A connection test must identify the failure layer it actually measures.

Also test a wrong credential in a controlled configuration exercise. Repeatedly retrying an incorrect password will not eventually make it correct. Report a configuration problem and preserve a usable management route so that it can be fixed.

Keep diagnostics useful during a long outage

A diagnostic log should record state changes and meaningful failures rather than printing the same disconnected line hundreds of times. Include the elapsed time since the last successful application exchange and the current retry interval. This lets you distinguish a brief interruption from a device that has remained offline for an hour.

Do not include passwords in diagnostic output. Be selective when copying configuration files or command output into a public support request, because complete wireless configuration can contain credentials. The read-only queries above deliberately request individual non-key fields rather than dumping the whole configuration.

The demonstration sketch streams status text to avoid keeping a large response in the AVR's small memory. If you need automated decisions, parse the required status fields on the Linux side and return a compact, documented result to the AVR. A small result such as a state code and address is easier to validate than an unrestricted JSON document on a memory-constrained microcontroller.

Asynchronous execution prevents the sketch from deliberately waiting for a process to finish in one blocking call, but it is not a hard real-time guarantee. Bridge communication itself and serial output still take time. A production monitor also needs a defined response if the Linux status process or Bridge service stops responding.

Distinguish a network reset from a board reset

The Yún contains more than one processing domain, so resetting the Arduino sketch is not the same operation as restarting Linux networking. Choose the narrowest recovery action that addresses the observed fault. Rebooting the whole board for every failed upload interrupts local sensing and discards any volatile state.

For an application that must keep operating offline, test its local behavior while Linux is still booting. Decide whether the AVR should begin essential I/O work before waiting for Bridge, or whether startup must wait for a service. The simple diagnostic sketch initializes Bridge immediately because observing Linux status is its only task.

Finally, document the management path used to recover from a mistaken configuration. A known USB or wired route makes experimentation much easier than relying entirely on the Wi-Fi connection being edited. This is especially useful when a saved profile points to an access point that is no longer available.

Troubleshooting and Practical Review

ObservationFirst area to inspect
Bridge does not initializeLinux boot state and Bridge service compatibility
SSID is visible but association failsCredentials and supported authentication settings
Associated but no usable addressDHCP and logical-interface configuration
Address exists but service failsRouting, name resolution and the service itself
Connection drops at regular intervalsA sketch or script repeatedly restarting networking
Status command failsUtility path and logical network name on this firmware

The Yún's two-processor design is useful when a small control program needs Linux networking services. Its extra software layer also means that AVR, Bridge, Linux and network states must be distinguished. A reliable project observes those states and responds deliberately rather than assuming that running a shell command proves connection success.

Keep a record of the firmware, logical interface name and successful recovery test with the project. Those details make later troubleshooting more useful than a screenshot that only shows a Connected message without identifying what was checked.

Frequently Asked Questions

Does Bridge.begin connect to an SSID?

It initializes communication with the Linux side. The Linux network configuration determines which Wi-Fi network the board attempts to join.

Should the sketch save credentials on every loop?

No. Save a profile when configuration changes. Ordinary monitoring and recovery should use that stored configuration.

Why does the example query lan?

It is an explicit placeholder for the logical network name. Inspect your own board and replace it if the station interface belongs to another network section.

Is an IP address enough to confirm Internet access?

No. Address assignment is one stage. Test the actual service your application needs, and interpret the result at that layer.

Will reconnection preserve every sensor sample?

Only if the application has an appropriate buffering and retry design. Rejoining Wi-Fi does not recover measurements that were never stored.


Comments

5

Join the conversation

1 reply
1 reply
1 reply
Reply2.1.1
Replying to syedzainnasir

thanks for reply
i am actually monitoring a machine in a factory. i am logging the data to SD card continuously.
as the nature of the factory the WiFi signal gets lost intermediately.
i was trying if the WiFi signal get lost it shouldn't affect or delay the SD logging system and the WiFi should auto reconnect.
in my understanding the above code will continuously reconnect to WiFi and might delay SD logging.
please advice