How to lower power consumption ARDUINO and RFID mfrc522 - arduino

Im making a project that i scan rfid cards to gain access to a door. I have made the code the way i want it to function but currently its drawing 22mA. I want this project to be powered by an 4Ah Lead acid battery.
I have removed the leds from the reader and from the arduino to lower consumption. Also i run arduino at 1Mhz and that looks that lowered the consumption a lot. Also i disabled Analog converter of arduino.
IM using arduino nano and RFID-RC522 reader
the output is an 5 volt relay.
Here is the code:
#include <SPI.h>
#include <MFRC522.h>
#include <EEPROM.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);
#define relay 4
#define led 2
#define button 5
byte readCard[4];
byte storeCard[4];
byte lastCard[4] = {1,2,3,4};
uint8_t successread = 0;
int flag=0;
void setup() {
CLKPR = 0x80;
CLKPR = 0x04;
ADCSRA = 0;
pinMode(relay, OUTPUT);
pinMode(button, INPUT_PULLUP);
pinMode(led, OUTPUT);
digitalWrite(relay, LOW);
digitalWrite(led, LOW);
SPI.begin();
mfrc522.PCD_Init();
}
void loop() {
do {
successread = getID();
}
while(!successread);
digitalWrite(led, HIGH);
delayMicroseconds(100);
digitalWrite(led, LOW);
lastcard();
if(digitalRead(button)==LOW){
save_delCard();
}
if(checkID(readCard) && !(digitalRead(button)==LOW)){
if(flag==0){
digitalWrite(relay, HIGH);
flag = !flag;
}
else{
digitalWrite(relay, LOW);
flag = !flag;
}
}
}
/////////READ CARD FROM READER/////////////////
uint8_t getID(){
if ( ! mfrc522.PICC_IsNewCardPresent()) { //If a new PICC placed to RFID
reader continue
return 0;
}
if ( ! mfrc522.PICC_ReadCardSerial()) { //Since a PICC placed get
Serial and continue
return 0;
}
for (uint8_t i=0; i<4; i++){
readCard[i] = mfrc522.uid.uidByte[i];
}
mfrc522.PICC_HaltA(); // stop reading
return 1;
}
///////////////////SAVE OR DELETE CARD/////////////////////////
uint8_t save_delCard(){
uint8_t count = EEPROM.read(0);
int start = (count*4) + 1;
int num = count*4 +1;
if(checkID(readCard)){
uint8_t slot = slotcheck(readCard);
for(uint8_t m=0;m<4;m++){
EEPROM.write((num-m-1),0);
}
for(uint8_t k=0;k<4;k++){
EEPROM.write((((slot-1)*4)+1+k),lastCard[k]);
}
count--;
}
else{
count++;
}
for(uint8_t j=0; j<4;j++){
EEPROM.write(j + start, readCard[j]);
}
EEPROM.write(0,count);
return 0;
}
////////////////////READ FROM MEMORY//////////////////////////////////
uint8_t readID(uint8_t number){
uint8_t start = (number*4) + 1;
for(uint8_t j=0;j<4;j++){
storeCard[j] = EEPROM.read(start + j);
}
}
///////////////////COMPARE IDS///////////////////////////////
bool compare(byte arraya[],byte arrayb[]){
for(uint8_t i=0;i<4;i++){
if(arraya[i]!=arrayb[i]){
return false;
}
else{
return true;
}
}
}
/////////CHECK IF CARD IS IN MEMORY/////////////////////////////////////
bool checkID(byte arraya[]){
uint8_t count = EEPROM.read(0);
for(int i=0;i<count;i++){
readID(i);
if(compare(arraya, storeCard)){
return true;
}
else {
}
}
return false;
}
////////////////FINDS WHERE CARD IS IN MEMORY//////////////////
uint8_t slotcheck(byte arraya[]){
uint8_t count = EEPROM.read(0);
uint8_t slot=0;
for(int i=0;i<count;i++){
readID(i);
slot = i+1;
if(compare(arraya, storeCard)){
return slot;
}
else {
}
}
return NULL;
}
///////////////SAVES LAST CARD/////////////////////
void lastcard(){
uint8_t count = EEPROM.read(0);
for(uint8_t p=0;p<4;p++){
lastCard[p] = EEPROM.read((count*4)-3+p);
}
}
//////////////////////////////////////////////////////////////////

Related

AttachIntrerrupt stops NRF24L01+ from working - ARDUINO

If I remove attachInterrupt(digitalPinToInterrupt(encoder1),readEncoder,RISING); The code works. But once its added, the radio.available doesnt let anything under it run.
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
struct InputData // define stuct
{
int x;
int y;
};
InputData data;
// Motor A connections
int motor_enA = 9;
int motor_in1 = 10;
int motor_in2 = 6;
int encoder1 = 2;
int encoder2 = 3;
int counter = 0;
int angle = 0;
void setup() {
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(1, address);
radio.setPALevel(RF24_PA_MIN);
radio.startListening();
// Set all the motor control pins to outputs
pinMode(motor_enA, OUTPUT);
pinMode(motor_in1, OUTPUT);
pinMode(motor_in2, OUTPUT);
// Turn off motors - Initial state
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, LOW);
analogWrite(motor_enA, 255);
pinMode (encoder1, INPUT);
pinMode (encoder2, INPUT);
attachInterrupt(digitalPinToInterrupt(encoder1),readEncoder,RISING);
}
void loop() {
readEncoder();
if (radio.available()) {
radio.read(&data, sizeof(data));
// Serial.println(data.y);
if (data.y > 5) {
digitalWrite(motor_in1, HIGH);
digitalWrite(motor_in2, LOW);
}
else if (data.y < -5) {
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, HIGH);
}
else {
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, LOW);
}
}
if(counter>1){
counter=0;
angle+=2;
}else if(counter<-1){
counter=0;
angle-=2;
}
Serial.print("Position: ");
Serial.println(angle);
}
void readEncoder()
{
if(digitalRead(encoder1)==HIGH){
int b = digitalRead(encoder2);
if(b>0){
counter++;
}
else{
counter--;
}
}
}
I have tried removing and adding the line, as described above^^
as mentioned by Hcheung, make counter volatile and remove readEncoder(); from loop.
I simplify a bit ISR readEncoder();
volatile int counter = 0;
[....]
void readEncoder() {
//if(digitalRead(encoder1)==HIGH){ //we are precisely here because digitalRead(encoder1) = HIGH !
if(digitalRead(encoder2)) counter++;
else counter--;
}

Can you help me fix the error message I am getting on my code?

I have these two sets of code and they both run fine on their own, but when I am trying to merge them together I am getting a ton of error messages. I'm new to coding and don't really know a whole lot so I was wondering if someone could just quickly look it over and see what's wrong. The compiler is saying that there is an expected unqualified id before the '{' token at the bottom where I have the code for the pushbutton. However I have tried and removed this and then I get the same message but instead of '{' it says 'if'
Thank you very much
EDIT: I don't know what properly formatting an error message looks like but here is my attempt:
Complete_Code:69:1: error: expected unqualified-id before '{' token
{
^
exit status 1
expected unqualified-id before '{' token
Here is the code in question
int pinButton = 5;
#include <Servo.h>
int servo1Pin = 8;
Servo servo1;
#include <Servo.h>
#define mainArm 0
#define jib 1
#define bucket 2
#define slew 3
Servo servo[2]; //code used for attaching upto 4 servos
byte angle[2] = {90, 90}; // middle point for servo angle
byte potPin[2] = {A1, A2}; // input pins to attach your potentiometers
byte servoPin[2] = {7, 6};
void setup() {
Serial.begin(9600);
Serial.println("Starting DiggerCode.ino");
for (byte n = 0; n < 4; n++) {
servo[n].attach(servoPin[n]);
}
pinMode(pinButton, INPUT);
pinMode(12, OUTPUT); //red LED
pinMode(11, OUTPUT); // yellow LED
pinMode(10, OUTPUT); // green LED
servo1.attach(servo1Pin);
}
void loop() {
readPotentiometers();
moveServos();
delay(10);
}
void readPotentiometers() {
int potVal;
for (byte n = 0; n < 4; n++) {
potVal = analogRead(potPin[n]);
if (potVal < 200) { // dead zone for the joystick I used is 200 to 550.
angle[n] += 1;
if (angle[n] > 170) {
angle[n] = 170;
}
}
if (potVal > 550) { // deadzone upper value
angle[n] -= 1;
if (angle[n] < 10) {
angle[n] = 10;
}
}
}
}
void moveServos() {
for (byte n = 0; n < 4; n++) {
servo[n].write(angle[n]);
}
}
{
int stateButton = digitalRead(pinButton); //read the state of the button
if (stateButton == HIGH) { //if is pressed
Serial.println("Switch = High");
digitalWrite(12, HIGH);
delay(1000);
digitalWrite(12, LOW);
digitalWrite(11, HIGH);
delay(1000);
digitalWrite(11, LOW);
digitalWrite(10, HIGH);
delay(1000);
digitalWrite(10, LOW);
delay(500);
servo1.write(180);
delay(1000);
// Make servo go to 180 degrees
servo1.write(90);
delay(1000);
servo1.write(180);
}
}
It seems you dropped the first things of function definition for some reason.
Add function return type, name and arguments for example
void anImportedFunction()
Before the part starting from
{
int stateButton = digitalRead(pinButton); //read the state of the button
You may also need to call the added function from somewhere.
I looked through your code and edited, some unnecessary and missing parts.
I checked it, no more syntax errors. I think it must work.
#include <Servo.h>
#define mainArm 0
#define jib 1
#define bucket 2
#define slew 3
Servo servo1;
Servo servo[4]; //code used for attaching upto 4 servos
int pinButton = 5;
int servo1Pin = 8;
byte angle[2] = {90, 90}; // middle point for servo angle
byte potPin[2] = {A1, A2}; // input pins to attach your potentiometers
byte servoPin[2] = {7, 6};
void setup() {
Serial.begin(9600);
Serial.println("Starting DiggerCode.ino");
for (byte n = 0; n <= 4; n++) {
servo[n].attach(servoPin[n]);
}
pinMode(pinButton, INPUT);
pinMode(12, OUTPUT); //red LED
pinMode(11, OUTPUT); // yellow LED
pinMode(10, OUTPUT); // green LED
servo1.attach(servo1Pin);
}
void loop() {
readPotentiometers();
moveServos();
delay(10);
}
void readPotentiometers() {
int potVal;
for (byte n = 0; n <= 4; n++) {
potVal = analogRead(potPin[n]);
if (potVal < 200) { // dead zone for the joystick I used is 200 to 550.
angle[n] += 1;
if (angle[n] > 170) {
angle[n] = 170;
}
}
if (potVal > 550) { // deadzone upper value
angle[n] -= 1;
if (angle[n] < 10) {
angle[n] = 10;
}
}
}
}
void moveServos() {
for (byte n = 0; n <= 4; n++) {
servo[n].write(angle[n]);
}
}
void Switch() //here instead of "Switch" you can use any function name you want
{
int stateButton = digitalRead(pinButton); //read the state of the button
if (stateButton == HIGH) { //if is pressed
Serial.println("Switch = High");
digitalWrite(12, HIGH);
delay(1000);
digitalWrite(12, LOW);
digitalWrite(11, HIGH);
delay(1000);
digitalWrite(11, LOW);
digitalWrite(10, HIGH);
delay(1000);
digitalWrite(10, LOW);
delay(500);
servo1.write(180);
delay(1000);
// Make servo go to 180 degrees
servo1.write(90);
delay(1000);
servo1.write(180);
}
}

Implementing the function interrupt with if statements

I want to implement the function interrupt () but I don't know exactly how..In this case there is 2 for loops which can be seen in the code:I want whenever one of the 2 buttons is pressed the process inside the loop to be interrupted immediately:
void loop() {
int brightButton = digitalRead(K1);
int ldrStatus = analogRead(ldrPin);
if (brightButton == LOW && ldrStatus >= 200)
{
for (int i = 0; i < 10; i++)
{
digitalWrite(greenLed, HIGH);
tone(buzzer,400);
delay(500);
noTone(buzzer);
delay(500);
}
}
else {
digitalWrite(greenLed, LOW);
}
int tempButton = digitalRead(K2);
int valNTC = analogRead(NTC);
if (tempButton == LOW && valNTC > 512)
{
for (int i = 0; i <10; i++)
{
digitalWrite(redLed, HIGH);
tone(buzzer,450);
delay(300);
noTone(buzzer);
delay(1000);
}
}
else {
digitalWrite(redLed, LOW);
}
}
Example code from the Arduino manual:
https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}
void loop() {
digitalWrite(ledPin, state);
}
void blink() {
state = !state;
}
Note that this will interrupt the for loop and return to it once the interrupt service routine is finished.
If you want to abort the for loop check the pin state in every loop cycle and break if you want to leave the for loop or return if you want to leave loop().
Of course this is not "immediately".

Openhab doesn't change the status of switch from manual overide

I have just made an account because of this particular problem I'm having with OpenHAB. I was following a tutorial from this https://openhardwarecoza.wordpress.com/2015/03/29/openhab-mqtt-arduino-and-esp8266-part-3-hardware-arduino-with-ethernet-shield/ site but since the reply there didn't help me. I decided to go to this site.
I have successfully installed OpenHAB and use it. When I turn the switch off and on from both the HTTP page and android device, It works just fine. But when I tried to manual override using a push button on an Arduino. It didn't update the state of the switch in both of them. I'm using windows with OpenHAB version 1.71
The Openhab server notices that there is an update of the state from the push button, but the button in the HTTP page and android device didn't change at all.
I have tested the connection using MQTTlens and it works just fine.
Below is my code
items configuration
Group All
Switch mqttsw1 "Switch 1" (all) {mqtt=">[mymosquitto:/arduino/l1/com:command:off:0],>[mymosquitto:/arduino/l1/com:command:on:1],<[mymosquitto:/arduino/l1/state:state:default]"}
Switch mqttsw2 "Switch 2" (all) {mqtt=">[mymosquitto:/arduino/l2/com:command:off:0],>[mymosquitto:/arduino/l2/com:command:on:1],<[mymosquitto:/arduino/l2/state:state:default]"}
Number temp "Temperature [%.1f °C]" <temperature> {mqtt="<[mymosquitto:/arduino/temp/state:state:default]"}
Number hum "Humidity [%.1f &#37]" <temperature> {mqtt="<[mymosquitto:/arduino/hum/state:state:default]"}
Sitemap configuration
sitemap dolphin label="Main Menu"
{
Frame label="Switch" {
Switch item=mqttsw1 label="Switch 1"
Switch item=mqttsw2 label="Switch 2"
}
Frame label="Weather" {
Text item=temp
Text item=hum
}
The Arduino Code
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <DHT.h>
const int butt1 = 3;// the pin that the pushbutton is attached to
const int butt2 = 2;
const int ledPin1 = 5;
const int ledPin2 = 4;
int ledState1 = HIGH;
int buttonState1;
int lastButtonState1 = LOW;
int ledState2 = HIGH;
int buttonState2;
int lastButtonState2 = LOW;
long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 60000; // READING INTERVAL
int t = 0; // TEMPERATURE VAR
int h = 0; // HUMIDITY VAR
#define DHTPIN 24 // SENSOR PIN
#define DHTTYPE DHT11 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
DHT dht(DHTPIN, DHTTYPE);
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xEF };
IPAddress ip(192, 168, 1, 103);
IPAddress server(192, 168, 1, 100);
void callback(char* topic, byte* payload, unsigned int length);
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println();
Serial.println("Callback");
Serial.print("Topic = ");
Serial.println(topic);
Serial.print("Payload = ");
for (int i=0;i<length;i++){
Serial.print((char)payload[i]);
}
Serial.println();
if (strcmp(topic,"/esp1/l1/com")==0) {
if (payload[0] == '0')
{
digitalWrite(ledPin1, LOW);
delay(100);
client.publish("/esp1/l1/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(ledPin1, HIGH);
delay(100);
client.publish("/esp1/l1/state","1");
}
}
if (strcmp(topic,"/esp1/l2/com")==0) {
if (payload[0] == '0')
{
digitalWrite(ledPin2, LOW);
delay(100);
client.publish("/esp1/l2/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(ledPin2, HIGH);
delay(100);
client.publish("/esp1/l2/state","1");
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
Serial.println("connected");
client.subscribe("/esp1/#");
client.publish("conn","Connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void push1() {
int reading1 = digitalRead(butt1);
buttonState1 = reading1;
if (buttonState1 == HIGH) {
ledState1 = !ledState1;
if (ledState1 < 1)
{
digitalWrite(ledPin1, LOW);
delay(100);
client.publish("/esp1/l1/com","0");
client.publish("/esp1/l1/state","0");
}
else
{
digitalWrite(ledPin1, HIGH);
delay(100);
client.publish("/esp1/l1/com","1");
client.publish("/esp1/l1/state","1");
}
}
}
void push2() {
int reading2 = digitalRead(butt2);
buttonState2 = reading2;
if (buttonState2 == HIGH) {
ledState2 = !ledState2;
if (ledState2 < 1)
{
digitalWrite(ledPin2, LOW);
delay(100);
client.publish("/esp1/l2/com","0");
client.publish("/esp1/l2/state","0");
}
else
{
digitalWrite(ledPin2, HIGH);
delay(100);
client.publish("/esp1/l2/com","1");
client.publish("/esp1/l2/state","1");
}
}
}
void temp() {
h = (int)dht.readHumidity();
t = (int)dht.readTemperature();
char temp[2];
char hum[3];
sprintf(hum, "%d", h);
sprintf(temp, "%d", t);
client.publish("/esp1/temp/state", temp);
client.publish("/esp1/hum/state", hum);
}
void setup() {
// put your setup code here, to run once:
pinMode(butt1, INPUT);
pinMode(butt2, INPUT);
// initialize the LED as an output:
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
Serial.begin(9600);
Ethernet.begin(mac, ip);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
pinMode(26, OUTPUT); // sets the digital pin as output
pinMode(22, OUTPUT); // sets the digital pin as output
digitalWrite(26, HIGH); // sets +5v for the sensor
digitalWrite(22, LOW); // sets gnd for the sensor
h = (int)dht.readHumidity();
t = (int) dht.readTemperature();
if (client.connect("arduinoClient")) {
client.publish("conn","Connected");
client.subscribe("/esp1/#");
}
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()) {
reconnect();
}
currentMillis = millis();
if (currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
previousMillis = currentMillis;
temp();
}
int reading1 = digitalRead(butt1);
int reading2 = digitalRead(butt2);
if (reading1 != buttonState1) {
push1();
}
if (reading2 != buttonState2){
push2();
}
client.loop();
}
If there are anybody who can help me I would be very grateful. Thank you for your attention !
Best Regards,
Aldi
If I remember correctly you should post back a status of ON or OFF instead of 1 or 0.
Could you change your arduino code to publish back ON and OFF and test that?
e.g.
client.publish("/esp1/l1/state","ON");

RF transmitted Hex string comparison Vs embedded string Arduino

I am using the VirtualWire library on my Arduino Micro. I am having trouble in comparing the string of HEX received via rf module on pin 2 of the board. When reaching if stringOne == stringVal2, LED3 is always lit. I am not sure where to go from here or where to even begin on reading to figure out converting HEX to a readable comparator.
#include <VirtualWire.h>
#define RX 2
#define LED A0
#define LED2 PIND7
#define LED3 PIND6
void setup(){
Serial.begin(9600);
Serial.print("setup complete");
pinMode(RX, INPUT);
pinMode(LED, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
vw_set_rx_pin(RX);
vw_setup(2000);
vw_rx_start();
}
void loop(){
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen)){
int i;
Serial.print("Got:");
for (i = 0; i < buflen; i++){
//Serial.print(buf[i], HEX);
//String stringVal = String('65'+'6c'+'6c'+'6f'+'20'+'*','\0');
String stringVal2 = String('73'+'6F'+'20'+'6C'+'6F'+'6E'+'*', HEX);
String stringOne = String(buf[i], HEX);
Serial.print(stringOne);
Serial.print(' ');
digitalWrite(LED, HIGH);
delay(1000);
digitalWrite(LED,LOW);
delay(1000);
if (stringOne == stringVal2){
digitalWrite(LED2, HIGH);
}
else{
digitalWrite(LED3, HIGH);
}
}
Serial.println();
}
}
Here is the code for my transmitter as well. Using Adafruit Trinket5v 8Mhz
#include <VirtualWire.h>
const int TX = 3;
const int LED = 2;
const int buttonPin = 0; //Yellow Button
const int buttonPin2 =4; //Red Button
int buttonState = 0;
int buttonState2 = 0;
void setup(){
vw_set_tx_pin(TX);
// vw_set_ptt_pin(txpin);
// vw_set_ptt_inverted(false);
vw_setup(2000);
pinMode(LED, OUTPUT); //Signals button press/transmission being sent
pinMode(buttonPin, INPUT);
}
byte count = 1;
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(LED, HIGH);
char msg[7] = {'h','e','l','l','o',' ','#'};
msg[6] = count;
vw_send((uint8_t *)msg, 7);
vw_wait_tx();
count = count + 1;
}
else {
// turn LED off:
digitalWrite(LED, LOW);
}
buttonState2 = digitalRead(buttonPin2);
if (buttonState2 == HIGH){
digitalWrite(LED, HIGH);
char msg[7] = {'12','11','10','9','8','7','6'};
msg[6] = count;
vw_send((uint8_t *)msg, 7);
vw_wait_tx();
count = count + 1;
}
else {
digitalWrite(LED, LOW);
}
}
You are comparing a string that is just text to an array of chars. These will never evaluate out properly
If you want to initialise the stringVal2 properly to compare it directly you need to do this:
char strVal[] = {0x73, 0x6f, 0x20, 0x6c, 0x6f, 0x6e};
String stringVal2 = String(strVal);
This prints out the same as the other string you brought in.
Also, since you are basically just catching a char array then you might as well use a char array directly to evaluate the results and convert to a string when you need to output to a human

Resources