text:
Arduino ADS1115 PGA settings
I am trying to use an external ADC with my UNO for very precise measurement of my signal.
The ADC which I am using is ADS1115.
http://henrysbench.capnfatz.com/henrys-bench/arduino-voltage-measurements/arduino-ads1115-module-getting-started-tutorial/
This is the site which I am referring to.It says the default reference voltage of the PGA gives a resolution of 188microvolt per bit.It also indicates towards changing the reference voltage to 2.048, to still increase the resolution per bit.
Can you please guide me in how to achieve this 2.048V.
Update:
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0ahUKEwiFpq3P89vNAhXJro8KHa6IC04QFggpMAI&url=https%3A%2F%2Fcdn-learn.adafruit.com%2Fdownloads%2Fpdf%2Fadafruit-4-channel-adc-breakouts.pdf&usg=AFQjCNGhdMw47MRlXolMiMoHdsTwKMwMow
It seems that by adjusting the gain (page number 16-17 of 18) we can achive it.
WHat I need to know now, is where should I put that piece of code

ads1115.setgain(...)

in void loop() or in void setup()
Thanks
Anupam

Reference voltage inputs are usually high impedance requiring little current.  So you can get by with simple circuits like a resistor and zener diode.  Here is just one I happened across:

Do some research to find out more about this.
For your specific case, you should read the ADS1115 specification sheet.  As this ADC chip has it's own built in voltage reference.
In the Arduino paradigm, tasks that are to be executed once at the beginning of a program are placed in the setup() method.  Tasks which are to be executed repeatedly are placed in the loop() method.  As setting the gain of the ADC appears to only be done once (consult the ADS1115 PDF linked to above), it appears to fall into the former category.
Added later...
I changed the circuit diagram after I realized it was a bad example for creating an Analog to Digital Converter voltage reference.

setup() runs once at the beginning after the program is run.  However, loop() runs continuously after that.
The setgain() instruction is needed once at the beginning, so it should be in setup() function.
good luck!


text:
square wave with serial plotter
I have this code which produces a square wave:
int output_state = 0;
unsigned long start;

void setup() {
  Serial.begin(1200);
  start = millis();
}

void loop() {

  if((millis() - start) >=1000){
    output_state = ! output_state;
    //output_state *= 1023;
    start = millis();
  }

    Serial.println(output_state);
}

but should I multiply the signal by 1023:
output_state *= 1023;

this signal is produced by the Serial Plotter:

Mind that the timing is right, just the x axis speeds up in zero values. Why is that happening, and how can be solved?
Any thoughts would be appreciated.

It takes twice as long to print "1023" (6 bytes, including the CRLF line
terminator) than to print "0" (3 bytes). Thus, in the same time, you are
printing twice as many "0" than "1023".
If you want the data points to be printed at a consistent rate,
you can impose the printing timing just like you did on the
output_state. Keep in mind that you cannot print more than 20 samples
per second at 1200 bps. You could also pad the strings so that they
always have the same length:
char s[5];  // one byte for the NULL terminator
sprintf(s, "%4d", output_state);
Serial.println(s);

I would prefer the first solution (explicitly control the timing).

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Can I close an input?
I wan't to build a diversity controller similar to this one.

A diversity controller is basically a circuit which detects the strongest RSSI Signal of multiple receivers and provides the data signal of that (the strongest) receiver.

As a receiver I use boscam RX5808 receivers.
This receiver can be switchen between 8 channals through a 3 bit output interface. The CH1-3 outputs are active high 5V which got to be pulled to ground.
Is it possible to put these receiver-outputs on an arduino digital inputs, to either put them on ground or not?
How exactly do I implement this in software?

According to the document you linked to, the channel select pins look like internally pulled-up inputs, not outputs.

When you output HIGH you connect the pin to +5V. When you output LOW you connect the pin to ground.  It's called a push-pull interface, and looks like this:

When it's set HIGH the p-FET is turned on and the n-FET is turned off. That connects the output direct to VDD. When it's set LOW the p-FET is turned off and the n-FET is turned off. That connects the output direct to GND.
They are just like switches, as depicted to the right. Only one is closed at a time - when HIGH the upper switch is closed, when LOW the lower switch is closed.
So you just connect the output pins of the Arduino direct to the input pins of your device and write either HIGH or LOW to them to set the 5V or GND connections you need.

So basically, If i set the arduino I/O on HIGH, it's +5v vs +5v which get's 0v, and if I set the I/O to LOW it's +5v vs GND which get's +5V, right?

.... pardon .... ?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Making two points on a tm1637 display blink [ Solved ]

Hello! In my project, using a display controlled by a TM1637, I want to make the two points on the middle of the screen blink (as every clock does).
The following example, provided by the library I'm using, makes the two points blink as I want (tm1637.point(POINT_ON/POINT_OFF); is what enables/disbales the point):
#include <TimerOne.h>
#include "TM1637.h"
#define ON 1
#define OFF 0

int8_t TimeDisp[] = {0x00,0x00,0x00,0x00};
unsigned char ClockPoint = 1;
unsigned char Update;
unsigned char halfsecond = 0;
unsigned char second;
unsigned char minute = 0;
unsigned char hour = 12;

#define CLK 2//pins definitions for TM1637 and can be changed to other ports
#define DIO 3
TM1637 tm1637(CLK,DIO);

void setup()
{
  tm1637.set();
  tm1637.init();
  Timer1.initialize(500000);//timing for 500ms
  Timer1.attachInterrupt(TimingISR);//declare the interrupt serve routine:TimingISR
}
void loop()
{
  if(Update == ON)
  {
    TimeUpdate();
    tm1637.display(TimeDisp);
  }

}
void TimingISR()
{
  halfsecond ++;
  Update = ON;
  if(halfsecond == 2){
    second ++;
    if(second == 60)
    {
      minute ++;
      if(minute == 60)
      {
        hour ++;
        if(hour == 24)hour = 0;
        minute = 0;
      }
      second = 0;
    }
    halfsecond = 0;
  }
 // Serial.println(second);
  ClockPoint = (~ClockPoint) & 0x01;
}
void TimeUpdate(void)
{
  if(ClockPoint)tm1637.point(POINT_ON);
  else tm1637.point(POINT_OFF);
  TimeDisp[0] = hour / 10;
  TimeDisp[1] = hour % 10;
  TimeDisp[2] = minute / 10;
  TimeDisp[3] = minute % 10;
  Update = OFF;
}

I tried to do it as it was the famous "blink", but nothing works.
Here's what I have done:
#include "TM1637.h" // Library for the 4-Digit Display
#include "RTClib.h" // Library for the RTC
#include <SoftwareSerial.h>

#define CLK 6
#define DIO 7

TM1637 tm1637(CLK,DIO);
RTC_DS1307 RTC;

const int fotoRes = 2;

SoftwareSerial mySerial(10, 11);

void setup()
{
  pinMode(fotoRes, INPUT);

  RTC.begin();
  RTC.adjust(DateTime(__DATE__, __TIME__));

  tm1637.init();
}
void loop()
{
  DateTime now = RTC.now();

  tm1637.display(0,now.hour()/10);
  tm1637.display(1,now.hour()%10);
  tm1637.display(2,now.minute()/10);
  tm1637.display(3,now.minute()%10);

  tm1637.point(POINT_ON); //Like blink example.
  delay(500);
  tm1637.point(POINT_OFF);
  delay(500);
}

EDIT: tm1637.set(0-7) ONLY set the brightnes of the screen. What makes the two pints appear is tm1637.point(POINT_OFF/POINT_ON). I'm asking how can I do to make these two points blink. Thanks.
Arduino UNO R3, DigitalTube library by Grove

Instead of showing us someone else's code that does work, why not show us your code that doesn't work? We can't help you with your code if you show us something completely different.

By delaying for 500ms you are going to take longer than 1second to complete loop(), so the clock will drift quite rapidly and you will see it jumping 2 seconds at a time.  You haven't issued a tm1637.set(); call, is that relevant?

tm1637.set(0-7) is for adjusting the brightness of the display. If it's not declared on the scetch, the brightness for the display will be "typical_brightness" (2).

OK, but does set(7) work? Does it make the display very bright, and set(1) make it dim? If it doesn't even do that, then you've got a bigger problem - like maybe you haven't connected CLK to pin 6 and DIO to pin 7 on your breadboard.

Solution: After a lot of time, I've found the solution to it. Just I have to check if the seconds given are even. If seconds are even, enable both points using tm1637.point(POINT_OFF);.

sorry, disable is the right word there

Calling the point() method only updates a flag; you see the effect the next time you try to display a number. You can use something like this:
void show_time(DateTime &t){
  tm1637.display(0,t.hour()/10);
  tm1637.display(1,t.hour()%10);
  tm1637.display(2,t.minute()/10);
  tm1637.display(3,t.minute()%10);
}

void loop() {
  DateTime now = RTC.now();

  tm1637.point(POINT_ON);
  show_time(now);  // changes take effect here
  delay(500);
  tm1637.point(POINT_OFF);
  show_time(now);
  delay(500);
}

Using delay(); makes the void loop() waits x milis. So, it's a clock, and using that will make my clock go slow.

@spund3 Your question says you want it to be like the Blink example, which is what this is. Your example uses delay(). Have you tried running this code yet? If this isnt what you want then perhaps you should re-phrase your question.

@spund3 Your question says you want it to be like the Blink example, which is what this is. Your example uses delay(). Have you tried running this code yet? If this isnt what you want then perhaps you should re-phrase your question.

I was refering to the final result of the blink example, where the led blinks. I appreciate a lot your solution, but I've found mine yesterday. Thanks!

@spund3 Okay. The final result is still what you expect. You can run it to find out, so I can know if this is a valid answer for anyone else who has a similar question.

This is how I did it just use modulus and it will show the dots every even number of seconds then there is no need for delay --->
if (currentSeconds % 2==0) { tm1637.point(POINT_ON);  } else { tm1637.point(POINT_OFF); }

I haven't used the TM1637 code, but I (think I) understand how it works.
In the original code is the following:
void setup()
{
    tm1637.set();
    tm1637.init();

But in your code you only do the following:
void setup()
{
    ...
    tm1637.init();

Have you tried adding the tm1637.set(); line in?

Yes, and tm1637.set(0-9) only adjusts the brightness of the entire display. What enables/disables the points is tm1637.point(POINT_OFF/POINT_ON


text:
Find a time server for NTP to get the current time (EtherCard library)
There are lots of examples around how to connect with an NTP server, but I do not see how to find such an IP-address. From the examples I conclude I need to find it on for example pool.ntp.org, but I do not even see how to get IP-addresses out of there myself, let alone to let my Arduino do it. Of course I looked at the How do I use pool.ntp.org page, but it doesn't seem to say anything about finding IP-addresses.
Questions

Is it possible to let my Arduino find a working NTP server (using the EtherCard library), and if so, how?
All the examples I saw have an NTP server IP address hard coded, isn't that a bad practice and also a bad idea for a longer running project?

The code I currently find the easiest to understand is from the Arduino forum, and has an IP address hard coded.
I have an Arduino Nano ATmega328 with a ENC28j60 ethernet shield, and therefore use the EtherCard libray. I do know of existence of RTC devices but I would prefer NTP.

You need to perform a DNS lookup in order to convert the host name (e.g. "pool.ntp.org") into an IP address. Doesn't the EtherCard library have a facility for that?

@EdgarBonet That sounds logical, indeed EtherCard can do that, googling it it would be something like if (!ether.dnsLookup(website)) { Serial.println("DNS failed"); } ether.printIp("Server: ", ether.hisip); but I'm new to the ethernet connections so I need to find out how to get an ip address out of that to use later in the code...

I found an ip address with the code in the form of a string, but didn't manage to convert it to an array even with http://stackoverflow.com/questions/35227449/convert-ip-or-mac-address-from-string-to-byte-array-arduino-or-c so I'm leaving that for now. This question is solved I guess, although I am not sure of course if the ip is a correct one because I can't test it.

ether.hisip is not a string, it's an array of 4 bytes.

@EdgarBonet Oh indeed you are right! That solves my whole problem, thanks a lot! I was tricked into thinking it was a string by what ether.hisip printed to, but now I see that's why ether.printIP was used.

The EtherCard library offers a method called ether.dnsLookup(host) where you ask it to look up the IP address for you.
etherCard.dnsLookup("pool.ntp.org");

...only that might fail, so it returns a false:
if (!etherCard.dnsLookup("pool.ntp.org")) {
    // Error! Do something!
    return;
} // if

But if it works...
if (!etherCard.dnsLookup("pool.ntp.org")) {
    // Error! Do something!
    return;
} // if
// At this stage, dnsLookup() worked...

// Can now connect to IP adress in etherCard.hispip

Now: please note that ntp.org would prefer you to use a more precise locale than pool.ntp.org. If you're going to distribute your application worldwide, then that's fine. But I always use au.pool.ntp.org because I'm in the Australian region. There are others that you can/should use instead.

Thanks for writing Edgar's suggestion into an answer, the locale is a nice addition!


text:
How is the integration time set for a camera?
I using the TSL1401R-LF Linescan Camera Module, which reads in a 1 X 128 line of pixels, and I'm having trouble understanding how the integration time is set for this device.
I understand from page 9 that the minimum integration time is a constent that results from a function of the clock speed, but I don't fully understand when this integration period takes place.
According to the timing waveform (Figure 1 on Page 5) the integration period appears to be set after the first 18 clock cycles. Does this mean that the integration period is set while the camera is outputting pixels?

How is that even possible? Also does this mean that in order to achive the minimum delay time I would have to take that time and divide it across those remaining 110 clock cycles (i.e. 307 ns for a total of 33.75 us)?
UPDATE:
This is how I am currently programming the camera. I'm using delayMicrosecond() after the HIGH and LOW clock impulses as well as at the end. I have enough delays to achieve the minimum 33.75 microsecond delay, but I'm still having sensitivity problems.
int delayTime = 20;

void readPixels()
{
  digitalWriteFast(SI, HIGH);
  delayMicroseconds(delayTime/2);
  digitalWriteFast(CLK, HIGH);
  delayMicroseconds(delayTime/2);
  digitalWriteFast(SI, LOW);
  delayMicroseconds(delayTime/2);
  digitalWriteFast(CLK, LOW);
  delayMicroseconds(delayTime);

  for(int i = 0; i < 128; i++)
  {
    digitalWriteFast(CLK, HIGH);
    pixelsArray1[i]=analogRead(Cam1Aout);
    pixelsArray2[i]=analogRead(Cam2Aout);
    pixelsArray3[i]=analogRead(Cam3Aout);
    delayMicroseconds(delayTime);
    digitalWriteFast(CLK, LOW);
    delayMicroseconds(delayTime);
  }

  digitalWriteFast(CLK, HIGH);
  delayMicroseconds(delayTime);
  digitalWriteFast(CLK, LOW);
  delayMicroseconds(delayTime);

  delayMicroseconds(20);

}

It is quite a difficult system to get your head around, as you have noticed.  I'll try and break it down more logically for you...
An important thing to note is that there are two capacitors in each pixel - the integrating capacitor and the sampling capacitor. It's these two capacitors that lead to a certain amount of confusion, and it's vital to understand the role of each one.

Under normal sampling operation light falling on the photodiode of a pixel generates charge through the internal amplifier which is stored in the integrating capacitor. Simultaneously that stored voltage level is mirrored in the sampling capacitor.
When you send the pulse on SI a signal called HOLD is generated internally. This signal is sent to all of the pixels and tells them to disconnect their sampling capacitors. They do that through the switch S2.  At the same time the integrating capacitor is emptied by S1 causing a short circuit across it. That is held there for 18 clock cycles to make sure that it's completely empty. All this time the sampled voltage is still there in the sampling capacitor.
Then as you continue clocking the pulse you sent in through the SI pin is walked down a 128 bit shift register. As it pops out of each output in turn it connects the sampling capacitor of that pixel to the output buffer so you can read the voltage. It's then flushed out and re-connected to the integrating circuit again to sample the pixel again.
So there is actually multiple things happening during your 129 clocks. Reading and integrating are both happening at the same time. But you're not reading this set of clock's integration, but the last set of clocks integration.
So you have:

SI pulse - HOLD generated, samples frozen
18 clocks of clearing the integrators and reading nothing much.
110 clocks of reading nothing much (nothing is sampled yet) and integrating.
1 clock to terminate
SI pulse - HOLD generated, samples frozen
10 clocks of clearing the integrators and reading the previously integrated samples 1-18
110 clocks of reading the previously integrated samples 19-128 and integrating new ones
1 clock to terminate
... etc ...

So clocks 130 to 258 are reading the light that was sampled during clocks 19 to 128.
The upshot of all this is that your integrating period is the total time taken for the 110 clocks that occur between the end of the 18 clocks that clear the integrators and the next SI pulse that creates a new HOLD signal.

Thank you so much, you've made this whole process so clear. But I have a follow up question; why am I still having such poor sensitivity if my integration time is so long? When my delay is set to 170 us I get some really good readings, but when I reduce it to 20 us I suddenly lose all of it. But I'm still above the 33.75 us minimum delay.

You still don't understand what happens during integration do you? The longer you integrate for the more sensitive the pixels are. The minimum integration time is the absolute minimum amount of time you have to run for to get a result. That will only be a usable result in a very very bright environment. Sahara at midday bright. The darker your environment the longer you have to integrate for to get any real difference in your values. As I have said before it's like the shutter of a camera. Take a picture with 1/3200s shutter in a dark room and you get nothing. Take a picture with .....

... 5s shutter in full daylight and you get just white. It is up to you to get the optimal shutter speed (integrating time) that allows enough light in to see the image whilst not letting in too much light so you lose detail.

I didn't understand what the minimum delay meant, but I understand what you're saying now. So I have to just deal with the low sensitivity if I want my program to run faster.


text:
Port Not Being Found
Hey everyone I know this is a pretty common question, and I have read/tried almost everything on all the other posts here and on the arduino.cc forums, but I have been unable to fix my problem. Basically I have been using my Arduino Leonardo for a little over a month now for all sorts of things and have never had this issue with the Arduino not showing up under the port tab on the menu. I have no idea why this just started happening to me, I am using the same cable, etc, and was hoping someone could help me out. I am on a MacBook Pro by the way.
Thanks in advance.

Does the port appear for a few seconds when you press the reset button?

Okay I just tried, and no it does not.

Does the LED on the board "throb" (fade in and out) when you press reset?

Yes it does fade in and out.

Have you tried a new cable? Or tried the existing cable with another device? How about someone else's computer?

I have not, but I will right now. If it is any help, the "ON" LED is indeed shining bright, so there is a connection being made, it just seems that there is some error with the serial communication?

The ON LED just shows that there is power. USB has 4 wires - power and ground (fat wires) and two data wires (thin wires). It's more common for the thin data wires to break than the fatter power and ground wires.

Yeah so I just tried the connection on a Windows computer, and it the power came on again but the device was never registered. So is this a cable problem then, most likely?

Most likely - the cable is more fragile than the Arduino generally. Try the cable with your phone or something - or dig out a spare cable (you really should have a pile of them, everything needs them now).

Let us continue this discussion in chat.

If you have uploaded a sketch that doesn't use the serial port, then after a couple of seconds, the Leonardo won't show up in the ports list.
To upload a new sketch you need to press and release Reset a moment after the upload to the board starts.

I've been using Leonardos and other ATmega32U4 based boards for years and have never experienced anything like that.

@per1234 - I must admit that I can't reproduce it.

Try this...
Go to your Arduino IDE.
Under the Tools tab, go to "Board" and select Arduino Leonardo.
Then in the Tools tab, go to Port and check to see if a port is selected.
Use this link to try and find which Serial Port you should have: https://www.arduino.cc/en/Guide/MacOSX
Try plugging in the cable in different USB ports on your computer and see if the port number changes automatically.
Also, could you please say what peripherals or other things are connected to the arduino? Because for example, I know what using a Bluetooth slave with the Arduino while connected with the cable to your computer, doesn't let you upload your program. There could be similar problems to this.

Yeah so I have the Wireless SD Shield connected to it, but no XBEE Wifi Module. Other than that there is nothing.

I guess you should try disconnecting that before connecting the Arduino to your computer. And try all the USB ports on your computer to make sure they are working.

Just tried, still nothing. Also, my restart button no longer flashed the "L" LED, it simply lights it up as long as the button is depressed but no longer... @Majenko


text:
Arduino Mega Hall sensor interrupt for a speedometer
I am having difficulty setting up an interrupt to count how many times the magnet passes so that I can count something like every 100 ms the actual speed.
I have a little code put together from the Internet:
const byte LED_pin =13;
const unsigned long wheel_circumference = 431800UL * 2UL * 31416UL; // = 94,248,000
unsigned long Speed = 0;
unsigned long PrevSpeed = 0;
volatile byte hall_rising = 0; // interrupt flag
volatile unsigned long irqMicros;
unsigned long startMicros;
unsigned long elapsedMicros;
unsigned long ledFlashStartMillis;
const unsigned long ledFlashWaitMillis = 10;
unsigned long displayStartMillis;
const unsigned long displayWaitMillis = 100;

void wheel_IRQ()
{
  irqMicros = micros();
  hall_rising = 1;
}

void setup()
{
  pinMode( 2, INPUT_PULLUP ); // pin # is tied to the interrupt
  pinMode( LED_pin, OUTPUT );
  Serial.begin( 9600 ); // can this be faster? faster would be better
  delay( 1000 );

  attachInterrupt( 0, wheel_IRQ, RISING ); // pin 2 looks for LOW to HIGH change
}

void loop()
{
  if ( hall_rising == 1 )
  {
    elapsedMicros = irqMicros - startMicros;
    startMicros = irqMicros;
    hall_rising = 2;
  }
  else if  ( hall_rising == 2 )
  {
    if ( millis() - ledFlashStartMillis >= ledFlashWaitMillis )
    {
      hall_rising = 0;
    }
  }

  // print speed 1000/Wait (10) times per second
  if ( millis() - displayStartMillis >= displayWaitMillis )
  {
    Speed = wheel_circumference * 0.0009 / elapsedMicros;

    displayStartMillis += displayWaitMillis;
    if ( Speed != PrevSpeed )
    {
      Serial.print(Speed); // this shows mm/sec with no remainder
      Serial.println(" kmh");
    }
    PrevSpeed = Speed;
  }
}

But when I use this code in U8glib to display the value on a GLCD . Values are totally wrong. Can someone help me?

What hall effect sensor are you using? Do the values come out correct when used with the serial monitor? Could you post what values you are getting with the hall effect sensor that are totally wrong, with the values of should be, how are sure they are wrong or right??

count how many times the magnet passes. In your entire code, you never count the number of times the interrupt is fired. You're code assumes that the loop function is called at least as many times as the interrupt is fired. If the loop function takes longer, by e.g. using the GLCD library, multiple interrupts could have fired, leading to elapsedMicros being a multiple of the value you expect. Leading to your code thinking the motor is running at half, or one-third, etc. the speed.

so this code is obtained from elsewhere. I think the code counts the time between two magnets passes hence my 0*0009 coefficint to convert everything to kmh. when i put the code the output is 1/2 km h instead of 40 km h like in serial output. I still want to sample this way so that the speed output will be constant and will not slow down with the speed. How can i improve the code to handle the wheel circumference in meters? how can i show when the bike is not running? Is there any way to make this simpler?

You either need to change your code to count the number of revolutions in the interrupt.  Then divide that value in your main loop by the elapsed time to get the angular velocity.  This may or may not work, as the number of revolutions may be small or even zero when you do the calculations.  Thus contributing to errors.
Or, change your code to record the elapsed time between rising edges in the interrupt.  Then find the inverse of this value.  This may be better as you could even miss an event in your main loop and still calculate the speed.  Careful not to take the inverse of zero.
To calculate speed you need to find the rotational speed of the wheel, and, consequently, how fast you are bicycling.  Use this equation:

...where omega is the revolutions per time as calculated by the 1st method above or reported by the interrupt routine in the 2nd method above.  Do not forget that the interrupt routine is probably using milliseconds and not seconds.
Also, do not forget to clear out the last value reported by the interrupt.  No matter which of the above 2 approaches you take.
Also consider special cases.  For instance, when you stop bicycling the interrupt will never fire.  In your main loop you may have a second counter which, when exceeded, indicates that your speed is zero.

The code is already in micros to get a good resolution. Actually its for a motorcycle. Can you explain the 0kmh thing?

I did not say in the answer, but, from what you said, I think the U8glib display library is taking too much time to execute and the code to calculate speed, not being robust, is failing.  I think you need to change the code from counting revolutions to counting the time between revolutions.  As for 0kmh, you need a second way of timing to indicate there has not been a revolution for a long time.  Perhaps more than a dozen seconds.  When this occurs, replace the last displayed speed with zero.

So i should use an interrupt that says time = x microseconds every impulse?

That is the approach I would use. Remember to convert from ms to hours.


text:
Is there an easy way to turn integer values to pixels?
I'm working with a black & white camera and it gives me integer values to represent the amount of light hitting the sensor. Very bright is 1023 and totally dark is 0. The values are printed through serial and everything works fine but now I want to recreate the image based on the values.
Does anyone know if there is a simple way of doing this? I'm assuming the process would consist of looking up the value and giving a specific colored pixel in return, but I have no idea how to do this.

Simplest thing may be to write down your image in plain Portable Gray
Map format. This is a very
simple (and inefficient) ASCII format consisting of a signature (the
string "P2"), followed by the width and height of the image, followed by
the maximum possible gray level (1023 in your case), followed by the
pixel values. It's a free form format, meaning you can mix spaces and
newlines at your convenience.
Here is an example image: two rows of pixels, five columns, and
brightness increasing left to right and top to bottom:
P2
5 2
1023
  0 111 222 333 444
555 666 777 888 999

Then, any image conversion software should be able to convert that into
the format of your choice (PNG, JPEG, whatever...).

That kind of what I'm looking for, I just want to actually see the image and don't care much about efficiency. However, I did not get from the documentation how you would go about making of the these PGMs. Is it a file I make based on the numbers? Like do I take the values and past them into this PGM file?

@CrystalPritzker: It's just a text file. How would you write a text file on your computer?

@CrystalPritzker, your sketch could write PGM-formatted data, which you pipe to a .pgm file on the host, or you could write a program that receives data organized however you like and writes it to a .pgm file.  See eg tutorialspoint....c_file_io or cprogramming...cfileio re opening a file and writing to it.  With a .pgm file, use a pgm-to-jpg (or whatever) program.  (Search google for "pgm to jpg" and find eg pgm-to-jpg converters

@EdgarBonet So are you saying that it's really as simple as writing the number in a text file and then ending it with .pgm? Then convert that file to an image?

@CrystalPritzker: In essence yes, except that 1) you have to write "P2" before the numbers, c.f. my example 2) You don't “convert that file to an image”: it's already an image, you just convert it to a more common image format.


text:
Main Idea of Gyro

I have a L3G4200D (GY-50 model) gyroscope. I have been  trying to learn how a gyro sensor works. The circuit diagram is attached. I want to ask some questions;
a) According to the datasheet of L3G4200D,
    x_lsb and x_msb  (28h and 29h),
    y_lsb ,y_msb     (2Ah and 2Bh),
    z_lsb , z_msb    (2Ch and 2Dh) as  shown in the picture 3.
But according to code that in the picture first, Arduino requests bytes from 168 address of gyro (in the picture, the mark number is 1).
But, 0x28 (hex) stands for b00101000 .
What's wrong with it ?
b) Output of gyro is outputs degrees/second, is it correct?
c) In the picture 2, I did not move it, as it shown its results change, how can the angle change? It must be zero when it does not move.
d) In the picture 1, what I should calculate: highbyte*256+lowbyte ?
e) What does Fs=250,500,2000 dps mean? I know that Dps stands for Degree Per Second. But what would change by FS range, I mean if I pick either 500 or 2000 ?

Have you taken a look at the datasheet for your gyro?

Yes,I have.I have learned  how to control registers 1 and 4. That's all.
by the way,I have downloaded the code that is written above, I did not write it.

When I used LIS2DH last year, I found address byte has some extra complexity - read the entire datasheet for "gotchas". I think it was a bit to enable consecutive register reads. FS means Full Scale.

According to the datasheet of L3G4200D, x_lsb and x_msb (28h and 29h), y_lsb ,y_msb (2Ah and 2Bh), z_lsb , z_msb (2Ch and 2Dh) as shown in the picture 3. But according to code that in the picture first, arduino requests biytes from 168 adress of gyro(in the pciture ,mark number is 1). But , 0x28 (hex) stands for b00101000 . what's wrong with it ?

168 is, in hex, 0xA8.  That's 0x28 with the MSB set. Why? Well, the datasheet says:

In order to read multiple bytes, it is necessary to assert the most significant bit of the subaddress
  field. In other words, SUB(7) must be equal to 1, while SUB(6-0) represents the
  address of the first register to be read.

So address 0xA8 is the same as address 0x28 plus the instruction "I want to read multiple bytes".

Output of gyro is outputs degrees/second ,is it correct ?

Kind of. The number is actually a representation of the fraction of FS. See below.

in the picture 1,what I should calculate hightbyte*256+lowbyte ?

That is turning two 8-bit values into a single 16-bit value. It's easier to represent it using bit shifts:
(bighbyte << 8) | lowbyte

That is, the high byte is shifted left 8 bits and the low byte is then ORed over the lower (zero) 8 bits.

What does Fs=250,500,2000 dps mean ? I know that Dps stands for Degree Per Second .But what would change by FS range ,I mean if I pick either 500 or 2000 ?

That is the "Full Scale" value. It defines what the raw numbers from the gyro actually mean.  The gyro returns -32768 to +32767. -32768 is -FS, +32767 is +FS. So if the FS is set to 500 degrees per second then:

-32768 is -500 degrees per second
+32767 is +500 degrees per second

The simple formula is (using floating point maths):
DPS = Reading / 32768.0 * FS
The format is more commonly known as Q15 where a 16-bit value is split into 3 parts - a sign bit (bit 15), an integer part (there isn't one in this case), and 15 bits (14-0) of fraction. So the number actually represents, in Q15 format, between -1 and +1 in 65536 steps of 1/65536. That number is then multiplied by the full scale value, just like you would a percentage, to get the real DPS value.

Thank you, These are very precious informations.
I think it will take me long time understand whole part of it.

According to the datasheet, FS seems to be Measurement Range. Also, I think you will find useful information in the following discussions: Understanding the sensitivity of an L3G4200D gyroscope and in How do I get gyro sensor data (L3G4200D) into degrees/sec? Due to the fact that the gyro is 16 bit, the range of values would be 2^16, what makes 65536. So, the values on your screen are between -65536/2 and +65536/2, that's why max. values that you see are around 32000.   There is always very tiny motion that the sensor can detect due to vibrations and etc. So, you should not expect the output of gyro to be a set of constants. Ideally, you should combine the data, lets say for 1 second, and find RMS value(average it) to get the result, don't look just for few instances/samples. Also I should note that if there is ultrasound in the gyro environment, it might also cause wrong results. When outer frequencies coincide with the natural frequency of the gyro system, it leads to resonance and distorted data. This paper has explanation of this phenomenon among with other impacts to the gyroscope.

Thanks for replying.
I have already read that topics you recommend.
Do you suggest calibrating the gryo ? I mean,first I will get 1500-2000 measures and define 0 point, and every time you read values from gyro ,compare it to calibration values , if it does not move value will be 0 .

Yes, something like that. Let's say you average 2000 values, (use RMS instead of mean, because you have negative values), and get 300(x) 400(y) 100(z) values. This would be your 0 point. When you will get a new point, you could compare it to the 0 point to see how much the values has changed and make calculations. I guess there should be ready libraries to make the calculations easy. Just continue to research, there are many projects with reports and ready software done on this topic, I am sure you can find much more.

Yes,I have already found ready-code and its simulation,it works perfectly..But I have to learn how it is written,how it works.The first thing that I should do is to  run  that code step by step .
Thank you for your help.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

authors: Дмитрий Петров


text:
Why SD.exists() only looks for inside media/realroot on Intel's Galileo?
I'm following a tutorial which says SD.exists() only look for files inside media/realroot on Intel's Galileo board. I just confirmed this using SSH to create e remove files during a loop which was looking for some specific named file. Where's information about this? I searched for cpp files inside SD library and found nothing.

The Intel Galileo runs Linux.  Most Linux distributions (auto) mounts media under specific directories like "/media".  So this is likely not so much a feature of the Arduino paradigm but of the Linux paradigm.  If you really want to change this you will probably have to research how Linux (specifically how the Intel Galileo version of Linux) auto mounts media.
This is a stack exchange question about auto-mounting using a Linux distribution called Ubuntu.  I am not sure how close the Intel Galileo Linux is to Ubuntu.  But it's a starting point.


text:
'serialWrite' was not declared in this scope
Please help me! Once I click the upload button.
I get the following error:

'serialWrite' was not declared in this scope

Here is my code:
int buttonPin
void setup ()
{
beginSerial(9600);
pinMode (buttonPin, INPUT);
}
void loop ()
{
if (digitalRead(buttonPin) == HIGH)
serialWrite('H');
else
serialwrite('L');
delay(1000);
}

Where did you see that anything called "serialWrite" is supposed to exist?

Pay attention to the examples. They would have had Serial.begin (9600); - not beginSerial(9600);. You can't just re-arrange words and drop off punctuation.

Also, int buttonPin won't compile.

Same code! After I upload it. It was an error.  avrdude: stk500v2_getsync(): timeout (something like that


text:
Can't assign elements to index in array
I'm trying to create an array of strings. I'm building each individual string by parsing a json file and getting the strings between '{'s and '}'s. However, for some reason, my array is only assigning one index with the string i want. This is my code:
  String day = "";
  String Combo[] = {"0","0","0","0","0","0","0","0"};
  int x = 2;
  int number = 0;

  /* Read data until either the connection is closed, or the idle timeout is reached. */
  unsigned long lastRead = millis();
  while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    /* Reads one character at a time*/
    while (www.available()) {
      char sym = www.read();

      if (sym == '{') {
        x = 1;
      }
      if (x==1){
        if (!day.concat(sym)) {
          //Serial.println("concat() error!");
        }
      }
      if (x==1 && sym == '}'){
        x=0;
        Serial.println(number);
      }

      if ((number > 0) && (number < 9) && (x==0)) {
        Combo[number-1] = day;
        Serial.print(day);
        Combo[number-1] = day;

        Serial.println(F("-------------------------------------"));
        Serial.println(Combo[number-1]);

        Serial.println(F("-------------------------------------"));
        Serial.println(F("-------------------------------------"));
        day = "";
        number +=1;
        x = 2;
      } else if (number ==0 && x ==0){
        day = "";
        number +=1;
        x = 2;
      }
      lastRead = millis();

    }

  }

Which returns this:
{
    "firstString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "secondString"
    }-------------------------------------
{
    "secondString"
    }
-------------------------------------
-------------------------------------
{
    "thirdString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "fourthString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "fifthString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "sixthString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "seventhString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "eighthString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "secondString"
    }-------------------------------------

Based on this output I know that day is being constructed correctly but for some reason isn't assigned to an index in Combo (except "secondString")
Does anyone know what's going on?
Ideally Combo would equal: {"secondString", "thirdString", ... "eighthString"}

Any chance you could show us the JSON file you are trying to parse?

Perhaps you are out of memory?

I'm trying to understand your code.

It looks like x is a state variable, with the following values:
2 = "Looking for start brace (`{`)"
1 = "Found! Now accumulating `day` until stop brace (`}`)"
0 = "Finished!"

If so, you may instead want to use the following:
enum States { Looking, Adding, Done };

// int x = 2;
States state = Looking;

// x = 1
state = Adding;

// if (x==1){
if (state==Adding) {

If you follow the flow of code, when number is still 0 and x finally becomes 0, you:

Print out number - the first line of your output;
You then miss the main if (number is not greater than 0);
And enter the else (which is satisfied);
And then you immediately clear your hard-earned day.

The second time through, after x becomes 0 again, this time you:

Print out number - the second line of your ouptut;
You do enter the main if:

You assign day to Combo[1]
You print out only the first seven entries in the the array (you want <=7, not <7)

This should print out 0{?}000000 (I don't know what day should be).
The fact that it doesn't seems to imply that your concat() failed. Can you please change it to
// day.concat(sym);
if (!day.concat(sym)) {
    Serial.println("concat() error!");
} // if

You then print out the row of dashes - and start a new line.

The third time through, it seems to work - you get your {$ "first string" $} (where $ represents \n and/or \r - can you strip those out?)
      // if (x==1){
      //    day.concat(sym);
      if (x==1 && sym>=' '){ // Don't concat new line characters!
          day.concat(sym);

And the final few times concat() seems to have failed again.

The reason I say "concat() has failed" is that it looks like day is still "" when it is assigned to Combo
Edit
You've changed the code so that the main if now does the following:

Assigns day to Combo[number-1];
Prints out day - this seems to work;
Assigns day to Combo[number-1] again;
Prints out a line of hyphens - this works;
Prints out Combo[number-1] - this does NOT seem to work;
Prints out two lines of hyphens - this works.

Since 5 is printing out nothing, it implies that 3 failed. This really does look like you're in a low-memory condition, and the system is failing to allocate memory from the heap.
You don't say what Arduino you're working on - note that most don't have much memory, and if you're already parsing a JSON file you've probably used a lot of it. You also don't say which version of the Arduino IDE you're using. There was a String bug in the earlier versions.
Rather than trying to use the String class (a renowned heap hogger), you should try to use normal char arrays and work the buffer management yourself.

Thx for the advice. For #2, I don't want the first day string to be saved so that's normal. I implemented #3 and it does seem that my concat fails often. Do you have any advice on fixing this?


text:
Grouping multiple pins to one variable
I'm new to all of this, but it's there a way to group a cluster of pins to one variable? I don't necessarily want the grouped pounds to be sequential.

It's called an array.

Does it need to be byte form?

An array can be made from any data type you like. Google "Arduino Arrays".

Can you be more specific as to what you wish to accomplish?

One example of a application I am considering is a grid of LEDs. I may wait to group some LEDs to look like  constellations. I would like to have variables naming the constellations, that I can't turn on and off like a light switch.

Only if you drop to low-level access, and only if the pins are on the same port.
#define pinset 0x55

 ...

PORTC |= pinset;
delay(1000);
PORTC &= ~pinset;

In the example of the constellations, consider using an array for each constellation where each element in the array corresponds to an LED output pin. You could simply put a 1 or a 0 in each array element to indicate if you want the corresponding LED output pin on or off. It would be easy then to create a function that you would pass a constellation array and would turn the LED output pins on or off based on the contents of the array.


text:
Moving ATMEGA to 3.3V
I currently have a barebone arduino built from just an Atmega 328P and a 16Mhz external crystal.

I planning to move this system down to 3-3.6V but I have read that on low voltage I have to use 8Mhz crytstal so my only question is that because of this change do I have to take the chip out to reflash with the programmer again or it will work as it did before?
What will happen if I do not change the oscillator and leave it on 16MHZ ceramic?

I think in particular case you may get working result, but in large sample: some set of devices won't work. This relate to internal construction of oscillator circuit.

Software side could be easier than I thought: http://playground.arduino.cc/Learning/Atmega83-3V

If you use Serial to program the ATMege, you'd have to change the bootloader. Since it assumes it's running at 16MHz.

...I have read that on low voltage I have to use 8Mhz crytstal...

Technically you can run anywhere below 13Mhz or so, so you have lots of choice.
You may also be able to use the prescaler to divide the clock by 2, either by hoping the ATmega can run the short time at 16MHz, or by programming the CKDIV8 fuse to start it at 2MHz.

...do I have to take the chip out to reflash with the programmer again...

If you move to a frequency within spec with either a clock change or prescaler use, yes. The bootloader and Arduino libraries expect a 16MHz clock, so you will have to rebuild the bootloader with the new clock rate, and sketches that use delay() et alia as well as the intrinsic delay functions will also need to be rebuilt.

What will happen if I do not change the oscillator and leave it on 16MHZ ceramic?

It may work, it may not.

So can I use a programmer circuit with 16Mhz code for the reprogramming of the firmware (an arduino uno)? Even if after programming it becomes unavailable in the uno and works in the final circuit.

You would use a ISP programmer to program the bootloader for the new clock. After that you can program it as normal.

I planning to move this system down to 3-3.6V but I have read that on low voltage I have to use 8Mhz crytstal so my only question is that because of this change do I have to take the chip out to reflash with the programmer again or it will work as it did before?

Any time-sensitive code -- such as delays and UART I/O -- will run at half speed with the 8 MHz crystal. If any of this matters, you'll need to reprogram the chip. (This will include the bootloader, which will now run at half the baud rate it used to!) If this is OK, though, you can leave it alone.

What will happen if I do not change the oscillator and leave it on 16MHZ ceramic?

The ATmega328P isn't specified to run reliably at 16 MHz at 3.3V. Many chips will actually work at this speed, but some will fail, possibly in subtle ways or at inconvenient times. Don't rely on it working.


text:
Why doesn't this work on a Mega2560 although it works on an Arduino Uno
So, This is your code slightly altered. I am using it to read the readings of the roll and pitch of a quadcopter. I have tried using this code for a mega 2560 but it does not work in ports A0 and A1. I think it might in A5 and A6 but I am unsure how to alter this code.
THank you,
Rohan Paleja
/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: http://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */

#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[2]; // times of prev. rising edges
volatile unsigned long rcTimes[2]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter
int Roll, Pitch;
// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt

  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(9600);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[2]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    Roll = rcTimes[0];
    Pitch = rcTimes[1];

    sei();          // reenable interrupts

    Serial <<  " " << Roll << " " << Pitch
       << " "  << rcN << endl;

  }
  sei();            // reenable interrupts
  delay(1000);
}

Of course it doesn't. Port F doesn't support PCINT.

You are trying to do an Pin Change Interrupt on Port F (A0-A7). On the arduino Uno, this port does support PCINT but not on the Arduino Mega.
An option is to use the Port K for the PCINT. Instead of A0 and A1 you then use A8 and A9. A few little changes in the code should do the job:
void setup_rcTiming() {
rcOld = 0;
pinMode(A8, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
pinMode(A9, INPUT);  // pin 15, A1, PC1, for pin-change interrupt

PCMSK2 |= 0x0F;       // Four-bit mask for four channels
PCIFR  |= 0x04;       // clear pin-change interrupts if any
PCICR  |= 0x04;       // enable pin-change interrupts
}

and
ISR(PCINT2_vect) {
byte rcNew = PINK & 15;
...
}

I have tried this code. It still does not work. I changed the code, and  plugged my signal from the receiver into A8 and A9 and no readings are being read through my serial read. Do you know why this code still isn't working? @Janw

I did edit the code because I made a mistake. In PCIFR and PCICR bit 3 should be set and not bit 2.

If I was to use A9 and A12 or A10 and A11 would I have to change anything other than pinmode?  @Janw

If you want to use the pins you mention, you should change the value of PCMSK2. In this register you can set  the pins you want to use. It takes any byte or you can set each bit separately. The least significant bit corresponds with A8, the most significant bit with A15. You can find more info about this in the datasheet of the atmega2560. Its in chapter 15 (external interrupts). PCMSK2 is on page 113.


text:
How to make a Smart Light Bulb?
I was wondering what I would need and what I should do, to make a Smart Light Bulb, like the Hue one from Philips.

I know these light bulbs can be controlled by their Apps from the smartphone, is there a way I can achieve this too?
What components would I need to purchase?
Is there a reference or a tutorial on how I should program this light bulb?

What has this got to do with the Arduino? I'm going to close this question. Feel free to edit it with new information. Thanks for your understanding and cooperation!

This is a question of how to achieve this with Arduino, that's why I posted it here @NickGammon

Which Arduino were you planning to insert into the light bulb? Your question is still incredibly broad. You may as well say "I would like to fly to the moon - is there a way I can achieve this?". What components would I need to purchase? - well, a light bulb and an Arduino? This sounds like you are trying to get us to do a project for you, sorry.

I asked what to start with, if you got it in that way I'm sorry as It isn't meant to be that. @NickGammon

You could use an ESP8266 NODEMCU. There is an example for making it emulate a Hue bridge ( https://github.com/probonopd/ESP8266HueEmulator ).
To have the official bridge control your lights would take Zigbee and finding out the protocol that Philips uses. Their API is open source, however the zigbee protocol they use is not afaik.
ESP8266 is a very cheap solution that works with arduino ide and does not need an arduino. There are powerplugs which have an ESP8266 in them (https://www.itead.cc/smart-home/sonoff-sv.html)

Mh cool, thank you, will have a look at it tomorrow morning and then will let you know :)

Oh, so this would work with iOS too right? I mean, the bulb would be then controllable by the iOS hue app? Or not?

yes it will work with any Hue app !! so also on iOS :)

oh when getting an esp8266.. make sure it is esp8266-12e. the older ones only have 2 outputs and very limited compared to the newer model. you be up and running for around $10.

Oh, and the light bulbs, how should I make them? I mean the first link is for the hub, the second one for the light bulb?

yep :) the second link is esp8266 with a relais connected to a gpio port, you can load the bridge software on there or get a seperate esp8266 to play bridge and get more bulbs to listen to your Leonardo Hue ....

Alright! Will get to work asap and will let you know! So for now this is the right answer, thank you!

Let us continue this discussion in chat.


text:
Running sensor input for given time, stopping, then running seperate scheduled relay output
I've set up an Arduino Uno to run a pretty basic garden watering schedule, with the delay function.
I've now built a solar thermal water heater with a pump and tried running it separately through a 555 timer using a thermistor (33k Ohm approx). I couldn't get this running as the change in resistance with a water temperature rise to 30 deg or so wasn't enough to trip and untrip the 555 timer (thermistor at about 20 k at 20 deg, maybe 50k at 30 deg). (Any pointers to circuits that achieve this would be appreciated by the way.)
I've decided to try to run the solar thermal motor with my arduino set up as I have 2 relays free in a relay shield. My question is how I can run the sensor to start the solar thermal pump, then stop operating the solar thermal system and return to the garden watering code, then restart the sensor input, and so on. The issue is that my power supply is only 1 Amp, and running both systems at once might overheat it.
Hope this makes sense,
Brian

Is the watering system running off the same relay board?

If you are just running the relays off the 1 Amp supply, and there aren't more than 6 relays they shouldn't draw more than an amp.(I will edit this statement if need be)
What you can do in the way of coding you can is to do a classic spinoff of using the millis() function.
//monitors temperature and schedules its operations
//RSM
#define TimeBetweenHydration 10000  //10 seconds
#define TimeBetweenThermal 1000  //1 second
#define Temperature_Thresh  25   //25°C

float temperature = 0.00;

unsigned long lastTempReadTime = 0;  //keep track of the time temperature was checked
//boolean MotorOn = false;  //state monitoring

unsigned long lastWaterTime = 0; //last time the system did something with the watering thing
//boolean Watering = false; //state monitoring

// other variables related to specifics
//…
//

void setup(){

//setup of analog inputs
//setup of digital pins

}

void loop(){

 unsigned long presentTime = millis();

if((presentTime - lastTempReadTime) > TimeBetweenThermal){
lastTempReadTime = presentTime;
 int inADC = analogRead(0);

  //do whatever conversion is needed to get a value of the temperature
temperature = inADC*3.14;

if(temperature > Temperature_Thresh){

//   if(!MotorOn){
     digtalWrite(RLY, HIGH); //turn on pump
//     MotorOn = true;
//  }
 }
  else{
  digitalWrite(RLY, LOW); //turn off pump
  }
}

   if((presentTime - lastWaterTime) > TimeBetweenHydration){
   lastWaterTime = presentTime;

//put your watering code stuff here

  }
}

If you want to make the pump run without a microcontroller you could use a comparator with the thermistor and use its output to switch a transistor. I do not have the 555 timer art skills.

T1 is you thermistor. You should use the values listed for R1 - R3. The transistor, coil and flyback diode are there to show how you should connect it up, the coil could be a motor or a relay to control the motor. The comparator changes around the 30-40Kohm mark.

Hi RMS, I really appreciate your answer, thanks.

In your schematic one leg of the relay coil (the one connected to the anode of the diode) connects to the transistor. I think the other leg of the relay coil (the one connected to the cathode of the diode) is missing a connection to +VCC (5v).

@linhartr22     yes it is missing the connection to 5V, 12V. The OP wasn't specific about there way the relays were hooked up and I didn't have a way to mark that with what I was using.

RMS, you are some man. I tracked down not an LM393, but an LM2904 and it took me a while, but it's working like a dream. Response time is great, and what a classy solution.

@BrianOCallaghan glad the circuit helped you, I think at a point certain things can be removed from the control of the  microcontroller and code ;). If you feel this solved the query, could you mark it as accepted to stop the system from bumping it and to help others looking for a solution.

I really appreciate your answer, thanks. I knew I'd have to let go of the delay function at some stage, and this is the moment I think ;)
As for the PS, I'm actually also powering two solenoid valves and the arduino through the same PS, so just being on the safe side.
I wasn't too happy with a transistor circuit I made previously, but I'll give yours a go for sure. I actually came up with a workaround, which is probably pretty lame. I rigged up a second 555 timer with a large resistor to switch on and off the supply to the first 555 with thermistor every minute or so (a la flashing LED). So the thermistor now goes to temp, switches on the load, but then won't switch it off; the second 555 then resets the first 555, load switches off and either immediately switches on again if at temp, or stays off. Pretty ugly, right!

The rig with the 555 timer sounds pretty good actually, you have made something that the code I did work in hardware.


text:
Arduino fast start not working properly
I have an Arduino 328p (custom) and I can program it using a FTDI header.
However, when I power it from the FTDI using only the RAW (5V) and GND, it only executes simple programs (example blink). If in my sketch I attempt to use SPI for example, it will just get stuck.
If I power the arduino from the FTDI with the DTR pin connected, it will work just as expected for any sketch. I can even remove the DTR pin at this point and there will be no issue.
What could be the cause of this behavior?
Can it be an issue with optiboot fast start?
PS: FTDI is configured for 5V but VCC for the Arduino is 3.3V (I'm using the MCP1703 regulator). This means that the Arduino is powered by 3.3V but the RST pin will have 5V.
PPS: The Arduino is running at 16MHz

I didn't think arduino would run @16MHz on 3.3V

@JaromandaX Just to be sure, I switched the arduino to 8Mhz with the internal oscillator and the results are the same. Fuse settings are: -Uefuse:w:0xFD:m -Uhfuse:w:0xDC:m -Ulfuse:w:0xE2:m

If you provide a higher voltage to the reset pin, you might make it enter high-voltage-programming-mode.

@Gerben        I thought the AVRs only went into HV mode if the voltage was over 12V, I think if it worked the other way round it would cause issues.

The reason for this issue is to do with SPI.
Basically in my custom arduino I have a 4Mbit flash and it communicates over SPI.
It seems that when the RST pin is connected it also automatically initializes the SPI protocol.
When the arduino is powered from RAW + GND directly from an external power source you need to initialize SPI manually.
In your sketch you need to:
    #include <SPI.h>

    void setup() {
        SPI.begin(); // this needs to be invoked before any SPI device gets initialized

        // initialize and use SPI devices
    }

You need to initialize the SPI before use regardless.


text:
Cannot enter programming mode on Arduino Uno
I have an Arduino Uno that I've been programming with an AVR Dragon through Atmel Studio 7.
I did two things in close proximity, and I'm not entire sure which action is the culprit. I tried using the DebugWIRE interface (for the first time) instead of ISP in the tool select screen. I also hit the Arduino's reset button as Atmel Studio was compiling/uploading to the Arduino (stupid, I know.)
Now I cannot program with ISP the normal way, or do anything really.  If I try to upload to the Arduino I get:

I've tried to use the device programming feature using the Dragon and change the fuses as I've read about in other posts and get:

I've tried burning a new bootloader with the Arduino IDE and the IDE tries ten times, but it tells me that the programmer is not responding.
When I plug my AVR ISP mk2 into a different Arduino Uno I get a nice constant green light. If I plug it into the board I've been discussing it blinks red.
I'm not sure where to go from here...

I think either the chip or the board is fried. Try swap the chip (only the chip) to the other board and retry loading the program.

I swapped the chip from the good board to the bad board and it works.  I guess I'll order another atmega328p.   How can i determine if the chip is actually fried or just needs reprogramming?  I had heard of people forcibly reprogramming a chip after you "goober" it up using hvpp mode with the Dragon.
I was reading an article here that talked about it while trying to debug with dragon which is what i was doing when it happened (as well as resetting the board while atmel studio was programming it).

@Khaines0625 You need something that can perform High Voltage Parallel Programming, which, by applying 12V to RESET pin, bypasses all fuse settings to program the device. You can check out the TL866A (not the CS variant) for this.


text:
arduino + GSM/GPRS SIM 900A cannot able to read a message
Here I am using Arduino uno and GSM sim900A, I want to read sms from sim900A. But i am trying to read message, it is showing the empty values. I tried different methods, but no use. Here I have added my script. Please help me.
#include <avr wdt.h="">
String phoneSMS = "+91xxxxxxxxxx";
String messageTxt;
void setup()
{
Serial.begin(9600);
delay(60000);
srl_msg();
}
String srl_msg()
{
Serial.println("AT+CMGF=1\r");
delay(1000);
Serial.println("AT+CNMI=2,2,0,0,0");
delay(1000);
Serial.println("AT+CMGL=\"ALL\"\r"); // to read ALL the SMS in text mode
delay(1000);
char txtmsg2[100]; // AT command output
String date = readSerial(txtmsg2);
String value = date.substring(1, 50);
messageTxt = "Internal - Heart Beat;";
messageTxt.concat(value);
Serial.println(value);
SendSMS(messageTxt);
}
void loop()
{
}
void SendSMS(String message)
{
Serial.print("at+cmgf=1\r");
delay(1000);
Serial.print("at+cmgs=\"");
Serial.print(phoneSMS);
Serial.println("\"");
delay(1000);
Serial.println(message);
delay(1000);
Serial.print((char)26);
delay(15000); // AAN
}
String readSerial(char result[])
{
int i = 0;
while (Serial.available() > 0)
{
char inChar = Serial.read();
if (inChar != '\r')
{
result[i] = inChar;
i++;
}
}
return result;
}

output is look like this:
AT+CMGF=1
OK
AT+CNMI=2,2,0,0,0
OK
AT+CMGL="ALL"
OK

Check you sim card inbox. I also had the same problem, and it turns out the sim card sms inbox capacity is full.
You can also try to use another library, here is one of them

wdt.h is just time handling data library, and have no methods for send or receive sms...
Your method: SendSMS(String message)
is just printing serial labels and counting a char that you are putting in the serial monitor.
Try this GSM example...


text:
Why/when to use IoT publish/subscribe protocols rather then RESTful HTTP?
I am sending data (GPS coordinates) from Arduino once a minute with HTTP POST request to REST API (in OpenShift PaaS). Data is then stored to MySQL db.
Would so called "IoT" publish/subscribe protocols (XMPP, MQTT) be better? Why?
When exactly do you use those two protocols rather than Restful HTTP? Would I really save a significant baterry energy using them?
AFAIK in those protocols machine would "publish" a data to broker and my app would subscribe to it. If I would like to gather data every minute in my app I guess that I would got to have some CRON job that would subscribe to data every minute? Or how would data gathering be achieved?

Your arduino won't change, other that instead of a POST package to your webserver, it sends a MQTT packet to a MQTT server. You won't get any difference in battery usage. I'm still trying to figure out what's so special about MQTT, especially if you are already proficient in MySQL and something like PHP.

In my experience ReST is good for real-time data transfer and processing but has a lot of overhead for simple message passing. Plus, there's no queuing in it so store-forward configurations are troublesome.
MQTT is a message queue transport system where the message can be placed on the channel by the publisher and will stay there until the subscriber picks it up. So you can have some rudimentary store-forward capabilities with this. Also MQTT is more transparent and multicast so communicating to many nodes is no different than communicating to one.
With that, each have their place and use and ReST is great for sending large items (JSON blobs), sending data for calculation and getting it back, and for requesting a specific dataset. MQTT is more for "here's my sensor data every second, enjoy".

(shameless self-promotion)  I did a talk on iot stuff this year at our local code camp.  Notes are here: https://github.com/adbacker/bcc2016/blob/master/2016bcc-iotonthecheap.pdf
Super simplified per my limited experience:
(experts correct at will :-)  )
MQTT protocol:

requires a broker
maintains a connection to the broker (which allows for push notifications back to the device)
was specifically designed for "small footprint" applications (read: limited RAM and processing power)

MQTT is optimized for sending simple data.  GPS coordinates would be a good fit. I'm sure MQTT could be used to send complex data (ie: large json objects) but that doesn't seem to be what it's designed for.
You're not looking for push notifications back to the device, nor are you maintaining a connection to the REST server so (from a practical standpoint) I'm guessing your battery life improvement would be minuscule at the very best converting the solution to mqtt.
Adafruit has a pretty good mqtt tutorial and libraries, as well as a beta service that provides broker services: https://learn.adafruit.com/adafruit-io/mqtt-api
Also, for super-duper-easy IOT setups (that admittedly use a custom protocol), let me recommend blynk.  ( www.blynk.cc )  It's free and so easy I rewrote my entire presentation around it.  Additionally, there are (free) blynk ios and android apps that allow creation of custom dashboards that communicate (via the also-free blynk broker) with your device of choice.  If you host the broker server (also free) yourself, it has it's own REST api that allows data access to/from your device.

Basically, MQTT reduces latency where there's relatively high latency like Wi-Fi by keeping the TCP connection alive so that data can be published and received very quickly. It uses port 1883 and not 80.
As I understand it, the publishers and subscribers connect once to the broker and then ping the broker regularly to keep the connection alive; how often the broker is pinged depends on the pre-agreed keep-alive period. MQTT packets are also significantly smaller than HTTP requests. If the connection is somehow broken, the client repeatedly tries to re-establish the connection and when successful, the subscribers re-subscribe.
Subscribers define callbacks that are called after a topic has has been updated by some publisher. MQTT is best for time-critical jobs where HTTP requests would just take too long and where quick notification of changed topics is desired. I'm not sure but it will probably consume more battery power, since there's that matter of a constant TCP link to the broker.
Since you're only expecting data updates every minute, I think it makes more sense to connect and GET the feed data from the server every 60 seconds. You can use the feed's Last-updated time-stamp (if it doesn't exist, create one) to check if the feed has been updated by the Arduino yet. An MQTT technique would just spend most of the time connected to a broker for no reason since you already know that the update events occur every minute; that is a significant amount of time and power spent waiting for predictable data.
However, you could wait for about 55 seconds, subscribe to the topic and when you get the new data, you disconnect and then wait for 55 seconds again, though I dont know if this will be much of an improvement over REST. If you use this method, you can also set the keep-alive period to be just about 10 seconds, so that the Arduino has enough time to update the feed before your app is notified and there's no need for regular pings.
If you decide to go with MQTT, check out this Arduino library.

MQTT node does not poll broker except keeping connection alive on TCP level. If a message is available for the node, it is send by the broker to the node at that time.

In my applications, the biggest power drain is turning on the radio to transmit data. I often keep the radio off, collect data points, and then turn on the radio to send multiple pieces of data together as one request using a RESTful HTTP call. For my case, RESTful HTTP is way more efficient since I do not need an always on connection.

authors: محمد الكويكبي


text:
Arduino PWM fading led in assembly
I'm writing Arduino UNO (=ATMega328P-PU) programs in assembly to save memory, so I use avra.exe (same as atmel studio's avrasm32) to compile and avrdude to upload, and simple programs like blinking run fine. But now i tried to half-bright a LED with pwm. I checked up my code for errors but I didn't find any, and the LED just full brighs. I checked wiring too. I'm getting struck :c. Here's my pwm.asm code:
.nolist
.include "m328pdef.inc"
.list

.cseg
.org 0x00
     rjmp start
.org 0x34
 start: sbi ddrb, 5 ;pin 13
        sbi portb, 5 ;pin 13 on, just to compare with the PWMed led
        sbi ddrd, 5 ;pin 5 pwm
        ldi r16, 0b00100011 ;fast pwm mode, non inverted pwm at oc0b = pin 5 (right?)
        out tccr0a, r16 ;I'm using Timer0
        ldi r16, 0b00000001 ;no prescaler
        out tccr0b, r16
        ldi r16, 128 ; duty cycle = 50%
        out ocr0b, r16

  loop: rjmp loop

Try writing the code in C and see if you get any other output using avr-objdump -S <filename>.elf. From my limited knowledge of assembly, the code looks file. What happens if you connect the led the other way around (VCC--resistor--led--pwm-pin vs. pwm-pin--resistor--led--GND)? Out eyes don't perceive different light levels in a linear scale.

I tried your program, after converting it to GNU-as syntax. It works as expected, as seen on the scope. Your problem may be simply that the difference between 50% ON and 100% ON is not very obvious to the eye because of its logarithmic perception.

Got it! i tried to set the duty cycle to 16 (6.25% duty cycle) and I noticed a difference. I didn't know about its logarithmic perception. Thanks!

you have to set the PRR timers on
start:  lds     r16,PRR
andi    r16,0b10010111 ; PRTIM2 | PRTIM0 | PRTIM1
sts     PRR,r16

I'm having trouble making sense of this as an answer to the question, which has an accepted answer which mentions nothing about PRR.  PRR defaults to 0x00 on reset, which is to say nothing is being shut off to reduce power by default.  This is not changed by the bootloader or his code.  Why would they need to change PRR?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Best practices for really long distance sensor deployments
I'm noob to Arduino and electronics, but here is a problem from life which I need to solve for myself:
We grow strawberries and early spring freezes can take most of the flowers from the plants. One way to protect this is to have some kind of heating in solar houses, but if you grow outside, your best option is to watering the flowers on the crops when the freezing comes.
I want to deploy at least 3-4 temperature sensors, which are placed at every parts of the land, which will send the data for an Arduino which will turn on the pump with a relay (for this part I also want to use a pre-built relay solution with socket plugs already built, I don't want to mess around with high electricity myself).
For a cable solution (like catKIT system) I need at least 100m cable for the farest part of the land, which can be managable, but later on, scaling the land lots of cables everywhere can be a problem.
So the best solution would be if every temperature sensor is a standalone station, data transmitted by wireless to the main Arduino which is triggering the pump. This way there will be lass cables on the land, less change to cable break by tractor, etc.
Also, with a wireless system, I don't have to deal with signal loss over the cable, just only wireless signal loss. Is it possible to correct this by middle wireless signal transmitter stations? Or even better, all of them connected to each other!?
Like if the farest sensor reading Celsius 0.8, middle sensor reading Celsius 1.2. Middle sensor have a variable to also consider any reading from the farest sensor, which is reading 0.8. If that reading under Celsius 1, than don't bother his own output, send 0.8 to the main Arduino which is triggering the pump.
These station's power input still need to be solved, but maybe solar panels can be an option? However I have a clue that night they will not work, most of them freezing comes at night.
I saw wireless shields for arduino which offering even a km range in ideal conditions. But how degrading when the conditions are not ideal, like a house wall, rain, fog, snow?
Is it possible to feed multiple wireless inputs too one arduino? 3-4-10-20 standalone stations which transmitting temperature reads for the main arduino. If one of them sends lower temperature than +1 Celsius, than the pump will be turned on. Is it possible to solve this?
Thank You for your answers!

Is temperature really that different, in different locations? I'd go with a single sensor, and maybe a larger safety margin of e.g. 1.5 degrees C. Don't make things too complicated.

Probably not, but in altitude can be a difference (0 to 200cm, if we implement vertical towers). Also consider the environment (open vs tree shades). Happened in our garden that the flowers at open field frozen, the ones was in little shade won't. Covering the entire land with sensors just saves it from partial freezing, which can be still relevant.

Seems like you already know where the coldest spot is. Just place the one sensor there (on ground level).

There's as many ways of solving your problem as there are of skinning a cat (those poor poor cats - always getting skinned... ;) )
As you have already noted there are two basic solutions: wired or wireless.
Wired does have one major advantage that you haven't really touched on (only mentioned in passing) and that is power. With a wired solution you can provide power over those same wires so you don't need to worry about solar panels, batteries, whatever. But wires can break, yes. So they're not ideal. But then what is?
With wireless you then introduce the major problem of power. Solar panels are one possible way of getting power, though they are expensive, and you need to "over spec" them to charge batteries so you continue to have enough power for the times when is little or no sun.  Complementing them with wind power is also an option to boost the battery charge when its windy. It all adds up to very expensive sensors though.
A compromise might be to consider both options together.  Turn the sensors into small clusters of sensors that are near by with a base station for those sensors that both gathers and stores the power needed for them, and performs the wireless communication. The sensors would then be wired to the base station.  Your wires are then shorter, and your power is more centralised.
But what to then use for the wireless itself? Well, there it's really all down to frequency.  There's two basic gropings here:

High frequency - 2.4GHz - is great at unobstructed communication. That's the frequency your WiFi works on, and as you probably know it's great if there's no walls in the way. Add walls and the signal drops off considerably.
Low frequency - 433MHz - Far far better at penetrating walls and things but much less bandwidth.

I have had distances of hundreds of meters using a 2.4GHz nRF24L01+ module with power amplifier and antenna. That's in open air with (pretty much) line of sight. Indoors the range is much much shorter. Put buildings in the way and your hundreds of meters drop down to tens of meters.
So if there are obstructions you're pretty much going to want to use the 433MHz range (there is another frequency, which is different depending on where in the world you are - 868MHz or 915MHz, so we'll ignore that for now).
There's plenty of modules around that run at 433MHz, some better than others. There is, however, a new standard emerging now that is designed specifically for this kind of thing - long range, low bandwidth, just for sensors (as part of the IoT bandwagon) called LoRa (short for Long Range) which aims at distances of 15km using very small amounts of power (tens of mA) which is ideal for solar powered operation. It also can use the 868/915MHz region as well.
The final option that you touched on without knowing it is that of a mesh. This is where all the nodes form a network and each node is capable of relaying data from other nodes to get to their destination. Kind of like how the internet works. There are some mesh libraries available for some radio modules on the Arduino, but I have no idea how good or reliable they are. The best ones would be completely self-healing with auto-discovery - add a node and the whole mesh works out how to route messages to the destination node; remove a node and the mesh works out new routes to pass the data around the hole it's created.
Creating a good mesh stack is not child's play, so you would want to research it properly and find the best modules with the best library support if you wanted to take this route. That's why LoRa is taking off - it's so much simpler to get wide coverage without the need of complex mesh systems.

Personally I wouldn't use an Arduino as a wireless sensor controller, I would use an ESP8226, which comes with WIFI interface built in.  You can program this through the Arduino IDE in the same language, and its compatible with most Arduino sensors.
The ESP8266 also has the advantage that it can create a WIFI network of its own, because it can act as a WIFI client, a WIFI access point or both at the same time.  So if you do have an issue with the range of the signals then you can program your own WIFI repeater, which could also measure the temperature at the same time.   They come in many different shapes and sizes, I think you might be better having an external aerial capability, have a look around and see what you can find.  They cost around $2 so they should break the bank.
As for powering it you could use solar or wind power to charge a battery.  Probably the best sort of battery for this is a Lead Acid battery because they don't object to being trickle charged.  Assuming you sensor station runs at 5V, you want at least a 6V battery.  You charge a 6V battery at 7.2V, so your solar panel(s) should generate at least 7.2V in average sunshine.  You also need to work out how much power you sensor station is going to need, factor in an extra for working in cold weather, etc and then multiply it by the number of hours per day want it to work (24?).  This is the total power you need per day, so the output of you panels must be = (Required Power / Hours of Sun).  At this point you are best looking for a COTs device to charge the batteries and achieve your needs.


text:
Burn bootloader on custom ATmega 2560 board
I have developed and produced a custom board with a ATmega 2560 on it and a FT232RL for USB communication. I want to burn an Arduino bootloader onto the board without using an external Arduino as ISP. I can't seem to figure out how.
When I just click "burn bootloader" from the arduino software it says:
avrdude: stk500_recv(): programmer not responding
What am I doing wrong and how can I correctly burn the bootloader?

To burn a bootloader you have to use some external device. That can either be another Arduino or a hardware programmer, like an USBASP or something similar.
You can't just magic the bootloader on there through the USB and a dose of wishful thinking. To use the USB you first have to have the bootloader on there.

Okay, thanks for your quick reply. Is there any way I can use other pins than the MOSI and SCK? I don't have those available in the design, the MISO, Reset, GND an VCC are available.

No. You have to program the chip through the pins that you program the chip through. If you didn't provide access to those pins in your design then your design is wrong. You will have to manually solder wires to those pins either direct to the chip or to somewhere that those pins are connected to.


text:
RFID RF522 kit for access control
I am trying the RFID RC522 reader kit with an Arduino UNO to built a controlled access system for a door.
Using the code below, I am able to read the UID of my card and light up an LED when the reader detects the card or the badge, however it will light up whatever card is presented to it even if the UID of this card is not entered as a String in my program.
My question is how can I enter hundreds of cards (depending on memory) that will unlock the door and have all the others set as unknown if not in my program.
Thank you very much for your help
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         //(or SDA) Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
// ===========================================================================
String read_rfid;
String ok_rfid_1 = "C5 12 E3 52"; // for the badge
String ok_rfid_2 = "9A 48 3A D5"; // for the card
// ==========================================================================
int led = 3;
// ===========================================================================
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.PCD_Init(); // Init MFRC522
 mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
 Serial.println(F("Scan PICC to see UID, SAK, type, and data bleds..."));
  pinMode(led, OUTPUT);
}
// ===========================================================================
 void dump_byte_array(byte *buffer, byte bufferSize) {
  read_rfid="";
  for (byte i = 0; i < bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
 }
// ==========================================================================
void unlock() {
  digitalWrite(led, HIGH);
  delay(2000);
  digitalWrite(led, LOW);
}
// ======================================================================
void loop() {
 // Look for new cards
 if (! mfrc522.PICC_IsNewCardPresent())
 return;
 // Select one of the cards
 if (! mfrc522.PICC_ReadCardSerial())
 return;

  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println(read_rfid);

  if (read_rfid == ok_rfid_1 || ok_rfid_2) {
    Serial.println("Open");
    unlock(); // turns LED on
  }

  else {
    Serial.println("Stay Closed");
  }
}

Your IF statement is the problem. if (read_rfid == ok_rfid_1 || ok_rfid_2) always evaluates to True. Your condition should be:
if (read_rfid == ok_rfid_1 || read_rfid == ok_rfid_2)

You also need to remove the spaces in the string literals if you want this condition to have the desired effect.
This approach isn't very good though, since you have to add more comparisons to the IF condition if you want to match more cards. You should use the byte arrays as they are, without converting to Strings; it can actually be a lot simpler to compare as well as memory-safe. Store all your allowed card UIDs in a 2-D array:
#define ALLOWED 2   // no of allowed cards
byte read_card[4];   // same purpose as before
bool found = false;  // to know when a valid card match occurs
byte cards[ALLOWED][4] = {{0xC5, 0x12, 0xE3, 0x52},
                         {0x9A, 0x48, 0x3A, 0xD5}};

Then you should get rid of dump_byte_array() and compare cards like this:
memcpy(read_card, mfrc522.uid.uidByte, 4); // copy UID into array with shorter name ;)

for (int i = 0; i < ALLOWED; i++){
  if (memcmp(read_card, cards[i], 4) == 0){

      found = true;
      break;
  }
}

if (found){
  Serial.println("Open");
  unlock(); // turns LED on
  found = false;
}
else {
  Serial.println("Stay Closed");
}

Thanks TisteAndii, I will give it a go, byte arrays is defenitely what I should use. cheers.


text:
How can I get analog-in reading from Digital-PWM-out on the same board?
I have a wire going from PWM4 to A0 but I don't dare turn on my Arduino Mega in case this is incorrect.
PWM4 will eventually go to an analog device but I want to make sure the read value is what I expect it to be. Am I okay to proceed with my current setup or do I need to throw in a resistor / conversion?

A resistor/capacitor conversion?  Yes.  An RC filter on PWM4 could smooth out the square wave.  If you don't, you'll get the 0 or the +5 values into A0, depending on the sample time.

@DaveX So with the correct sample time would my analog pick up the pseudo analog signal?

No-The default analog sample time (<0.0001s) is short compared to the PWM frequency 490Hz, 980Hz , so the value you read at any particular point in time will be probabilistic.  If you average enough samples of the binary +5 and 0V PWM output, it would approach the analog value statistically.  Or you could use an RC filter to make an exponentially-weighted moving average in electrical-analong component space, rather than programming space.

You are fine by doing that, but you won't get what you expect.
A PWM signal isn't an analog value. It's a series of pulses, the duration of those pulses is set by the (not accurately called) analogWrite. So sometimes the value is 5V and sometimes it's 0V. You need to get the average value by adding e.g. an RC-filter.
Another option is to add a proper DAC (digital to analog converter) chip to your circuit.

If I understand you correctly, I need to set the correct on/off interval for my pwm out before I can get the desired value for my analog read but this is otherwise doable and safe?

No, you set the on/off interval ratio using analogWrite. The average voltage will be proportional to the ratio. However to get the average voltage you need to create a filter average the 0V and 5V signals going out of the PWM pin.


text:
Converting char array to int
I'm trying to use nRF24L01 module to send a messages between 2 arduinos
Transmiter code:
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));

  delay(1000);

Reciver code:
char text[32] = {0};
radio.read(&text, sizeof(text));

Serial.println(text);

How I can put into char array an int value?
I tried doing it in this way
For example:
      int a = 60;
      const char text[] = String(a);
      radio.write(&text, sizeof(text));
  delay(1000);

radio.println(a) maybe?

Are you just looking for a way to get an arbitrary number expressed as a string? If so, you'll likely want to use some existing functions to help you along.
I recommend using sprintf
sprintf(char * str, char * format, args)

Where str is the string you're storing results in, format is the string you're inserting your values into for, you guessed it, formatting, and args are all the args, separated by commas, that you'll be passing into the format string to be inserted into the str string. An example might be:
char[x] result;    //x is the number of elements in your array, atleast one for every letter and one for the end character, ex: "hello" needs 6.
int number = 24;
sprintf(result, "My number is %d", number);
sendSomewhere(result);   //sends "My number is 24"

You forgot to declare the size of result. Also, if your “somewhere” inherits from Print (most things that implement write() do), then you can somewhere.print("My number is "); somewhere.print(24);.

I did forget to declare a size for result! for OP, that line should read "char[x] result" where x is the number of elements in your char array.
As for sendSomewhere(result), it was just supposed to be an open-ended function for the OP to get the concept with.

By char[x] result; you probably mean char result[x];. 2) I understand the virtues of an open-ended answer, but using sprintf() instead of Print::print() will make the compiled program grow by 1 K or so. If the program already uses Print::print() (which is likely, since it is so common in Arduinoland), then the cost of sprintf() is more like 1.5 K.

sprtintf() returns the length of the string created so you can do int length=sprintf(result, "My number is %d", number); radio.write(result, length); This saves using strlen() to calculate how many bytes to send.

You can not have 'const' prefixed the 'text' variable as it then become 'read-only'.
    char text[32];
    int a = 60;
    sprintf(text, "Number %d", a);
    radio.write(&text, sizeof(text));

The simplest method is to send the integer in binary format (skipping the conversion to text).
int a = 60;
radio.write((char*) &a, sizeof(a));

Cheers!


text:
How can you speed up the ADC on an ATtiny85?
I'm reading input from a camera and trying to reach a fast frame rate. Problem is my ATtiny85 has a pretty slow conversion time (65 - 260 µs Conversion Time). Is there any way to make this faster? I heard that you can set-up a prescaler for the analogRead() method by doing the following:
#define FASTADC 1

// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

void setup()
{
  #if FASTADC
   // set prescale to 16
   sbi(ADCSRA,ADPS2) ;
   cbi(ADCSRA,ADPS1) ;
   cbi(ADCSRA,ADPS0) ;
  #endif

  /*Rest of the code goes here.*/
}

I can't really make sense of the code and I found it on a less then reliable website so I was wondering if any of the gurus on here could let me know if what I'm attempting is possible and if this is the proper way of achieving my goal.
Also, would this also work for the Arduino Mega? I'm currently using it to test and debug my project since the ATtiny84 doesn't have serial output.
Datasheet: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf

How many bits of precision do you need? You can speed up the conversion at the cost of loosing precision in the lower bits down to 1us/conversion.

Can you explain what bits of precision is? This is my first Arduino Project and first time working with a camera so I'm a little confused on the lingo.

The ATTINY ADC normally gives 10 bits of precision- so you get a value between 0 and 2^10 (1024) and each number is different, so (say) 787 (1100010011) is always bigger than 786 (1100010010) even though 787 and 786 only differ by the lowest bit. You can make the ADC go faster, but the bottom bits start to not matter so you can only care about the topmost bits - so in our case if you only had 9 bits of precision then 786 and 787 would be the same (both would be (110001001x where the x means don't know or care). Make sense?

Makes a lot of sense. So when you set a prescaler you are reducing the number of bits used we can get the ADC to be faster but we will have less accuracy.

The prescaler just divides the clock that goes into the ADC. So if you start with a 1MHz clock and a prescaler of /2, then the lock that goes into the ADC will be 500Khz. The ADC clock (after the prescaller) needs to be 50-200Khz to get all 10 bits of precision, but you can run it up to 1mhz but more of the bottom bits will start being wrong the faster you go.  How much precision do you need and how fast you do need samples?

I'd be fine with 4 bits of precision eventually and for me the faster the better. I'm also trying to understand what the code above is doing. Since it's setting a prescaler of 16 does that mean that it's actually making my program slower?

If you only need 4 bits, then I'd ditch the ADC and just use 2 op amps - or even just a resistor ladder connected to input pins so that you get the voltage window you want. Very very simple (at most 4 resistors) and very fast (as fast as the ATTINY can read the input PINs).

Sorry again I'm kind of lost with the lingo. What are 2 op amps? And how can I just ditch the ADC if the signal coming in from the clock are in analog?

What is the camera?

@bigjosh The TSL1401R-LF linescan module. It reads in a 1 X 128 array of pixels.

Besides lowering the ADC clock prescaler, you can also do the conversions asynchronously. Arduino's analogRead for example, starts a AD conversion, waits till it's finished, and then returns the value. However during this waiting you could be doing something useful. So you could e.g. do something like; start conversion, do some calculations on the previous conversion value, wait till conversion is done, and start all over again.

The ADCs in the ATtiny85 and ATmega2560 (the chip powering the Arduino
Mega 2560) are pretty similar, except for the Mega having more inputs.
In particular, the way you set the clock prescaler is the same, namely
the bits ADPS2:0 in the register ADCSRA. You could use the same code to
set the prescaler on both chips, but you probably don't want to unless
your ATtiny is clocked at 16 MHz, like your Mega. I would normally
just set the control register to the value I want, rather than
touching only a few bits, but that is a matter of personal preference.
So, to set the ADC clock of the Mega to 1 MHz, I would
ADCSRA = _BV(ADEN)    // enable the ADC
       | _BV(ADPS2);  // clock at F_CPU / 16 = 1 MHz

The same code would do the same thing on an ATtiny clocked at
16 MHz. If the ATtiny runs at 8 MHz, I would instead
ADCSRA = _BV(ADEN)    // enable the ADC
       | _BV(ADPS1)   // clock at
       | _BV(ADPS0);  //     F_CPU / 8 = 1 MHz

If you want to be generic:
#if F_CPU >= 12000000
# define ADPS_SETTING _BV(ADPS2)                 // F_CPU / 16
#else
# define ADPS_SETTING (_BV(ADPS1) | _BV(ADPS0))  // F_CPU / 8
#endif

ADCSRA = _BV(ADEN)      // enable the ADC
       | ADPS_SETTING;  // clock somewhere near 1 MHz

As bigjosh explained in comments, the prescaler setting is a trade-off
between speed and accuracy. I recommend you read the article on the
Arduino ADC by Nick Gammon. He did some tests at various speeds
which showed that you can get decent results with clock speeds up to
1 MHz, then it becomes pretty bad at 2 MHz and mostly
useless beyond. You may want to run the same tests with your particular
setup.
Except for the very first conversion, which takes longer, an ADC
conversion takes 13 cycles of the ADC clock. If you run that clock
at 1 MHz, that is 13 µs per reading. If you get the readings
with analogRead(), you won't get one reading every 13 µs, because
the CPU needs extra time to execute the code you have between successive
calls of analogRead(). You can save time by having the CPU and the ADC
work in parallel, maybe along these lines:
ADCSRA |= ADSC;     // start the first conversion
for (int i = 0; i < NB_READINGS; i++) {
    loop_until_bit_is_clear(ADCSRA, ADSC);  // wait for the ADC
    uint16_t reading = ADC;     // get the reading
    ADCSRA |= ADSC;             // start the next conversion
    process(reading);           // process the reading we have
}

This way you process one reading while the ADC is taking the next one.
Or you can set the ADC to “free running mode” (where it takes one
reading after another without ever stopping) and get the readings in an
interrupt service routine. Whichever method works best depends on your
particular application: the amount of works your CPU has to do while
reading the ADC and whether you can afford to do the whole series of
readings with interrupts disabled.

If that's how you make the ADC faster then what does the code I posted do?

It sets the prescaler to 16, just like my first code snippet.

Okay, then I might be understanding the concept behind a prescaler. I thought prescalers made things slower because they divided the speed at which things happen. Meaning if my ADC is operating at a 1MHz speed and I set a prescaler of 2 then it would run at half the speed.

@CrystalPritzker: No. The prescaler sits between the CPU clock and the ADC clock. C.f. section 17.5 of the datasheet. If your CPU runs at 16 MHz (which is the case on the Mega), setting the prescaler to 2 would clock your ADC at 8 MHz, way too fast. The Arduino core sets it to 128, which clocks the ADC at 125 kHz, which is fine but too slow for your needs. I suggest you clock your ADC at 1 MHz, which means setting the prescaler to 16 on the Mega (I do not know F_CPU on your Tiny).

I see, but what happens if I just don't set a prescaler? Is their a default speed at which the ADC runs?

@CrystalPritzker: The hardware defaults to prescaler = 2 (see the datasheet). If you use an Arduino core, it will be set to 128 (c.f. my previous comment).