Im working on a project to build an autonomous lego car. Im running into some problems here, and i could use some help. Right now, im struggling to send and receive data from RPI (4) to Arduino (Nano). In my case, the Nano is the slave and RPI the master. I want to simulate the PiCamera until i receive mine, so i tought to use the keyboard like that: If i press "W" key GoForward() If i press "S" key GoBackwards()
The problem is that im not sure how to use bus.write_byte to send data to my arduino, which then set my two motors in any direction
This is my Arduino code #slave:
Some of the comments are in Romanian, ignore them. I translated the useful ones
#include <Wire.h>
//pinii motoarelor atasati la L298N
//motors pins attached to L298N
#define M1_vit 6 //ENA
#define M1_d1 7 //in1
#define M1_d2 8 //in2
#define M2_vit 9 //ENB
#define M2_d2 10 //in4
#define M2_d1 11 //in3
void setup() {
//intram pe i2c pe adresa 8
//using the addres 8
Wire.begin(0x8);
Wire.onReceive(SemnaleMotoare);
//setam pinii atasati L298N ca OUTPUT
//motors pins attached to L298N as OUTPUTS
pinMode(M1_vit, OUTPUT);
pinMode(M1_d1, OUTPUT);
pinMode(M1_d2, OUTPUT);
pinMode(M2_vit, OUTPUT);
pinMode(M2_d1, OUTPUT);
pinMode(M2_d2, OUTPUT);
//oprim motoarele ca sa evitam orice problema
//turn off the engines
digitalWrite(M1_vit, LOW);
digitalWrite(M2_vit, LOW);
digitalWrite(M1_d1, LOW);
digitalWrite(M1_d2, LOW);
digitalWrite(M2_d1, LOW);
digitalWrite(M2_d2, LOW);
}
//functia folosita pentru primirea comenzilor de la RPI
//function used to receive data from RPI
void SemnaleMotoare(int cat)
{
while(Wire.available() )//wait for commands
{
char c = Wire.read();//catch the command as a char
if(c == "W")
{
GoForward();
}
else if(c == "S")
{
GoBackwards();
}
}
}
void GoForward ()
{
digitalWrite(M1_d1, HIGH);
digitalWrite(M1_d2, LOW);
digitalWrite(M2_d1, HIGH);
digitalWrite(M2_d2, LOW);
analogWrite(M1_vit, 255);
analogWrite(M2_vit, 255);
}
void GoBackwards()
{
digitalWrite(M1_d1, LOW);
digitalWrite(M1_d2, HIGH);
digitalWrite(M2_d1, LOW);
digitalWrite(M2_d2, HIGH);
analogWrite(M1_vit, 255);
analogWrite(M2_vit, 255);
}
void loop() {
delay(100); //nu face nmc asta, e pus la shto
}
And the RPI code is here as #master:
addr = 0X8 #adresa busului/bus addres
bus = SMBus(1) #obiect numit bus de tip SMBus indicand /dev/i2c-1
numb = 1
print("Apasa W pentru inainte sau S pentru inapoi")#press W for forward and S for backwards
while numb == 1:
motoare = input("---- ")#store the user input in motoare
if (motoare == "W" ):
print("INAINTE")#forward
print("")
bus.write_byte(addr,motoare);
elif (motoare == "S"):
print("INAPOI")#backwards
print("")
bus.write_byte(addr,motoare);
else:
numb = 0;
I would appreciate any help!