Smart Cities - Tiny House at Home: Difference between revisions

From Sensors in Schools
Jump to navigation Jump to search
No edit summary
 
(9 intermediate revisions by the same user not shown)
Line 281: Line 281:
* VNC Viewer allows you to save connections for easy access later.
* VNC Viewer allows you to save connections for easy access later.
* Click File > New Connection in VNC Viewer and save the remote Pi's details.
* Click File > New Connection in VNC Viewer and save the remote Pi's details.
=Log into another Pi on the same Network using SSH=
==Enable SSH on the Target Pi==
* Check if SSH is Enabled:
* On the target Pi, open the terminal and run:
<syntaxhighlight lang="bash">
sudo systemctl status ssh
</syntaxhighlight>
If SSH is not running, enable it with:
<syntaxhighlight lang="bash">
sudo systemctl enable ssh
sudo systemctl start ssh
</syntaxhighlight>
* Alternatively, Enable SSH via Raspberry Pi Configuration:
* Open the Raspberry Pi Configuration tool:
<syntaxhighlight lang="bash">
sudo raspi-config
</syntaxhighlight>
Go to Interfacing Options > SSH and select Enable.
==2. Find the Target Pi’s IP Address==
Run the following command on the target Pi to get its IP address:
<syntaxhighlight lang="bash">
hostname -I
</syntaxhighlight>
Example output:
<syntaxhighlight lang="bash">
192.168.1.20
</syntaxhighlight>
This is the IP address you'll use to connect.
If you’re unsure of the IP address, you can use a network scanning tool like nmap from another Pi:
<syntaxhighlight lang="bash">
sudo apt install nmap  # If not already installed
nmap -sn 192.168.1.0/24
</syntaxhighlight>
Replace 192.168.1.0/24 with your network’s IP range. Look for the Pi's hostname (e.g., raspberrypi.local) in the results.
==3. Log into the Target Pi==
On your source Pi (the one you're connecting from), use the ssh command:
<syntaxhighlight lang="bash">
ssh pi@192.168.1.20
</syntaxhighlight>
Replace 192.168.1.20 with the target Pi's IP address.
Authenticate:
* You'll be prompted for the password of the pi user on the target Pi (default password is raspberry unless it has been changed).
Success:
* After entering the correct password, you'll have terminal access to the target Pi.
==4. Using Hostnames Instead of IP Addresses==
If both Raspberry Pis are on the same network, you can often use the hostname instead of the IP address. The default hostname for a Raspberry Pi is raspberrypi.local.
Connect with:
<syntaxhighlight lang="bash">
ssh pi@raspberrypi.local
</syntaxhighlight>
If the hostname was changed during setup, use that instead (e.g., mycustompi.local).
==5. Optional: Set Up SSH Key-Based Authentication==
To avoid entering the password every time, you can set up SSH key-based authentication:
Generate an SSH Key on the Source Pi:
<syntaxhighlight lang="bash">
ssh-keygen -t rsa
</syntaxhighlight>
* Press Enter to accept the default file location and leave the passphrase empty for no password.
* Copy the SSH Key to the Target Pi:
<syntaxhighlight lang="bash">
ssh-copy-id pi@192.168.1.20
</syntaxhighlight>
* Enter the target Pi's password when prompted.
* Log in Without Password:
* From now on, you can log in without entering the password:
<syntaxhighlight lang="bash">
ssh pi@192.168.1.20
</syntaxhighlight>
Troubleshooting
* Connection Refused: Ensure SSH is enabled and the target Pi’s IP address is correct.
* Firewall Issues: Check that no firewall rules are blocking SSH (unlikely on default Raspberry Pi setups).
* Multiple Pis with the Same Hostname: Change the hostname of each Pi to avoid conflicts:
<syntaxhighlight lang="bash">
sudo raspi-config
</syntaxhighlight>
Go to System Options > Hostname, and set a unique name.


=Setting Static IP Address on Raspberry Pi=
=Setting Static IP Address on Raspberry Pi=
Line 332: Line 441:


[[File:Screenshot 2024-12-15 at 2.14.43 PM.png | 900px]]
[[File:Screenshot 2024-12-15 at 2.14.43 PM.png | 900px]]
=How to set a Static IP Address using the Terminal=
* You can set a fixed IP address for a Raspberry Pi without relying on your router by editing the network configuration file directly on the Raspberry Pi.
* The instructions are generally the same for the Raspberry Pi 3 and Pi 4, as both use similar versions of Raspberry Pi OS, which is based on Debian Linux.
==Steps to Set a Fixed IP Address==
* Determine Network Details:
* Run the following command to find your current network details:
<syntaxhighlight lang="bash">
ip addr
</syntaxhighlight>
Note the following:
* Interface name (e.g., eth0 for Ethernet, wlan0 for Wi-Fi).
* Current IP address, subnet mask, gateway, and DNS servers.
==Example network details:==
<syntaxhighlight lang="bash">
IP address: 192.168.1.50
Subnet mask: 255.255.255.0
Gateway: 192.168.1.1
DNS Server: 8.8.8.8 (Google DNS)
</syntaxhighlight>
Edit the DHCP Client Configuration File: Use sudo to edit the dhcpcd.conf file:
<syntaxhighlight lang="bash">
sudo nano /etc/dhcpcd.conf
</syntaxhighlight>
Add Static IP Configuration: Scroll to the bottom of the file and add the following lines, replacing values with your network details:
For Ethernet (eth0):
<syntaxhighlight lang="bash">
interface eth0
static ip_address=192.168.1.50/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8
</syntaxhighlight>
For Wi-Fi (wlan0):
<syntaxhighlight lang="bash">
interface wlan0
static ip_address=192.168.1.50/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8
</syntaxhighlight>
* Replace 192.168.1.50 with your desired fixed IP address.
* /24 indicates the subnet mask (255.255.255.0).
* Replace 192.168.1.1 with your network gateway.
* Replace 8.8.8.8 with your preferred DNS server.
==Save and Exit:==
* Press Ctrl+O to save the file.
* Press Ctrl+X to exit the editor.
==Restart the DHCP Service:==
<syntaxhighlight lang="bash">
sudo systemctl restart dhcpcd
</syntaxhighlight>
==Verify the Fixed IP:==
Check if the new static IP is active:
<syntaxhighlight lang="bash">
ip addr
</syntaxhighlight>
==Test connectivity:==
<syntaxhighlight lang="bash">
ping -c 4 8.8.8.8
</syntaxhighlight>
==Differences Between Pi 3 and Pi 4==
* The process is identical for both Raspberry Pi 3 and Raspberry Pi 4.
* The only potential difference is the network interface names:
* Pi 3: eth0 for Ethernet, wlan0 for Wi-Fi.
* Pi 4: May use eth0 for Ethernet, but sometimes interfaces can have predictable names like enx... for Ethernet and wlx... for Wi-Fi. You can confirm the interface name using the ip addr command.
==Additional Notes==
* If you switch between networks, ensure that the static IP address is unique and does not conflict with other devices on the same network.
* To revert to dynamic IP assignment, remove or comment out the added lines in /etc/dhcpcd.conf.
=How to copy files from one Pi to another using the Terminal=
To securely copy files from one Raspberry Pi to another on the same network, you can use the scp (secure copy) command in the terminal. Here's how:
==Prerequisites==
* Ensure SSH is enabled on both Raspberry Pi devices.
* You can enable SSH via raspi-config or the Raspberry Pi OS settings.
* Know the IP address or hostname of the target Raspberry Pi.
* Find it using hostname -I or ifconfig on the target Pi.
==Command Syntax==
The basic scp syntax is:
<syntaxhighlight lang="bash">
scp [options] source_file username@target_pi_ip:/destination_directory
</syntaxhighlight>
==Example Steps==
* From the Source Pi's Terminal:
* Copy a file from the source Pi to the target Pi:
<syntaxhighlight lang="bash">
scp myfile.txt pi@192.168.1.10:/home/pi/
</syntaxhighlight>
==Replace:==
* myfile.txt with the file you want to copy.
* pi with the target Pi's username.
* 192.168.1.10 with the target Pi's IP address or hostname.
* /home/pi/ with the destination directory on the target Pi.
* If the SSH key is not set up, you will be prompted for the password of the target Pi's user (pi in this case).
Copy an Entire Directory: Use the -r option to copy a directory recursively:
<syntaxhighlight lang="bash">
scp -r myfolder/ pi@192.168.1.10:/home/pi/
</syntaxhighlight>
Copy from the Target Pi to the Source Pi: Reverse the order of the source and destination paths:
<syntaxhighlight lang="bash">
scp pi@192.168.1.10:/home/pi/myfile.txt /home/pi/
</syntaxhighlight>
==Additional Options==
Use a Different Port: If the target Pi's SSH server uses a port other than the default 22, specify it with the -P option:
<syntaxhighlight lang="bash">
scp -P 2222 myfile.txt pi@192.168.1.10:/home/pi/
</syntaxhighlight>
Preserve File Permissions and Timestamps: Add the -p option:
<syntaxhighlight lang="bash">
scp -p myfile.txt pi@192.168.1.10:/home/pi/
</syntaxhighlight>
This method encrypts the data during transfer, ensuring secure file copying over the network.


=Interpreting Data from Arduino on Raspberry using Python=
=Interpreting Data from Arduino on Raspberry using Python=
== Installing python libraries==
* Install python libraries in the Virtual Environment.
* Enter the project folder '''env'''
* Activate the virtual environment
<syntaxhighlight lang="bash">
source bin/activate
</syntaxhighlight>
Enter the following command to install the serial, datetime and requests python libraries.
<syntaxhighlight lang="bash">
pip3 install serial pyserial datetime requests
</syntaxhighlight>
Verify the installation


<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
#!/usr/bin/env python3
pip list | grep pyserial
# dweet data
</syntaxhighlight>
 
==Python code to read serial data from the Arduino==
* Open the Arduino IDE and enter the following code.
* Save the file as '''serialReceive.py'''
* Run the code.
 
<syntaxhighlight lang="python">
 
import serial
import serial
import time
# Replace '/dev/ttyUSB0' with your device's port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
time.sleep(2)  # Wait for Arduino to reset
while True:
    if ser.in_waiting > 0:
        data = ser.readline().decode('utf-8').strip()
        print("Received:", data)
</syntaxhighlight>
==Python code to add Datetime==
<syntaxhighlight lang="python">
import serial
import time
import datetime
import datetime
# Replace '/dev/ttyUSB0' with your device's port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
time.sleep(2)  # Wait for Arduino to reset
while True:
    if ser.in_waiting > 0:
        data = ser.readline().decode('utf-8').strip()
        print("Received:", data)
        now = datetime.datetime.now()
        date_stamp = now.strftime("%Y-%m-%d %H:%M:%S")
        print(f'The current time is {date_stamp}')
           
        data = str(line) + "," + date_stamp + "\n"
        print(f'The data is =  {data}')
</syntaxhighlight>
==Python code Save data to a file==
<syntaxhighlight lang="python">
import serial
import time
import time
import requests
import datetime
 
# Replace '/dev/ttyUSB0' with your device's port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
time.sleep(2)  # Wait for Arduino to reset
 
while True:
    if ser.in_waiting > 0:
        data = ser.readline().decode('utf-8').strip()
        print("Received:", data)
 
        now = datetime.datetime.now()
        date_stamp = now.strftime("%Y-%m-%d %H:%M:%S")
        print(f'The current time is {date_stamp}')
           
        data = str(line) + "," + date_stamp + "\n"
        print(f'The data is =  {data}')


if __name__ == '__main__':
        f = open('/home/pi/<folder>/<filename>.txt','a')
    ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
        f.write(data)
    ser.reset_input_buffer()
         f.close()
    while True:
         print("The data has been written to the file greenhouse_data.txt")
         time.sleep(0.1)
         if ser.in_waiting > 0:
            line = ser.readline().decode('utf-8').rstrip()


</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 08:24, 25 December 2024

Raspberry Pi OS

  • Starting with a fresh install of the Raspberry Pi Debian Bookworm OS with desktop (64 bit).
  • Use the Raspberry Pi Imager to install the OS on a 16MB micro SD card.
  • Complete the set up and updates on the Raspberry Pi.

Install the Python IDE (not thonny) and the MQTT broker

  • Open the Terminal and enter these commands
sudo apt update
sudo apt -y full-upgrade 
sudo apt install -y idle3 arduino

Install Virtual Environment

  • These days Python must run in a virtual environment so that each user gets their own Python
  • The virtual environment has to be activated before each use
  • The linux prompt then changes from:
  • <username>@home:~ $ to (env) <username>@home:~ $
  • Create a virtual environment for Python called env in your /home/<username> directory.
    • In Linux (and other operating systems), a virtual environment is an isolated Python environment that allows you to install and manage Python packages separately from the system-wide Python installation.
    • This ensures that your Python projects have their own dependencies and versions of libraries without affecting or being affected by other projects or the global Python environment.
  • Enter the commands in the Terminal.
cd ~
python3 -m venv env


  • Activate the virtual environment with the commands.
cd ~/env
source bin/activate
  • Dectivate the virtual environment with the command.
deactivate

Configure the Python Idle3 shortcut to auto-activate the Python virtual environment

  • Click Raspberry | Programming
  • Right Click IDLE (using Python-3.11)
  • Click Properties | Desktop Entry
  • In the Command: field enter
/home/<username>/env/bin/python3.11 -m idlelib.idle

Arduino Uno - One Wire Temperature sensor

Frizing - Circuit diagram

  • In this circuit diagram the data line is connected to pin 2.
  • In the Arduino code below the data line is connected to pin 4.

One Wire Library installation

  • Select Sketch > Include Library > Manage Libraries
  • Wait for libraries to update. This may take 1-2 minutes.
  • In the search bar enter onewire and press Enter.

  • Install the One Wire library.
  • Use the One wire library with the author Paul Stoffregen

  • In this example the onewire library version 2.3.7 was installed.

Dallas Temperature Library installation

  • After installing the onewire library now enter Dallas as the search term.

  • In this instance version 3.9.0 of the DallasTemperature library was installed.

Arduino Uno Code

#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is conntec to the Arduino digital pin 4
#define ONE_WIRE_BUS 4

// Setup a oneWire instance to communicate with any OneWire devices
OneWire sensor_1_wire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature sensor 
DallasTemperature sensor1(&sensor_1_wire);

void setup(void)
{
  // Start serial communication for debugging purposes
  Serial.begin(9600);
  // Start up the library
  sensor1.begin();
}

void loop(void){ 
  // Call sensor1.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
  sensor1.requestTemperatures(); 
  
  Serial.print("Celsius temperature: ");
  // Why "byIndex"? You can have more than one IC on the same bus (pin). 0 refers to the first IC on the wire
  Serial.println(sensor1.getTempCByIndex(0)); 
  delay(1000);
}

Serial Monitor output

  • Temperature readings output to the Serial Monitor.

Setting up VNC Server

Check if VNC is Already Installed

In recent versions of Raspberry Pi OS, VNC comes pre-installed but might be disabled by default.

  • Check Installation:
  • Open a terminal on your Raspberry Pi.
  • Run:
vncserver --version

If VNC is installed, it will display the version. If not, install it (see step 3).

Enable VNC on Raspberry Pi

  • Open the Raspberry Pi Configuration Tool:
  • GUI: Go to Start Menu > Preferences > Raspberry Pi Configuration.
  • CLI: Run:
sudo raspi-config
  • Navigate to:
  • Interface Options > VNC > Enable
  • Confirm and exit the configuration tool.
  • Verify that the VNC service is running:
systemctl status vncserver-x11-serviced.service

If not running, start it:

sudo systemctl start vncserver-x11-serviced.service

Install VNC (if not installed)

If VNC isn't pre-installed:

  • Update the package list:
sudo apt update

Install VNC Server:

sudo apt install realvnc-vnc-server

Connect to the Raspberry Pi Using VNC Viewer

Find the Raspberry Pi’s IP Address:

hostname -I
  • Note the first IP address (e.g., 192.168.1.100).
  • Install VNC Viewer on your client device:
  • Download VNC Viewer for Windows, macOS, or Linux.
  • Open VNC Viewer on your client device and enter the Raspberry Pi’s IP address (e.g., 192.168.1.100).
  • Log in with your Raspberry Pi's credentials:
Username: pi
Password: (default is raspberry, or your custom password).

Optional: Configure VNC

  • Resolution Adjustment:

Edit /boot/config.txt to set a virtual desktop resolution:

sudo nano /boot/firmware/config.txt

Add or modify:

hdmi_force_hotplug=1
hdmi_group=2  # Set to 2 for DMT (monitor resolutions)
hdmi_mode=9   # Example: 800x600 @ 60Hz

This sets a resolution of 800x600. Save and reboot:

sudo reboot


hdmi_force_hotplug=1

  • Forces the Raspberry Pi to output HDMI signals even if no HDMI display is detected at boot.
  • This is essential when you're using VNC without a physical monitor connected.

Now you can access your Raspberry Pi 4 from any device on the same network!


Setting up VNC Viewer

To install a VNC client on a Raspberry Pi 4 and use it to access another Raspberry Pi with a VNC server already running, follow these steps:

Install VNC Viewer on the Raspberry Pi 4

  • Open a terminal on your Raspberry Pi 4.
  • Install the RealVNC Viewer (the VNC client):
sudo apt update
sudo apt install realvnc-vnc-viewer

Confirm the installation by running:

vncviewer --version

This should display the version of VNC Viewer installed.

Get the IP Address of the Remote Raspberry Pi

  • On the Raspberry Pi with the VNC server running, open a terminal.
  • Find its IP address by running:
hostname -I

Note the first IP address (e.g., 192.168.1.102).


Use VNC Viewer to Access the Remote Raspberry Pi

Launch VNC Viewer on your Raspberry Pi 4 by typing:

vncviewer
  • In the VNC Viewer window:
  • Enter the IP address of the remote Raspberry Pi (e.g., 192.168.1.102).
  • Click Connect.
  • Log in to the remote Raspberry Pi:
  • Enter the username and password of the remote Raspberry Pi.
  • After successful authentication, you will see the remote Raspberry Pi's desktop.


Save Connection for Future Use

  • VNC Viewer allows you to save connections for easy access later.
  • Click File > New Connection in VNC Viewer and save the remote Pi's details.

Log into another Pi on the same Network using SSH

Enable SSH on the Target Pi

  • Check if SSH is Enabled:
  • On the target Pi, open the terminal and run:
sudo systemctl status ssh

If SSH is not running, enable it with:

sudo systemctl enable ssh
sudo systemctl start ssh
  • Alternatively, Enable SSH via Raspberry Pi Configuration:
  • Open the Raspberry Pi Configuration tool:
sudo raspi-config

Go to Interfacing Options > SSH and select Enable.

2. Find the Target Pi’s IP Address

Run the following command on the target Pi to get its IP address:

hostname -I

Example output:

192.168.1.20

This is the IP address you'll use to connect. If you’re unsure of the IP address, you can use a network scanning tool like nmap from another Pi:

sudo apt install nmap  # If not already installed
nmap -sn 192.168.1.0/24

Replace 192.168.1.0/24 with your network’s IP range. Look for the Pi's hostname (e.g., raspberrypi.local) in the results.

3. Log into the Target Pi

On your source Pi (the one you're connecting from), use the ssh command:

ssh pi@192.168.1.20

Replace 192.168.1.20 with the target Pi's IP address.

Authenticate:

  • You'll be prompted for the password of the pi user on the target Pi (default password is raspberry unless it has been changed).

Success:

  • After entering the correct password, you'll have terminal access to the target Pi.


4. Using Hostnames Instead of IP Addresses

If both Raspberry Pis are on the same network, you can often use the hostname instead of the IP address. The default hostname for a Raspberry Pi is raspberrypi.local.

Connect with:

ssh pi@raspberrypi.local

If the hostname was changed during setup, use that instead (e.g., mycustompi.local).

5. Optional: Set Up SSH Key-Based Authentication

To avoid entering the password every time, you can set up SSH key-based authentication:

Generate an SSH Key on the Source Pi:

ssh-keygen -t rsa
  • Press Enter to accept the default file location and leave the passphrase empty for no password.
  • Copy the SSH Key to the Target Pi:
ssh-copy-id pi@192.168.1.20
  • Enter the target Pi's password when prompted.
  • Log in Without Password:
  • From now on, you can log in without entering the password:
ssh pi@192.168.1.20

Troubleshooting

  • Connection Refused: Ensure SSH is enabled and the target Pi’s IP address is correct.
  • Firewall Issues: Check that no firewall rules are blocking SSH (unlikely on default Raspberry Pi setups).
  • Multiple Pis with the Same Hostname: Change the hostname of each Pi to avoid conflicts:
sudo raspi-config

Go to System Options > Hostname, and set a unique name.

Setting Static IP Address on Raspberry Pi

To set a fixed IP address on a Raspberry Pi using the Advanced Options > Edit Connections graphical interface, follow these steps:

Open the Network Connections Settings

  • On your Raspberry Pi, open the desktop environment.
  • Click on the network icon in the top-right corner of the screen (usually looks like Wi-Fi or two arrows).
  • Select Advanced Options > Edit Connections.

Select the Connection to Configure

  • In the Edit Connections window, you'll see a list of network connections.
  • Find the connection you want to configure (e.g., your Ethernet or Wi-Fi connection).
  • Select the connection and click Edit.

Set a Static IP Address

  • Navigate to the IPv4 Settings tab.
  • Change the Method from Automatic (DHCP) to Manual.
  • Click the Add button to input the following details:
  • Address: The desired static IP address (e.g., 192.168.1.100).
  • Netmask: The subnet mask (usually 255.255.255.0 for home networks) or enter 24which is equivalent to 255.255.255.0.
  • Gateway: The IP address of your router (e.g., 192.168.1.1).
  • Enter the DNS server(s) under the DNS Servers field, separated by commas if multiple, or just enter the IP address of the router.
    • For example, 8.8.8.8, 8.8.4.4 (Google DNS) or your router's IP address.

Save and Apply

  • Click Save to save your changes.
  • Restart the network connection:
  • Disable and re-enable the connection from the network icon, or
  • Reboot the Raspberry Pi for the changes to take effect.

Verify the Static IP

  • Open a terminal and check your IP address:
hostname -I

Ensure it matches the static IP you configured. Test network connectivity:

ping 8.8.8.8

This will verify that your Pi can reach the internet.

Notes

  • Choose a static IP outside your router's DHCP range to avoid conflicts with dynamically assigned IPs. You can find the range in your router's settings (typically via 192.168.1.1 in a browser).
  • If you encounter connectivity issues, double-check the gateway and DNS server settings.

How to set a Static IP Address using the Terminal

  • You can set a fixed IP address for a Raspberry Pi without relying on your router by editing the network configuration file directly on the Raspberry Pi.
  • The instructions are generally the same for the Raspberry Pi 3 and Pi 4, as both use similar versions of Raspberry Pi OS, which is based on Debian Linux.

Steps to Set a Fixed IP Address

  • Determine Network Details:
  • Run the following command to find your current network details:
ip addr

Note the following:

  • Interface name (e.g., eth0 for Ethernet, wlan0 for Wi-Fi).
  • Current IP address, subnet mask, gateway, and DNS servers.

Example network details:

IP address: 192.168.1.50
Subnet mask: 255.255.255.0
Gateway: 192.168.1.1
DNS Server: 8.8.8.8 (Google DNS)

Edit the DHCP Client Configuration File: Use sudo to edit the dhcpcd.conf file:

sudo nano /etc/dhcpcd.conf

Add Static IP Configuration: Scroll to the bottom of the file and add the following lines, replacing values with your network details: For Ethernet (eth0):

interface eth0
static ip_address=192.168.1.50/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8

For Wi-Fi (wlan0):

interface wlan0
static ip_address=192.168.1.50/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8
  • Replace 192.168.1.50 with your desired fixed IP address.
  • /24 indicates the subnet mask (255.255.255.0).
  • Replace 192.168.1.1 with your network gateway.
  • Replace 8.8.8.8 with your preferred DNS server.

Save and Exit:

  • Press Ctrl+O to save the file.
  • Press Ctrl+X to exit the editor.

Restart the DHCP Service:

sudo systemctl restart dhcpcd

Verify the Fixed IP:

Check if the new static IP is active:

ip addr

Test connectivity:

ping -c 4 8.8.8.8

Differences Between Pi 3 and Pi 4

  • The process is identical for both Raspberry Pi 3 and Raspberry Pi 4.
  • The only potential difference is the network interface names:
  • Pi 3: eth0 for Ethernet, wlan0 for Wi-Fi.
  • Pi 4: May use eth0 for Ethernet, but sometimes interfaces can have predictable names like enx... for Ethernet and wlx... for Wi-Fi. You can confirm the interface name using the ip addr command.

Additional Notes

  • If you switch between networks, ensure that the static IP address is unique and does not conflict with other devices on the same network.
  • To revert to dynamic IP assignment, remove or comment out the added lines in /etc/dhcpcd.conf.


How to copy files from one Pi to another using the Terminal

To securely copy files from one Raspberry Pi to another on the same network, you can use the scp (secure copy) command in the terminal. Here's how:

Prerequisites

  • Ensure SSH is enabled on both Raspberry Pi devices.
  • You can enable SSH via raspi-config or the Raspberry Pi OS settings.
  • Know the IP address or hostname of the target Raspberry Pi.
  • Find it using hostname -I or ifconfig on the target Pi.

Command Syntax

The basic scp syntax is:

scp [options] source_file username@target_pi_ip:/destination_directory

Example Steps

  • From the Source Pi's Terminal:
  • Copy a file from the source Pi to the target Pi:
scp myfile.txt pi@192.168.1.10:/home/pi/

Replace:

  • myfile.txt with the file you want to copy.
  • pi with the target Pi's username.
  • 192.168.1.10 with the target Pi's IP address or hostname.
  • /home/pi/ with the destination directory on the target Pi.
  • If the SSH key is not set up, you will be prompted for the password of the target Pi's user (pi in this case).

Copy an Entire Directory: Use the -r option to copy a directory recursively:

scp -r myfolder/ pi@192.168.1.10:/home/pi/

Copy from the Target Pi to the Source Pi: Reverse the order of the source and destination paths:

scp pi@192.168.1.10:/home/pi/myfile.txt /home/pi/

Additional Options

Use a Different Port: If the target Pi's SSH server uses a port other than the default 22, specify it with the -P option:

scp -P 2222 myfile.txt pi@192.168.1.10:/home/pi/

Preserve File Permissions and Timestamps: Add the -p option:

scp -p myfile.txt pi@192.168.1.10:/home/pi/

This method encrypts the data during transfer, ensuring secure file copying over the network.

Interpreting Data from Arduino on Raspberry using Python

Installing python libraries

  • Install python libraries in the Virtual Environment.
  • Enter the project folder env
  • Activate the virtual environment
source bin/activate

Enter the following command to install the serial, datetime and requests python libraries.

pip3 install serial pyserial datetime requests

Verify the installation

pip list | grep pyserial

Python code to read serial data from the Arduino

  • Open the Arduino IDE and enter the following code.
  • Save the file as serialReceive.py
  • Run the code.
import serial
import time

# Replace '/dev/ttyUSB0' with your device's port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
time.sleep(2)  # Wait for Arduino to reset

while True:
    if ser.in_waiting > 0:
        data = ser.readline().decode('utf-8').strip()
        print("Received:", data)


Python code to add Datetime

import serial
import time
import datetime

# Replace '/dev/ttyUSB0' with your device's port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
time.sleep(2)  # Wait for Arduino to reset

while True:
    if ser.in_waiting > 0:
        data = ser.readline().decode('utf-8').strip()
        print("Received:", data)

        now = datetime.datetime.now()
        date_stamp = now.strftime("%Y-%m-%d %H:%M:%S")
        print(f'The current time is {date_stamp}')
            
        data = str(line) + "," + date_stamp + "\n"
        print(f'The data is =  {data}')

Python code Save data to a file

import serial
import time
import datetime

# Replace '/dev/ttyUSB0' with your device's port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
time.sleep(2)  # Wait for Arduino to reset

while True:
    if ser.in_waiting > 0:
        data = ser.readline().decode('utf-8').strip()
        print("Received:", data)

        now = datetime.datetime.now()
        date_stamp = now.strftime("%Y-%m-%d %H:%M:%S")
        print(f'The current time is {date_stamp}')
            
        data = str(line) + "," + date_stamp + "\n"
        print(f'The data is =  {data}')

        f = open('/home/pi/<folder>/<filename>.txt','a')
        f.write(data)
        f.close()
        print("The data has been written to the file greenhouse_data.txt")