Raspberry Pi Quick Start
RaspberryPi 4 Model B
Simple communicate to Arduino code
Send and receive data via Serial
Quick Start
Pinout
Seconde Diagram:
Code BOX
what is a virtual environment and why you are asked to create one for most codes?
How to create and activate a virtual environment
Create
$ python3 -m venv venv-name
Activate
$ source venv-name/bin/activate
(venv-name) $
Install pakages in the virtual Environment
(venv-name) $ python -m pip install <package-name>
When you're done with the environment you'd better to diactivate it
(venv-name) $ deactivate
$
NOTE: If you want to get back to the created environment, just Return up to the ACTIVATED section.
Simple LED blink with RPi
install RPi.GPIO
***NOTE:*** install this module in virtual environment.
pip install RPi.GPIO
# Simple LED blink...
import RPi.GPIO as GPIO
import time
led_pin = 23
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)
blink_repeat = int(input("blink repeats >> "))
while(blink_repeat>0)
GPIO.output(led_pin, GPIO.HIGH)
time.sleep(1)
GPIO.output(led_pin, GPIO.LOW)
time.sleep(1)
blink_repeat -= 1
what is BCM in GPIO.setmode(GPIO.BCM)
There are two kinds of Input and Output pin numbering for the Raspberry pi. One is the BCM and the other is BOARD. Basically these pin numberings are useful for writing python script for the Raspberry Pi.
**GPIO BOARD**– This type of pin numbering refers to the number of the pin in the plug, i.e, the numbers printed on the board, for example, P1. The advantage of this type of numbering is, it will not change even though the version of board changes.
**GPIO BCM**– The BCM option refers to the pin by “Broadcom SOC Channel. They signify the Broadcom SOC channel designation. The BCM channel changes as the version number changes.
**Broadcom SOC Channel**– BCM refers to the “Broadcom SOC channel” number, which is the numbering inside the chip which is used on the Raspberry Pi. These numbers changed between board versions as you can see in the previous tables for the 26-pin header type 1 versus 2, and or not sequential.
***NOTE:***
The BCM numbers changed between versions of the Pi1 Model B, and you’ll need to work out which one you have guide here. So it may be safer to use the BOARD numbers if you are going to use more than one Raspberry Pi in a project.
In a nutshell, BCM pins maybe differ in raspberrypi's boards but Board pins are the same.
[Further details](https://iot4beginners.com/difference-between-bcm-and-board-pin-numbering-in-raspberry-pi/)
Connecting Raspberry pi to Arduino
You can simply send data via USB cable.
Or use GPIO pins.. BUT it's recommended to use USB port.
NOTE: Raspbery pi operating at 3.3v, so if it's connected to Arduino a logic level converter should be used.
Detecting Arduino Board:
$ ls /dev/tty*
NOTE: when Arduino is connected /dev/ttyACM0 or /dev/ttyUSB0 may appear in the list. BUT keep in mind that the number maybe different.
To find ACM in the list of ports:
from os import system
print("Connected devices include 'ACM' are: ")
system("ls /dev/tty* | grep ACM")
Hardware permission for Serial access
To avoid Errorssuch as serial.serialutil.SerialException: [Errno 13] could not open port /dev/ttyACM0: [Errno 13] Permission denied: ‘/dev/ttyACM0’ run the following code block to make sure you have access to the port:
$ sudo adduser your_username dialout
Once you've been added the dialgroup you need to REBOOT your RPi or just logout nad login again to apply changes.
Use pyserial to use Serial interface with Python
NOTE: Do not forget to install the package in the Virtual Environment that you've created.
$ python3 -m pip install pyserial
Further information for RPi prmissions
Simple communicate to Arduino
Arduino code:
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serila.println("Hi to you");
delay(500);
}
RPi code:
from os import system
import serial
def ReceivedData(port):
ser = serial.Serial(port, 9600, timeout=1)
ser.reset_input_buffer()
while True:
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8').rstrip()
return line
system("ls /dev/tty* | grep ACM > command_output.txt")
with open ("./command_output.txt", 'r') as port_name:
port = port_name.readline()
# There is a '\n' at the end of the port that has to be removed
port = port.strip()
if len(port)>0:
arduino_port = port
data = ReceivedData(arduino_port)
print(data)
else:
print("Error: No Device is connected")
NOTE: if the error
in open
raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 13] could not open port /dev/ttyACM0: [Errno 13] Permission denied: '/dev/ttyACM0'
pops up, run the following code block
$ sudo chmod 666 /dev/ttyACM0
Send and Receive data via Serial port
Arduino code
#define LED_pin 13
void setup()
{
Serial.begin(9600)
pinMode(LED_pin, OUTPUT);
}
void loop()
{
String command = ""
while(Serial.available()>0)
{
command = Serial.readString();
if (command == "LED on")
{
Serial.println("LED is on");
digitalWrite(LED_pin, HIGH);
}
else if(command == "LED off")
{
Serial.println("LED is off");
digitalWrite(LED_pin, LOW);
}
}
}
RPI code
from os import system
from serial import Serial
import time
validCommands = ['LED on','LED off']
def discoverConnectedPort():
## find 'ACM' in the list of ports and write it in a txt file
system("ls /dev/tty* | grep ACM > command_output.txt")
with open ("./command_output.txt", 'r') as grepOutputFile:
portName = grepOutputFile.readline()
# There is a '\n' at the end of the port that has to be removed
portName = portName.strip()
## it returns a string like '/dev/ttyACM1'
return portName
with Serial(port = discoverConnectedPort(), baudrate= 9600, timeout=1) as arduino:
if arduino.isOpen():
# split the port name string by / and create a list of it, print the last element of it
# /dev/ttyACM1 -> ['dev', 'ttyACM1']
print("{} connected!".format(arduino.port.split(sep='/')[-1]))
while True:
command = input("your command >> ")
if (command == 'exit'):
exit()
time.sleep(0.1) #wait for serial to open
# Encode the command to utf-8
arduino.write(command.encode())
if command in validCommands:
# wait until something is in the buffer
while arduino.inWaiting()==0: pass
# if there is more that 0 byte in the buffer, read it
if (arduino.inWaiting() > 0):
# There is a '\n' at the end of the message that has to be removed
message = arduino.readline().decode('utf-8').rstrip()
print(message)
# reset input buffer
arduino.flushInput()
NOTE: if you want to send muliple lines to RPi, you need to change message = arduino.readline().decode('utf-8').rstrip()
to th efollowing code block
for line in arduino.readlines():
message = line.decode('utf-8').rstrip()
print(message)
Remote Connection (via SSH)
Find your Raspberry pi Username and IP (host ip)
Username:
$ whoami
Host IP:
$ hostname -I
Note: You should enabled port 22 before trying to connect to your pi from the other device.
HOW?
$ apt install ufw
$ ufw allow ssh
$ ufw enable
Check the status of your firewall:
$ ufw status
Then, You can ssh to your PI:
$ ssh [username]@[IP address]
Congratulations!
If you got this Error message:
ssh: connect to username@hostname_id port 22: Connection refused
make sure you have installed openssh-server
.
1- To install it
$ sudo apt install openssh-server
2- check the status of ssh service, make ssh service start.
$ sudo service ssh status
$ sudo service ssh start
```
3- Check whether port 22 in that system is blocked by iptables. Just allow port in iptables and then check.
```shell
$ sudo iptables -A INPUT -p tcp --dport ssh -j ACCEPT
4- Else change port number of ssh from 22 to 2222 by editing
$ vi /etc/ssh/sshd_config
$ /etc/init.d/ssh restart.
Hope you Enjoy!
Camera
First you need to check if camera is connected properly.
Get a fame
$ raspistill -o test.jpg
If you get mmal: No data received from sensor.
Check all connections, including the Sunny one on the camera board
error:
Make sure that the sunny connector is firmly attached. You jist need to remove
the sunny connector and fixed in the same place
.
Then camera world work fine.
The sunny connector