ERROR SPI on ATmega328P of Arduino - arduino

I use SPI on ATmega328 with raw code, data is transferred correctly, but the value return just correct in the second time. I don't know why. I think the data buffer register doesn't update immediately, when I push the button (this is video left is yellow LED, right is red LED: https://drive.google.com/open?id=1bf2XlxRBGCaUo0j2ezB2XFxfSItUmChN and code below)
I use Arduino Uno is a master to send data and get response. Arduino Nano is a slave to receive data and response to master.
Arduino Uno (master) code:
#define DDR_SPI DDRB
#define PORT_SPI PORTB
#define MOSI 3
#define SCK 5
#define SS 2
#define red 2
#define cbi(port, bits) (port) &= ~(1 << (bits))
#define sbi(port, bits) (port) |= (1 << (bits))
volatile uint8_t Data1;
volatile uint8_t Data2;
void setup()
{
Serial.begin(9600); //debug by UART
SPCR = 0; // Reset SPCR = 0
DDR_SPI |= (1<<MOSI)|(1<<SCK)|(1<<SS);// MOSI,SCK,SS - OUTPUT , MISO - INPUT
SPCR |= (1<<SPE)|(1<<MSTR)|(1<<SPR0); // Enable spi , Set master , div/16
pinMode(red,OUTPUT); // led output at pin 2
pinMode(6,INPUT_PULLUP); // internal res input at pin6
pinMode(7,INPUT_PULLUP); // internal res input at pin7
sbi(PORT_SPI,SS); // disable slave
}
uint8_t SPI_MasterTransmit(uint8_t cData)
{
SPDR = cData; // Start transmission
delay(50);
while(bit_is_clear(SPSR,SPIF)); //Wait for transmission complete
return SPDR;
}
void loop()
{
if(bit_is_clear(PIND,6)) // if i push button at pin 6
{
while(bit_is_clear(PIND,6)); // if i still push button at pin 6
cbi(PORTB,SS); // enable slave
Data1 = SPI_MasterTransmit(1); // send value 1 to slave
Serial.print(Data1); // debug
delay(50);
if(Data1 == 2) //if slave response value = 2
digitalWrite(red,LOW); //turnOFF led at pin 2
sbi(PORT_SPI,SS); // disable slave
}
else if(bit_is_clear(PIND,7)) // if i push button at pin 7
{
while(bit_is_clear(PIND,7)); // if i still push button at pin 7
cbi(PORT_SPI,SS); // disable slave
Data2 = SPI_MasterTransmit(3); // send value 3 to slave
Serial.print(Data2); // debug
delay(50);
if(Data2==4) //if slave response value = 4
digitalWrite(red,HIGH); //turnON led at pin 2
sbi(PORT_SPI,SS); // disable slave
}
}
Arduino Nano (slave) code:
#define MISO 4
#define yellow 2
#define cbi(port, bits) (port) &= ~(1 << (bits))
#define sbi(port, bits) (port) |= (1 << (bits))
volatile uint8_t Data;
void setup()
{
SPCR = 0; // reset SPCR = 0
DDRB |= (1<<MISO); // MISO - OUTPUT , SCK,MOSI,SS - INPUT
SPCR |= (1<<SPE)|(1<<SPIE); // enable spi , spi_interrupt
pinMode(yellow ,OUTPUT); // Led output at pin2
}
void SPI_Response(uint8_t cData)
{
SPDR = cData; //Start transmission
while(bit_is_clear(SPSR,SPIF)); //Wait for transmission complete
}
void loop()
{
}
ISR(SPI_STC_vect) // Vector interrupt spi
{
Data = SPDR; // volatile Data = data receive
if(Data == 1)
{
digitalWrite(yellow ,HIGH); // i turnOn led if i receive data = 5
SPI_Response(2); // and response to master a value = 7
delay(10);
}
else if(Data == 3)
{
digitalWrite(yellow,LOW); // i turnOFF led if i receive data = 6
SPI_Response(4); //and response to master a value = 8
delay(10);
}
}

You know the four wire SPI is full duplex, right? The master and the slave are sending the data simultaneously.
The common way how to do what you want is sending control byte and then dummy byte (or bytes) to receive the data.

Related

TTGO ESP32 + GSM 800l AT Commands

Good day all
I'm working on a project that takes sensor data and sends it to an online database using HTTP requests.Im ussing the TTGO esp32 sim 800 board, Everything works fine and all the data is stored in my online database the problem is that I cant get the AT commands to work, I need the Signal strength, battery voltage, and amount of Data available on the sim card.
Can someone please assist with this matter?
kind regards Hansie
Code
#include <HCSR04.h>
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
// Set serial for debug console (to Serial Monitor, default speed 115200)
#define SerialMon Serial
// Set serial for AT commands (to SIM800 module)
#define SerialAT Serial1
// Configure TinyGSM library
#define TINY_GSM_MODEM_SIM800 // Modem is SIM800
#define TINY_GSM_RX_BUFFER 1024 // Set RX buffer to 1Kb
// Define the serial console for debug prints, if needed
//#define DUMP_AT_COMMANDS
#include <Wire.h>
#include <TinyGsmClient.h>
#define uS_TO_S_FACTOR 1000000UL /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 36 /* Time ESP32 will go to sleep (in seconds) 3600 seconds = 1 hour */
#define IP5306_ADDR 0x75
#define IP5306_REG_SYS_CTL0 0x00
// TTGO T-Call pins
#define MODEM_RST 5
#define MODEM_PWKEY 4
#define MODEM_POWER_ON 23
#define MODEM_TX 27
#define MODEM_RX 26
#define I2C_SDA 21
#define I2C_SCL 22
int deviceID=101;
const int trigPin = 5;
const int echoPin = 18;
//Calculation variable for depth
//define sound speed in cm/uS
long duration;
float distanceCm;
double damDepth =200;
// Your GPRS credentials
const char apn[] = "Vodacom APN"; // APN
const char gprsUser[] = ""; // GPRS User
const char gprsPass[] = ""; // GPRS Password
// SIM card PIN (leave empty, if not defined)
const char simPIN[] = "";
// Server details
const char server[] = "grow-with-pierre.com"; // domain name:
const char resource[] = "/post-data.php"; // resource path, for example: /post-data.php
const int port = 80; // server port number
// Keep this API Key value to be compatible with the PHP code
String apiKeyValue = "tPmAT5Ab3j7F9";
#ifdef DUMP_AT_COMMANDS
#include <StreamDebugger.h>
StreamDebugger debugger(SerialAT, SerialMon);
TinyGsm modem(debugger);
#else
TinyGsm modem(SerialAT);
#endif
// I2C for SIM800 (to keep it running when powered from battery)
TwoWire I2CPower = TwoWire(0);
// TinyGSM Client for Internet connection
TinyGsmClient client(modem);
bool setPowerBoostKeepOn(int en)
{
I2CPower.beginTransmission(IP5306_ADDR);
I2CPower.write(IP5306_REG_SYS_CTL0);
if (en)
{
I2CPower.write(0x37); // Set bit1: 1 enable 0 disable boost keep on
} else
{
I2CPower.write(0x35); // 0x37 is default reg value
}
return I2CPower.endTransmission() == 0;
}
void setup()
{
Serial.begin(115200); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
// Set serial monitor debugging window baud rate to 115200
SerialMon.begin(115200);
// Start I2C communication
I2CPower.begin(I2C_SDA, I2C_SCL, 400000);
// Keep power when running from battery
bool isOk = setPowerBoostKeepOn(1);
SerialMon.println(String("IP5306 KeepOn ") + (isOk ? "OK" : "FAIL"));
// Set modem reset, enable, power pins
pinMode(MODEM_PWKEY, OUTPUT);
pinMode(MODEM_RST, OUTPUT);
pinMode(MODEM_POWER_ON, OUTPUT);
digitalWrite(MODEM_PWKEY, LOW);
digitalWrite(MODEM_RST, HIGH);
digitalWrite(MODEM_POWER_ON, HIGH);
// Set GSM module baud rate and UART pins
SerialAT.begin(115200, SERIAL_8N1, MODEM_RX, MODEM_TX);
delay(3000);
// Restart SIM800 module, it takes quite some time
// To skip it, call init() instead of restart()
SerialMon.println("Initializing modem...");
modem.restart();
// use modem.init() if you don't need the complete restart
// Unlock your SIM card with a PIN if needed
if (strlen(simPIN) && modem.getSimStatus() != 3 )
{
modem.simUnlock(simPIN);
}
// Configure the wake up source as timer wake up
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
}
void loop()
{
postData();
Serial.print(String(" Percentage: ") + depth());
// Put ESP32 into deep sleep mode (with timer wake up)
esp_deep_sleep_start();
}
String postData()
{
SerialMon.print("Connecting to APN: ");
SerialMon.print(apn);
if (!modem.gprsConnect(apn, gprsUser, gprsPass))
{
SerialMon.println(" fail");
}
else
{
SerialMon.println(" OK");
SerialMon.print("Connecting to ");
SerialMon.print(server);
if (!client.connect(server, port))
{
SerialMon.println(" fail");
}
else
{
SerialMon.println(" OK");
// Making an HTTP POST request
SerialMon.println("Performing HTTP POST request...");
String httpRequestData = "api_key=" + apiKeyValue + "&value1=" + String(deviceID)
+ "&value2=" + String(distanceCm) + "&value3=" + String(80) + "&value4=" + String(40) + ""+ "&value5=" + String(50) + "";
// then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)
// String httpRequestData = "api_key=tPmAT5Ab3j7F9&value1=24.75&value2=49.54&value3=1005.14";
client.print(String("POST ") + resource + " HTTP/1.1\r\n");
client.print(String("Host: ") + server + "\r\n");
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(httpRequestData.length());
client.println();
client.println(httpRequestData);
unsigned long timeout = millis();
while (client.connected() && millis() - timeout < 10000L)
{
// Print available data (HTTP response from server)
while (client.available())
{
char c = client.read();
SerialMon.print(c);
timeout = millis();
}
}
SerialMon.println();
// Close client and disconnect
client.stop();
SerialMon.println(F("Server disconnected"));
modem.gprsDisconnect();
SerialMon.println(F("GPRS disconnected"));
}
}
}
float depth() //Find Depth in cm
{
double persentage;
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
persentage = (distanceCm/damDepth)*100;
if(persentage>=100)
{
persentage=100;
}
else
{
persentage=100- persentage;
}
return persentage;
}
For at least some of the desired functions, it isn't necessary to push AT-commands.
Try signalStrength = modem.getSignalQuality(); instead. It works for me on the Lilygo T-Call SIM800L. You can check out TinyGSM's Github-page for additional commands or this handy class reference

SPI Problem Arduino Mega with pressure sensor MS5803-05BA

I need your help for a project.
I have actually 2 parallel sensors of the type: MS5803-05BA, which supports I2C and SPI connection. One sensor is on I2C bus and one sensor is on SPI. They are both sending to my Arduino Mega. The I2C works perfect with short cables.
Here the datasheet of the sensor:
https://www.amsys.de/downloads/data/MS5803-05BA-AMSYS-datasheet.pdf
For some informations who wants to do the same with I2C. Here you can find a good code. (You can find the other MS580X typs there too). For the communication between the sensor and the Arduino Mega you need an logic converter like this txs0108e, which can be bought with a break out board (you need pull up resistors on the sensor side!):
https://github.com/millerlp/MS5803_05
But to my problem: I have an sensor distance for about 3-5 meters and the I2C connections doesnt work. Yes I can try to fix the pullup resistors but it doesnt worked for me (I have tried some different lower resistors between 3-10kOhm). Therefore I want to switch to the SPI bus.
I have edit the code from https://github.com/millerlp/MS5803_05, https://github.com/vic320/Arduino-MS5803-14BA and https://arduino.stackexchange.com/questions/13720/teensy-spi-and-pressure-sensor.
The File is added. (You have to put the .h and .cpp files in the folder of the arduino code (.spi).
I have problems with the code from the SPI (ccp and header). There is no right communication. I have checked my cables twice. I couldnt find a problem and the connection with the txs0108e works for parallel I2C sensor. Both sensors are working on I2C.
Here is the main code (arduino .spi) for SPI and I2C parallel:
/_____ I N C L U D E S
#include <stdio.h>
#include <math.h>
#include <SPI.h>
#include <Wire.h>
#include "MS5803_05.h"
#include "MS5803_05_SPI.h"
const int miso_port = 50; //SDI
const int mosi_port = 51; //SDO
const int sck_port = 52; //SLCK
const int slaveSelectPin = 53; // CSB
MS_5803 sensor = MS_5803(512);
MS_5803_SPI sensor_spi = MS_5803_SPI(4096, slaveSelectPin);
void setup()
{
pinMode(miso_port, INPUT);
pinMode(mosi_port, OUTPUT);
pinMode(slaveSelectPin, OUTPUT);
pinMode(sck_port, OUTPUT);
Serial.begin(9600);
//SPI BUS
if (sensor_spi.initializeMS_5803_SPI()) {
Serial.println( "MS5803 SPI CRC check OK." );
}
else {
Serial.println( "MS5803 SPI CRC check FAILED!" );
}
//I2C BUS
delay(1000);
if (sensor.initializeMS_5803()) {
Serial.println( "MS5803 I2C CRC check OK." );
}
else {
Serial.println( "MS5803 I2C CRC check FAILED!" );
}
}
void loop()
{
Serial.println("SPI Sensor first pressure [mbar], than temperature[°C]:");
sensor_spi.readSensor();
// Show pressure
Serial.print("Pressure = ");
Serial.print(sensor_spi.pressure());
Serial.println(" mbar");
// Show temperature
Serial.print("Temperature = ");
Serial.print(sensor_spi.temperature());
Serial.println("C");
////********************************************************
Serial.println("");
Serial.println("I2C Sensor first pressure [mbar], than temperature[°C]:");
sensor.readSensor();
// Show pressure
Serial.print("Pressure = ");
Serial.print(sensor.pressure());
Serial.println(" mbar");
// Show temperature
Serial.print("Temperature = ");
Serial.print(sensor.temperature());
Serial.println("C");
delay(2000);
}
}
The first connection with SPI is here (.cpp):
#include "MS5803_05_SPI.h"
#include <SPI.h>
#define CMD_RESET 0x1E // ADC reset command
#define CMD_ADC_READ 0x00 // ADC read command
#define CMD_ADC_CONV 0x40 // ADC conversion command
#define CMD_ADC_D1 0x00 // ADC D1 conversion
#define CMD_ADC_D2 0x10 // ADC D2 conversion
#define CMD_ADC_256 0x00 // ADC resolution=256
#define CMD_ADC_512 0x02 // ADC resolution=512
#define CMD_ADC_1024 0x04 // ADC resolution=1024
#define CMD_ADC_2048 0x06 // ADC resolution=2048
#define CMD_ADC_4096 0x08 // ADC resolution=4096
#define CMD_PROM_RD 0xA0 // Prom read command
#define spi_write SPI_MODE3
#define spi_write2 SPI_MODE1
// Create array to hold the 8 sensor calibration coefficients
static unsigned int sensorCoeffs[8]; // unsigned 16-bit integer (0-65535)
// D1 and D2 need to be unsigned 32-bit integers (long 0-4294967295)
static uint32_t D1 = 0; // Store uncompensated pressure value
static uint32_t D2 = 0; // Store uncompensated temperature value
// These three variables are used for the conversion steps
// They should be signed 32-bit integer initially
// i.e. signed long from -2147483648 to 2147483647
static int32_t dT = 0;
static int32_t TEMP = 0;
// These values need to be signed 64 bit integers
// (long long = int64_t)
static int64_t Offset = 0;
static int64_t Sensitivity = 0;
static int64_t T2 = 0;
static int64_t OFF2 = 0;
static int64_t Sens2 = 0;
// Some constants used in calculations below
const uint64_t POW_2_33 = 8589934592ULL; // 2^33 = 8589934592
SPISettings settings_write(500000, MSBFIRST, spi_write);
SPISettings settings_write2(500000, MSBFIRST, spi_write2);
//-------------------------------------------------
// Constructor
MS_5803_SPI::MS_5803_SPI( uint16_t Resolution, uint16_t cs) {
// The argument is the oversampling resolution, which may have values
// of 256, 512, 1024, 2048, or 4096.
_Resolution = Resolution;
//Chip Select
_cs=cs;
}
boolean MS_5803_SPI::initializeMS_5803_SPI(boolean Verbose) {
digitalWrite( _cs, HIGH );
SPI.begin();
// Reset the sensor during startup
resetSensor();
if (Verbose)
{
// Display the oversampling resolution or an error message
if (_Resolution == 256 | _Resolution == 512 | _Resolution == 1024 | _Resolution == 2048 | _Resolution == 4096){
Serial.print("Oversampling setting: ");
Serial.println(_Resolution);
} else {
Serial.println("*******************************************");
Serial.println("Error: specify a valid oversampling value");
Serial.println("Choices are 256, 512, 1024, 2048, or 4096");
Serial.println("*******************************************");
}
}
// Read sensor coefficients
for (int i = 0; i < 8; i++ )
{
SPI.beginTransaction(settings_write2);
digitalWrite(_cs, LOW); //csb_lo(); // pull CSB low
unsigned int ret;
unsigned int rC = 0;
SPI.transfer(CMD_PROM_RD + i * 2); // send PROM READ command
/*
ret = SPI.transfer(0x00); // send 0 to read the MSB
rC = 256 * ret;
ret = SPI.transfer(0x00); // send 0 to read the LSB
rC = rC + ret;
*/
// send a value of 0 to read the first byte returned:
rC = SPI.transfer( 0x00 );
rC = rC << 8;
rC |= SPI.transfer( 0x00 ); // and the second byte
sensorCoeffs[i] = (rC);
digitalWrite( _cs, HIGH );
delay(3);
}
//SPI.endTransaction(); // interrupt can now be accepted
// The last 4 bits of the 7th coefficient form a CRC error checking code.
unsigned char p_crc = sensorCoeffs[7];
// Use a function to calculate the CRC value
unsigned char n_crc = MS_5803_CRC(sensorCoeffs);
if (Verbose) {
for (int i = 0; i < 8; i++ )
{
// Print out coefficients
Serial.print("C");
Serial.print(i);
Serial.print(" = ");
Serial.println(sensorCoeffs[i]);
delay(10);
}
Serial.print("p_crc: ");
Serial.println(p_crc);
Serial.print("n_crc: ");
Serial.println(n_crc);
}
// If the CRC value doesn't match the sensor's CRC value, then the
// connection can't be trusted. Check your wiring.
if (p_crc != n_crc) {
return false;
}
// Otherwise, return true when everything checks out OK.
return true;
}
// Sends a power on reset command to the sensor.
void MS_5803_SPI::resetSensor() {
SPI.beginTransaction(settings_write);
digitalWrite(_cs, LOW); //csb_lo(); // pull CSB low to start the command
SPI.transfer(CMD_RESET); // send reset sequence
delay(3); // wait for the reset sequence timing delay(3)
digitalWrite(_cs, HIGH); //csb_hi(); // pull CSB high to finish the command
SPI.endTransaction(); // interrupt can now be accepted
}
The Code can be downloaded at: https://forum.arduino.cc/index.php?topic=670661.0
There you can find the schematic and output picture too.
Thanks a lot :).

SPI on ADE7953 board

So, I've been trying to emplement a SPI communication between the board and my arduino. In the board's manual, it says that it is required to send two bytes with the address I want to read/write and another byte to choose read or write (most significant bit tells you which will apply). However, my code does not seem to be running. Anyone care to help? Code
I've not used the actual Arduino SPI library, but I will offer you an Arduino snippet that will bitbang SPI instead. It will allow you to send some bytes just to see if everything is working. It might be useful to try another approach just to see if it works. You will need to change the pins and registers to match your target application.
#define PIN_SPIDATA 16
#define PIN_SPICLK 17
#define PIN_SPILOAD 18
#define REG_DECODEMODE 0x09
#define REG_INTENSITY 0x0A
#define REG_SCANLIMIT 0x0B
#define REG_SHUTDOWN 0x0C
#define REG_DISPLAYTEST 0x0F
void setup() {
// set ddr for sw spi pins
pinMode(PIN_SPICLK, OUTPUT);
pinMode(PIN_SPIDATA, OUTPUT);
pinMode(PIN_SPILOAD, OUTPUT);
setRegister(REG_INTENSITY, 0x04);
setRegister(REG_SCANLIMIT, 0x07);
setRegister(REG_SHUTDOWN, 0x01); // normal operation
setRegister(REG_DECODEMODE, 0x00); // pixels not integers
setRegister(REG_DISPLAYTEST, 0x00); // not in test mode
}
// sends a single byte by sw spi (no latching)
void putByte(uint8_t data)
{
uint8_t i = 8;
uint8_t mask;
while(i > 0) {
mask = 0x01 << (i - 1); // get bitmask
digitalWrite(PIN_SPICLK, LOW); // tick
if (data & mask){ // choose bit
digitalWrite(PIN_SPIDATA, HIGH); // set 1
}else{
digitalWrite(PIN_SPIDATA, LOW); // set 0
}
digitalWrite(PIN_SPICLK, HIGH); // tock
--i; // move to lesser bit
}
}
// sets register to the same byte value for all screens
void setRegister(uint8_t reg, uint8_t data)
{
digitalWrite(PIN_SPILOAD, LOW); // begin
for(uint8_t i = 0; i < numChips; ++i){
putByte(reg); // specify register
putByte(data); // send data
}
digitalWrite(PIN_SPILOAD, HIGH); // latch in data
digitalWrite(PIN_SPILOAD, LOW); // end
}

Arduino with two RC522

To pimp up my Carrera I'm going to build a round counter.
It contains an Arduino Nano, a lcd and 2 rc522 rfid-reader.
The readers share the pins for scd, miso, mosi and have own pins for sda and rst.
Actually I'm not able to get the two readers work together at the same time. Only if the one or the other reader is physically plugged (hardcore!) into the breadbord it works (without code changing). But not together.
It has to be an issue with my code, but where?
(The RFID-Communication ist inpired by the example from [addicore][1]http://www.addicore.com/v/vspfiles/downloadables/Product%20Downloadables/RFID_RC522/RFIDQuickStartGuide.pdf)
Is there anyone who has a hint for me?
#include <AddicoreRFID.h>
#include <SPI.h>
#include <LiquidCrystal.h>
#define uchar unsigned char
#define uint unsigned int
// create AddicoreRFID object to control the RFID module
/////////////////////////////////////////////////////////////////////
//set the pins
/////////////////////////////////////////////////////////////////////
//2 - SCK Digital 13
//3 - MOSI Digital 11
//4 - MISO Digital 12
const int SS1 = 8; //RFID1
const int RST1 = 9;
AddicoreRFID myRFID1 (SS1, RST1);
const int SS2 = 10; //RFID2
const int RST2 = A0;
AddicoreRFID myRFID2 (SS2, RST2);
//Maximum length of the array
#define MAX_LEN 16
//LCD init
// * LCD RS pin to digital pin 7
// * LCD Enable pin to digital pin 6
// * LCD D4 pin to digital pin 5
// * LCD D5 pin to digital pin 4
// * LCD D6 pin to digital pin 3
// * LCD D7 pin to digital pin 2
LiquidCrystal lcd1(7, 6, 5, 4, 3, 2);
//Counter
int a = 0;
int b = 0;
void setup() {
Serial.begin(9600);
//LCD init
init_lcd1();
myRFID1.AddicoreRFID_Init();
myRFID2.AddicoreRFID_Init();
}
void loop() {
uchar i, tmp, checksum1;
uchar status;
uchar str1[MAX_LEN];
uchar str2[MAX_LEN];
///////////// RFID1 ///////////////////
// 0x4400 = Mifare_UltraLight -Tag Type
str1[1] = 0x4400;
//Find tags, return tag type
// Manipuliert str1(!);
//AddicoreRFID::AddicoreRFID_Request(byte reqMode, byte *TagType)
status = myRFID1.AddicoreRFID_Request(PICC_REQIDL, str1);
if (status == MI_OK) {
serial_TagDetect(str1, 1);
}
//Anti-collision, return tag serial number 4 bytes
// Manipuliert str1(!);
status = myRFID1.AddicoreRFID_Anticoll(str1);
if (status == MI_OK) {
serial_TagData(str1);
lcd_counter(str1, lcd1);
//delay(500);
}
myRFID1.AddicoreRFID_Halt(); //Command tag into hibernation
///////////// RFID2 ///////////////////
str2[1] = 0x4400;
//Find tags, return tag type
status = myRFID2.AddicoreRFID_Request(PICC_REQIDL, str2);
if (status == MI_OK) {
serial_TagDetect(str2, 2);
}
//Anti-collision, return tag serial number 4 bytes
status = myRFID2.AddicoreRFID_Anticoll(str1);
if (status == MI_OK) {
serial_TagData(str2);
lcd_counter(str2, lcd1);
// liest sonst nonstop die Tags!
//delay(500);
}
myRFID2.AddicoreRFID_Halt(); //Command tag into hibernation
}
void init_lcd1() {
... inits the lcd ...
}
// Zählt das Auftreten der Tags
void lcd_counter (uchar *str, LiquidCrystal lcd ) {
... output to the lcd ....
}
// Meldet gefundenen Tag auf der Konsole
void serial_TagDetect(uchar *str, int reader) {
if (reader == 1) {
Serial.print("RFID1 tag detected: ");
} else {
Serial.print("RFID2 tag detected: ");
}
Serial.print(str[0], BIN);
Serial.print(" , ");
Serial.print(str[1], BIN); Serial.println(" ");
}
// gibt Tagdaten auf der Konsole aus
void serial_TagData(uchar *str) {
uchar checksum1 = str[0] ^ str[1] ^ str[2] ^ str[3];
Serial.print("The tag's number is: ");
//Serial.print(2);
Serial.print(str[0]);
Serial.print(" , ");
Serial.print(str[1], BIN);
Serial.print(" , ");
Serial.print(str[2], BIN);
Serial.print(" , ");
Serial.print(str[3], BIN);
Serial.print(" , ");
Serial.print(str[4], BIN);
Serial.print(" , ");
Serial.println(checksum1, BIN);
}
I wonder about that the same(!!) rfid tag has different values depending it gets read from RFID1 or RFID2:
RFID1 tag detected: 1000100 , 0
The tag's number is: 136 , 100 , 11100 , 1101011 , 11111011 , 11111011
RFID2 tag detected: 1000100 , 0
The tag's number is: 68 , 0 , 0 , 0 , 0 , 1000100
I use 10 RC522 together at the same time with Ardunio mega .
Try this example for 2 ncf reader, its work for me. I tested in Arduino Nano.
The readers share the pins for 3,3V, GND. SCD, MISO, MOSI, RST and have own pins for SDA. I don't use the IRQ pin.
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS1_PIN 10 // Configurable, see typical pin layout above
#define SS2_PIN 8 // Configurable, see typical pin layout above
MFRC522 mfrc522_1(SS1_PIN, RST_PIN); // Create MFRC522 instance
MFRC522 mfrc522_2(SS2_PIN, RST_PIN);
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522_1.PCD_Init(); // Init MFRC522
mfrc522_1.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
mfrc522_2.PCD_Init(); // Init MFRC522
mfrc522_2.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
}
void loop() {
// Look for new cards
if ( mfrc522_1.PICC_IsNewCardPresent() || mfrc522_2.PICC_IsNewCardPresent()) {
Serial.println(F("New card..."));
} else {
return;
}
// Select one of the cards
if ( ! mfrc522_1.PICC_ReadCardSerial() && ! mfrc522_2.PICC_ReadCardSerial()) {
Serial.println(F("Read..."));
return;
}
// Dump debug info about the card; PICC_HaltA() is automatically called
mfrc522_1.PICC_DumpToSerial(&(mfrc522_1.uid));
mfrc522_2.PICC_DumpToSerial(&(mfrc522_2.uid));
}
//Anti-collision, return tag serial number 4 bytes
status = myRFID2.AddicoreRFID_Anticoll(str1); // <<<< needs to be strl2

Arduino - deleting variables after radio send doesn't work

I have tried so hard but i just can't understand why the two lines in my Tx code :
inputString = "";
stringComplete = false;
Stop my radio is working.
If I delete this code, it just keeps sending the values over and over without being able to stop it.
Tx:
/* YourDuinoStarter Example: nRF24L01 Transmit Joystick values
- WHAT IT DOES: Reads Analog values on A0, A1 and transmits
them over a nRF24L01 Radio Link to another transceiver.
- SEE the comments after "//" on each line below
- CONNECTIONS: nRF24L01 Modules See:
http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
1 - GND
2 - VCC 3.3V !!! NOT 5V
3 - CE to Arduino pin 9
4 - CSN to Arduino pin 10
5 - SCK to Arduino pin 13
6 - MOSI to Arduino pin 11
7 - MISO to Arduino pin 12
8 - UNUSED
-
Analog Joystick or two 10K potentiometers:
GND to Arduino GND
VCC to Arduino +5V
X Pot to Arduino A0
Y Pot to Arduino A1
- V1.00 11/26/13
Based on examples at http://www.bajdi.com/
Questions: terry#yourduino.com */
/*-----( Import needed libraries )-----*/
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
/*-----( Declare Constants and Pin Numbers )-----*/
#define CE_PIN 9
#define CSN_PIN 10
// NOTE: the "LL" at the end of the constant is "LongLong" type
const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe
/*-----( Declare objects )-----*/
RF24 radio(CE_PIN, CSN_PIN); // Create a Radio
/*-----( Declare Variables )-----*/
String inputString = "";
boolean stringComplete = false;
int msg[1]; // 2 element array holding Joystick readings
int msgNum = 0;
void setup() /****** SETUP: RUNS ONCE ******/
{
Serial.begin(9600);
radio.begin();
radio.openWritingPipe(pipe);
}//--(end setup )---
void loop() /****** LOOP: RUNS CONSTANTLY ******/
{
serialEvent();
if (stringComplete) {
inputString.trim();
String on1 = "onone";
on1.trim();
String on2 = "ontwo";
on2.trim();
String off1 = "offone";
off1.trim();
String off2 = "offtwo";
off2.trim();
if (inputString.equals(on1)) {
Serial.print("1 is On");
msg[0] = 111;
radio.write(msg, 1);
inputString = "";
stringComplete = false;
} else if (inputString.equals(off1)) {
Serial.print("1 Is Off");
msg[0] = 112;
radio.write(msg, 1);
inputString = "";
stringComplete = false;
} else if (inputString.equals(on2)) {
Serial.print("2 Is On");
msg[0] = 113;
radio.write(msg, 1);
inputString = "";
stringComplete = false;
} else if (inputString.equals(off2)) {
Serial.print("2 Is Off");
msg[0] = 114;
radio.write(msg, 1);
inputString = "";
stringComplete = false;
} else {
inputString = "";
stringComplete = false;
}
}
}//--(end main loop )---
/*-----( Declare User-written Functions )-----*/
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
delay(100);
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
//NONE
//*********( THE END )***********
Rx:
/* YourDuinoStarter Example: nRF24L01 Receive Joystick values
- WHAT IT DOES: Receives data from another transceiver with
2 Analog values from a Joystick or 2 Potentiometers
Displays received values on Serial Monitor
- SEE the comments after "//" on each line below
- CONNECTIONS: nRF24L01 Modules See:
http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
1 - GND
2 - VCC 3.3V !!! NOT 5V
3 - CE to Arduino pin 9
4 - CSN to Arduino pin 10
5 - SCK to Arduino pin 13
6 - MOSI to Arduino pin 11
7 - MISO to Arduino pin 12
8 - UNUSED
- V1.00 11/26/13
Based on examples at http://www.bajdi.com/
Questions: terry#yourduino.com */
/*-----( Import needed libraries )-----*/
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
/*-----( Declare Constants and Pin Numbers )-----*/
#define CE_PIN 9
#define CSN_PIN 10
int ledPin = 3;
// NOTE: the "LL" at the end of the constant is "LongLong" type
const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe
/*-----( Declare objects )-----*/
RF24 radio(CE_PIN, CSN_PIN); // Create a Radio
/*-----( Declare Variables )-----*/
int msg[1]; // 2 element array holding Joystick readings
int lastMsgNum;
void setup() /****** SETUP: RUNS ONCE ******/
{
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
delay(1000);
Serial.println("Nrf24L01 Receiver Starting");
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();;
}//--(end setup )---
void loop() /****** LOOP: RUNS CONSTANTLY ******/
{
if ( radio.available() )
{
// Read the data payload until we've received everything
bool done = false;
while (!done)
{
// Fetch the data payload
done = radio.read( msg, sizeof(msg) );
Serial.print(msg[0]);
if (msg[0] == 111) {
digitalWrite(3, HIGH);
} else if (msg[0] == 112) {
digitalWrite(3, LOW);
} else if (msg[0] == 113) {
digitalWrite(5, HIGH);
} else if (msg[0] == 114) {
digitalWrite(5, LOW);
}
}
}
else
{
//Serial.println("No radio available");
}
}//--(end main loop )---
/*-----( Declare User-written Functions )-----*/
//NONE
//*********( THE END )***********
I think that you don't understand why you must initialize/set your variables.
inputString and stringComplete are global variables, so when you changed it in serialEvent() you could see it in loop() so when you read a '\n' in serialEvent(). You understand that the sender has finished transmission so you must analize it. Once you finished the corresponding action, you must initialize the global variable again to start again. Unless you have done that, you see stringComplete == true so you start to analize it again in the next cycle of loop().
Usually we call this boolean variables as 'flag', you can see it in several places of code to 'sync' it. In this case, you set true when you have finished the reception and set false when you have finished the analisys.

Resources