text:
Connecting E-paper display (GD) to Arduino?
I'm still learning how to use Arduino and electrical components, but I will try my best to understand any answers!
So I just bought an e-paper display off a website, not from the manufacturer itself (http://www.good-display.com/products_detail/productId=305.html). The product is a 1.54 inch E-paper display 200x200 partial update GDEP015OC1.

I was a bit puzzled by how to connect the display to the Arduino Uno. Turns out that to connect the display to a board, it needs a breakout board (is this the correct term?). I could buy it online from the manufacturer, however, it will take me at least a month and the shipping cost is too high.
I was wondering if it is possible for me to make my own breakout board? Is there any 'general' breakout board for an e-paper display, or does it have any special from the manufacturer? If it is possible, how difficult would it be for a beginner who has almost no knowledge on circuit building/electrical components?
The aim is just to display an image onto the e-ink display.
Thanks!
edit: I bought the mentioned display because of the size. I was afraid of not knowing how to connect the mention display (which is where I am now), so I bought this e-ink display also: https://www.smart-prototyping.com/E-ink-E-paper-Display-module-3.3V-2.04-inch-177x72.html I was thinking to take the 60mmx30mm display off the board and try connecting the 30mmx30mm display to the 'breakout board' if I am unable to build my own board. Both seemed to have the same pin number (need to confirm later).

Hi and welcom to the Arduino SE community. This question is not directly about Arduino. Please take the tour and read the on topic and don't ask help pages.

This is the E-Ink / Paper display device integrated by the image display technology of Microencapsulated Electrophoretic Display (MED). This device has an approach to create a tiny spheres in which the charge color pigments are suspending the transparent electrode. Wiring to your microcontroller Follow this link 1.52 Inch Epaper Wiring E-Ink/E-Paper with Microcontroller

E-ink displays require high voltages to operate them. They are electrostatic devices and the pixels need charging up to a high voltage (high compared to what an Arduino runs at) to attract the pigment powder (basically the same as laser printer toner) to create an image.
While it is possible to make your own board it's not something that is simple and straight forward. Designing boost converters requires a certain base level of knowledge and expertise to get it right. Not something I would recommend a beginner attempting.
Even though a display may have the same pin number as another it doesn't follow that the pins are in the same order on the connector. There is no standard and each display from different manufacturers (and even different displays from the same manufacturer) will have a different pin-out. You will need to compare the datasheets for the two displays to see if the pin-out is the same and if it isn't you would have to somehow map from one to the other on the driver board.
The simplest option is to just order the correct driver board for that display.
(Note: in this context it is called a driver board not a breakout board. A breakout board is typically a passive circuit board that converts from one hard-to-use connector or footprint to a simpler, say 0.1", header. A driver board contains active electronics, in this case a boost converter, to drive the device it is connected to.)


text:
Issue with If statement and boolean logic
I'm trying to control motor based on rain sensor and my own build anemometer. It should only controlling motor clockwise/CW for open the roof if there are no rain (indicated by value above 900) AND the wind speed below 4 km/h. If there are raining (analog value below 650) and/or wind speed above 4 km/h the motor should spin counterclockwise/CCW. I succeed to rotate the motor CCW if rain and/or high wind speed happen, but when the motor hit the limit switch for stopping the motor, motor only stop for maybe 2 seconds and then back rotating CW (open the roof), even the wind still above 4 km/h. The roof should be open only when there is no rain (analog value above 900) and the wind speed below 2 km/h. Here is my If Statement logic program:
if ((analogRead(rain) < 650 || (Wind > 4)){
  motor_closed();
}

else if (analogRead(rain) < 650 && (Wind > 4)){
  motor_closed();
}

else if (analogRead(rain) < 650 && (Wind < 2)){
  motor_closed();
}

else if (analogRead(rain) > 900 && Wind > 4){
  motor_closed();
}

else if (analogRead(rain) > 900 && Wind < 2){
  motor_open();
}

Did I make mistake when using && boolean operator? Or its something else?

Why do you call analogRead() multiple times? Do you expect the result to change that quickly?

Only the first and last options will be possible there.

Use analogRead() once and reuse the variable, also what about nesting if statements instead? I think that would improve readability as you can first check if it's raining and then check if it's windy, follows human pattern of thought a bit more than two comparisons at once. Another thing I would avoid is separating else statements from the if statement with a newline, harder to read.

I don't expect for fast result change, only want that the motor respond accordingly. I'm thought it would work with multiple if statements and raining and windy comparisons.

You only need two tests: "is it too windy or too wet?" Yes, close it. Otherwise, "is it not windy enough and not rainy enough?" Yes, open it.

The first paragraph of your question says no rain and wind speed below 4 km/h, roof open. The last paragraph of your question says "The roof should be open only when there is no rain (analog value above 900) and the wind speed below 2 km/h". If the wind is 3 km/h, should the roof be open or closed?

Sorry the first was typo, it should be 2 km/h.

Could you update your question please.

i want to control motor movement (open and closed) based on rain and wind condition. If rain below 650 or wind above 4 km/h then motor closing the roof. And if rain above 900 (which indicates the rain has stop or no rain at all) and wind below 2 km/h then motor open the roof. And I had an issue with motor movement (spin direction), when the limit switch for stopping the motor (when it closing the roof) is pressed, only about 1-2 seconds after the motor stopped, it suddenly activating the motor for opening the roof, even in high wind speed (above 4 km/h).

Personally I like to force precedence in my if statements to ensure that things always work precisely as I intend.  Group your logical predicates with brackets:
if ((analogRead(rain) < 650) || (Wind > 4)) {
    motor_close();
} else if ((analogRead(rain) > 900) and (Wind < 2)) {
    motor_open();
}

Using intermediate variables would make it more readable:
bool tooWindy = (Wind > 4);
bool notWindy = (Wind < 2);
bool tooRainy = (analogRead(rain) < 650);
bool notRainy = (analogRead(rain) > 900);

if (tooWindy || tooRainy) {
    motor_close();
} else if (notWindy && notRainy) {
    motor_open();
}

Giving names to the logical conditions makes it far more obvious what is going on:

If it is too window or it is too rainy then close the roof.
Otherwise, if it's not too windy and it's not too rainy then you can open the roof.

And of course you have the time when it's between too rainy and not too rainy, or between too windy and not too windy, in which case nothing should happen. This is called hysteresis and is good to have since it stops the roof from opening and then immediately wanting to close.
You could also improve the logic of the system even more and implement a small Finite State Machine:
enum {
    CLOSED, OPENING, OPEN, CLOSING
};

int state = CLOSED;

switch (state) {
    case CLOSED:
        if ((analogRead(rain) > 900) && (Wind < 2)) {
            motor_open();
            state = OPENING;
        }
        break;

    case OPENING:
        if (digitalRead(limit_open) == HIGH) {
            motor_stop();
            state = OPEN;
        }
        break;

    case OPEN:
        if ((analogRead(rain) < 650) || (Wind > 4)) {
            motor_closed();
            state = CLOSING;
        }
        break;

    case CLOSING:
        if (digitalRead(limit_close) == HIGH) {
            motor_stop();
            state = CLOSED;
        }
        break;
}

In that you only attempt to open the roof (and even check to see if you should open the roof) if the roof is actually closed. Similarly for checking for and closing the roof - it only happens when the roof is actually open.  Nothing happens in the way of checks while the roof is in the process of opening or closing, so it has to complete its open or close operation first before any more decisions are made as to whether the roof should be open or closed.

Did I make mistake when using && boolean operator? Or its something else?

use brackets liberally.
rather than
if (x > 65 && y < 10)

instead,
if ((x > 65) && (y < 10))

source: Stack Exchange

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

sort: votes


text:
Stopping motor DC with 2 limit switches
I try to build an automatic roof with rain sensor input, when it's rain the roof then closed pulled by DC motor on the tracks and activate a buzzer. When it reach the end (limit switch pressed) then the motor stopped and buzzer off. And when the rain stopped, motor will turning again to open the roof until the second limit switch pressed to stop the DC motor.
I have try to make my own program but it have an error, when it's has no rain detected the motor spin to close the roof and stop when limit switch pressed (LOW logic), but when rain detected the buzzer turned on but the motor doesn't spin at all. Here is my code, I'm using L293D for motor driver and using its enable pin.
void setup() {
  digitalWrite(enable_motor, HIGH);
  digitalWrite(motor_open, LOW);
  digitalWrite(motor_close, LOW);
  digitalWrite(alarm, LOW);
}

void loop() {
  if (analogRead(rainSensor) < 650){
    digitalWrite(alarm, HIGH);
    digitalWrite(motor_close, HIGH);
    digitalWrite(motor_open, LOW);
  }
  else if (digitalRead(stop_close) == LOW){
    digitalWrite(alarm, LOW);
    digitalWrite(enable_motor, LOW);
  }
  else if (analogRead(rainSensor) > 850){
    digitalWrite(alarm, LOW);
    digitalWrite(motor_close, LOW);
    digitalWrite(motor_open, HIGH);
  }
  else if (digitalRead(stop_open) == LOW){
    digitalWrite(alarm, LOW);
    digitalWrite(enable_motor, LOW);
  }
  else {
    digitalWrite(enable_motor, HIGH);
    digitalWrite(alarm, LOW);
  }
}

Can I use If-Else logic? Or I make a mistake?

Your logic is a bit off. For example, when it is raining and rainSensor < 650, only that part of the if gets executed and the else if parts never happen.
You could just wait for the roof to open/close in a loop. Also, you will find it helpful to break your code into smaller functions. (I'm not sure what the enable_motor pin is for, so that part may need fixing).
// This function determines the current status of the roof
enum {OPEN, CLOSED, OPENING, CLOSING, UNKNOWN};
byte get_roof_status()
{
    if (digitalRead(stop_close) == LOW) return CLOSED;
    else if (digitalRead(stop_open) == LOW) return OPEN; // Fixed typo
    else if (digitalRead(motor_open) == HIGH) return OPENING;
    else if (digitalRead(motor_close) == HIGH) return CLOSING;
    return UNKNOWN;
}

// Helper functions
void open_roof() {
    digitalWrite(alarm, HIGH);
    digitalWrite(enable_motor, HIGH);
    digitalWrite(motor_close, LOW);
    digitalWrite(motor_open, HIGH);
    // Loop until roof is open
    while (OPEN != get_roof_status()) /* NULL */;
    stop();
}
void close_roof() {
    digitalWrite(alarm, HIGH);
    digitalWrite(enable_motor, HIGH);
    digitalWrite(motor_open, LOW);
    digitalWrite(motor_close, HIGH);
    // Loop until roof is closed
    while (CLOSED != get_roof_status()) /* NULL */;
    stop();
}
void stop() {
    digitalWrite(alarm, LOW);
    digitalWrite(enable_motor, LOW);
    digitalWrite(motor_open, LOW);
    digitalWrite(motor_close, LOW);
}

void setup() {
  // Set the pinmodes
  pinMode(enable_motor, OUTPUT);
  pinMode(motor_open, OUTPUT);
  pinMode(motor_close, OUTPUT);
  pinMode(stop_close, INPUT_PULLUP);
  pinMode(stop_open, INPUT_PULLUP);
  pinMode(alarm, OUTPUT);

  digitalWrite(enable_motor, HIGH);
  digitalWrite(motor_open, LOW);
  digitalWrite(motor_close, LOW);
  digitalWrite(alarm, LOW);
}

void loop() {
  // This function is much simpler now
  if (analogRead(rainSensor) < 650) {
    close_roof();
  }
  else if (analogRead(rainSensor) > 850){
    open_roof();
  }
}

enable_motor is for enabling two input in L293D because I use its enable pin. I have try using your code structure, it works for opening the roof, but when motor start to spin for closing the roof and it hit the limit switch it suddenly reversing the motor spin and back to open the roof. Did I missed something?

There was a typo in get_roof_status() and the enable_motor logic was reversed. I've fixed these issues. I don't have any spare motors laying around but I do have some L293D chips. I simulated this (with LEDs and push buttons) and it seems to work.

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


text:
Proportional water flow control
I've been looking at water flow control with Arduino and I'm finding a huge difficulty in managing to do an 'analog' control on water flow. The mainstream solution seems to be the well known solenoid valve, however those seem to be binary (full flow, no flow), and I'm looking for a more variable answer.
Is it possible to get middlegrounds with solenoids? Maybe actuating them with less voltage or amperage will cause it to partially actuate? If not, does anyone know of embedded solutions using servos or steppers maybe?

Only thing that comes to mind is multiple solenoids, which is probably not what you are looking for.

Because there is no pump. This is connected to a pressurized water pipe.

Is it possible to get middle grounds with solenoids?

No.  The solenoid will be all or nothing.  If you have used a magnet, you have seen that the force decreases rapidly with distance.  As you move something closer, it will typically snap to a magnet at one point.  The same thing happens in a solenoid valve: once you apply enough voltage to start motion, the motion will complete.
Side note: that is actually a common trick to saving much power with solenoid valve.  You might apply 12 V to actuate, but then you can reduce the voltage very low (maybe 2 V or lower) and the valve will still say actuated.
So if you want flow, you need a flow control valve.  A common 1/4 turn ball valve will provide the fractional flow you seek.  You should be able to hook a servo or gear motor to that.
A typical ball valve will not provide a constant change of flow with angle.  That means the change in flow between the first 5 degrees opening will be large while the last 5 degrees of motion will have little effect.  If the application is not critical, that would be fine.
If you want more precise flow control, valves are made with a particular cutout in the ball that makes the flow control more linear.  You can get a commercial type valve with motor attached in cost range of 100 $US.  For hooking up to an Arduino, a Belimo flow valve (one example vendor) only seems appropriately named

These are commercial type valves used to control water in heater systems and such.  They take a 0 - 10 V input signal as control and will rotate the vale.  The keyword search is "motorized flow control valve" and that will find you many.  These are not exotic, you will find many in all sorts of sizes.  You may even find from a local plumbing supplier where you can pick one up at will call.

Do you use a pump to circulate the water flow, if so maybe you have a better result with a variable pump speed (PWM), in state of a variable valve opening.


text:
Assigning value inside structure array outside setup and loop functions
I'm having some difficulty assigning a value to a variable in a struct array outside the loop and setup functions. Assigning a value to an int or char array works completely fine but this doesn't.
The example code and error message returned after trying to compile are below. Any help is greatly appriciated. Thanks
void setup()
{
}

struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
} trap_game_details[2];

trap_game_details[0].random_min = 1;

void loop()
{

}

src/sketch.ino:13:5: error: ‘trap_game_details’ does not name a type
     trap_game_details[0].random_min = 1;
     ^
.build/uno/Makefile:166: recipe for target '.build/uno/src/sketch.o' failed

Assigning a value to an int or char array works completely fine but this doesn't.

It only works fine if you do it on the declaration.
eg.
This works:
int foo = 42;  < ---- declare and define with initial value

This doesn't:
int foo;   // < ---- declare and define

foo = 42;  // < ---- assignment statement

Your code was like the second example.

Majenko has shown one way. He split the declaration into two parts. The first part declared the type trap_game_detail, and the second part is an instance of that type, like this:
struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
};

struct trap_game_details trap_game_details[2] = {
    { 10, 5, 1, 100, 4 },
    { 8, 23, 5, 95, 8 }
};

Alternatively, and a bit closer to what you were doing, just keep going with the initialization values after you define the structure, like this:
struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
} trap_game_details[2] =
  {
    { 10, 5, 1, 100, 4 },
    { 8, 23, 5, 95, 8 }
  };

Ah I see. Thanks very much for the explanation Nick, that was really helpful.

You can't access array contents in the global scope like that.  You have to assign the entire block of data in one go:
struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
};

struct trap_game_details trap_game_details[2] = {
    { 10, 5, 1, 100, 4 },
    { 8, 23, 5, 95, 8 }
};

Items in the global scope aren't executed - only things in functions are executed.  Accessing individual parts of an array or struct like you are trying to is a programatic operation, so can't be executed since it's not in a function.


text:
Non line of sight radio and arduino uno
I've been using a pair of arduino uno and nrf24l01 and found it wasn't really suitable due to low range when it comes to obstacles.
Essentially I'd like to use it in country areas where it would ideally transmit through dense trees and over hills at around 500 meters.
I've spotted the SI4432 and the sx1272 (which seems ideal but it doesn't seem popular despite it's high NLOS range capabilities?)
I was just wondering if anyone had any recommendations on which would be the best radio module to try? Any help would be really appreciated. Many thanks in advance.

Which country are you in, oduffy?

Hi  chaaarlie2, I'm in England

Then check out www.rfsolutions.co.uk, and their BRAVO transceiver modules.

@chaaarlie2 thanks I'll check them out

General rule is, the lower the frequency, the longer the range (but lower bandwidth). So both should have a better range at 433Mhz and 137MHz instead of the 2.4Ghz of the NRF. Antennas also affect the range.
The "over the hills" part I think will be problematic. The RF won't be able to penetrate through the hill. So the signal has to bounce of the ionosphere to get over the hill, which is to long a distance. So you probably have to have some kind of repeater on top of the hill to accomplish this.

Not sure I would agree with the proposed frequency vs. range rule.  It is true that the ionosphere is more often reflective at lower frequencies (it's most basic characterization model being a "maximum usable frequency") but that will be more a source or interference than propagation here.  And there are bands where vegetation and atmospheric moisture absorb more.  But generally I'd look at trying to build a digital repeater or mesh network around one of the already digital-packet-oriented chipsets, even at 2.4 GHz.

@ChrisStratton Frequency vs Range is proved in the Friis equation (too complex to add in comments!) but is observerd by playing around with an online calculator such as http://www.random-science-tools.com/electronics/friis.htm .

@chaaarlie2 - that has essentially no application in terrestrial settings, such as this question.

@ChrisStratton on what grounds?

Here on earth, the grounds are curved, bumpy, and prickly with stuff - those facts dominate.

Since you already have the uno+nrf24 working, it might be worth trying a better nrf24 module before trashing the work you've already done. You can buy nrf24 modules with an integrated LNA, PA, and external antenna port. Just do a search for NRF24L01+LNA+PA. You can find them on amazon for < $10 and usually come with an external antenna.

Thanks Curtis, I do have one of the NRF24L01 with an aerials (http://goo.gl/nGfDDw). However, am I right in thinking that one doesn't have the LNA and PA circuits on?

@oduffy yes, some nrf24's have an external antenna but no LNA/PA.

Great, thanks, I'll buy a pair and see how I get on.

@oduffy Come back and add your results when you're done. This is a common topic and others would be interested. A quick search brings up some comparisons other people have done between different nrf24 modules... Like this. https://hallard.me/nrf24l01-real-life-range-test/

I will do, I'll write something up once I've done some tests


text:
NRF24L0 wireless modules
I have two arduinos (one uno and another nano) with NRF24L0 modules attached to both and they are communicating between each other. All good.
However, I have a load of different ones and have switched them with the working receivers to test them but they just refuse to work despite the pinouts being correct.
Does the pinout vary between manufacturers or something else perhaps? What really perplexes me is that some of the modules I've tried are brand new (just taken out of the antistatic)
I have followed https://maniacbug.wordpress.com/2011/11/02/getting-started-rf24/
Any help would be really appriciated. Thanks

The library probably works fine, but I'd still recommend that you'd either download the updated version through the IDE or from https://tmrh20.github.io/RF24/.

Second thing is that some modules are fake/counterfeits they do not work according to the specs in terms of registers, power usage, range, required decoupling and possibly in more aspects. See http://hackaday.com/2015/02/23/nordic-nrf24l01-real-vs-fake/ for more information.

I was having the same kind of problems (even with new modules) when supplying them by mistake with 5v instead of 3,3V. It even happened that the system was working fine for days after the communication problems due to wrong power supply started to appear.
Also many people have reported similar problems(sometimes communicating, sometimes not) with this module due to poor built-in decoupling especially when using relatively long cables between arduino and module. Just to make sure, put a decoupling capacitor near the module's power and ground pins.
(this is more of a comment but I cannot comment due to reputation.)


text:
Verifying the timing between relay activations
I would like to verify timings of a relay controlled by an arduino (uno R3). There is a lot going on in the sketch and it does not use the delay function but one which is based on counting milliseconds. The arduino then transmits to another arduino using a radio module (nRF24L01). I'd like to confirm the intervals between the relay, so for instance if the relay is acivated 10 times and there are 5 seconds between each actvation.
So what I was wondering was whether anyone had any reccomendations on methods to verify timings using an external source.
Two ideas I came up with were: have another arduino with a very simple script that measures the timings or try and find/write a verilog script to upload to a mojo fpga and measures the timings.
An ideal situation would be where I have a seperate device that hooks up to the relay and then measures and displays the timings between the relay switches and is extremely precise.
I hope that makes sense, if not please let me know and I'll explain further. Thank you for reading and any help is greatly appriciated.

You could use sigrok with one of the many supported devices.
For example, you can find on ebay an 8 channell 24MHz probe for less than $10.
It's a nice tool to have laying around. For example you can use it as less-invasive-than-serial-print way to detect when internal states of a program change value: just toggle some unused GPIO.

Thank you very much Igor. I've tried pulseview and that seems perfect. I'll go ahead and order a compatable device now. Thanks again


text:
Problem with Pulse Sensor signal
I'm making alarm with input from pulse sensor. When it detect high heart rate then it send a text message. Everything works fine when i am using potentiometer (as input) for simulating triggering SMS. I made several heart rate trigger options based on ages, so i'm using switch-case in my loop. I'm using PulseSensor Playground library and some sample skecth that came from with it, but when i put program that read beat per minute and put that value inside if statement it become doesn't work at all. Even if i put the BPM value to serial monitor it only display 0. What can i do to fix this problem? Thanks
Here is my program:
#define USE_ARDUINO_INTERRUPTS true
#include <PulseSensorPlayground.h>
#include <SoftwareSerial.h>
#include <JC_Button.h>

const int OUTPUT_TYPE = SERIAL_PLOTTER;
const int PulseSensor = A0;
const int THRESHOLD = 550;

PulseSensorPlayground pulseSensor;
SoftwareSerial SIM800L(2, 3);  //(RX | TX)
const byte switchButton = 4;
int LED1 = 5;   //ages range 1
int LED2 = 6;   //ages range 2
int LED3 = 7;   //ages range 3
int greenLED  = 8;    //for normal heart rate
int yellowLED  = 9;   //for medium heart rate
int redLED = 10;      //for high heart rate

Button mybutton(switchButton);
boolean SMSsent = false;
int x = 0;

void setup(){
  mybutton.begin();
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);
  pinMode(redLED, OUTPUT);

  Serial.begin(115200);
  pulseSensor.analogInput(PulseSensor);
  pulseSensor.setSerial(Serial);
  pulseSensor.setOutputType(OUTPUT_TYPE);
  pulseSensor.setThreshold(THRESHOLD);

  SIM800L.begin(115200);
  Serial.println("SIM800L ready");
}

void led_for_ages_range_1(){
  digitalWrite(LED1, HIGH);
  digitalWrite(LED2, LOW);
  digitalWrite(LED3, LOW);
}
void led_for_ages_range_2(){
  digitalWrite(LED1, LOW);
  digitalWrite(LED2, HIGH);
  digitalWrite(LED3, LOW);
}
void led_for_ages_range_3(){
  digitalWrite(LED1, LOW);
  digitalWrite(LED2, LOW);
  digitalWrite(LED3, HIGH);
}

void led_indicator_1(){
  digitalWrite(greenLED, HIGH);
  digitalWrite(yellowLED, LOW);
  digitalWrite(redLED, LOW);
}
void led_indicator_2(){
  digitalWrite(greenLED, LOW);
  digitalWrite(yellowLED, HIGH);
  digitalWrite(redLED, LOW);
}
void led_indicator_3(){
  digitalWrite(greenLED, LOW);
  digitalWrite(yellowLED, LOW);
  digitalWrite(redLED, HIGH);
}

void range_1_indicator(){
  int BPMval = pulseSensor.getBeatsPerMinute();

  if (BPMval > 60 && BPMval < 85){
    led_indicator_1();
    SMSsent = false;
  }
  else if (BPMval > 86 && BPMval < 100){
    led_indicator_2();
    if(SMSsent == false){
      text_message_1();
      SMSsent = true;
    }
  }
  else if (BPMval > 101){
    if(SMSsent == false){
      text_message_2();
      SMSsent = true;
    }
  }
  else {
    SMSsent = false;
  }
}

void range_2_indicator(){
  int BPMval = pulseSensor.getBeatsPerMinute();

  if (BPMval > 60 && BPMval < 75){
    led_indicator_1();
    SMSsent = false;
  }
  else if (BPMval > 76 && BPMval < 90){
    led_indicator_2();
    if(SMSsent == false){
      text_message_1();
      SMSsent = true;
    }
  }
  else if (BPMval > 91){
    if(SMSsent == false){
      text_message_2();
      SMSsent = true;
    }
  }
  else {
    SMSsent = false;
  }
}

void range_3_indicator(){
  int BPMval = pulseSensor.getBeatsPerMinute();

  if (BPMval > 60 && BPMval < 70){
    led_indicator_1();
    SMSsent = false;
  }
  else if (BPMval > 71 && BPMval < 80){
    led_indicator_2();
    if(SMSsent == false){
      text_message_1();
      SMSsent = true;
    }
  }
  else if (BPMval > 81){
    if(SMSsent == false){
      text_message_2();
      SMSsent = true;
    }
  }
  else {
    SMSsent = false;
  }
}

void text_message_1(){
  int BPMval = pulseSensor.getBeatsPerMinute();
  SIM800L.write("AT+CMGF=1\r");
  delay(100);
  Serial.println("SIM800L set destination number.");
  SIM800L.write("AT+CMGS=\"0123456789\"\r");
  delay(100);
  Serial.println("Sending text message...");
  SIM800L.write("Your heart rate are: ");
  SIM800L.write(BPMval);
  SIM800L.write(" BPM");
  SIM800L.write("\r");
  Serial.println("Your heart rate are: ");
  Serial.print(BPMval);
  Serial.println(" BPM");
  SIM800L.write((char)26);
  delay(100);
  Serial.println("SMS sent.");
}

void text_message_2(){
  int BPMval = pulseSensor.getBeatsPerMinute();
  SIM800L.write("AT+CMGF=1\r");
  delay(100);
  Serial.println("SIM800L set destination number.");
  SIM800L.write("AT+CMGS=\"0123456789\"\r");
  delay(100);
  Serial.println("Sending text message...");
  SIM800L.write("Warning! Your heart rate are: ");
  SIM800L.write(BPMval);
  SIM800L.write(" BPM");
  SIM800L.write("\r");
  Serial.println("Warning! Your heart rate are: ");
  Serial.print(BPMval);
  Serial.println(" BPM");
  SIM800L.write((char)26);
  delay(100);
  Serial.println("SMS sent.");
}

void loop(){
  //int BPMval = pulseSensor.getBeatsPerMinute();
  static enum {OPTION_ONE, OPTION_TWO, OPTION_THREE} condition;
  while (x == 0){
    mybutton.read();
    switch (condition){
      case OPTION_ONE:
      led_for_ages_range_1();
      range_1_indicator();
      if (mybutton.wasReleased()){
        condition = OPTION_TWO;
      }
      break;

      case OPTION_TWO:
      led_for_ages_range_2();
      range_2_indicator();
      if (mybutton.wasReleased()){
        condition = OPTION_THREE;
      }
      break;

      case OPTION_THREE:
      led_for_ages_range_3();
      range_3_indicator();
      if (mybutton.wasReleased()){
        condition = OPTION_ONE;
      }
      break;
    }
  }
}

examine you code carefully ... for example, you get no warning at 90bpm  (there are more like that)

That just an example value, i intend to use >= and <=.

do you have a test sketch or some example sketch for the pulse sensor? does it work? or it doesn't work only in a sketch with SIM800 and SoftwareSerial

@Juraj. Yes i have, and it works perfectly when i use example sketch from the PulseSensorPlayground library. Also it works with SIM800L and SoftwareSerial when it still in simple sketch, i'm not adding switch-case for switching for the ages range and LED status at that time, because i don't insert any ages options program. Is it because of my faulty switch-case logic? But that switch-case logic also works for changing LED status and 3 different range values when i use potentiometer for changing the analog input value that change the LED indicator. And the text message also works.

add this to question

I'm getting fluctuations in BPM (it varies from 40 to 250). Most of the times, its in the 200s. Sometimes, it comes down to 90 or 80. pulse sensor

You forgot pulseSensor.begin() and you don't use pulseSensor.sawNewSample(). See the examples of the library.
The library uses interrupts to measure the pulse. (It takes time, which would otherwise block the loop execution). The begin() function starts this interrupts.
The value measured by interrupts is accessible with getBeatsPerMinute() and sawNewSample() function indicates that new value is available.
The library can work without interrupts (PulseSensor_BPM_Alternative.ino), but even then the begin() function initializes the library and sawNewSample() is then the function which reads the sensor.

Did you see that in "Getting BPM_to_Monitor" sample sketch? In that sketch pulseSensor.begin() run only once and it's to print text inside Serial.println. Why i need to use pulseSensor.sawNewSample()? Its only return true or false because it's a boolean.

without begin the library doesn't read the sensor. getBeatsPerMinute is only a getter which reads a variable in library.

I enhanced the answer.

Oh i see.  I will try that.

I added pulseSensor.begin() and it works. But it getting error when i write pulseSensor.sawNewSample(), some of the LEDs always fast blinking and not in full brightness. But overall it works by adding pulseSensor.begin(). Thanks

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


text:
Blueduino Rev2 service UUID for web bluetooth
I have a Blueduino Rev2 board that I would like to have communicating with a web app (running the chrome bluetooth software) but I'm having trouble sorting out the service UUIDs that the web bluetooth library requires.
According to the wiki, it uses the service UUID 0xFFF0, write characteristic UUID 0xFFF1 and read characteristic UUID 0xFFF2 (source) but when I scan for the device through the web app filtering for that service UUID it doesn't appear, but does when I remove the service UUID filter.
Code used to scan for the blueduino:
navigator.bluetooth.requestDevice({
    filters: [{
        name: 'ZeroBeacon',
        services: [0xFFF0]
    }]
})

Does anyone know what the UUIDs are that I should be using? The documentation is quite unclear and lacking.

If the 0xFFF0 Bluetooth Service is not advertised by the Blueduino Rev2 board, you should not include it in the "services" key. It should be in "optionalServices. See https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web#request_bluetooth_devices
I think your code should look like:
navigator.bluetooth.requestDevice({
  filters: [{ name: 'ZeroBeacon' }],
  optionalServices: [0xFFF0]
});


text:
Specifying port in Ciao.write
As far as I know, Ciao uses port 80 as the default and I haven't found a way of changing the port it attempts to connect to.
I tried using "192.168.0.23:8080" but the Ciao.write() seems to timeout after a while. Is there a way to specify the port to use?
P.S I'm using an Arduino Uno WiFi DevEd

You can't. The factory firmware of Uno Wifi is discontinued.
Uno WiFi and WiFi Link doc


text:
TEENSY 3.2 RS-232 throughput
I have an application where I need 4 serial ports - 3 will be sending and receiving.  The packet size will be up to 255 bytes on these 3 "main" ports.  The 4th port will be receive only, and its packet size will be 6 bytes. There is no flow control. The data rate on all ports is 115,200 baud. The 3 main ports will send or receive data packets approximately once per second. Most data will be half-duplex, although occasionally it will be necessary to send and receive simultaneously from a port . The 4th port (the one that handles 6 bytes), will get packets at an approx 50 packets/second rate.
The TEENSY will have to calculate CRCs on all ports, and will have to do a small amount of data manipulation as well.
I was planning to use the hardware serial ports for the 3 main ports, and software serial for the port that has to deal with only 6 bytes.  It is important that the 3 main ports be able to not miss any incoming data.  The 4th port is less important and can "miss" a packet now and then with no ill effects.
Will a TEENSY 3.2 running 90MHz be able to keep up?

Once per second? I don't see any problem, I will try to calculate:
3 ports: send + receive 255 bytes, let's say 270 bytes (with start/stop bits, probably way too much) per message:
3 * 2 (send + receive) * 270 = 1620 bytes
4th port: 50 * 6 bytes = 300 bytes
Total: 1920 bps
The serials can easily keep up with this, so that is not a problem.
90 MHz is 90 million instructions per second. As you can see, handling 1620 bytes is nothing ... it could do many more, a factor of multiple thousands more.
Unless of course you want to do heavily calculations for the received/sent data.


text:
Very long range wireless communication between two arduinos(500-1000 KM)
I searched for very long range wireless communications between two Arduinos, but can't find solutions. I don't live in USA, In my country there are regions, where GSM does not work.
I want wireless communication approximately 500-1 000 KMs.
What are options without GSM for that distance wireless communication(500-1000 KM)?

What do you want to send between them? How many bytes and how often?

I want to send text and voice, 4096 bytes in 1-5 seconds interval

Do you have a budget in mind for the initial build? Ongoing costs?

Satelite communication is expensive, but that can be used for voice and for short data messages. The short data messages are used for example by ships. Do you have a shortwave license for an extremely powerful transmitter ? As far as I know, everything else is illegal.

I don't have license, but I have budget.

What are options without GSM for that distance wireless communication(500-1000 KM)?

1) use the internet;
2) use narrow band transmission, like qrp;
3) use relays;
4) use satellite phones;
5) use a high-powered lw transceivers.
6) ...


text:
IEEE 754 for integer
Maybe is to easy to answer but i don't know it. I know IEEE-754 is for float values and double but i don't know if is exclusive for those type.
I use this to convert float and works fine i have another code in javascript to revert it.
But when used it with integer values it just gives some values and the revert doesn't work as supposed to.
So, this definitely doesn't work for integer values?, i can parse it to float and pass it to IEE754 but i just want to know.
this is the code i use in arduino.
void IEEE754( float val, int pos)
{
  byte* array = (byte*) &val;
  for (int i = 0 ; i < 4 ; i++) {
      payload[pos + i] = array[i];
  }
}

also, does anyone has the revert code for arduino?..

IEEE 754 is the specification for floating point values. Integers aren't floating point values so this function of yours can have nothing to do with integers.
On an Arduino (8-bit):

A float value is 4 bytes in IEEE-754 format.
A long value is 4 bytes in little-endian format.
An int value is 2 bytes in little-endian format.
A byte is a byte.

To convert 4 bytes into a long you can use:
long val = (payload[3] << 24) | (payload[2] << 16) | (payload[1] << 8) | payload[0];

An int value is just the lower two bytes of the same kind of conversion:
int val = (payload[1] << 8) | payload[0];

You can use the same method (albeit backwards) to get the bytes to put in your payload:
long val = 12345678L
payload[0] = val & 0xFF;
payload[1] = (val >> 8) & 0xFF;
payload[2] = (val >> 16) & 0xFF;
payload[3] = (val >> 24) & 0xFF;

You can also use the same technique as your existing function with different datatypes, since all you care about is the byte content not the format or meaning of the bits within it:
void int2payload( int val, int pos) {
  byte* array = (byte*) &val;
  for (int i = 0 ; i < 2 ; i++) {
      payload[pos + i] = array[i];
  }
}

void long2payload( long val, int pos) {
  byte* array = (byte*) &val;
  for (int i = 0 ; i < 4 ; i++) {
      payload[pos + i] = array[i];
  }
}

Although rather than shifting it's probably more effective to cast to a byte array there too.

On an 8 bit system it makes no difference. It's all bytewise access either way. On 16 and 32 bit systems it can make a difference if the architecture has bytewise access operators.


text:
Problems splitting a string to get authentication and command
Good afternoon,
In a nutshell I'm having some difficulty with splitting and returning part of a string.
Essentially I'm working on the code for transmitting a password (24 character string) and command (string) in a single packet. However, the 'get_command' function is only returning the first character of the string (T) as opposed to the whole string (T1) and I'm not sure why. Any help would be greatly appreciated. Thanks in advance.
The entire sketch is below so you should be able to just drop it in and compile.
char *received_data = "KkV3vKvLgC4PdBZRs5kkKM86T1";
char *password = "KkV3vKvLgC4PdBZRs5kkKM86";

int authenticate_transmission(char *data) {
    if(strncmp(data, password, 24)) {
        Serial.println("no match");
        return false;
    } else {
        Serial.println("match");
        return true;
    }
}

char *get_command(char *data) {
    char command[3];
    strncpy(command, data + 24, 3);
    // Fine here
    Serial.println(command);
    return command;
}

void setup()
{
    Serial.begin(9600);
}

void loop() {
    // test received data - message is T1 at the end.
    if (authenticate_transmission(received_data)) {
        char *command = get_command(received_data);
        // But just prints out first char when returned from a function
        Serial.println(*command);
    }
    delay(10000);
}

The command array created inside get_command() is local data. That means it's only available while that function is being executed.
However, you're returning a pointer to it. That means when you're trying to use command afterwards from inside loop(), you're trying to refer to data which has been deallocated. By that point, it's getting used for something else.
There are various solutions to this. A fairly simple approach would be to have the caller allocate the command array, passing a pointer to it into get_command(). For example:
void get_command(char *data, char *command) {
    strncpy(command, data + 24, 3);
}

From loop(), you would call it like this:
char command[3];
get_command(received_data, command);

The command array is still local data in this case. However, it's local to the loop() function (or wherever else you put that code). That means it will still be available when get_command() is called.

Saying static char command[3] instead is slightly easier

@jwpat7 That would work, but it's not good programming practice.

Thanks Peter, that's very helpful. I've got it all sorted now and a bit more insight. Thanks again.

The direct issue is you have a dereference operator (*) in the loop that you don't need:
Serial.println(*command);

This causes it to pass only the first character to Serial.println() instead of the pointer to the memory location. That's the first issue.
Like Peter mentioned, the string gets deallocated when returned from the get_command() function. It's undefined behavior, but it's luck that it worked the way it did.

Good catch. Hadn't spotted that myself.


text:
Is it possible to reprogram an atMega328 chip inside of a pcb?
I have already soldered the atMega chip with instructions onto the perfboard, and I may need to make changes to it. Is it possible to reprogram it without taking it out of the PCB?

I'm assuming you're trying to program using an AVR programmer.
Yes, it's very likely you'll be able to do that. You need to connect the AVR programmer to the correct MCU pins (Sck, Si, So and Rst), including ground and vcc... as you would do with the chip by itself.
If you have any othe SPI device connected to the same pins, make sure it's not enabled - that might be as simple as having the device's CS pulled high.
The way you'll make the connection is up to you, you might need to use some clips, pogo pins or simply solder some wires to the MCU pins.
If you have other things connected to any of the MCU programming pins, you might need to disconnect, but that will vary case by case.
Cheers


text:
Arduino mini being programmed with CH340G
So, I have bought this USB programmer with CH340G chip on it, but it seems, that I cannot program arduino mini clone.
So, this programmer has pinout of 5V|GND|TX|RX|3V3.
I have connected TX to TX and RX to RX (and also switched, because these programmers sometimes have marked where certain pins supposed to go, not what they represent).
I have also wired the DSR leg from the chip and connected it to the RESET on arduino mini clone.
There's still no connection between them.
Now I'm wondering, if I just connect the power supply and TX and RX connectors, when am I supposed to press reset for the succesfull programming?

First of all you should connect the DTR (not the DSR) pin to the reset terminal WITH a 100nF capacitor. See this page or the arduino uno schematics to see how to put the capacitor (it's simply in series with the signal.
However I suggest you to start programming WITHOUT the autoreset; once you are sure that you can program it then try soldering that capacitor to program the arduino without having to hit the reset button.
As for when, watch the IDE status: when it stops compiling and shows the "Uploading" string, press the reset button on the board. You will usually have a couple of seconds to press it.


text:
Programming ATmega328p on external board with FT232R
I am making a 100W AC-DC linear power supply, for which I want to show output Voltage and Output current on LCD display. I already used shunt resistor and voltage resistor to bring both values to analog pins on my ATmega328P in DIP socket, which has an Arduino bootloader on it. I want to programm my ATmega328P on the board without taking it off everytime and putting it into Arduino UNO board to just programm it and put it back, so how can I integrate a programmer onto board?
I intend to use the FT232R ic, which I think would work more than fine for this application.
On finished product I want to have a USB connector on the case just to update/correct the software.

If you want an USB connector, an Arduino Nano or 32u4 based Arduino may be a better solution.

I suggest use ICSP(In circuit serial programming) feature of the Atmega 328 chip. Grab the .hex file from the arduino IDE and a USB ISP external programmer to write the program to the chip. Here you will have to use a 6 pin header on your custom board to take out the pins which are used to program the atmega.

External programmers are cool, but if you want your end-user to connect to the board, you'll most likely want USB. But I agree that it is useful to have the ICSP header available, so you can put on the bootloader if you're making more of these boards.

That's correct paul. But here the OP has said that she plug the chip into an UNO for programming and then remove it to the target board. And she want to avoid that. In that case this is the simplest solution rather than building an UNO in the application.

I use an FTDI cable with my home-builds. Then the board doesn't need the interface hardware (it's in the cable) and the MCU doesn't need to be removed.
I put a 6-pin male header on the board to match 6-pin female socket my cables come with. The header is direct-wired to the Tx, Rx, +5, & Gnd pins. If you have an auto-reset circuit on your board, connect the RTS pins to that. Then, reprogramming is as simple as connecting your board and clicking 'upload'. Without the auto-reset circuit, you just hold the reset button while you click upload, count 3, and release the reset.
Update:
You can do it with only 4 pins on the board. If I understand correctly, just wire Tx, Rx, +5 & Ground of the Arduino to the 4 pins and replace the Arduino-end socket on the FTDI cable with one wired to match however you wired the board. If you use L-shaped male pins, they'll lie parallel to the board and won't add any height (above what is already on it).

Hmm..that doesn't sound as a bad idea, but I'd like to make only 4 pins onto the PCB and from there connect the USB cable panel mount. In other words, I'm searching for a schematics for USB cable - ftdi - atmega connection.

Check the schematics of the Arduino Nano, they are basically exactly the circuit you describe.


text:
How do I update the serial monitor without printing a new line each time?
I'm testing out an accelerometer and I want to know if there's a way to make it so that the serial monitor will update the values without printing a new line. Ideally the serial monitor would say something like:
Accelerometer X: $xval
Accelerometer y: $yval

and then instead of printing two new lines each time, it just updates the values. Is there anyway to do that in Arduino? Thanks.

What happens if you make the serial monitor 20 lines long. And then print your 2 lines + 18 lines? I'm not sure, but it might fake a 'value update'

The ultra-basic "serial monitor" in the Arduino IDE cannot do what you want.
Instead you need to either write a special client program, or use a more standard serial terminal program, such as Tera Term (Windows), Minicom (Linux), etc.
These standard serial terminal programs use a special sequence of characters called ANSI escape codes which manipulate the display, doing such things as setting colours, moving the cursor around, etc.
More information on ANSI escape codes can be found here: http://en.wikipedia.org/wiki/ANSI_escape_code

No. The serial monitor does not support terminal handling. Either use a serial communications program that does and use those features, or write a custom client that will only update those values in its interface.

Okay, thanks. Is there any other client that's recommended?

Not really. Most serial programs, even Hyperterminal (or whatever Windows drags along these days) will do.

You might want to look into processing. You can use that to view the accelerometers position in 3d and see the values changing if that's what you want. The official Arduino site talks about it here.  Here is a great tutorial on it.

I would recommend this as a client option.

Probably would have been better as a comment on Ignacio
But yes processing is a good option IF you want to write code by yourself.


text:
Servotimer2.h is not recognised as a library by arduino uno
I'm doing a project for school with an arduino uno. I want to control a motor using a RF-module as remote control. I need the library Virtualwire.h to use the RF-module and the library Servo.h to control the motor. I downloaded the library Servotimer2.h because Virtualwire.h and Servo.h both want to use timer 1 of the arduino. I added this library to arduino libraries but arduino doesn't recognise it as a library when I include it to my program.
can someone help me with this issue? I tried to find a solution but can't find it.
Many thanks allready!

Could you explain exactly how and where you added the Servertimer2.h library? Also, how are you including it in your source code?

Thanks allready for your first reaction.
This is the proces I followed : I downloaded the library Servotimer2.h as a Zip file. Then I added this zip file by clicking -> include library -> add ZIP library... an then selected the zip file servotimer2.

Afterwards I included the library to my program. And allready from hereone I remark that the library is not accepted like other libraries. Arduino doesn't seem to recognize it as a library because the name of the library stays black.
When I compile this, I get this error messages:
error: conflicting declaration 'typedef bool boolean'
typedef bool boolean;
error: 'boolean' has a previous declaration as 'typedef uint8_t boolean'
typedef uint8_t boolean;
I am just starting to use arduino and error could be obvious, but I don't get it yet.
Thanks for your help.


text:
Using delay(1000); without influence on analogWrite?
So, I'm trying to read the voltage on analog pin A0 and make a "regulation", where if the voltage will be lower than 2.5V (analog value 512), then it should be output pin 9 used as PWM with duty cycle of 50% ( analogWrite(ledPin, 128); ) unless the voltage rises again higher than 2.5V.
Where/how am I supposed to use mentioned line ( analogWrite(ledPin, 128); in IF sentence, so it will be used continuous untill it is reached the limit?
PS: I just want to refresh LCD with frequency of 1 Hz while PWM works independently of delay(1000). How is that even possible?
How am I able to do that?
#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

const int numRows = 2;
const int numCols = 16;

void setup() {
  lcd.begin(numCols, numRows);
}

void loop() {

    int sensorValue = analogRead(A0);
    float voltage = sensorValue * (5.0 / 1023.0);
        lcd.setCursor(0, 0);
        lcd.write(voltage);

        delay(1000);
}

you make no progress. you ask always a variation of the same thing. study the BlinkWithoutDelay example

You didn't understood the question.
I'm not asking for finished code, I'm asking for an explanation on how-to.

read this post .... it is one of yours .... https://arduino.stackexchange.com/questions/56061/refreshing-lcd-with-different-frequency-than-output

The PWM started by analogWrite will not be influenced be the delay, because the analogWrite function only sets the registers and starts the PWM. The PWM generator is independent from the CPU on AVR microcontrollers. On esp8266 for example the PWM is generated with use of interrupt and it is too not influenced by the delay function. To stop the PWM you must call analogWrite with 0 or change the pin mode.

You don't need an if-statement here. You can simply contineously take the measurements and act accordingly.
About the delay(1000):
It is considered a bad coding practice to use delay(), especially for longer periods, because it's just busy waiting. In real life you wouldn't just sit fiddling your thumbs, until a task is done. You would do something else in the intermediate time. Here you can reach this by using non-blocking code like in the BlinkWithoutDelay example of the Arduino IDE.
About PWM:
PWM is not handled by the software, but by the hardware. The Atmega on the Arduino has dedicated PWM hardware included in the package, which will handle the control of the PWM pin, so that the CPU can do other things.

Okay, but is there then a line, which WILL refresh the state shown on LCD?
I can't figure out this part of the job.

the OP has posted a question here ...https://arduino.stackexchange.com/questions/56061/refreshing-lcd-with-different-frequency-than-output .... the use of delay() was addressed ..... it appears that the OP is unable to learn from experience

I think you need something like this, with a flag so you are not contantly restarting the PWM on pin 8 and making the output erratic:
void loop(){
if (analogRead(A0)<512  && halfLevel9 == 0){
analogWrite (9, 128);
halfLevel9 = 1; // flag to let you know it's been set
}
else {
analogWrite (9, withWhat?);
halfLevel9 = 0;
}
// use blink without delay to determine if 1 second has passed
{
// write whatever is going to the LCD
}
// do other stuff while the 1 second passes
}

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


text:
Hex output although I always define integer
Code below is to read 4 thermometers and use values to turn on or off the heaters (I'm stuck at reading).
I'm reading and displaying temperature very well, but it comes to the problem, where I want to set the limit of heating, a value of 37 degrees. It comes to the problem, when I want to read the value of "tempa", but the Arduino doesn't respond properly: it somehow reads the value as char or I get the output in hex instead of integer (although I never declared a character in whole program).
It can be seen in last 2 lines before "CHANNEL_2".
Lines are:
lcd.setCursor(10, 0);    //termometer
lcd.write(tempa);    //termometer

absoluta, absolutb, absolutc and absolutd are variables, which are technically values of temperature in Kelvin.
tempa, temb, tempc and tempd are variables, the temperature in celsius.
#include <LiquidCrystal.h>
#define  LM335_pin  0                          // LM335 output pin is connected to Arduino A0 pin
#define  LM335_pio  1                          // LM335 output pin is connected to Arduino A0 pin
#define  LM335_pip  2                          // LM335 output pin is connected to Arduino A0 pin
#define  LM335_pir  3                          // LM335 output pin is connected to Arduino A0 pin

const int rs = 7, en = 8, d4 = 5, d5 = 4, d6 = 3, d7 = 2; // LCD module connections (RS, E, D4, D5, D6, D7)
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

  //-----------------------HEATERS----------------------------------------
//int grelea = 11;  //heater_1
//int greleb = 10;  //heater_2
//int grelec = 9;   //heater_3

void setup() {
  lcd.begin(20, 4);

//  pinMode(grelea, OUTPUT);
//  pinMode(greleb, OUTPUT);
//  pinMode(grelec, OUTPUT);

}
int  absoluta, tempa; //sensor_1
int  absolutb, tempb; //sensor_2
int  absolutc, tempc; //sensor_3
int  absolutd, tempd; //sensor_4

void loop() {

  delay(1000);

  //-----------------------CHANNEL_1----------------------------------------
  absoluta = analogRead(LM335_pin) * 0.489;
  tempa = absoluta - 273;

  lcd.setCursor(0, 0);    //termometer

  lcd.setCursor(0, 0);    //termometer
  lcd.write("Temp1=");    //termometer

  lcd.setCursor(8, 0);    //termometer
  lcd.write((tempa / 10)% 10  + 48);    //termometer

  lcd.setCursor(9, 0);    //termometer
  lcd.write(tempa % 10  + 48);    //termometer

  lcd.setCursor(10, 0);    //termometer
  lcd.write(char(223));    //termometer

  lcd.setCursor(11, 0);    //termometer
  lcd.write("C");    //termometer

  lcd.setCursor(15, 0);    //termometer
  lcd.write(tempa);    //termometer

  //---------------------------------------------------------------

  //-----------------------CHANNEL_2----------------------------------------
  absolutb = analogRead(LM335_pio) * 0.489;
  tempb = absolutb - 273;

  lcd.setCursor(0, 1);    //termometer
  lcd.write("Temp2=");    //termometer

  lcd.setCursor(8, 1);    //termometer
  lcd.write((tempb / 10) % 10  + 48);    //termometer

  lcd.setCursor(9, 1);    //termometer
  lcd.write(tempb % 10  + 48);    //termometer

  lcd.setCursor(10, 1);    //termometer
  lcd.write(char(223));    //termometer

  lcd.setCursor(11, 1);    //termometer
  lcd.write("C");    //termometer
  //---------------------------------------------------------------

  //-----------------------CHANNEL_3----------------------------------------
  absolutc = analogRead(LM335_pip) * 0.489;
  tempc = absolutc - 273;

  lcd.setCursor(0, 2);    //termometer
  lcd.write("Temp3=");    //termometer

  lcd.setCursor(8, 2);    //termometer
  lcd.write((tempc / 10) % 10  + 48);    //termometer

  lcd.setCursor(9, 2);    //termometer
  lcd.write(tempc % 10  + 48);    //termometer

  lcd.setCursor(10, 2);    //termometer
  lcd.write(char(223));    //termometer

  lcd.setCursor(11, 2);    //termometer
  lcd.write("C");    //termometer
  //---------------------------------------------------------------

  //-----------------------CHANNEL_4----------------------------------------
  absolutd = analogRead(LM335_pir) * 0.489;
  tempd = absolutd - 273;

  lcd.setCursor(0, 3);    //termometer
  lcd.write("Temp4=");    //termometer

  lcd.setCursor(8, 3);    //termometer
  lcd.write((tempd / 10) % 10  + 48);    //termometer

  lcd.setCursor(9, 3);    //termometer
  lcd.write(tempd % 10  + 48);    //termometer

  lcd.setCursor(10, 3);    //termometer
  lcd.write(char(223));    //termometer

  lcd.setCursor(11, 3);    //termometer
  lcd.write("C");    //termometer
  //---------------------------------------------------------------
}

try lcd.print(tempa);

btw: it is not hex, only your calculated ascii values run out of digits section of ascii codes

lcd.write() will write one byte to the LCD. It makes no attempt to try to interpret the data type of the input parameter. You can think of it like sending "raw data" to the LCD.
lcd.print() can be called with many types as input and will interpret that the user wishes to print a human-readable expression of the data. Also, it can print more than one byte.
As an example, the char variable with content 'A' is represented in RAM by the byte with value 65 (the ASCII code for 'A'). If you call lcd.print('A'), it will see that 'A' is a char and will send whatever raw data to the LCD to get an "A" on the screen. It just so happens that sending a raw byte 65 will accomplish this, but that is a coincidence; the LCD driver understands ASCII for getting characters to print on the screen.
If you call lcd.write(125), then the actual byte 125 (in binary, 01111101) is sent to the LCD. If you wanted to actually print the 3-digit number 125, lcd.print(125) would end up sending 3 bytes to the LCD: The ASCII values for '1', '2', and '5' (which are 49, 50, and 53). The print() function takes care of this interpretation for you.

she has v / 10 + 48 in code. I don"t think she needs to explain binary and ascii


text:
Measuring high frequencies (300kHz) with arduino
I'm designing a frequency generator with ICL8038, which would output sine, square and triangle waves, which would reach frequency such as 300kHz.
I've already designed a circuit around the ICL8038, but I'm unsure how to measure the frequency, to show on LCD display.
I'm leaving down a schematics I've drawn.
A.Duty is going to the analog input of arduino, which will show the duty cycle between 2% and 98%. This will be going to a voltage divider to make a proportional input for the arduino analog input.
The "frequency pin" would be connected directly from the BNC connector from the casing, which means, that the input can be triangular, sine or square.
Just to mension, in case it makes any kind of difference, I'm planning to use just Atmega328 with 16MHz quartz and 2 capacitors, not exactly as Arduino UNO or NANO.
But the Atmega will have a arduino bootloader on it.

By the time asking about ICL8038, I've got also few questions about the IC:

You connect the FM Bias(pin 7) and SWEEP (pin 8) together to create sweep on the output of any kind of signal, whichever it is? This is fixed time constant or should I add some kinda coapacitor there?
What exactly does Tcap (pin 10) does? I've read through the datasheet but couldn't understand it's meaning.
How would I get proper voltage range every time, when I would change the input voltage of the ICL8038? (it has wide range of output signal, proportionall to the input; it goes from 36V to input, 28V max output)
For power supply would be proper LM317 as adjustable power supply (since it has low power consumption) and just use a potentiometer to adjust input of the ICL8038 and monitor the OUTPUT levels?
PIn 13 and PIn 14 are NC (not connected). Can I just connect them together and connect them to GND?

As if anybody knows for any "better" IC as this one is, please let me know.
I'm already going to have to buy it from China (this gives me doubts about the capabilities), I'd rather just order one from Europe or US.

Why measure the sine output when you have a perfectly good square wave output needing at most voltage adjust that you can count??

Okay, I've never thought of that :D But thanks, sure will use this tip!

the 2nd 1/2 of your post is not Arduino related.

To sample a 300kHz signal you need to sample at at least 600,000 samples per second (see Nyquist-Shannon Theorem).
The Arduino can sample at an absolute maximum of 125,000 samples per second.
A normal Arduino will not be able to sample the analog input fast enough to even remotely have a clue what the frequency is - let alone what shape the signal is (for that you would have to be sampling in the millions of samples per second).
You will need a much more powerful board than an Arduino to do it.
The other option is to feed the signal through a comparator (an op-amp with infinite gain) to convert the signal into a square wave. You can then use simple frequency counting to get the frequency (count the pulses within a given time frame - maybe 1 second).
As for the rest of your questions, you would be better off asking those on Electrical Engineering.

Certanly I realize that, the arduino fails to read such frequencies. But I tend to use "additional" PCB only to measure frequency and convert it into proper signal for the arduino. It can be either analog either digial. But I'd prefer digital, since analog has only 1024 bites.

Of course you wouldn't sample this - you would count whole periods!

In counting you lose the waveform shape information. If you don't care, then yes frequency counting is definitely the way to go.

It doesn't matter the waveform information. This part will be solved otherwise (already got a solution).
And how am I supposed to do the counting part, while it's range will be between 0.1 Hz and 300 kHz?

That makes it simpler then. The comparator and counting is the way to go. The comparator is optional but will give more reliable results and is a jellybean part anyway.

Okay, so a comparator and an up/down counter, which resets every 0.5 seconds?
And how am I supposed to read it with Arduino?

The Arduino is the counter. Google for Arduino frequency counting.

Yes, but you've probably missed out the point, that I'm going up to 300kHz.

Yes? And? That's fine for digital - especially if you use Timer 1's T1 pin (PD5 on the 328P)...

Let us continue this discussion in chat.

Made a research, wrong informations.
A 6MHz frequency counter, made with arduinio.
https://www.hackster.io/moty/counter-92ec57

Frequency counting (what you point to) is what I talk about in the 5th paragraph of my answer. It is not getting the frequency of a sine wave, but the frequency of a square wave. To use it you should really first convert the sine wave into a square wave. Frequency counting is not for sine waves. Frequency counting is easy, and 6MHz I would count as inefficient - you could go much faster than that - but is not suitable for all signals.


text:
What is the phase of tone?
Is it garanteed (with some precision) that the phase of a PWM-signal generated by tone is the same on each pin? Can it be altered (by internal means of Arduino) so that it's different on different pins?
I'm looking for a way to adjust phases of signals from several pueso-buzzers by either adjusting distances (least preferrable) or programmaticaly (most preferrable) or by external components (if they're not very complicated).

an inverter should work. the NOT gate kind, not the AC making kind...

If you want fine control over the phases, I assume you may also care
about having low phase noise. In this case your best bet is to avoid
toggling the pins in software and go for a hardware signal generation.
With an Arduino Uno or similar board, this can probably achieved by
programming a timer. I would try the following:
Configure Timer 1 in waveform generation mode 12, i.e. CTC
mode with TOP = ICR1. Set the compare output mode of both channels
to toggle on compare match. Set ICR1 so that the timer has half the
period of the signal you want. Now you can independently adjust the
phases of both outputs by writing to OCR1A and OCR1B.
Note that those registers are not double buffered in this mode, so you
have to be careful about when you write them.
The Arduino core library has no support for such timer configuration:
you will have to learn how to program it yourself. If you are not
familiar with the subject matter, I recommend you start by reading
Nick Gammon's tutorial on timers.

But is it garanteed that if I turn on two tones simultaneously than I get those PWMs with the same phase and if I turn those on with certain delay than I get phase difference = delay/period?

@YakovL: No, with this approach you do not turn the PWMs one after the other: you configure the timer to generate both signals, and when you start the timer you get both of them. The phase difference is not controlled by when you start the signals. It is controlled by the difference between the numbers you write to the OCR1A and OCR1B registers. And you can get single-cycle accuracy on the phase difference provided your frequency is lower than 122 Hz.

The main principle behind working with buzzers, in its simplest form, comes down to something along the lines of
digitalWrite(buzzerPin,HIGH);
delay(half_tone_frequency);
digitalWrite(buzzerPin,LOW);
delay(half_tone_frequency)

that, when repeated is enough to generate some tone on a single buzzer. However - to get desired tones (frequencies) right, you have to be mindful of the exact time that passes between each part of the code (the pin needs to oscillate in some frequency to produce a tone of that frequency)
So technically, its possible to create different sounds on different buzzers connected on different(!) pins at the same time, if you know exactly how much time each pin spends HIGH and LOW. This is naturally simpler when they do not need to be active concurrently.

But is it garanteed that if I turn on two tones simultaneously than I get those PWMs with the same phase and if I turn those on with certain delay than I get phase difference = delay/period?

No, this approach is to not use the tone API at all, rather control the "PWM" manually by manipulating the pin states at precise intervals

Ah, sorry, I wasn't attentive enough, very nice, I'll try suggested stuff, but your answer clarifies the issue in the simplest terms (at least theoretically).

The arduino.cc description of tone() says “Only one tone can be generated at a time”, so presumably you are using some other software to generate tones on multiple pins.  For example, Brett Hagman's play() code, which Arduino tone() is derived from, uses multiple timers, one per tone.
When using play(), you probably can adjust phase by calling  delayMicroseconds() between the two  play() calls that start up the tone generation; for example:
play(11, 440);
delayMicroseconds(235); // Move 2nd tone 8 cm closer
play(9, 440);

Note, because tone() and play() use one timer per output (for example, timer 2 for first tone, timer 1 for next tone, timer 0 for third tone) there usually will be some timer prescale mismatches between 8-bit and 16-bit timers, which may result in slightly different frequencies, leading to some constant phase shift rate if you use that method.
With the speed of sound about 340.29 m/s in air at standard pressure, the wavelength of say 440 Hz would be under a meter, so I presume you would move speakers just a few tens of cm for phasing; hence a few hundred to a few thousand microseconds of phase offset.  If you want good programmatic control, and also want to have quite a few speakers, external hardware in the form of a delay line or a bucket brigade chip is an obvious approach.
You could simulate a program-controlled delay line fairly easily using a handful of 74HC595 SIPO shift registers, as follows:  Connect the DS of the first '595 to your tone() output pin.  Connect the Q7S output of each '595 except the last to the DS of the following '595.
Now use another timer to repeatedly clock your tone data into the shift register chain.  That is, connect all STCP and SHCP inputs in parallel to a timer output pin.  (Eg, OC1A, OC1B, OC2A, or OC2B, which might be pins like 9–12 on an Uno or Nano).  Run that timer at 10 to 100 KHz, ie, at some rate f that gives you the resolution and range of phase changing that you need.
Calling the shift register outputs o₀, o₁, o₂..., we have oⱼ delayed by (j-i)/f seconds relative to oᵢ.  That is, successive SR outputs represent different taps for different delays.

But is it garanteed that if I turn on two plays simultaneously than I get those PWMs with the same phase and if I turn those on with certain delay than I get phase difference = delay/period?


text:
Read and store data with the usb
Hi i am new to Arduino and I want to know if it is possible to read the data from a sensor that it is connected to the Arduino, I am using the Arduino mega 2560, which is already working, as I have a LED which change color depending on the detection of the object and then store it in a file as txt or another normal extension.

You need to edit this question to be more specific about what you are asking.  A typical Arduino can report data back to a USB host such as a PC (typically actually through a serial port like channel, although the transport is USB), however at least the ATmega-based ones are unable to act as hosts themselves, which means that they cannot directly write data to a USB device such as a flash drive.

That's correct.  I use Arduinos of many flavors to write data out their serial port, and have a Python program on  the PC side waiting for data on /dev/ttyUSB0 (for example).  That works fine.  Please take the tour at https://arduino.stackexchange.com/Tour then come back and edit this question to be more specifically about the Arduino.  You are welcome here.  But this question is in danger of being closed as-is.

I don't have experience with Processing, but probably that is what you need. It communicates through USB and with the CreateWriter function, you can create a text file.
More about Processing can be found at Processing
Also another thread at Electronics stack exchange might help:
Related question
Alternatives (also mentioned in the above thread):

Use serial port directly with a terminal application on the PC
Use an SD card inside the Arduino to log

Thanks I would want to do that with the serial port directly with a terminal application as putty or the Arduino serial monitor.

Than just copy the content to a text file.

From what I understand from your question, you want to store the data displayed in the Serial monitor to a text file or something similar. As the Arduino itself cannot do this task, I used "GoBetwino" to save my data from an Arduino into a text file, from where you can export the data into Excel if you want charts and graphs. The process is fairly easy and described properly in their user manual.
https://playground.arduino.cc/Interfacing/GoBetwino


text:
waking up arduino mini with a external signal
I have an arduino mini with an ultrasonic sensor conected to the pins 2 and 3, and a RGB LED connected to the 4,5, and 6, I want to include a wake up and sleep functionality that wakes up when receive a high signal in another pin as 7.
I have seen that normaly the pins for that are 2 and 3, as in the arduino web: Arduino sleep web
But can it be done with another pin?

As well as the normal external interrupts INT0 and INT1 you can also wake the chip through a variety of other interrupts. One of those is the pin change interrupt.
In the datasheet is a table of what is available in the different sleep modes, and what can wake you from that sleep mode. I have compressed the table to remove a lot of the stuff you don't care about at the moment and just show the "wake-up sources":

As you can see both INT and PCINT can wake from all modes (along with TWI [Wire.h] slave mode address matching).
The note (3) on the table just says that for INT0 and INT1 it must be a LOW level interrupt, not a RISING or FALLING. No mention is made of the type of interrupt for PCINT.
So yes, since pin 7 has PCINT facilities (all pins on the ATMega328P have PCINT) you can configure that as a wake-up source and wake the MCU using pin 7.


text:
Wake up arduino mini with a external signal from a rf wake up receiver
I am working in an arduino which sleeps after 1.2 seconds of running time and wake up when receiving a signal in the pin 2, but this last part is not working. I tried with the four modes of the interrupt ( LOW, CHANGE, RISING, FALLING) and also tring to connect it to vcc and disconect it myself, depending on the mode.
The sleeping part works as wanted
#include <avr/sleep.h>

// ### pin paging ### \\

#define RLEDPIN 13       //pin for red led
#define GLEDPIN 12       //pin for green led
#define BLEDPIN 11       //pin for blue led
#define wakePin 2        // pin used for waking up

// ### measure variables ### \\
unsigned long times;

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

void setup()
{
  Serial.begin(115200);
  pinMode(RLEDPIN, OUTPUT);
  pinMode(GLEDPIN, OUTPUT);
  pinMode(BLEDPIN, OUTPUT);
  pinMode(wakePin, INPUT);

  attachInterrupt(0, wakeUpNow, CHANGE);
}

void sleepNow()         // here we put the arduino to sleep
{

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    sleep_enable();          // enables the sleep bit in the mcucr register
                             // so sleep is possible. just a safety pin

    attachInterrupt(0,wakeUpNow, CHANGE); // use interrupt 0 (pin 2) and run function
                                       // wakeUpNow when pin 2 gets LOW

    sleep_mode();            // here the device is actually put to sleep!!
                             // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

    sleep_disable();         // first thing after waking from sleep:
                             // disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the
                             // wakeUpNow code will not be executed
                             // during normal running time.

}

void loop()
{

    digitalWrite(GLEDPIN, HIGH); //set green led high

  times = millis();

  if(times>=1200)
  {

    digitalWrite(GLEDPIN, LOW); //Reset the LED's
    digitalWrite(BLEDPIN, LOW);
    digitalWrite(RLEDPIN, LOW);
    sleepNow();
  }
}

Only a LOW interrupt will wake the chip from PWR_DOWN mode. Does your device set the pin LOW when it's activated?

@Majenko I tried that and also having the pin 2 conected to vcc and when the arduino is sleeping putting it to ground and nothing happend, in case it was a failure of my device

By the way: sleep_mode() does all of sleep_enable() and sleep_disable() for you - you don't need to call them.

@Majenko  I had the code from the arduino web: code for sleep


text:
What minimal resistance should be between an input and output pin not to burn Arduino?
So, I'd like to put a button between input and output pins to read when button is pressed. What minimal resistance should I add to the scheme not to burn Arduino when the button is pressed? Does this value depend on Arduino model?

Why between an input and output? Have you read the Button tutorial on the Arduino site? https://www.arduino.cc/en/Tutorial/Button

@Majenko I see, it should probably be "what minimal resistance should be between ground and 5V", I guess..

@Majenko to make sure I understand you correctly, I've asked another question: http://arduino.stackexchange.com/questions/22672/is-that-correct-that-input-and-output-pins-are-not-supposed-to-have-current-thro

@YakovL - posting additional closely relations questions is frowned upon, it is better to edit the existing question.

@ChrisStratton I was going to edit this question after I get an answer to that other question, and "correct" question would be "What minimal resistance should be between 5V and GND pins not to burn Arduino?", but as you have answered this first formulation, I'm not sure what would be more appropriate now..

"What resistance should be between 5V and GND" pins  has nothing to do with the Arduino's processor, but only its power supply.  It's also a rather pointless question as putting a resistor there does little but drain the power supply capacitor once the supply is off.

Looking towards the high end of recommended (vs absolute maximum) current and considering Ohm's law at a 5v difference if two outputs are trying to drive each other to opposite values, you would probably get away with as little as 250 ohms.  But in most cases that would needlessly waste power, and in the case of multiple instance you could start totaling towards the limit of power supply current for the chip overall.
Typical values for external pull up resistors are more in the range of 1K-10K though higher is not uncommon - the internal pullup which you can optionally activate by setting the output state of an input pin high has a value of several tens of kilo ohms.  Lower values will consume more power, higher values may be less reliable in a noisy situation.

To read a button, normally you hook one end of the button to ground and one end to a pin in INPUT_PULLUP mode. Normally the pin reads 'high' because it is connected to +5v with a biggish resistor inside the arduino. When you press the button, it shorts out to ground and the input reads 'low'. The chip already has suitable resistors in it to handle this, and you don't need to worry about it. Just connect one end of your button the the pin, the other to the chassis, INPUT_PULLUP and away you go.
Output pins should have no less than 250Ω on them.
Beats me why you are thinking of connecting an output pin and an input pin together.


text:
Can I cause breaking the main loop from an interrupt?
Consider this simple approach to make a light work in 3 different modes: on, off and blink:
attachInterrupt(buttonVector, switchMode, FALLING);

void loop() {
  switch(mode) {
    case 0: turnOff(); break;
    case 1: turnOn(); break;
    case 2: blinkOnce(); break;
  }
}

now if switchMode is something like this:
unsigned long last_interrupt_time = 0;
unsigned long interrupt_time = 0;
void switchMode()
{
  interrupt_time = millis();
  // debounce measures
  if (interrupt_time - last_interrupt_time > 200)
  {
    mode = (mode + 1) % 3;
  }
  last_interrupt_time = interrupt_time;
}

then once the button is pressed, the mode is changed and if we were in the blink mode (mode == 2) we'll wait until the blink is done (let's say that's 2 seconds) and only then the mode is actually switched to the "off" mode. Now, can I stop whatever was in the process of current loop, break it and get the "off" instantly?
PS Of'course there can be some workarounds, like
void switchMode()
{
  interrupt_time = millis();
  // debounce measures
  if (interrupt_time - last_interrupt_time > 200)
  {
    mode = (mode + 1) % 3;
    if(mode == 0)
      turnOff();
    if(mode == 1)
      turnOn();
  }
  last_interrupt_time = interrupt_time;
}

but is there something more elegant and general? (note that if there's 4 modes: on, off, blink, blink_slowly, than this won't work)

No, you can't. An interrupt cannot affect the flow of the existing procedure except by passing data or status to it through a variable.
In multi-threading terms what you are talking about is a semaphore - a shared flag which one thread or context (the interrupt) sets and another thread or context (the main loop) reads and responds to.
If you want to respond to it fast you must write your main loop in such a way that it is possible to respond to it fast.

It is possible. You could use a setjmp()/longjmp()
combination, or you could just manipulate the stack in assembly right
before returning from the interrupt. This however, makes the program
very difficult to reason about, which can easily lead to introducing
very hard to find bugs. It is certainly not a good solution for your
specific problem.
The straightforward solution to your actual problem is to make your loop
non blocking, and this is achieved with the technique explained in the
Blink without delay Arduino tutorial. Your case is a little bit more
complex, as your LED can be in three modes. I suggest you consider
instead that it can actually be in four modes by saying that, while
it's blinking, the ON and OFF states are different modes:
static enum { OFF, BLINK_OFF, BLINK_ON, ON } mode;

I would let the interrupt handler take care of the button-controlled
mode switching:
void switchMode()
{
    // Debounce.
    static uint32_t last_interrupt_time;
    uint32_t interrupt_time = millis();
    if (interrupt_time - last_interrupt_time < DEBOUNCE_TIME)
        return;
    last_interrupt_time = interrupt_time;

    // Switch modes.
    switch (mode) {
        case OFF:  // OFF -> blink
            digitalWrite(LED_PIN, HIGH);
            mode = BLINK_ON;
            break;
        case BLINK_OFF:  // blink -> ON
        case BLINK_ON:   // ditto
            digitalWrite(LED_PIN, HIGH);
            mode = ON;
            break;
        case ON:  // ON -> OFF
            mode = OFF;
            break;
    }
}

And the loop() only has to deal with the blinking:
void loop()
{
    // This only has to handle the timing of the blinking.
    uint32_t now = millis();
    static uint32_t last_toggle_time;
    switch (mode) {
        case BLINK_OFF:
            if (now - last_toggle_time > TIME_OFF) {
                digitalWrite(LED_PIN, HIGH);
                mode = BLINK_ON;
                last_toggle_time = now;
            }
            break;
        case BLINK_ON:
            if (now - last_toggle_time > TIME_ON) {
                digitalWrite(LED_PIN, LOW);
                mode = BLINK_OFF;
                last_toggle_time = now;
            }
            break;
        default:
            // Nothing to do in the other modes.
            break;
    }
}

Another option is to have the interrupt handler only set a flag to
signal the button press. Then loop() would take care off all mode
changes. This can be a good option if you want the “state machine” (the
control of the mode) contained in a single function.

but is there something more elegant and general?

there are certainly ways to do what you want to do. whether they are elegant / generic is up to debate. however, they are all well known and widely used so i suppose they are at least accepted.
the simplest would be to prohibit interrupt at beginning of the switch / case block. "mode" will always be atomic.
the 2nd would be a double read on "mode".
  do {
    mode_shadow = mode; //save mode
    switch (mode_shadow) {
      case ...
    }
  } while (mode_shadow != mode); //continue to execute the switch block if mode has changed

this is a classic case to ensure atomicity without inhibiting interrupts.
the 3rd possible approach is to make the switch / case block dependent on "mode" at each step of execution. this is often used in high reliability computing where you aren't sure if a piece of data you read is ever valid. here you can ensure that through two ways: 1) affirmative: a statement is only executed if "mode" meets expectation. or 2) exclusive: all statements are not executed as soon as "mode" fails to meet expectation. This will drop you out of any of the branches of the switch / case block. atomicity isn't assured in this case but it is only violated for a short period of time.
the last I would mention would be typical of an OS where a "global" variable is maintained so that each task accesses that global variable to know what's going on. RTOS does that via messages for example. Not as real time as approach #1 / #2 above but it is fairly generic.

As for delays, I have to reimplement them, right? Something like void interruptableDelay(int milliseconds, byte *stopThis) { usigned long t0 = millis(); while(!*stopThis && millis() - t0 < milliseconds) ; }


text:
LCDs measuring volts arduino
How do we measure 100 Volts Arduino LCD Proje
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
int analogInput = 0;
float vout = 0.0;
float vin = 0.0;
float R1 = 100000.0; // 100K ohm direnç
float R2 = 10000.0; // 10K ohm direnç
int value = 0;
void setup(){
   pinMode(analogInput, INPUT);
   lcd.begin(16, 2);
   lcd.print("DC VOLTMETRE-PROJEHOCAM");
}
void loop(){
   // read the value at analog input
   value = analogRead(analogInput);
   vout = (value * 5.0) / 1024.0;
   vin = vout / (R2/(R1+R2));
   if (vin<0.09) {
   vin=0.0;
}
lcd.setCursor(0, 1);
lcd.print("VOLTAJ V= ");
lcd.print(vin);
delay(500);
}

Attenuate it...

The project that you show as your reference : link in your question,  shows this picture :

Change R1 to 200 K ohms.   The Arduino will receive 4.76 volts when the input is 100 volts.
You will also need to change your program line for float R1 = 100000.0;
CAUTION :  Beware of high voltage.  Also, the Arduino is not isolated from the 100 volts.

It's probably a good idea not to deal with HV if a voltage divider needs to be asked about.


text:
How to control nokia 5110 display using esp-01
I am working on a smart device using esp-01 to pull data from internet and display on Nokia 5110 LCD display, and send back the resistive touch inputs to my server and display those on my lcd I am using an Arduino UNO as a secondary device that talks to esp-01, my display and the resistive touch panel. As the esp-01 has got a system on chip, I can program it and do most of the thing my UNO is doing, but because of lack of ports I am using UNO (as far as i know that's the only limitation.. I dont exactly know how is the analog pins on UNO different from the gpio pins on esp) is there any ways if I can do the whole task using only my esp-01 by eliminating UNO. If its only about the less gpio pins on esp-01, will I be able to eliminate UNO by using higher esp such as esp-07 or esp-12E? if not, could you suggest a best way of bi-directional communication between esp and UNO? (so that esp can sent the display info to uno and based on that info, uno can send the resistive touch inputs to esp)

Your question consists of multiple questions tossed around informative text. Also, it consists of multiple questions which are merely related and does not involve any schematics or diagrams to make visible what you mean. Try to make your question more concrete.

Yes, you can use a NodeMCU ESP12E board for example as a standalone microcontroller, you actually don't need an Arduino in your case.

Since the restive touch is connected on the analog inputs, will the esp still read the analog values?

The ESP-12 (don't know about other versions) does have one ADC pin.
https://github.com/esp8266/Arduino/blob/master/doc/reference.md#analog-input
I don't know how much your pins display needs. If this is more than one, then you will need a seperate ADC. There are many available as a single chip, but you could also use an arduino as you're doing now.


text:
Can the Arduino Due be used as a serial to USB converter?
The Arduino due exclusively runs on 3.3V, so I am wondering if this can be used as a USB to serial converter just like the Arduino Uno could, or do you need to do level shifting?? Will I ruin the board if I just hook up RX and TX to a 5v device?

Yes it will work as a USB to serial device, however the serial will be at 3.3V not 5V. It'll still be serial though.
For it to send data to a 5V device, depending on the device, it might work.  3.3V is often around the "high" threshold for an input pin on a 5V device, but check the datasheet for the 5V device to be sure.
For receiving data the 5V will be above the 3.3V supply voltage of the main SAM3X chip, so should be avoided. As with most Atmel datasheets, actually finding the information you want is almost impossible, and I haven't found if there is a maximum "over voltage input current" or not, so to be on the safe side a full level shifting voltage divider should be used on the RX pin.

According to the datasheet 'Absolute Maximum Ratings' on page 1378 (where you'd look for things like these...) Voltage on Input Pins with Respect to Ground (except VBUS)...............-0.3V to +4.0V. No idea what you mean with "over voltage input current" but I'm not surprised it isn't in the datasheet.

Well, I said s***w it, and went ahead and tried it. Everything actually worked just fine! I was able to communicate with a serial device with putty and send and receive commands. I probably am going over recommended voltage, but I have not fried my Arduino (checked Rx and Tx with 3.3v device afterwards), so I guess it's fine.

The "over voltage input current" is basically the current rating of the ESD diodes on the input pin. I fyou know that you can get away with just a series resistor on the RX pin to protect it. I would advocate at least having a series resistor if you are reticent to make a voltage divider. 1K would most likely give enough protection.


text:
Can I use this cheap GPS module with arduino
For my project I need a GPS module, it should be cheap and I should be able to use it with arduino, after some search I got a product on ebay, I'm a 16 year old school boy and I didn't know that it will work with Arduino or not. Help me.
Here is the link--
http://www.ebay.co.uk/itm/DIYMALL-VK16E-Module-Gmouse-GPS-Module-SIRF3-Chip-with-Ceramic-Antenna-TTL-Level-/181594912168?hash=item2a47e675a8

After some research it seems you can use that gps module with an Arduino. Here's a link to the data sheet for it: http://www.hanssummers.com/images/stories/ultimategps/vk16e.pdf. Also it seems like you have to use the TinyGPSPlus library to get it to work. Here's a link to learn more about it: http://arduiniana.org/libraries/tinygpsplus/. You may have to use the protocols in this data sheet: https://www.sparkfun.com/datasheets/GPS/NMEA%20Reference%20Manual-Rev2.1-Dec07.pdf.
All of this information was taken from this thread: https://www.linkedin.com/grp/post/4573843-5806249757395406852.

Yes.  You can tell that from two entries in the specification:

TTL Level 9600 Baud Rate

That tells you it uses standard TTL (5V) serial to communicate, so on an Uno that would be pins 0 and 1 and the Serial object, or any pins of your choice and the SoftwareSerial library.

Output SiRF binary system OR nmea0183 V3.0(GGA, GSA, GSV, RMC, VTG)

It outputs NMEA encoded data (bold added by me) which is what most of the Arduino GPS libraries are written to use.

authors: Евгений Новиков


text:
Can I use these cheap GSM module with arduino?
I found two cheap GSM module on ebay but didn't know that I can use them with Arduino or not.
Will you help me please?
Here are the link-
http://www.ebay.co.uk/itm/Smallest-SIM800L-GSM-Module-Micro-SIM-Board-Quad-band-Port-Onboard-Antenna-/111789339320?hash=item1a0729f2b8
http://www.ebay.co.uk/itm/SIM900A-Development-Board-Extension-Module-GSM-GPRS-Antenna-TTL-e/281517486292?_trksid=p2045573.c100033.m2042&_trkparms=aid%3D111001%26algo%3DREC.SEED%26ao%3D1%26asc%3D20131017132637%26meid%3D70128bc79b60410d862b64d36cc479b3%26pid%3D100033%26rk%3D1%26rkt%3D4%26sd%3D281517486292

Both seem to have the pin header for a serial port. So chances are that they can take standard AT commands.
I've seen many modems using additional AT commands for special functions, but they all supported also the basic AT commands.

The SIM900A won't work in the UK, it's dual band.
The SIM800L is cheap as there is no power regulation on board. IIRC it requires 3.4V - 4.5V, min 2 amp supply. Check the data sheet to be sure.

You can actually use the sim900a and 900a mini in the uk but you will have to download firmware and flashing tools that you will find with a web search, not for the beginner though, an 800l is your best bet with a SMA Female JACK Connector to U.FL/IPX Converter Pigtail Cable F1445K so you can attach an sma antenna
cheers
Stuart


text:
Can I use GSM and GPS modules at the same time?
In my project I want to retrieve the Latitude and longitude and then transmit to a cell phone through GSM module. But the GSM as well as GPS modules uses the same pins i.e. Tx and Rx, so is it possible to use both modules at the same time?
Link to products
GSM - http://www.ebay.co.uk/itm/SIM800L-GPRS-GSM-Module-SIM-Board-Quadband-PCB-Antenna-for-MCU-Arduino-/191611848583?hash=item2c9cf4c787
GPS-- http://www.ebay.co.uk/itm/New-1PC-Ublox-NEO6MV2-GPS-Module-Aircraft-Flight-Controller-For-Arduino-/400830328802?hash=item5d53596fe2
Thank you.

Yes.  Use SoftwareSerial for one of them.  That way you can use any pins you like for that module.
I'd recommend using the GPS module on the SoftwareSerial since it's (mainly) half duplex, and SoftwareSerial can't both transmit and receive at the same time like the hardware UART can.
Either that or switch to a different Arduino board that has more than one hardware UART.

Well, thanks for the answer, and please will you suggest any arduno board other than MEGA which has more hardware UART.

This table is useful: https://www.arduino.cc/en/Products/Compare Also you might want to consider other boards than Arduino - there are other makes using other kinds of chips that do so much more using the same (or similar) footprints.

If you are using two software serial then you can always use the listen() function to listen to specific object.
Suppose you have two software serial objects named GSM and GPS.
Now if you are reading or writing data to GSM then start with this, gsm.listen();
Now you can read/write data to GSM.
Next if you plan to read or write data to GPS then do this, gps.listen();


text:
Writing a value to 7-segment max7219 displays
I am new to arduino and I am trying to build an interface for my flight simulator. I am using a plugin for the simulator software which returns a float variable to my arduino, which I then want to display on a series of 7-segment displays. I have connected three max7219 modules, each with 8 digits.
I found the LedControl library which I managed to get to display on my modules like this:
#include <LedControl.h>

// inputs: DIN pin, CLK pin, LOAD pin. number of chips
LedControl mydisplay = LedControl(48, 44, 46, 3);

void setup() {
  mydisplay.shutdown(0, false);  // turns on display
  mydisplay.shutdown(1, false);  // turns on display
  mydisplay.setIntensity(0, 7); // 15 = brightest
  mydisplay.setDigit(0, 0, 9, false);
  mydisplay.setDigit(0, 1, 8, false);
  mydisplay.setDigit(0, 2, 7, false);
  mydisplay.setDigit(0, 3, 6, false);
  mydisplay.setDigit(0, 4, 5, true);
  mydisplay.setDigit(0, 5, 4, false);
  mydisplay.setDigit(0, 6, 3, false);
  mydisplay.setDigit(0, 7, 2, false);

  mydisplay.setDigit(1, 0, 9, false);
  mydisplay.setDigit(1, 1, 8, false);
  mydisplay.setDigit(1, 2, 7, false);
  mydisplay.setDigit(1, 3, 6, false);
  mydisplay.setDigit(1, 4, 5, true);
  mydisplay.setDigit(1, 5, 4, false);
  mydisplay.setDigit(1, 6, 3, false);
  mydisplay.setDigit(1, 7, 2, false);

}

void loop() {
}

The arduino code however for the plugin I am using has this function:
void ProgOut(byte id, float val) {

  if (id == 1)
  {
       // print this to display
  }
}

So my question is, right now based on the LedControl test sketch, I have to display each individual character one by one, but I receive a float variable.. so how can I just do something like "mydisplay.set(floatvariable)" ?

Why not use a library that supports that directly? https://github.com/mikaelpatel/Arduino-LCD. Then you can write code like "led.print(3.1415, 4)", i.e. use the same interface as Serial.

I didn't know about that library. I'll check it out, thanks.

how can I just do something like "mydisplay.set(floatvariable)" ?

write your own code.
let's say that you want to display up to two decimal points. Multiply the float vary by 100, save it into an int variable, and utilize the existing code to display that integer variable + decimal point at the right digit.