JDutchNL
Posts: 6
Joined: Fri Nov 02, 2018 5:01 pm

Convert arduino code to python

Wed Nov 07, 2018 5:15 pm

Hello,

At the moment i'm bussy with a little project which include 4 RFID readers. The readers are connected to a arduino uno.
I've connected the arduino as a slave on the RPi 3 using this tutorial: https://www.youtube.com/watch?v=QumIhvYtRKQ
It is using the Napy module. However in the tutorial they give a example of a arduino code converted to python.

Right now i'm converting the code of my MFRC522 module to python, unfortunally it is not working.
I'm kinda new to python so it is very hard to, i must say the arduino code is not the most basic module.

I've installed the MFRC522 librarie and included it to the Nanpy module.

Can someone tell me what i'm doing wrong?
Thank you a lot in advance.

Arduino code:

Code: Select all


// DEFINES
// Provides debugging information over serial connection if defined
#define DEBUG

// LIBRARIES
// Standard SPI library comes bundled with the Arduino IDE
#include <SPI.h>
// Download and install from https://github.com/miguelbalboa/rfid
#include <MFRC522.h>

// CONSTANTS
// The number of RFID readers
const byte numReaders = 4;
// Each reader has a unique Slave Select pin
const byte ssPins[] = {5, 6, 7, 8};
// They'll share the same reset pin
const byte resetPin = 9;
// This pin will be driven LOW to release a lock when puzzle is solved
const byte lockPin = A0;
// The sequence of NFC tag IDs required to solve the puzzle
const String correctIDs[] = {"1c3560d3", "1bc95fd3", "7e7b5cd3", "f1325d59"};

// GLOBALS
// Initialise an array of MFRC522 instances representing each reader
MFRC522 mfrc522[numReaders];
// The tag IDs currently detected by each reader
String currentIDs[numReaders];


/**
 * Initialisation
 */
void setup() {

  #ifdef DEBUG
  // Initialise serial communications channel with the PC
  Serial.begin(9600);
  Serial.println(F("Serial communication started"));
  #endif
  
  // Set the lock pin as output and secure the lock
  pinMode(lockPin, OUTPUT);
  digitalWrite(lockPin, LOW);
  
  // Initialise the SPI bus
  SPI.begin();

  for (uint8_t i=0; i<numReaders; i++) {
  
    // Initialise the reader
    // Note that SPI pins on the reader must always be connected to certain
    // Arduino pins (on an Uno, MOSI=> pin11, MISO=> pin12, SCK=>pin13)
    // The Slave Select (SS) pin and reset pin can be assigned to any pin
    mfrc522[i].PCD_Init(ssPins[i], resetPin);
    
    // Set the gain to max - not sure this makes any difference...
    // mfrc522[i].PCD_SetAntennaGain(MFRC522::PCD_RxGain::RxGain_max);
    
	#ifdef DEBUG
    // Dump some debug information to the serial monitor
    Serial.print(F("Reader #"));
    Serial.print(i);
    Serial.print(F(" initialised on pin "));
    Serial.print(String(ssPins[i]));
    Serial.print(F(". Antenna strength: "));
    Serial.print(mfrc522[i].PCD_GetAntennaGain());
    Serial.print(F(". Version : "));
    mfrc522[i].PCD_DumpVersionToSerial();
	#endif
    
    // Slight delay before activating next reader
    delay(00);
  }
  
  #ifdef DEBUG
  Serial.println(F("--- END SETUP ---"));
  #endif
}

/**
 * Main loop
 */
void loop() {

  // Assume that the puzzle has been solved
  boolean puzzleSolved = true;

  // Assume that the tags have not changed since last reading
  boolean changedValue = false;

  // Loop through each reader
  for (uint8_t i=0; i<numReaders; i++) {

    // Initialise the sensor
    mfrc522[i].PCD_Init();
    
    // String to hold the ID detected by each sensor
    String readRFID = "";
    
    // If the sensor detects a tag and is able to read it
    if(mfrc522[i].PICC_IsNewCardPresent() && mfrc522[i].PICC_ReadCardSerial()) {
      // Extract the ID from the tag
      readRFID = dump_byte_array(mfrc522[i].uid.uidByte, mfrc522[i].uid.size);
    }
    
    // If the current reading is different from the last known reading
    if(readRFID != currentIDs[i]){
      // Set the flag to show that the puzzle state has changed
      changedValue = true;
      // Update the stored value for this sensor
      currentIDs[i] = readRFID;
    }
    
    // If the reading fails to match the correct ID for this sensor 
    if(currentIDs[i] != correctIDs[i]) {
      // The puzzle has not been solved
      puzzleSolved = false;
    }

    // Halt PICC
    mfrc522[i].PICC_HaltA();
    // Stop encryption on PCD
    mfrc522[i].PCD_StopCrypto1(); 
  }

  #ifdef DEBUG
  // If the changedValue flag has been set, at least one sensor has changed
  if(changedValue){
    // Dump to serial the current state of all sensors
    for (uint8_t i=0; i<numReaders; i++) {
      Serial.print(F("Reader #"));
      Serial.print(String(i));
      Serial.print(F(" on Pin #"));
      Serial.print(String((ssPins[i])));
      Serial.print(F(" detected tag: "));
      Serial.println(currentIDs[i]);
    }
    Serial.println(F("---"));
  }
  #endif

  // If the puzzleSolved flag is set, all sensors detected the correct ID
  if(puzzleSolved){
    onSolve();
  }
 
  // Add a short delay before next polling sensors
  //delay(100); 
}

/**
 * Called when correct puzzle solution has been entered
 */
void onSolve(){

  #ifdef DEBUG
  // Print debugging message
  Serial.println(F("Puzzle Solved!"));
  #endif
  
  // Release the lock
  digitalWrite(lockPin, HIGH);

  while(true) {
    delay(100);
  }
  
}

/**
 * Helper function to return a string ID from byte array
 */
String dump_byte_array(byte *buffer, byte bufferSize) {
  String read_rfid = "";
  for (byte i=0; i<bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
  return read_rfid;
}
Python code:

Code: Select all

from nanpy import (ArduinoApi, SerialManager)
from time import sleep
import os

numReaders = 4
ssPins = 5, 6, 7, 8
resetPin = 9
lockPin = A0
correctIDs = "1c3560d3", "1bc95fd3", "7e7b5cd3", "f1325d59"

try:
    connection = SerialManager()
    a = ArduinoApi (connection = connection)
except:
    print("Faled to connect to Arduino")

a.MFRC522 mfrc522(numReaders)
str currentIDs(numReaders)
a.SPI.begin()

try:
    while:
        a.uint8_t 1=0, i<numReaders, i++
        mfrc622(1).PCD_Init(ssPins(i), resetPin)

try:
    while True:
        print(F("Reader {}",format(i)))
        print(F(" initalised on pin ",format(str(ssPins(i)))))
        print(F(". Antenna strength: ",format(mfrc522(i).PCD_GetAntennaGain())))
        print(F(". Version: ",format(mfrc522(1).PCD_DumpVersionToSerial())))
        sleep(1)

try:
    while True:
        a.boolean puzzleSolved = True
        a.boolean changedValue = False
        if unit8_t i=0, i<numReaders, i++:
            mfrc(i).PCD_Init()
            str(readRFID) = ""
            if mfrc522(i).PICC_IsNewCardPresent(), mfrc522(i).PICC_ReadCardSerial():
                readRFID = dump_byte_array(mfrc522(i).uid.uiByte, mfrc522(i).uid.size)

            if readRFID ! = cuurentIDs(i):
               changedValue = True
               currentIDs(i) = readRFID

            if currentIDs(i) ! = correctIDs(i):
                puzzleSolved = False

            mfrc522(i).PICC_HaltA()
            mfrc522(i).PCD_StopCrypto1()

        if changedValue:
            for: utint8_t i=0, i<numReaders, i++:
                print("Reader {}",format(str(i)))
                print(F(" on Pin {}",format(str((ssPins(i))))))
                print(F(" detected tag: {}",format(currentIDs(i))))
                print"---")

    try onSolve():
        while True:
            print(F("Solved"))

        a.digitalWrite(lockPin, a.HIGH)

        while True:
            sleep(1)

str dump_byte_array(a.byte *a.buffer, a.byte bufferSize):
    str read_rfid = ""
    for a.byte i=0, i<bufferSize, i++:
        read_rfid = read_rfid + str(a.buffer(i), a.HEX)
    except:
        return read_rfid



gordon77
Posts: 4992
Joined: Sun Aug 05, 2012 3:12 pm

Re: Convert arduino code to python

Wed Nov 07, 2018 5:22 pm

It may assist in diagnosing the problem(s) if you show what happens when you run it, and what errors you get.

JDutchNL
Posts: 6
Joined: Fri Nov 02, 2018 5:01 pm

Re: Convert arduino code to python

Wed Nov 07, 2018 5:23 pm

gordon77 wrote:
Wed Nov 07, 2018 5:22 pm
It may assist in diagnosing the problem(s) if you show what happens when you run it, and what errors you get.
Right now i'm getting:

File "RFID.py", line 17
a.MFRC522 mfrc522(numReaders)
^
SyntaxError: invalid syntax

scotty101
Posts: 3958
Joined: Fri Jun 08, 2012 6:03 pm

Re: Convert arduino code to python

Wed Nov 07, 2018 7:38 pm

This line is totally wrong

Code: Select all

a.uint8_t 1=0, i<numReaders, i++
It used to be part of a for loop. The python equivalent would be

Code: Select all

for i in range(numReaders):
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

User avatar
B.Goode
Posts: 10191
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: Convert arduino code to python

Wed Nov 07, 2018 8:56 pm

JDutchNL wrote:
Wed Nov 07, 2018 5:23 pm
gordon77 wrote:
Wed Nov 07, 2018 5:22 pm
It may assist in diagnosing the problem(s) if you show what happens when you run it, and what errors you get.
Right now i'm getting:

File "RFID.py", line 17
a.MFRC522 mfrc522(numReaders)
^
SyntaxError: invalid syntax

Literally, the syntax error in that line is due to the extraneous 'space' character. You have a similar problem in the following line too.

JDutchNL
Posts: 6
Joined: Fri Nov 02, 2018 5:01 pm

Re: Convert arduino code to python

Wed Nov 07, 2018 9:01 pm

B.Goode wrote:
Wed Nov 07, 2018 8:56 pm
JDutchNL wrote:
Wed Nov 07, 2018 5:23 pm
gordon77 wrote:
Wed Nov 07, 2018 5:22 pm
It may assist in diagnosing the problem(s) if you show what happens when you run it, and what errors you get.
Right now i'm getting:

File "RFID.py", line 17
a.MFRC522 mfrc522(numReaders)
^
SyntaxError: invalid syntax

Literally, the syntax error in that line is due to the extraneous 'space' character. You have a similar problem in the following line too.
Thank you! that was the problem indeed.
As i said i'm verry new to python so i don't even understand the basics.
That why i'm looking for help.

Right now i'm getting the following error:


File "RFID.py", line 24
mfrc522(1).a.PCD_Init(ssPins(i),format(resetPin))
^
IndentationError: expected an indented block

DirkS
Posts: 10347
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: Convert arduino code to python

Wed Nov 07, 2018 9:15 pm

See @scotty's post a bit further up.
Essentially you split the condition from the while statement itself and the condition is not correct.


BTW: had a quick glance at the code and I think you can expect many more errors.
For example:
- try without finally or except (a simple 'pass' would be sufficient)
- At least one while loop that will never exit
- Several C / C++ style loop conditionals that will not work in Python

Personally I would not try to convert the script line by line, but just use the flow and rewrite it for Python.

JDutchNL
Posts: 6
Joined: Fri Nov 02, 2018 5:01 pm

Re: Convert arduino code to python

Wed Nov 07, 2018 9:19 pm

DirkS wrote:
Wed Nov 07, 2018 9:15 pm
See @scotty's post a bit further up.
Essentially you split the condition from the while statement itself and the condition is not correct.


BTW: had a quick glance at the code and I think you can expect many more errors.
For example:
- try without finally or except (a simple 'pass' would be sufficient)
- At least one while loop that will never exit
- Several C / C++ style loop conditionals that will not work in Python

Personally I would not try to convert the script line by line, but just use the flow and rewrite it for Python.
Thank you for you reply! according to your message i think i'm going to search for someone who will write it for me for a small fee. i't is for a work related project. has to be done in a few weeks.

if someone is interested in writng the code for me for a small payment please let me know!

jehutting
Posts: 143
Joined: Sun Feb 15, 2015 8:37 am
Location: The Netherlands

Re: Convert arduino code to python

Sat Nov 10, 2018 9:29 am

I might be interested to help you out. Please contact me at jehutting AT gmail DOT com.

Return to “Python”