Can you confirm that the Uno receives the correct message with
ArduinoUno.write(bytes(bits[i], 'utf-8'))
If that is so, then the problem is with the python receiving code.
Have you tried
recu = ArduinoNano.readline()
Can you confirm that the Uno receives the correct message with
ArduinoUno.write(bytes(bits[i], 'utf-8'))
If that is so, then the problem is with the python receiving code.
Have you tried
recu = ArduinoNano.readline()
I don't know if it's a correct way to test that, but if I add :
print(ArduinoUno.read() )
just after the line ArduinoUno.write... I get an empty byte.
Therefore it would mean nothing is sent to the Uno ?
How is that possible ?
read / read_all / readline all give the same empty variable
In order to focus on the Python>Uno sending of the message,
I think that you will need to echo the received message back to python and and use .readline() to confirm that it has received the correct message from python.
Or, to eliminate the python readback, send a predetermined message like "test" and if the Uno receives it and it matches, blink the built-in LED (or similar)
Or, implement the echo back and test it using the Serial Monitor and using your python code.
Yes, I like this suggestion. It solves the problem of not having the monitor available to the Uno when its connected to python.
Hi,
I finally had the time to deal with it. I ran these codes :
On the Uno :
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
char caractere = Serial.read();
if (Serial.available()== true) {
digitalWrite(LED_BUILTIN, HIGH);
}
}
On Python :
import serial
import CRC
import numpy as np
a = '0110010010111000110'
CRC.Codage_Canal(a)
print(CRC.Codage_Canal(a))
ArduinoUno = serial.Serial(port="COM3", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
#ArduinoNano = serial.Serial(port="COM4", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
ArduinoUno.write(bytes('test', encoding = 'ASCII'))
print('stop')
The part over ArduinoUno = ... should not be relevant here.
I tried utf-8 and ASCII for the bytes encoding in Python.
The Python code outputs this :
>>> ArduinoUno.write(bytes('test', encoding = 'ASCII'))
4
>>> print('stop')
stop
Which tells me Python Understood I asked him to send 4 bytes to the Uno.
However, the built-in LED of the Uno doesn't turn on, whereas it does turn on if do not use a if condition.
How shall I understand that ? And how can I deal with it ?
Just went back to Python to test a few things.
I ran this simple code with the Arduino sketch that is just above in this post :
import serial
ArduinoUno = serial.Serial(port="COM3", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
ArduinoUno.write(bytes('test', encoding = 'ASCII'))
print(ArduinoUno.read_all())
Output is an empty byte : b''
However, the TX LED turns on and remains lit.
what is that? You read 1 char and then see if a char is available? You need to use the recvWithEndMarker() function like your original code so you collect an entire line and then see if it compares to "test" [strcmp()] and, if it does, blink the LED.
I wrote that because I was about to test for "test", but then I thought it could be even more meaningful to only test if something had been received. Turns out it doesn't since the LED remains off.
I do not believe that you are giving time for python to open the serial port and for the Arduino to reset. All my python/Arduino serial programs begin with a waiting period for the port to open.
With your port selection it would be
import serial
import time
ArduinoUno = serial.Serial(port="COM3", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
time.sleep(2) #allow time for Serial port to open
I changed my code as you said, and I now get :
\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\
dozens of time as the print output. The built-in led doesn't turn on.
Have you encountered this situation before ?
If you just want to test if a single char has arrived:
void loop() {
if (Serial.available()) {
Serial.read(); // discard
digitalWrite(LED_BUILTIN, HIGH);
delay(250);
digitalWrite(LED_BUILTIN, LOW);
}
}
Note: Serial.available() returns the number of chars in the buffer, not true/false. It will happen to work when one char is in the buffer since true == 1
Hi,
I just used these codes :
for Python
import serial
import time
ArduinoUno = serial.Serial(port="COM3", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
time.sleep(2)
ArduinoUno.write(bytes('test', encoding = 'ASCII'))
print(ArduinoUno.read())
For the Uno :
void loop() {
if (Serial.available()) {
Serial.read() // discard
digitalWrite(LED_BUILTIN, HIGH);
delay(250);
digitalWrite(LED_BUILTIN, LOW);
}
}
And everything worked well. Adding lu = Serial.read() and Serial.write(lu) to the Uno sketch makes Python print the letter 't', which is expected. This side works.
With this code :
void loop() {
if (Serial.available()) {
recvWithEndMarker(); // discard
digitalWrite(LED_BUILTIN, HIGH);
delay(250);
digitalWrite(LED_BUILTIN, LOW);
showNewData();
}
}
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
void showNewData() {
if (newData == true) {
Serial.write(receivedChars);
newData = false;
}
}
I underline that I chagend the end-of-line character in recvWithEndMarker() so that I can add it in a Python string safely.
With this code then, Python only prints the first letter 't' too.
Newdata variable is set back to false when I call showNewData() and I don't understand where the problem can be.
Now if I keep this Uno sketch and use this Python code :
import serial
import time
ArduinoUno = serial.Serial(port="COM3", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
time.sleep(2)
ArduinoUno.write(bytes('test>', encoding = 'ASCII'))
print(ArduinoUno.read())
print(ArduinoUno.read())
print(ArduinoUno.read())
print(ArduinoUno.read())
print(ArduinoUno.read())
I get :
b't'
b'e'
b's'
b't'
b''
As you can see, the characters come one after another, and the end of line characater is recognized as such. Which means recvWithEndMarker actually works. Why can't I have all the characters at the same time then ?
ArduinoUno.read() reads 1 char so that is what you get. use readline() if you want an entire line read in using python.
It works with readline.
However, if I implement this exact syntax in my actual code, this way :
while True :
ArduinoUno.write(bytes('test>', encoding = 'ASCII')) #On envoie à travers le moniteur chaque groupe de 8 bits #write(bytes(bits[i]))
print(ArduinoUno.readline())
recu = str(ArduinoNano.readline()) #On stocke tout ce qui est dans le buffer de la Nano
print("reçu = ", recu)
I get :
b''
b''
b''
b''
reçu = b''
It doesn't work anymore. And I don't understand why.
It is ok if reçu is empty, because I turned off the code to send it through the NRF24, but the bytes before shouldn't be empty
Your python code is calling readline() twice. What do you expect to be returned the second time since you have only sent 1 string to the Uno.
You also have to realize that serial communication at 9600 baud is very slow compared to the speed of the Uno and your python code. Most likely, you will have to send a string, wait 500ms or so and then read it back. There is a tutorial for serial communication with a PC using python code here on the forums somewhere. Maybe have a search?
Your python code is calling readline() twice. What do you expect to be returned the second time since you have only sent 1 string to the Uno.
The second call is to store what has been received on the Nano. It should not work for now, since I turned off the transmission. But the first call aims to check what has been received in the Uno, and it outputs nothing, whereas on the other Python code (see #32) I used, the same code gives an output. The first call will be removed as soon as I find where the errors come from, but it doesn't even work for now.
I've read a few tutorials, and they say the computer, the Uno, and the serial commmunication work at different speed. But I can't evaluate how different these speeds are, neither do I know which problems are due to this difference.
As you saw, I'm able to have it working on their own (sometimes with a little help, due to the little time I have off the holidays). I managed to communicate with Arduino's IDE serial monitor, I managed to have fuctional Python codes, I managed to send a wireless message through the NRF modules. But when I put everything together, errors that I don't understand arise and I'm almost sure there are no tutorials for these.
Please post the complete python code and Uno code which are failing to show the readline() response from the Uno.
It works now !
The only thing I did is implementing time.sleep(2) in two different places and the bytes are not empty anymore. Thank you @blh64 ! This delay thing is much more important than it looked to me.
Here are the codes, because I have another problem now (as always).
It is still about a message being send from the computer to the Arduinos and not being able to know where it arrived.
The codes :
For Python :
import serial
import CRC
import numpy as np
import time
a = '0110010010111000110'
CRC.Codage_Canal(a)
print(CRC.Codage_Canal(a))
ArduinoUno = serial.Serial(port="COM3", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
ArduinoNano = serial.Serial(port="COM4", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
time.sleep(2)
file = open('message.txt', 'r')
message = file.read()
file.close()
print(message)
messagecode = CRC.Codage_Canal(message) + '>'
print(messagecode)
#Le code fonctionne jusqu'ici
bits = []
Generateur = np.array([1, 0, 1, 1])
for i in range(len(messagecode)//8 + 1) : #On découpe en chaines de 8 bits car bytesize = 8 plus haut
chaine = ''
chaine += messagecode[8*i:8*i+8]
bits.append(chaine)
print(bits)
while True :
for i in range(len(bits)):
ArduinoUno.write(bytes(bits[i], encoding = 'ASCII')) #On envoie à travers le moniteur chaque groupe de 8 bits #write(bytes(bits[i]))
time.sleep(2)
print(ArduinoUno.readline())
For the transmitter :
#include <SPI.h>
#include <RF24.h>
#define pinCE 7 // On associe la broche "CE" du NRF24L01 à la sortie digitale D7 de l'arduino
#define pinCSN 8 // On associe la broche "CSN" du NRF24L01 à la sortie digitale D8 de l'arduino
#define tunnel "PIPE1" // On définit un "nom de tunnel" (5 caractères), pour pouvoir communiquer d'un NRF24 à l'autre
RF24 radio(pinCE, pinCSN); // Instanciation du NRF24L01
const byte adresse[6] = tunnel; // Mise au format "byte array" du nom du tunnel
// Message à transmettre à l'autre NRF24 (32 caractères maxi, avec cette librairie)
const byte numChars = 32;
char receivedChars[numChars]; // an array to store the received data
boolean newData = false;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
radio.begin(); // Initialisation du module NRF24
radio.openWritingPipe(adresse); // Ouverture du tunnel en ÉCRITURE, avec le "nom" qu'on lui a donné
radio.setPALevel(RF24_PA_MIN); // Sélection d'un niveau "MINIMAL" pour communiquer (pas besoin d'une forte puissance, pour nos essais)
radio.setAutoAck(false);
radio.setCRCLength(RF24_CRC_DISABLED);
radio.stopListening();// Arrêt de l'écoute du NRF24 (signifiant qu'on va émettre, et non recevoir, ici
}
//void loop() {
// recvWithEndMarker();
// sendNewData();
// showNewData();
//}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
delay(250);
digitalWrite(LED_BUILTIN, LOW);
if (Serial.available()) {
recvWithEndMarker(); // discard
digitalWrite(LED_BUILTIN, HIGH);
delay(250);
digitalWrite(LED_BUILTIN, LOW);
radio.write(&receivedChars, sizeof(receivedChars)); // Envoi de notre message
delay(1000);
newData = false;
}
}
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
void showNewData() {
if (newData == true) {
Serial.print(receivedChars);
newData = false;
}
}
void sendNewData() {
if (newData == true){
radio.write(receivedChars, sizeof(receivedChars)); // Envoi de notre message
delay(1000);
}
}
For the receiver :
#include <SPI.h>
#include <RF24.h>
#define pinCE 7 // On associe la broche "CE" du NRF24L01 à la sortie digitale D7 de l'arduino
#define pinCSN 8 // On associe la broche "CSN" du NRF24L01 à la sortie digitale D8 de l'arduino
#define tunnel "PIPE1" // On définit le "nom de tunnel" (5 caractères) à travers lequel on va recevoir les données de l'émetteur
RF24 radio(pinCE, pinCSN); // Instanciation du NRF24L01
const byte adresse[6] = tunnel; // Mise au format "byte array" du nom du tunnel
char message[32];
boolean newData = false;
const byte numChars = 32;
char receivedChars[numChars];
char add = '\0';
void setup() {
// Initialisation du port série (pour afficher les infos reçues, sur le "Moniteur Série" de l'IDE Arduino)
Serial.begin(9600);
// Partie NRF24
radio.begin(); // Initialisation du module NRF24
radio.openReadingPipe(0, adresse); // Ouverture du tunnel en LECTURE, avec le "nom" qu'on lui a donné
radio.setPALevel(RF24_PA_MIN); // Sélection d'un niveau "MINIMAL" pour communiquer (pas besoin d'une forte puissance, pour nos essais)
radio.setAutoAck(false);
radio.startListening(); // Démarrage de l'écoute du NRF24 (signifiant qu'on va recevoir, et non émettre quoi que ce soit, ici)
}
void loop() {
if (radio.available()) { // On vérifie si un message est en attente de lecture
radio.read(&message, sizeof(message));// Si oui, on le charge dans la variable "message"
newData = true;
}
showNewData();
}
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = ">" ;
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
void showNewData() {
if (newData == true) {
Serial.write(message);
newData = false;
}
}
I'm now working directly from Uno to Nano, without Python, only the Arduino IDE to locate my potential mistakes more effectively. Currently, a message sent from the Uno's serial is not printed on the Nano's serial. That is the aim of my whole Arduino code.
If you look at the transmitter code, you'll see the built-in LED is told to blink once when a message is received from the serial.
However, it doesn't. But I can confirm that recvwithEndMarker() and showNewData() are working as expected when I write something in the Uno's serial. But the LED doesn't blink. Why ? It is worrying because I think it might be related to the radio.read() line not working.
I don't have the radios to test with, and when I comment out all the radio related lines and just test the Serial portion of your sketch, i can see the led blink when a message is sent from the monitor.
This would indicate that the issue is with your radio setup and code. I would go back to basics and see if you can get the library example for send and receive working.
I just tried basic communication from the Uno to the Nano, and everything works fine.
What is weird, is that on the Uno, when I run the code, the RX led blinks when I send a message on the Serial, and the Tx blinks when it sends it back for printing on the serial monitor. However, in between, the built-in LED should blink and it does not. That, is something I don't understand.