In this tutorial, we are going to set up Bluetooth communication between Arduino Due and Raspberry Pi 4B. HC06 is the Bluetooth device.
Task: The Raspberry Pi transmits a signal to the Arduino and meanwhile the Arduino sends the voltage data to the Raspberry Pi.
Step 1: Initiate the HC06
Please run the following commands to install the library in the Raspberry Pi
1) sudo apt-get install pi-bluetooth
2) sudo apt-get install bluetooth bluez blueman
After that, you have to restart the Raspberry Pi. Look for the Bluetooth manager icon
Search the BT manager logo |
Search the HC06 |
Bluetooth connection = OK |
Write down the dev address
Step 2: Run the python code in the Raspberry Pi
Step 2: Run the python code in the Raspberry Pi
import serial
import time
BTport = serial.Serial("/dev/rfcomm0", baudrate=9600)
#you may need to change the dev address
while True:
BTport.write(str.encode('1')) #send '1' to Arduino
data = BTport.readline() #receive data from Arduino
if data:
print(data.decode('utf-8'))
time.sleep(0.1)
Step 3: Upload code to the Arduino
int adcValue;
float voltage;
int ledPin = 13;
void setup()
{
Serial.begin(9600); // baud rate for the serial BT communication
pinMode(ledPin,OUTPUT);
}
void loop()
{
adcValue = analogRead(A0); // A0 port
voltage = adcValue * (3.3 / 1023.0);// Calculate voltage
// listen for the data from raspberry pi
if ( Serial.available() > 0 )
{
// read a numbers from serial port
int inputVal = Serial.parseInt();
if (inputVal > 0)
{
Serial.print(voltage);
Serial.println(String(inputVal));
// If receive signals from RPi, the LED 13 will be turned on
blinkLED(inputVal);
}
}
}
void blinkLED(int inputVal)
{
if(inputVal==1)
{
digitalWrite(ledPin, HIGH);
}
if(inputVal==2)
{
digitalWrite(ledPin, LOW);
}
if(inputVal==3)
{
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
}
}
Let's test the system!
When you type '1' in "str.encode('1')" in the Raspberry Pi, the LED 13 in the Arduino will light up.
When you type '2' in "str.encode('2')" in the Raspberry Pi, the LED 13 in the Arduino will be turned off.
When you type '3' in "str.encode('3')" in the Raspberry Pi, the LED 13 in the Arduino will flash.
When you rotate the rheostat, the variation of voltage will appear on the Raspberry Pi's screen
Comments
Post a Comment