So I am working on a project to establish CAN bus communication between raspberry pi 4 and arduino. Unfortunately, I don't have great success. So I already established connection between multiples raspberry pies and it is working perfectly. So to configure my raspberry pi I followed the steps of online tutorial. I added this lines in the /boot/config.txt:
dtoverlay=mcp2515-can0,oscillator=8000000,interupt=12
dtoverlay=spi-bcm2835-overlay
installed the can utilities and initiate the can using
sudo ip link set can0 up type can bitrate 500000
After that I created python code to control the receiving and sending of data to the CAN bus. Here is my code for sending data:
import time
import can
bustype = 'socketcan'
channel = 'can0'
bus = can.interface.Bus(channel=channel, bustype=bustype,bitrate=500000)
while True:
msg = can.Message(arbitration_id=2, data=[0, 0, 0, 0, 0, 0], is_extended_id=False)
bus.send(msg)
time.sleep(0.1)
</code></pre>
and here's is the one for receiving:
import time
import can
bustype = 'socketcan'
channel = 'can0'
bus = can.interface.Bus(channel=channel, bustype=bustype,bitrate=500000)
while True:
print(bus.recv())
time.sleep(0.1)
So for the arduino part I tried using UNO and Mega2560.
My connection on both boards is the same:
VCC --> 5V
GND --> GND
CS --> pin 10
SO --> pin12
SI --> pin11
SCK --> pin 13
INT --> pin 2
Tried multiple libraries on of them https://github.com/Seeed-Studio/Seeed_Arduino_CAN/blob/master/examples/recv_sd/recv_sd.ino
and the https://www.arduinolibraries.info/libraries/can. So I uploaded the example code to the arduino. Here it is:
#include
void setup() {
Serial.begin(9600);
while (!Serial);
Serial.println("CAN Sender");
// start the CAN bus at 500 kbps
// if (!CAN.begin(500E3)) {
// Serial.println("Starting CAN failed!");
// while (1);
// }
}
void loop() {
// send packet: id is 11 bits, packet can contain up to 8 bytes of data
Serial.print("Sending packet ... ");
CAN.beginPacket(0x12);
CAN.write('h');
CAN.write('e');
CAN.write('l');
CAN.write('l');
CAN.write('o');
CAN.endPacket();
Serial.println("done");
delay(1000);
// send extended packet: id is 29 bits, packet can contain up to 8 bytes of data
Serial.print("Sending extended packet ... ");
CAN.beginExtendedPacket(0xabcdef);
CAN.write('w');
CAN.write('o');
CAN.write('r');
CAN.write('l');
CAN.write('d');
CAN.endPacket();
Serial.println("done");
delay(1000);
}
and when i upload it to the Arduino Uno it gives "Starting CAN failed!", but on the Arduino Mega everything seems to work fine, but both times no data is received by the raspberry pi no matter if i use the python code or simple "candump can0" command. Tried it even with the receiving example :
#include
void setup() {
Serial.begin(9600);
while (!Serial);
Serial.println("CAN Receiver");
// start the CAN bus at 500 kbps
if (!CAN.begin(500E3)) {
Serial.println("Starting CAN failed!");
while (1);
}
}
void loop() {
// try to parse packet
int packetSize = CAN.parsePacket();
if (packetSize || CAN.packetId() != -1) {
// received a packet
Serial.print("Received ");
if (CAN.packetExtended()) {
Serial.print("extended ");
}
if (CAN.packetRtr()) {
// Remote transmission request, packet contains no data
Serial.print("RTR ");
}
Serial.print("packet with id 0x");
Serial.print(CAN.packetId(), HEX);
if (CAN.packetRtr()) {
Serial.print(" and requested length ");
Serial.println(CAN.packetDlc());
} else {
Serial.print(" and length ");
Serial.println(packetSize);
// only print packet data for non-RTR packets
while (CAN.available()) {
Serial.print((char)CAN.read());
}
Serial.println();
}
Serial.println();
}
}
So I will greatly appreciate help from anybody, because I have struggled with this problem for the last 2 weeks and I really want to solve it. Thank you for your time
So I have finally found a solution. I guess the other libraries had some problem sending data, cause I set everything with the same configuration. However, today I found this library->https://www.arduinolibraries.info/libraries/mcp_can, which helped me program correctly the arduino and it works perfectly in connection with another arduino or raspberry pi.
Related
I have an ESP8266-01 and I want to send sensor data from Arduino to ESP8266 via serial communication but the data I receive is not correct, I tried changing baud rates but no luck, here is the code
Code for ESP8266:
#include <SoftwareSerial.h>
void setup() {
// put your setup code here, to run once:
Serial.begin(38400);
}
void loop() {
// put your main code here, to run repeatedly:
while(Serial.available()) {
Serial.println("yes");
Serial.println(Serial.read());
}
delay(5);
}
Code for Arduino
#include <SoftwareSerial.h>
SoftwareSerial esp(1, 0);
String str;
void setup(){
Serial.begin(38400);
esp.begin(38400);
delay(2000);
}
void loop() {
// put your main code here, to run repeatedly:
str = String("Hi there");
esp.println(str);
esp.println("hi there");
delay(1000);
}
Here is the serial monitor:
Serial monitor showing numbers instead of "hi there"
The wiring connections are correct.
if you are using simple wires for the connection you might need to reduce the baud rate at 9600 or lower.
For higher speed you will need coaxial cables to get a decent communication distance. Moreover I am sure that you have checked the electrical connection obvously.
On the programming side, Serial.read() returns the first byte of incoming serial data available (or -1 if no data is available). Data type: int. This is why you are getting a single number instead of your string.
I would suggest to use Serial.readString() instead.
Please see the proper documentation here:
https://www.arduino.cc/reference/en/language/functions/communication/serial/
All the best
I recently got a HC-05 Bluetooth module for my arduino, but I cannot send or receive data from it. I used a code to turn on or off a led, but after I send a character from the Serial Monitor of my PC, I get ⸮. Also the module does not respond to any AT command. HC-05 ConnectionArduino connection I ran the Serial both in 9600 and 38400 baud but nothing changed. Also I have tried both no line ending and both NL and CR. But is wrong with this module? Here is my code:
/*
Arduino Turn LED On/Off using Serial Commands
Created April 22, 2015
Hammad Tariq, Incubator (Pakistan)
It's a simple sketch which waits for a character on serial
and in case of a desirable character, it turns an LED on/off.
Possible string values:
a (to turn the LED on)
b (tor turn the LED off)
*/
char junk;
String inputString="";
void setup() // run once, when the sketch starts
{
Serial.begin(9600); // set the baud rate to 9600, same should be of your Serial Monitor
pinMode(13, OUTPUT);
}
void loop()
{
if(Serial.available()){
while(Serial.available())
{
char inChar = (char)Serial.read(); //read the input
inputString += inChar; //make a string of the characters coming on serial
}
Serial.println(inputString);
while (Serial.available() > 0)
{ junk = Serial.read() ; } // clear the serial buffer
if(inputString == "a"){ //in case of 'a' turn the LED on
digitalWrite(13, HIGH);
}else if(inputString == "b"){ //incase of 'b' turn the LED off
digitalWrite(13, LOW);
}
inputString = "";
}
}
I will go step by step-
The connection
Arduino Pins Bluetooth Pins
RX (Pin 0) ———-> TX
TX (Pin 1) ———-> RX
5V ———-> VCC
GND ———-> GND
Connect a LED negative to GND of arduino and positive to pin 13 with a resistance valued between 220Ω – 1KΩ. And your done with the circuit.
Note : Don’t Connect RX to RX and TX to TX of Bluetooth to arduinoyou will receive no data , Here TX means Transmit and RX means Receive.
/*
* This program lets you to control a LED on pin 13 of arduino using a bluetooth module
*/
char data = 0; //Variable for storing received data
void setup()
{
Serial.begin(9600); //Sets the baud for serial data transmission
pinMode(13, OUTPUT); //Sets digital pin 13 as output pin
}
void loop()
{
if(Serial.available() > 0) // Send data only when you receive data:
{
data = Serial.read(); //Read the incoming data & store into data
Serial.print(data); //Print Value inside data in Serial monitor
Serial.print("\n");
if(data == '1') // Checks whether value of data is equal to 1
digitalWrite(13, HIGH); //If value is 1 then LED turns ON
else if(data == '0') // Checks whether value of data is equal to 0
digitalWrite(13, LOW); //If value is 0 then LED turns OFF
}
}
Link to Connection : https://halckemy.s3.amazonaws.com/uploads/image_file/file/153200/hc-05-LED%20blink%20Circuit.png
NOTE : While uploading the code , remove the TX and RX wires of Bluetooth Module from Arduino, once upload is completed, connect them.
#include <SoftwareSerial.h>
SoftwareSerial hc(2, 3); // RX | TX
void setup()
{
pinMode(4, OUTPUT);
digitalWrite(4, HIGH);
Serial.begin(9600);
Serial.println("Enter AT commands:");
hc.begin(38400); // HC-05 default speed in AT command more
}
void loop()
{
// Keep reading from HC-05 and send to Arduino Serial Monitor
if (hc.available())
Serial.write(hc.read());
// Keep reading from Arduino Serial Monitor and send to HC-05
if (Serial.available())
hc.write(Serial.read());
}
Use this code to test the bluetooth module in command mode.there are two modes in hc-05. one is command mode and other is data mode.
Press the button which is on bluetooth module for few sec. then the led Toggles slowly at this point the module is in command mode and in this you can test the AT commands.
Note: Open the serial monitor in 9600 baud rate
I am currently working on my mini-project under the domain "Internet of Things". I chose to design a wireless Notice board using a GSM module.
I divided the project into two modules. First, the Arduino-LED board interface which perfectly completed.
Second, GSM-Arduino interface. Basically, a message/SMS will be sent from the mobile phone to the GSM module and then we have to read that message from GSM module using Arduino. I am facing a problem here. The message is being sent to the GSM modem but I am not able to read it. I tried writing different codes, but its not working. The message is not being displayed.
Here is the code snippet I tried.
`#include SoftwareSerial.h
SoftwareSerial SIM900A(2,3);// RX | TX
// Connect the SIM900A TX to Arduino pin 2 RX
// Connect the SIM900A RX to Arduino pin 3 TX.
void setup()
{
SIM900A.begin(9600); // Setting the baud rate of GSM Module
Serial.begin(9600); // Setting the baud rate of Serial Monitor(Arduino)
Serial.println ("SIM900A Ready");
delay(100);
Serial.println (" Press s to send and r to recieve ");
}
void loop()
{
if (Serial.available()>0)
switch(Serial.read())
{
case 's': SendMessage();
break;
case 'r': RecieveMessage();
break;
}
if (SIM900A.available()>0)
Serial.write(SIM900A.read());
}
void SendMessage()
{
SIM900A.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
delay(1000); // Delay of 1000 milli seconds or 1 second
Serial.println ("Set SMS Number");
SIM900A.println("AT+CMGS=\"+91xxxxxxxxxx\"\r"); //Replace with your mobileno.
delay(1000);
Serial.println ("Set SMS Content");
SIM900A.println("Hello, I am SIM900A GSM Module");// The SMS text you want to send
delay(100);
Serial.println ("Finish");
SIM900A.println((char)26);// ASCII code of CTRL+Z
delay(1000);
Serial.println (" ->SMS Sent");
}
void RecieveMessage()
{
Serial.println ("SIM900A Receiving SMS");
delay (1000);
SIM900A.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
delay(1000);
Serial.write (" ->Unread SMS Recieved");
}`
You might have to set the preferred SMS storage to SIM card using the command:
SIM900A.print("AT+CPMS=\"SM\"\r");
Also, move this command to setup():
SIM900A.print("AT+CMGF=1\r");
Lastly, note how I have used SIM900A.print() instead of SIM900A.println() and send a '\r' or 0x0d after each command. println() sends a "\n\r" and that causes problems in some modems.
I have nexus duino 3WD and tried to do serial comm to move the robot. I have to remove shield to upload sketch code. This is my sketch:
#include <fuzzy_table.h>
#include <PID_Beta6.h>
#include <PinChangeInt.h>
#include <PinChangeIntConfig.h>
#include <MotorWheel.h>
#include <Omni3WD.h>
#include <EEPROM.h>
#define _NAMIKI_MOTOR //for Namiki 22CL-103501PG80:1
/*******************************************/
int incoming = 0;
int speed = 100;
// Motors
irqISR(irq1,isr1);
MotorWheel wheel1(9,8,6,7,&irq1); // Pin9:PWM, Pin8:DIR, Pin6:PhaseA, Pin7:PhaseB
irqISR(irq2,isr2);
MotorWheel wheel2(10,11,14,15,&irq2); // Pin10:PWM, Pin11:DIR, Pin14:PhaseA, Pin15:PhaseB
irqISR(irq3,isr3);
MotorWheel wheel3(3,2,4,5,&irq3); // Pin3:PWM, Pin2:DIR, Pin4:PhaseA, Pin5:PhaseB
Omni3WD Omni(&wheel1,&wheel2,&wheel3);
/******************************************/
void setup() {
Serial.begin(38400);
Serial.println("setup");
TCCR1B=TCCR1B&0xf8|0x01; // Pin9,Pin10 PWM 31250Hz
TCCR2B=TCCR2B&0xf8|0x01; // Pin3,Pin11 PWM 31250Hz
Omni.PIDEnable(0.26,0.02,0,10);
}
/****************************************/
void loop() {
if(Serial.available() > 0) {
incoming = Serial.read();
Serial.print(incoming);
if(incoming==0) {
Omni.setCarStop();
} else if(incoming==1) {
Omni.setCarAdvance(speed);
} else if(incoming==2) {
Omni.setCarRotateLeft(speed);
} else if(incoming==3) {
Omni.setCarRotateRight(speed);
}
}
Omni.PIDRegulate();
}
I tried to send data both from Serial Monitor and also PC app with USB cable. When shield is not attached I can send data and receive feedback from arduino. But when shield is attached it seem arduino not receiving data, the RX led flash but not the TX led, got 'setup' text output so arduino can send data to PC. Other thing is I can only use 38400 baud rate, otherwise the output will be garbagish.
I'm not sure if I do wrong in the code? Probably device power issues?
If you change the jumpers from RS-485 to Bluetooth like what it says here http://www.dfrobot.com/wiki/index.php/Arduino_I/O_Expansion_Shield_(SKU:_DFR0014)
then everything will work fine. uploading to the board without removing the shield might still be an issue, and sonars probably will not work, but at least you'll be able to read serial through the board.
Im working on connecting an Arduino Mega 2560 into max msp, I have adapted the Arduino2max arduino code and max patch.
I have adapted the max patch and succeeded with all 16 analog inputs from arduino into max but cannot get any digital pins over number 13 into max msp. I was wondering if anyone had had any sucsess with this?
Any help and comments would be greatly appreciated!
Many thanks
Joe
here is the arduino code adapted from Arduino2max v.5 which can be found here http://www.arduino.cc/playground/Interfacing/MaxMSP
int x = 0;
int ledpin = 13;
void setup ()
{
// 115200 is the default Arduino Bluetooth speed
Serial.begin(115200);
///startup blink
digitalWrite(13,HIGH);
delay(600);
digitalWrite(13,LOW);
pinMode(13,INPUT);
}
void loop()
{
// Check serial buffer for characters
if (Serial.available() > 0){
if (1){ //Serial.read() == 'r') { // If an 'r' is received then read the pins
// Read and send analog pins 0-15
for (int pin= 0; pin<=15; pin++)
{
x = analogRead(pin);
sendValue (x);
}
// Read and send digital pins 2-53
for (int pin= 2; pin<=53; pin++)
{
x = digitalRead(pin);
sendValue (x);
}
// Send a carriage return to mark end of pin data.
Serial.println();
// add a delay to prevent crashing/overloading of the serial port
delay (5);
}
}
}
// function to send the pin value followed by a "space".
void sendValue (int x){
Serial.print(x);
Serial.print(32, BYTE);
}
Thanks again!
I suggest you to use the OSC Protocol to communicate between the Arduino Mega and Max.
I use the library ardosc. There is no documentation on it but its not really hard to use it and it is a good library.
If you cannot use it do not hesitate to ask me some explanations