RF transmitted Hex string comparison Vs embedded string Arduino - 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

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--;
}

Some LED fade and others will flash when all LED should flash Adrunio Nano

I am having trouble with my Arduino code and circuit. The goal is to have each LED fade one after another. This is not happening correctly. Some LED will fade up and down properly and then some will blink instead. I have been trying to troubleshoot and here is what I have done and has not fixed it.
used a different board
Swap LEDs
Used different resistors
Swapped pins that blink to pins that faded and the blink will be fading
Moved circuit to a different breadboard
Check that the code is sending the correct light level through the serial monitor
Here is a picture of my board
Here is the code:
const int BUTTON = 2; // Naming switch button pin
const int LED1 = 3; // Namin LED pin
const int LED2 = 4;
const int LED3 = 5;
const int LED4 = 6;
const int LED5 = 7;
const int LED6 = 8;
const int LED7 =9;
const int LED8 = 10;
const int LED9 = 11;
int BUTTONstate = 0; // A variable to store Button Status / Input
int brightness = 0;
int fadeAmount =5;
void setup(){
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);
pinMode(LED5, OUTPUT);
pinMode(LED6, OUTPUT);
pinMode(LED7, OUTPUT);
pinMode(LED8, OUTPUT);
pinMode(LED9, OUTPUT);
pinMode (BUTTON, INPUT);
Serial.begin(9600);
}
void loop() {
BUTTONstate = digitalRead(BUTTON); // Reading button status / input
if (BUTTONstate == HIGH) // Condition to check button input
{
FlashingLight();
}
else
{
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
digitalWrite(LED4, LOW);
digitalWrite(LED5, LOW);
digitalWrite(LED6, LOW);
digitalWrite(LED7, LOW);
digitalWrite(LED8, LOW);
digitalWrite(LED9, LOW);
}
}
void FlashingLight()
{
for ( int i = 0; i<=4;i++){
//digitalWrite(LED, LOW);
fading(LED1); //Fades
fading(LED2); // blinks
fading(LED3); //fades
fading(LED4); //fades
fading(LED5); //blinks
fading(LED6); //blinks
fading(LED7); //fades
fading(LED8); //fades
fading(LED9); //fades
delay(1000);
}
}
void fading(int val) {
//brightness =0;
//digitalWrite(LED, LOW);
analogWrite(val,brightness);
for (brightness = 0; brightness <= 150; brightness += 5) {
analogWrite(val,brightness);
delay(30);
Serial.println(brightness);
}
for (brightness = 150; brightness >= 0; brightness -= 5) {
analogWrite(val,brightness);
delay(30);
Serial.println(brightness);
}
delay(100);
//brightness =0;
}
Thank you for your help and let me know if you have any questions,
According to this Arduino.cc reference not all pins of the Arduino Nano are suitable for PWM control (using analogWrite()). On the Nano, only pins 3, 5, 6, 9, 10, 11 can be used to output a PWM signal.

How to lower power consumption ARDUINO and RFID mfrc522

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);
}
}
//////////////////////////////////////////////////////////////////

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");

How to write a state change (edge detection) using analogRead() on Arduino?

I'm having trouble creating a toggle switch using an analog input connected to an RF receiver. I'm attempting to make a servo turn 180 degrees when the voltage reads higher than 800 and stay at 180 degrees until the button is pressed again. It only reads higher than 800 when I press a button on my key fob (RF transmitter). In my code it does this, but it doesn't hold at 180 degrees and wait until the button is pressed again to go back to 0 degrees.
#include <Servo.h>
Servo myservo;
const int analogInPin = A0;
int led = 13;
float sensorValue = 0;
void setup(){
Serial.begin(2400);
pinMode(led, OUTPUT);
myservo.attach(6);
myservo.write(0);
}
void loop(){
sensorValue = analogRead(analogInPin);
Serial.print("Voltage Output = ");
Serial.print(sensorValue);
Serial.println(" ");
delay(100);
if (sensorValue > 800) {
digitalWrite(led, HIGH);
myservo.write(180);
delay(100);
}
else{
digitalWrite(led, LOW);
myservo.write(0);
delay(100);
}
}
EDIT: I'm pretty close with this edited code. I added a variable and an if statement. It turns the LED on and it stays on, but when pressed again it doesn't turn off. So close...
const int analogInPin = A0;
int led = 13;
int ledState = 0;
float sensorValue = 0;
void setup(){
Serial.begin(2400);
pinMode(led, OUTPUT);
}
void loop(){
sensorValue = analogRead(analogInPin);
Serial.print("Voltage Output = ");
Serial.print(sensorValue);
Serial.println(" ");
delay(100);
if (sensorValue < 400 && ledState == 0) {
digitalWrite(led, HIGH);
delay(500);
ledState == 1;
}
if (sensorValue < 400 && ledState == 1) {
digitalWrite(led, LOW);
delay(500);
ledState == 0;
}
}
OK. I think I solved it! Take a look. It now turns the LED on when the button is pressed and stays on until the button is pressed again. This is how to create a switch using an analog input reading.
const int analogInPin = A0;
int led = 13;
int ledState = 0;
float sensorValue = 0;
void setup(){
Serial.begin(2400);
pinMode(led, OUTPUT);
}
void loop(){
sensorValue = analogRead(analogInPin);
Serial.print("Voltage Output = ");
Serial.print(sensorValue);
Serial.println(" ");
delay(100);
if (sensorValue < 400 && ledState == 0) {
digitalWrite(led, HIGH);
delay(100);
ledState = 1;
Serial.println(ledState);
delay(500);
}
else {
if (sensorValue < 400 && ledState == 1) {
digitalWrite(led, LOW);
delay(100);
ledState = 0;
Serial.println(ledState);
delay(500);
}
}
}

Resources