Why does the IR reciver gives diffrent value everytime I try to break a for loop - when new value is recived, Arduino ide? - arduino

I am new to Arduino programming and was trying to make an IR-controlled WS2812 led strip light, everything works fine apart from when I try to stop the for-loop when my IR receiver gets a new decoded value. It does get the job done but the received values are different every time. when I tested the same controller with a simple IR receiver program everything worked fine.
switch(value){
case 16720095:
delay (200);
irrecv.resume();
for (int i = 0; i <= 182; i++) {
leds[i] = CRGB (0,0,0);
FastLED.show();
if (irrecv.decode(&results))
{
value = results.value;
Serial.println(value);
break;
}
delay(40);
}
}
}
and the serial outputs:
first time:
16720095
-1572362453
second time:
16720095
-1406992986
third time:
16720095
811035822

It looks like you need to call "irrecv.resume()" within the if (irrecv.decode(&results)) block in order to tell the driver to keep looking for signals. The second values you are getting are garbage because you are asking it to provide data it hasn't received/ prepared.

Related

arduino uno with PWM driven motor and 433mhz wireless receiver don't work

I am fairly new to the arduino topic and try to get a few things to work together.
First i tried setting up a DC motor that can be controlled via PWM, which works perfectly when used standalone. I can start/stop the motor and change speed depending on the value i send to the PWM pin.
Second i tried to use an RF-5V wireless receiver to work with a remote control from remote switched power outlets. For this one i followed the instructions on how to build a 433mhz sniffer.
This all by itself works as well. I can receive diffent codes depending on which keys on the remote i am pressing.
Now the fun part started: I wanted to integrate both of the projects into one, so i could use the remote to start/stop the motor.
So i came up with the following circuit:
(Thanks for some of you pointing out that the circuit does not match the sketch. I made an error when drawing, but even with the cables attached to the right pins, it works as described)
and the following code (which is partly from the instructions mentioned above):
#include <RCSwitch.h>
// init 433MHz lib
RCSwitch mySwitch = RCSwitch();
unsigned long lOldValue=0; // to check for consecutive reads on 433MHz
int motorPin = 5; // PWM-Pin to use for motor
void setup()
{
pinMode(motorPin, OUTPUT);
Serial.begin(9600);
// set-up rf receiver
mySwitch.enableReceive(0); // 433MHz Receiver on interrupt 0 => that is pin #2
}
void loop()
{
if (mySwitch.available())
{
int value = mySwitch.getReceivedValue();
// only react, if at least two times same value received
if (value == lOldValue)
{
if (value == 0)
{
Serial.print("Unknown encoding");
}
else
{
Serial.print("Received ");
Serial.print( mySwitch.getReceivedValue() );
Serial.print(" / ");
Serial.print( mySwitch.getReceivedBitlength() );
Serial.print("bit ");
Serial.print("Protocol: ");
Serial.println( mySwitch.getReceivedProtocol() );
// One of the keys on the remote
if (value == 274393) {
Serial.println("got start code, starting motor");
analogWrite(motorPin, 100); // start the motor
}
// another key on the remote
if (value == 270384) {
Serial.println("got stop code, stopping motor");
analogWrite(motorPin, 0); // stop the motor
}
}
}
lOldValue = value;
mySwitch.resetAvailable();
}
}
when i run the code and click on the remote, i get different values shown depending on the key i press. So the wireless receiver works as expected.
When i receive the right value for starting the motor, the motor really begins to turn, so this works as well.
And here the fun part starts:
As soon as i use the analogWrite function to send data to the PWM port the motor is connected to, the wireless receiver stops working (or at least I do not get any more values when pressing a key on the remote).
I found a few similar posts/problem descriptions on the net which said to try the following:
Use another pin for PWM (due to possible interrupt conflicts). I tried that as well, same behaviour
Use external power supply instead of USB-Cable, which helped somebody resolve this issue. Not here. Does not work either
So the question is:
Does anybody know how to combine those two things together so a can use the wireless receiver to get commands and switch on/off the motor with it?
I have the same problem in the past. The problem is the ability of arduino to supply them both. I recommend to use external power supply for the receiver or for the motor (it's best to do that for the motor but according to your circuit it's impossible) like the 545043YwRobot and supply the other from the arduino (I hope this is not what you try already, if so i'm sorry).
Hope it's help.
Yoav

Arduino Function Execution Time

I have an Arduino and an APC220 wireless transceiver. I'm writing a library that reads in data from the APC using the SoftwareSerial class. I originally started with the (incorrect) code below that was causing a seg fault because the i variable is incremented even when there is no data available to read. In cases where it happened to work (by chance when the data was immediately available), this function took approximately 6 milliseconds to execute. When I put the i++; statement in its proper place (above the closing brace immediately above it), the function takes over 270 ms to run. Speed is crucial for this function, so I'm wondering what it is about that statement's placement that causes such a dramatic increase in time.
For the code below, buff is declared as char buff[10]; and sSerial is an instance of SoftwareSerial
unsigned long updateLocation(Marker* marker) {
this->sSerial->print('~');
//initiate request from vision system
this->sSerial->flush();
this->sSerial->print('#');
this->sSerial->print(marker->num);
this->sSerial->print('*');
this->sSerial->flush();
unsigned long start = millis();
int state = 0, i = 0;
while((millis() - start) < 600) {
if(this->sSerial->available()) {
buff[i] = this->sSerial->read();
if(buff[i] == ',') {
buff[i] = 0;
switch(state) {
case 0:
i = -1;
state++;
break;
case 1:
marker->x = atof(buff);
i = -1;
state++;
break;
case 2:
marker->y = atof(buff);
i = -1;
state++;
break;
case 3:
marker->theta = atof(buff);
i = -1;
return (millis() - start);
break;
default:
return 0;
break;
}
}
// Correct location for i++; takes 270 ms to execute
}
// Incorrect location for i++; Takes 6 ms to execute
i++;
}
this->sSerial->print('~');
this->sSerial->flush();
return 0;
}
Assuming that there's data ready and waiting from sSerial, there's no effective difference in the placement of i++.
You said yourself, in most cases the data isn't ready. With the incorrect placement of i++, i quickly grows to greater than the size of buff which causes the segfault.
With the correct placement, your code blocks for up to 600ms waiting for enough data to come in to reach case 3 and return. On average, you're seeing that it takes 270ms for that to happen.
You can test this theory yourself by timing the same function operating directly on a string rather than reading in from serial.
You may want to a) increase your baud rate b) check to see if there's a more efficient software serial implementation you can use c) switch to hardware serial. If you are only using hardware serial currently for debugging output, you can switch that around. Use an FTDI adapter ($6-10 on eBay) to pipe software serial to USB and reserve the hardware serial for your time sensitive function.
You might also be able to reconfigure your code so it doesn't block the whole time waiting. You can read in what's available, store it in a global and go back to your main loop to do something else until there's data available again.
edit: I see now that the APC220 is 9600 baud max. That's pretty slow, so the bottle neck may not be software serial (but you should test it). If the bottle neck is simply the baud rate, you will need to look at optimizing your code not to block waiting for input if there are other things your system can work on while it's waiting.

Repeat blink sketch for a specified time

I need help with an Arduino sketch , I want to repeat the blink sketch for a specified amount of time (3minutes for example) , then Stop .As we know , the loop() keeps runing forever which is not what I want . Any ideas how I can achieve this , blinking an LED for X minutes and Stopping ?
You should probably make use of some timer library. A simple (maybe naive) way to achieve what you want to do is to make use of a boolean that is set to 0 when 3 minutes has passed or simply digitalWrite the led to low when the timer has passed.
Check this link:
http://playground.arduino.cc/Code/Timer
I suggest that you use int after(long duration, callback).
Below is a (very) simple example of how you probably could do:
#include "Timer.h"
Timer t;
LED = 1;
void setup() {
int afterTime = t.after(180000, cancelLED);
}
void loop() {
t.update();
if(LED) {
//The "write HIGH" statement in your sketch here.
}
else {
//Write the led to LOW
}
}
void cancelLED() {
LED = 0;
}
I haven't used the library myself, I just checked the the docs and wrote an example to give you some ideas. Don't expect it to work right away.

How to read string using Serial.read outside of loop()?

I want to read a String in Arduino from the keyboard outside of the loop() method.
I have the following method:
void readFromKeyboard(byte arrayAddress[])
{
int count = 0, i = 0;
while ((count = Serial.available()) == 0);
while (i<count)
{
arrayAddress[i++] = Serial.read();
}
}
In the loop() method I am calling it like:
readFromKeyboard(userInput);
where userInput is a byte[];
The problem is that when I input more than one characters it read the 1st character initially and it call the readFromKeyboard again an then reads the rest.
Example; if I input "asdf":
--the 1st time it will do ==> userInput = "a"
--the 2nd time it will do ==> userInput = "sdf"
I have tryed many things but the same happens again and again...
Any suggestions??
So that's what worked:
In the loop():
while(Serial.available() == 0);
delay(100);
readInputFlag = readFromKeyboard(userInput);`
And in the readFromKeyboard method:
void readFromKeyboard(byte arrayAddress[])
{
int i = 0;
while (Serial.available() > 0)
{
arrayAddress[i++] = Serial.read();
}
}
This delay, in the loop method, somehow makes the Serial get the whole string instead of just the first letter.
I know you got it working, but I wanted to show you something that I use to deal with this issue. This is a two-tiered delay system for catching bytes that come in a bit late for whatever reason. It's designed to minimize the delay needed to accomplish that task.
int received_length = 0;
byte serial_incoming_buffer[200];
while(Serial.available()) {
serial_incoming_buffer[received_length++] = Serial.read();
if(!Serial.available()) {
delay(3);
if(!Serial.available()) {
delay(20);
}
}
}
Sometimes the Arduino falls behind in picking up serial from the sender and sometimes it grabs serial too fast. Sometimes the sender lags a little bit. This code will wait 3 ms for more bytes, and if they come in it goes back to receiving as many as are available having only had that very brief delay. This repeats as necessary, then when 3 ms goes by without anything being available, it waits a bit longer (20 ms here) for more bytes. If nothing comes in after the long delay, then the transmission is most likely done and you can safely move on.
I recommend tweaking the delays based on your baud rate.

Using a PushButton as a trigger in Arduino

I'm trying to work with a simple Arduino circuit that increments a counter variable on pressing a push button in the circuit (connected as INPUT to PIN 8). My code is as simple as follows:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int c = 0, btnPIN, btnVal;
void setup ()
{
btnPIN = 8;
pinMode(btnPIN, INPUT);
lcd.begin(16,2);
lcd.clear();
}
void void loop()
{
btnVal = digitalRead(btnPIN);
if (btnVal == LOW)
{
c++;
lcd.clear();
lcd.print(c);
}
}
Problem is the counter increases by more than 1 every time I push the button. A little bit of printing on the serial monitor indicates that each time the button is pressed and the voltage is LOW, the conditional code is executed multiple times and the counter increases by multiple times instead of 1.
Maybe, I need to write some logic that checks if the button was initially unpressed, then pushed and then released again and then these steps would trigger the required action.
The solution I'm currently working with is as under (which works just fine):
int btnStatus = 0;
void loop()
{
btnVal = digitalRead(btnPIN);
if (btnVal == LOW)
btnStatus = 1;
if(btnStatus == 1 && btnVal == HIGH)
{
c++;
lcd.clear();
lcd.print(c);
btnStatus = 0;
}
}
I'm not sure if there's a simpler solution available or if this approach is wrong for other reasons? Any advice would be most welcome!
Another problem you you may be having is that mechanical buttons bounce. That is, they jump between two positions several times quickly before settling to a final position. This is standard operation so it is necessary to "debounce" the button.
There are very many ways to do this, but Here is a tutorial using an Arduino.
The main issue, as you probably figured out, is that the loop function is getting called multiple times while the button is down. This is what is fixed by your code, and yours looks to be a good solution and I don't really see a simpler way. For another way, though, perhaps you could try just adding a call to delay at the end of loop to slow it down a bit. You would have to play with the delay amount a bit, but it could work. Really though, your solution looks just fine.
Your idea is correct, you need to track the previous state of the button to know if it is a new press or if it is simply being held down. Your code could be rewritten to look more like a state machine, however:
typedef enum {
BTN_STATE_RELEASED,
BTN_STATE_PRESSED
} ButtonState;
ButtonState btnStatus = BTN_STATE_RELEASED;
void increment_counter()
{
c++;
lcd.clear();
lcd.print(c);
}
void loop()
{
btnVal = digitalRead(btnPIN);
switch(btnStatus)
{
case BTN_STATE_PRESSED:
// Handle button release
if(btnVal == HIGH)
{
btnStatus = BTN_STATE_RELEASED;
}
break;
case BTN_STATE_RELEASED:
// Handle button press
if(btnVal == LOW)
{
increment_counter();
btnStatus = BTN_STATE_PRESSED;
}
break;
}
}
This was rewritten to use an enum to track the state of the system (a bit overkill for a simple button, but an important concept to know in case your system grows more complex).
The code to update the display was also moved into its own function to make it better separated between the display change and the actual update of the state.

Resources