text:
Stabilize data from four gyros/accelerometer
I am currently working on a university project. My aim is to get a rough estimate of the posture of a person's back. For this I have built a system that collects the data from 4 MPU6050 at a central service. From there it will be visualised. My first idea was to draw 4 lines and take the roll angles for the angles between the lines. My problem is that the data from the MPU6050s drifts a lot. I have already created calibration data and use a complementary filter on the nodeMCUs that read the data from the MPUs.
I am using the Adafruit_MPU6050.h lib to connect to the sensors and get data from it. To calculate roll, pitch and yaw I use the following code:
  sensors_event_t gyro_1;
  sensors_event_t accel_1;
  mpu_gyro_1->getEvent(&gyro_1);
  mpu_accel_1->getEvent(&accel_1);

  acc_1_angle_x = (atan(accel_1.acceleration.y / sqrt(pow(accel_1.acceleration.x, 2) + pow(accel_1.acceleration.z, 2))) * 180 / PI) - mpu_1_acc_err_x;
  acc_1_angle_y = (atan(-1 * accel_1.acceleration.x / sqrt(pow(accel_1.acceleration.y, 2) + pow(accel_1.acceleration.z, 2))) * 180 / PI) - mpu_1_acc_err_y;

  previousTime = currentTime;
  currentTime = millis();
  elapsedTime = (currentTime - previousTime) / 1000;

  gyro_1_angle_x = gyro_1_angle_x + (gyro_1.gyro.x - mpu_1_gyro_err_x) * elapsedTime; // deg/s * s = deg
  gyro_1_angle_y = gyro_1_angle_y + (gyro_1.gyro.y - mpu_1_gyro_err_y) * elapsedTime;
  yaw_1 = yaw_1 + (gyro_1.gyro.z - mpu_1_gyro_err_z) * elapsedTime;
  roll_1 = 0.96 * gyro_1_angle_x + 0.04 * acc_1_angle_x;
  pitch_1 = 0.96 * gyro_1_angle_y + 0.04 * acc_1_angle_y;

How can I make my data more stable?
I tried playing with the 0.96 and 0.04 to change the amount of data I use from the gyro but it only got worse.
If you are interested, this is my project github:
https://github.com/Trojan13/posture-control
Thanks in advance for your input!

The visualization of data on a PC is off topic here. What is wrong with your idea with the lines?

Okay thanks. Where would you suggest I should ask? The problem is currently about the lines being either way to jittery or drifting way to hard.

You need to isolate the problems. When the data is too jittery and drifting this has nothing to do with the visualization. You could ask about how to make your data more stable. Then you should show your Arduino code and show on the actual data how much jitter and drift you actually have.

The roll, pitch and yaw angles cannot be measured directly: the MPU measures accel and gyro, then it (or you) integrates the gyro in order to estimate the angles. Numerical integration of measured data is prone to drifts, so you have to use accel to estimate the low-frequency part of roll and pitch (and you need a compass if you want yaw). If you have too much drift, tweak your filter to give more weight to accel and less to the integration of gyro.

Sorry guys. I adjusted my question to make it more precise and fitting for this board.
@EdgarBonet I am already using a filter to correct the values. Additionally I am using a lowpas filter the adafruit library provided. "MPU6050_BAND_44_HZ"

If you add incorrect corrections to the gyro data, that could cause a pretty strong drift. Check your pull-requests.

the title of your post does not match the problem you are trying to solve ... someone that is an expert in getting stable readings may simply not look at your post

posture for spinal health is relative.  personally would have favored strain gauges.  your filters and or data sources are likely not being managed/filtered correctly.  with multiple mpu6050 on a rigid structure you need to blend accelerations from different devices with gyros from one device to get a reasonable angle for one device.  even so it will drift so you need to add more sources or assumptions (gravity is a nice freebie and with 4 points m8ght be sufficient)

Looking at your code, I see the only place where gyro_1_angle_x is
updated is here:
gyro_1_angle_x = gyro_1_angle_x
    + (gyro_1.gyro.x - mpu_1_gyro_err_x) * elapsedTime;

This is adding to gyro_1_angle_x a quantity that does not depend on
gyro_1_angle_x itself. This means that, if there is an uncorrected
systematic error in the measurement of gyro_1.gyro.x (which there
always is, as you can never achieve perfect calibration), the errors
will pile up, leading to an unbounded drift. Then, you estimate the roll
angle as
roll_1 = 0.96 * gyro_1_angle_x + 0.04 * acc_1_angle_x;

The factor 0.96 slightly reduces the amount of drift (by 4%), but does
not change the qualitative behavior: roll_1 is also prone to unbounded
drift.
Suggested approach
My suggestion will be to forget about angles. Using angles to keep track
of your device's attitude is a bad idea: the formulas needed to update
the angles are complex (and thus easy to get wrong), computationally
expensive, and prone to gimbal lock. For tracking the whole
attitude, it would be more reasonable to use rotation matrices or,
better yet, quaternions.
In your use case, however, you do not need to track the whole attitude.
You have no means to reliably track the yaw angle, and you actually do
not even care about this angle. You are only interested in the
orientation of the device relative to the vertical direction. Thus I
suggest you do no even try to track the attitude, and instead just track
the vertical direction. This direction is given by the coordinates of
the gravity vector in the device's reference frame. Then you just have
one vector to track. No angles, no matrices, no quaternions: just a
simple vector.
Using the accelerometers
The accelerometers are sensitive to the gravity, thus you can use their
readings as an estimate of the gravity vector, as in the following
pseudo-code:
at each time step:
    (accel, gyro) = read_MPU();
    gravity = accel;

This may give you the opposite of the gravity (direction of the zenith).
That's fine, as long as you know which vector you are tracking.
There is an issue with this approach though. The accelerometers are not
only sensitive to the gravity, they are also sensitive to the
acceleration (hence the name). If your subject moves, its acceleration
will cause an error in the estimate of the gravity vector. The estimate
is poor in the short term, but it should be good in the long term: as
your subject is unlikely to maintain sustained acceleration, a time
average of the accelerometer readings should closely match the gravity
vector.
Using the gyroscopes
In order to get rid of the acceleration-induced errors, you can instead
use the gyro readings. Assuming you somehow manage to get an initial
estimate of the gravity vector, you can use the gyro readings to
iteratively update this estimate:
at each time step:
    (accel, gyro) = read_MPU();
    dt = time_since_previous_time_step;
    rotation = - dt * gyro;
    gravity = apply_rotation(rotation, gravity);

here rotation is the rotation vector describing how much
the gravity has rotated since the previous time step. The minus sign in
its formula comes from the fact that the gyro gives you the rotation of
the device relative to a still reference frame, whereas you want the
rotation of a still vector relative to the device's reference frame. The
function apply_rotation() would apply Rodrigues' rotation
formula in order to rotate the gravity vector to its new
orientation.
This approach does not suffer from the acceleration induced errors. It
is, however prone to drift, as combining a large number of small
rotations ends up piling up a large number of small errors.
Combining gyroscope and accelerometer data
The accelerometer approach is prone to short-term errors, while the
gyroscope approach is prone to long-term drift. You can try to combine
these two approaches, and use the accelerometers to determine the
long-term behavior of your gravity estimate, while the gyroscopes
determine its short-term behavior. For this you would, at each time
step:

use the gyro data to rotate the current estimate of the gravity vector
then “stir” it gently towards the accelerometer readings.

In pseudo-code, this would look like:
at each time step:
    (accel, gyro) = read_MPU();
    dt = time_since_previous_time_step;
    rotation = - dt * gyro;
    gravity = apply_rotation(rotation, gravity);
    gravity = gravity + (dt/tau) * (accel - gravity)

The last line has the effect of slightly pushing the gravity estimate
towards the accelerometer readings. Note that this line looks like the
implementation of a first-order low-pass filter with time constant
tau. This time constant defines the boundary between the “short” time
scales, where you trust the gyroscopes more than the accelerometers, and
the “long” time scales, where you trust more the accelerometers. The
value of tau has to be chosen by experiment. It controls the trade-off
between the noise coming from the acceleration and the systematic error
coming from the gyros.
With this formula, the accumulated gyro errors will always stay bound,
with a total error proportional to tau. Since the step-wise rotations
are presumably very small, and since the rotation errors do not pile up
in an unbounded way, you can probably get away with using a
linearization of the Rodrigues' rotation formula (cos θ = 1, sin θ = θ):
gravity = gravity + rotation × gravity

and then you need no trigonometry at all.
It is also worth noting that, with this approach, you can safely
initialize gravity to zero: it will immediately start growing as the
program runs, and its magnitude will eventually converge to the
appropriate value.
Getting the pitch and roll
Once you know the gravity vector, you can easily compute the pitch and
roll. I am not saying that you should completely avoid using angles: you
probably want angles on your user interface. What I am saying is that
you should refrain from using angles for the purpose of keeping track of
the device's orientation. Computing the angles as a post-processing step
is fine.
Actually, you may as well compute those angles in the computer that does
the final processing of the data. The ESPs can simply send their best
estimate of the gravity vector, and let the computer do the
trigonometry.

I'm assuming this described approach will still result in yaw drifting, right?

@Runsva: This approach tracks only the gravity vector, from which you can compute pitch and roll, but not yaw. The assumption is that you do not care about yaw, which is the case for the OP.

You have the right idea fusing data from both gyro and accelerometer. However, I would strongly advise against doing the fusion yourself since there is a dedicated Digital Motion Processor (DMP) on your MPU-6050 that does this for you. You just need a library that grabs data from the DMP. As far as I know the only Arduino libraries that do this are ones based on Jeff Rowberg's work.
The data outputted by the DMP is in quaternion format. Jeff converts it to yaw pitch and roll but his conversion is flawed (it produces spurious flips and rotations at north and south poles, called gimbal lock). Don't worry, this can be fixed.
If using Jeff's library (or one based on it) you'll need to make sure the detector is level and still before sending a character over serial to trigger the calibration and you need to do this every time you power on. The library and sketches are somewhat overwhelming/intimidating to new users. This too can be fixed.
If you want to
(a) Learn more about this whole topic
(b) Use the correct conversion from quaternion to yaw pitch roll (one that does not produce gimbal lock)
(c) Hide Jeff's library behind a simple and easy to use interface
(d) Perform the calibration only once and have those results saved to persistent memory on your arduino so that you don't have to repeat the calibration every time you power on the device.
Then I would recommend the following tutorial:
https://youtu.be/k5i-vE5rZR0


text:
Why does a light bulb activate an infrared sensor? Is there a way I can filter this out?
I've made 3 programs. One is written in python, c++ processing and bash.
Everything seems to be okay but then sometimes I get a signal from the arduino that activates the function to lower down the volume on the python code listening for serial data. This is sometimes random but it seems that I can reproduce the same behavior when I turn the light on. I can cause the same disruption if I wave my hands over it quickly.
How can I filter this? I know that IR is part of the electromagnetic spectrum in which the visible light takes part. The sensor is facing upward for a type of omnidirectional receptor. I've placed a TV IR blackish cover over it but with the same results. Do I need to use the function to hash decode the incoming signal? I suppose that it needs a simple circuit as any other sensor.
I want to discard the possibility of a random activation in my code.
Edit:
Taken into consideration the answers until now I can confirm that this is part of a physical phenomena due to the distance between my light and the device.
As for the solution to my volume problem It seems that I used "0" in the same statement as the ir code I remapped in the python code. It turned out to be part of the IRlib library of the arduino code that returns a "0" when it encounters an unknown signal. (due to protocol specification? - out of useful range? )
The thing is that I can change the if statement value for other than "0" but that won't stop it from returning "0" and that's a disadvantage. The solution that came to me is simply intercepting the signal and use continue to skip this.
Is there any alternative to this?

This is why IR communications uses actual protocols instead of just presence of the signal.

Can you explain? I use a library to read IR signals from a remote control of a portable dvd player

You'll need to find out what encoding the remote uses, that will be trial and error.  You might be better of buying a cheep one that you know the encoding for off eBay or aliexpess.

Yes mine use the NEC protocol that seems generic because I have another that use the same protocol. I've kinda found my solution so I'll edit my first entry. Thanks

Remote controls use a carrier wave to make it easier to distinguish IR noise from IR signals. What kind of IR-sensor are you using?

I salvaged one from a fan and got another from the Microsoft Xbox control kit. To tell you the truth this often happened before with the other one.

What kind of light bulb is it?  Try using e.g. an LED instead of incandescent; you might get less IR signal.
Having a more complicated signal that is decoded by the receiver reduces your false positives.

That's a good idea!! Thanks
This can be reproduced depending on intensity of light, velocity of action(no slow dim), type of artificial light and distance between. We are talking about a physical phenomena here. I'll edit my question to propose an explanation.

Yes, a light bulb will put out some infrared light.
Decoding remote control signals isn't that hard - there is a tutorial at instructables - http://www.instructables.com/id/The-Easiest-Way-to-Use-Any-IR-Remote-with-Ardiuno/?ALLSTEPS
This also means you can tell the difference between different buttons.
P.S. - when posting in this forum, it helps to include your code and your wiring.

Yes that seems to be correct. Thanks for the link and fast answer.
My bad but I did not know where to point that first issue. With the help received I can propose an answer myself now. So I'll post some code for reference

source: Stack Exchange

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

sort: votes


text:
Arduino LCD Display 2x16 custom char byte limit
Some years ago I stumble with a problem while using the 2x16 LCD. What happened was that there was a limit to how may byte arrays I could declare. So my project came to a halt because I needed to create more custom characters to advance any further...
The lcd accept custom characters to store them but I suppose there is a limit to this, am I wrong?
I'm trying to create a set of custom characters that move on screen. Since there are a lot of animations I need several of them to have a smooth animation. The problem resides in the limit of characters I can pre-establish after executing lcd.begin()
I don't post code because to my understanding that is not relevant and because sincerely is a crap since I wrote it down when I was learning programming some years ago. I want to resolve this so I can rewrite the code.
LCD version: QAPASS 1602A
Here is an example:
byte Ghost[8] = {
  0b00000,
  0b01110,
  0b01110,
  0b10101,
  0b11111,
  0b11111,
  0b11111,
  0b10101
};
lcd.createChar(0, Ghost);
So the right question is: Do I need to reset the LCD chip then declare the new characters to the lcd to make it available? How?

there was a limit to how may byte arrays I could declare.

If the problem was that you ran out of free RAM, then the fix is to move those byte arrays into program space.
Atmega 328 processors (Uno) are very RAM-limited. Fortunately you can assign constant data - fixed character strings, lookup tables for math, fonts, CRC calculation, etc - to be stored in program space which is much more generous. The upside is you can free lots of RAM in an application like yours that needs lots of constant data. The downside is that access to the data is a little bit slower:
// Definitions for data in program space
#include <avr/pgmspace.h>

// Place the character table in Flash
byte const Ghost[8] PROGMEM = {
   0b00000,
   0b01110,
   0b01110,
   0b10101,
   0b11111,
   0b11111,
   0b11111,
   0b10101
};

// Read a byte of character data
OneByte = pgm_read_byte(&Seg7_segtbl[index]);

Update:

LCD version: QAPASS 1602

If that has an Hitachi HD44780 controller on it, its datasheetsays it has a 64-byte character RAM - more than enough for a full display of 2 x 16 unique characters, but if you need a wider choice of characters than a set of 64, you may need to re-load the RAM with a custom sub-set for any given screen-full. For animating, though, you'll probably need all of the individual parts of each animation in the LCD RAM at once; reloading during animation will most likely disturb the smoothness. One possibility is to load part of a subset between animation frames - if that's even possible. (I haven't studied this controller to that level of detail).

Thanks sir! So &Seg7_segtbl[index] where index means a specific value of the constant byte variable stored in flash memory... This can come in handy but I think my problem is more related to the lcd itself. I heard that the lcd can store custom characters on its own but obviously it has a limit.

Correct (about the address expression). To help with your LCD, we'll need to know what LCD and driver chip you're using (manufacturer and part#), and more specifics about the the problem you have: what are you trying to do and how did you do it? And what were you expecting to would happen, and what happened instead?

Check my edit and I'm grateful for the tips and your time

Typical HD44780-based   2x16 LCD support 8 programmable characters, not 16.  They show up as characters #0 to 7 and again as characters #8 to 15.  Definitely not 64 programmable characters, not 32, not 16 – just 8 of them.

@jwpat Then perhaps I misinterpreted the datasheet or I found the wrong one? But Itook that spec from the datasheet.

The 64 bytes of RAM are used 8 bytes per character.  Each byte represents one 5-dot line of a character.  See heading "Character Generator RAM (CGRAM)" in HD44780 spec, which says:   “In the character generator RAM, the user can rewrite character patterns by program. For 5 x 8 dots, eight character patterns can be written, and for 5 x 10 dots, four character patterns can be written.”  Note, typical  HD44780-based 2x16 LCDs are set up 5 x 8 rather than 5 x 10

@jwpat7 Yeah that's the current problem! It accept only 8 custom characters.

For now I came with the solution of reseting the arduino with asm volatile ("  jmp 0"); I write a number to the EEPROM and then reset so in the setup I use a statement to read the EEPROM to load the characters I need

Sorry not fixing anything! I still got my error

authors: นายสมชาย คุณสมบัติ

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


text:
EMG control of solenoid valve
I need some help with programming Arduino with EMG signals to control the solenoid pressure valve.
I wrote some program which is setting high and low state on the output pin, but it's not working properly.
First I create a plot to observe the signal level. And the plot looks like in the picture which I attached.
The basics concept of program is setting the high signal on the output when I flex muscles and when I relax the muscle it's should write low state on the output. My idea was based on triggering the on-off signals at the moment when the muscle is flexed, the value of signal is above 600 (now the diode should be ON and stay in ON state) and it drops and when I relax muscles the value rises once again to value around 600 more or less (now the diode should be OFF) and drops under 100.
const int ledPin=13;

const int sensorPin= 0;

int level;

const int threshold1=400;

const int threshold2 =500;

void setup() {

    pinMode (ledPin, OUTPUT);

    pinMode (sensorPin, INPUT);

    Serial.begin(9600);
    }

void loop(){

    level= analogRead(sensorPin);

    if (level > threshold1){

    digitalWrite(ledPin, HIGH);

    if (level > threshold2)

    digitalWrite(ledPin, LOW);

    }

I wrote new code, but I still have problems with proper sending of an ON and OFF     signal to the output.
When I flex the muscle I have high state on the output causing by first peak (LED is ON) but when I relax the muscle the second peak won't set the low state on the output. But when I flex the muscle once again the output change state to low and the diode is OFF. Do you have any suggestions what part of the code do I need to improve?
Here's the code:
const int ledPin=13;

const int sensorPin= 0;

int level;

int flex= 0;

int PreviousState = 501;

const int threshold1=600;

void setup() {

    pinMode (ledPin, OUTPUT);

    pinMode (sensorPin, INPUT);

    Serial.begin(9600);
}

void loop() {

    level= analogRead(sensorPin);

          if (level > threshold1 && PreviousState < threshold1){

          {

            flex =!flex;

          }

          if (flex == 1)
          {

            digitalWrite(ledPin, HIGH);

          }

          else

          {
            digitalWrite(ledPin, LOW);

          }

          PreviousState = level;

        }

    }

}

To mark code as code: In the editing box, highlight the code and press ctrl-k. Or highlight the code and click the {} icon in the toolbar at the top of the editing box. (To highlight text click-drag across it or use the arrow keys while holding the shift key.)  Note, short bits of code are enclosed in back-ticks, like ` which is why part of your text is formatted that way

you Can use Switch case. Switch(val) then take action according to value

In which case you want to switch the state to LOW? What is the meaning of two thresholds?

What behavior do you want in the 554570-558872 data?    I think I'd use some https://en.wikipedia.org/wiki/CUSUM filtering to debounce the level  signal, and maybe use some separate logic for switching into or out of the flex state.

I'd think there are 4 distinct states you should to keep track of separately: idle, flexing, flexed, and relaxing.

I'd use a https://en.wikipedia.org/wiki/CUSUM to filter the level data and track the idle, flexing, flexed, relaxing states and transitions separately:
...

int state = 0 ; // idle >> flexing >>flexed >> relaxing
long int cumsum = 0;

void loop() {
  level= analogRead(sensorPin);
  cumsum=max(0,cumsum+level-threshold);

  switch(state) {
  case 0 : // idle
      if (cumsum > 50*4) {state = 1 ;  // wait for long pulse
         flex =1;
         digitalWrite(ledPin, HIGH);
      }
      break;
  case 1 : // flexing
      if (cumsum ==0 ) state = 2 ;
      break;
  case 2 : // flexed
      if (cumsum > 50*2 ) state = 3 ;  // wait for shorter pulse
      break;
  case 3 : // relaxing
      if (cumsum == 0 ) {
        state = 0;
        flex = 0;
        digitalWrite(ledPin, LOW);
      }
      break;
  }
}

You might want to add an extra cumsum filter with a lower threshhold to potentially transition out of flexed if there is an exceptional period of low level.  e.g.:
...

long int cumsum2 = 0;
...
cumsum2 = max(0,cumsum2+level-200);
...

case 2:
   ...
   if (cumsum2 == 0) state=3; // missed a relaxing signal
   ...

I see this problem more profound than just some if and else. As you may observe, there may be two peaks in flex and always there is one in relax.
What makes difference is the width of the pulse: flex is wide and relax is narrow.
You should detect the width. It can be measured by amount of times, when you detect a value in input that is over the treshold.
When the amount is less than some value when signal is very low again, you detected a LOW for output and if it is more than some value it means HIGH.
in setup
unsigned int times = 0;
unsigned int threshold = xxx;
unsigned int low = xx;
unsigned int high = yyy;

...

in loop
...
if (level > high) {
      times = times + 1;
} else if (level < low) {
     if (times > threshold) {
          digitalWrite(ledPin, HIGH);
     } else {
          digitalWrite(ledPin, LOW);
     }
     times = 0;
}


text:
RGB LED strip inverted PWM
This bug/stupidity-of-myself/problem is killing me:
I'm have created an RGB strip controller that cycles through the additive-rgb-color spectrum while turning a potentiometer.
I have a pot hooked up to my Arduino Nano v3 (from AZ-Delivery, not official Arduino). Then I have an RGB amplifier hooked up to the Arduino with each phase (R, G, B, V+) and to an external power supply (12V by 2A max).
I shortened my program and removed all the value-to-colour-conversion because that has nothing to do with the problem:
void loop() {
    ColorVal = analogRead(pinPot); //read value of color poti
    ColorByte = map(ColorVal, 0, 1023, 0, 255); //Scales 0-1023 to 0-255

    // potvalue to color conversion
    // ...

    // write via PWM to LED
    analogWrite(pinR, R);
    analogWrite(pinG, G);
    analogWrite(pinB, B);
}

My problem: Theoretically you would expect the system to show white when all variables (R, G and B) are set to 255. However, it behaves the other way around. When all values are set to 255 it's off and vice versa. Another example: When R = 255 and G = 0 and B = 0 Green and Blue are lighting and Red is off.
I thought this has to do with polarity or something but I cannot seem to find it out.

The RGB LED strip has a common anode (V+). When you put 12 V on R, G or B, the LEDs have 12 V on both sides, so there is no voltage across it and no current.
And if you put 0 V, they have 12 V across it and light up.
To fix it, just invert the PWM value in your code:
analogWrite(255-pinR, R);
analogWrite(255-pinG, G);
analogWrite(255-pinB, B);

Man, I love you. Thank you so much. The physical explanation makes it even more reasonable.

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


text:
ATMega328P chip on breadboard does not work properly
I wanted to get some help about my ATMega328P on my breadboard. I programmed a simple clock like this -
#include <LiquidCrystal.h>
#include <dht.h>
#include <DS3231.h>

LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
dht DHT;
DS3231  rtc(SDA, SCL);

void setup() {
  rtc.begin();
  lcd.begin(16,2);

}

void loop() {

  int chk = DHT.read11(9);
  delay(1000);
  lcd.print("Temp: ");
  lcd.print(DHT.temperature);
  lcd.print(" ");
  lcd.print((char)223);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print("Humi: ");
  lcd.print(DHT.humidity);
  lcd.print(" %");
  lcd.setCursor(0,0);

  delay(5000);

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Time:  ");
  lcd.print(rtc.getTimeStr());
  lcd.setCursor(0,1);
  lcd.print("Date: ");
  lcd.print(rtc.getDateStr());
  delay(5000);

  lcd.clear();
 }

The code works when ATMega328P is connected on the Arduino Board itself, everything is showing correctly. But when I remove the chip (when it's already programmed) and place it on the breadboard, do all the necessary wirings, it only outputs me the words Humi and Temp without even showing the proper values (-999.0 degrees it shows me). I triple-checked my connections and found nothing. And after those 5 seconds of waiting, I finally got Time, and nothing is there, only the text, not even those weird numbers. And it doesn't even reload back to Temp and Humi, it just stays on Time word forever.
I have feeling that loop doesn't work properly somehow.
EDIT: I found out what was the problem about reseting, BUT STILL the proper values doesn't show up
Can you help me out, please?

Why do you suspect the loop() function, when you've already seen it work correctly? You've supplied the code but you already know that works. We need to see the breadboard wiring that you said is failing, since that is the difference between working and non-working systems. Despite triple-checking your wiring, you've apparently found a problem with reset. What was the problem and what was the solution? Could that guide you to other wiring problems? Please post a schematic, or at least a clear and accurate wiring diagram of your breadboard. Without that, we can only guess.

Did you add some (bypass) capacitors on the breadboard, between VCC and GND? Place them as near to the chip as possible. Secondly, try wiggling all the wires in the breadboard. Sometimes their don't make proper connection.

Pretty sure a hardware issue related to the breadboard environment...

Alright, I figured it out myself, thanks. Yeah, there was a hardware problem. A5 pin somehow didn't work properly.. Now it does.

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


text:
MIDIUSB - Why is the command put twice?
Consider this function:
void noteOn(uint8_t pitch) {
  midiEventPacket_t noteOn = {0x09, 0x90 | 9, pitch, 127};
  MidiUSB.sendMIDI(noteOn);
}

midiEventPacket_t is defined as:
typedef struct
{
    uint8_t header;
    uint8_t byte1;
    uint8_t byte2;
    uint8_t byte3;
}midiEventPacket_t;

The first nibble of the first byte of a MIDI message is the command: 0x90 ["note on"] and the second nibble is the MIDI channel: 9, so what's sent over the wire should be 0x99 meaning "Note On, channel 9", with the two more bytes representing the pitch and the velocity.
My question is, why do all of the examples start with: {0x09, 0x90 | 9,? I'm not understanding the use of the struct here. Intuitively, I thought I would need: {0x90 | 9, pitch, 127, 0}. Why do all of the examples have that seemingly strange syntax?
EDIT
After getting a great explanation below, here's my new function!
void noteOn(uint8_t pitch) {
  midiEventPacket_t noteOnPacket;
  noteOnPacket.header = USB_CABLE_NUMBER | (MIDI_NOTE_ON >> 4);
  noteOnPacket.byte1 = MIDI_NOTE_ON | CHANNEL;
  noteOnPacket.byte2 = pitch;
  noteOnPacket.byte3 = MIDI_BUTTON_ON_VELOCITY;
  MidiUSB.sendMIDI(noteOnPacket);
}

From the specs:

The first byte in each 32-bit USB-MIDI Event Packet is a Packet Header contains a Cable Number (4 bits)
  followed by a Code Index Number (4 bits). [...]
[...]
The Cable Number (CN) is a value ranging from 0x0 to 0xF indicating the number assignment of the
  Embedded MIDI Jack associated with the endpoint that is transferring the data. The Code Index Number
  (CIN) indicates the classification of the bytes in the MIDI_x fields. The following table summarizes these
  classifications.
CIN | MIDI_x Size | Description
[...]
0x9 | 3 | Note-on
[...]

No rationale is given why the CIN is required if the full message is also included, but it could be used for quicker routing of the event to the routine that will process it.

OH, LIGHTBULB moment. midiEventPacket_t represents the USB packet, not the MIDI packet


text:
Weird issue with software serial?
Hi i am trying to write a library to communicate between the arduino and the esp 8266. I wrote a command that that sends an AT command to the esp chip. So far I have tested these commands : AT, AT+GMR, AT+CIFSR, AT+CIPMUX=1 etc. with no issue the communication seem robust.
When I tried to send the AT+CIPSERVER=1 command the function did not work. After some attempts to debug the program I manage to get it working but I do not understand why. And this is my issue, I though it was working because of the extra delay that was occurring in my code but after some testing that was not the reason.
Could anyone please explain to me what is happening ? I will continue to work on the code until I figure it out.
The code :
Header file
#ifndef _ESPLIB_h
#define _ESPLIB_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

#include <SoftwareSerial.h>

// Definitions
#define DEBUG       1
#define BUFFSIZE    64
#define TCPORT      23050
#define ESPTIMEOUT  10000
enum espResponse {
    ok,
    error,
    other
};

// AT Commands
#define CRLF    "\r\n"
#define Q       "=?"
#define AT      "AT"
#define GMR     "+GMR"
#define RST     "+RST"
#define CMUX    "+CIPMUX=1"
#define CWMOD   "+CWMODE"
#define CSERV   "+CIPSERVER=1"
#define CFSR    "+CIFSR"
#define CSEND   "+CIPSEND"

class espdevice
{
    public:
        // Functions
        espdevice(int rx, int tx, int baud);
        void serialEnable(void);
        //boolean tcpServerInit(void);

        #if DEBUG
            void serialDebug(void);
        #endif

    private:

        // Variables
        // Serial Setup parameters
        int _rx;
        int _tx;
        int _baud;

        // Software Serial
        int _espSerialIndex = 0;
        char _espSerialBuffer[BUFFSIZE];
        SoftwareSerial *_espSerial;

        // private functions
        //espResponse _sendEspCommand(const char* cmd);
        boolean _sendEspCommand(const char* cmd);
        espResponse _espCommandOK(void);
        boolean _espSerialAvailable(void);

        // Debug mode
        #if DEBUG

        // variables
        int _serialIndex = 0;
        char _serialBuffer[BUFFSIZE];

        // functions
        void _serialDebug(int select);
        int _arduinofreeRam(void);
        boolean _serialAvailable(void);

        #endif

};

#endif

What I am executing
        _sendEspCommand("AT+CIPMUX=1\r\n");
        _sendEspCommand("AT+CIPSERVER=1,23050\r\n");
        _sendEspCommand("AT+CIFSR\r\n");

Now the function definition
boolean espdevice::_sendEspCommand(const char* cmd)
{
    // variables
    int count = 0;
    boolean flag = false;
    espResponse status = other;

    // sending the command to the ESP
    _espSerial->write(cmd);
    #if DEBUG
        Serial.print("command echo : ");
        Serial.write(cmd);
        Serial.println();
    #endif

    //while (!(status==ok||status==error) || count < 1000) **<- why this thing works  ??????????????**
    //while (status == other && count < ESPTIMEOUT) <- does not work
    while ((status == other) || (count < ESPTIMEOUT)) <- THIS works too
    //while(count < ESPTIMEOUT) <- does not work
    {
        //while (!_espSerial->available()) {};
        if (_espSerialAvailable())
        {
            Serial.println ("Data Are available");
            status = _espCommandOK();
            #if DEBUG
                Serial.print("Data Received from ESP : ");
                Serial.print(_espSerialBuffer);
                Serial.println("");
                Serial.println(status);
            #endif
            /* //code used with the not working part
            if (status == ok)
            {
                flag = true;
                break;
            }
            else if (status == error)
            {
                flag = false;
                break;
            }
            else
            {
            }
            */
        }
        count++;
    }
    Serial.println(count);
    return flag;
}

And the two other functions that are called
_espSerialAvailable()
boolean espdevice::_espSerialAvailable(void)
{
    boolean stringFound = false;
    // Read the serial buffer if data are available
    while (_espSerial->available() > 0)
    {
        char charBuffer = _espSerial->read();

        if (charBuffer == '\n')
        {
            _espSerialBuffer[_espSerialIndex] = 0; // terminate the string
            stringFound = (_espSerialIndex > 0); // only good if we sent more than an empty line
            _espSerialIndex = 0; // reset for next line of data
        }
        else if (charBuffer == '\r')
        {
            // ignoring carriage retun
        }
        else if (_espSerialIndex < BUFFSIZE && stringFound == false)
        {
            _espSerialBuffer[_espSerialIndex++] = charBuffer; // auto increment index
        }
    }

    return stringFound;

}

_espCommandOK()
espResponse espdevice::_espCommandOK(void)
{
    if (strcmp(_espSerialBuffer, "OK") == 0)
    {
        return ok;
    }
    else if (strcmp(_espSerialBuffer, "ERROR") == 0)
    {
        return error;
    }
    else
    {
        return other;
    }
}

The output from the serial ports for each case
working
creating an new tcp server
command echo : AT+CIPMUX=1

Data Are available
Data Received from ESP : AT+CIPMUX=1
2
Data Are available
Data Received from ESP : OK
0
10000
command echo : AT+CIPSERVER=1,23050

Data Are available
Data Received from ESP : AT+CIPSERVER=1,23050
2
Data Are available
Data Received from ESP : no change
2
Data Are available
Data Received from ESP : OK
0
10000
command echo : AT+CIFSR

Data Are available
Data Received from ESP : AT+CIFSR
2
Data Are available
Data Received from ESP : +CIFSR:STAIP,"192.168.1.16"
2
Data Are available
Data Received from ESP : +CIFSR:STAMAC,"5c:cf:7f:fd:ce:14"
2
Data Are available
Data Received from ESP : OK
0
10000

not working
creating an new tcp server
command echo : AT+CIPMUX=1

Data Are available
Data Received from ESP : AT+CIPMUX=1
2
Data Are available
Data Received from ESP : OK
0
98
command echo : AT+CIPSERVER=1,23050

10000
command echo : AT+CIFSR

Data Are available
Data Received from ESP : AT+CIFSR
2
Data Are available
Data Received from ESP : +CIFSR:STAIP,"192.168.1.16"
2
Data Are available
Data Received from ESP : +CIFSR:STAMAC,"5c:cf:7f:fd:ce:14"
2
Data Are available
Data Received from ESP : OK
0
224

I will leave this here in case anyone is interested. So i am communicating with the esp module at 9600 baud rate. After I send a command to the ESP I was waiting for its response before sending the next command without any delay.
What I found out is that for some reason although I was sending the command to the ESP the esp was not executing the command. So i added a delay(100) to see if the RX of the ESP was disabled during that time and i think i was correct since the commands were executed correctly.
I manage to get the delay down to delay(5). it Breaks after that.
I am using an Arduino micro and an ESP-01.

This may not be the answer you need if you are using it for something else, but if you are using a Micro, I would use the hardware serial Serial1 instead of SoftwareSerial. I've done many projects using a Leonardo (same processor) with ESP8266 as it gives me an extra hardware serial port which isn't connected to the Serial Monitor serial port.
I haven't tried the SoftwareSerial library for a few years, but I remember at the time that it doesn't handle duplex or high baud rates well.
What baud rate are you using? I couldn't see any begin in the code.
EDIT: You might also want to add the 'ATE0' command to turn off command echo.  The serial receiver is probably getting swamped with data.


text:
Program NOT responding to loop()- Arduino UNO+GSM + Sensor
I'm trying to monitor the sensor values (range 0-1000) connected to Arduino UNO's 12th-pin. If the value stays below say 500, then it should SEND SMS. I tested the sensor and GSM shield seperately and both of them are working fine. But my program is not giving the sensor reading in the serial monitor nor sending the SMS. I'm pretty sure it got stuck at sendRequest() part of the code.
// the setup routine runs once when you press reset:
#include "Adafruit_FONA.h"

#define FONA_TX 2
#define FONA_RX 3
#define FONA_RST 4

// this is a large buffer for replies
//char replybuffer[255];
char buffer[50];
char r[15];
// We default to using software serial. If you want to use hardware serial
// (because softserial isnt supported) comment out the following three lines
// and uncomment the HardwareSerial line
#include <SoftwareSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX,FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;
SoftwareSerial Sensor_Serial(12,13);

// Hardware serial is also possible!
//  HardwareSerial *fonaSerial = &Serial1;

// Use this for FONA 800 and 808s
//Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
// Use this one for FONA 3G
Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST);

uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);

uint8_t type;

byte readCO[] = {0xFF, 0X01, 0X86, 0X00, 0X00, 0X70};
byte response[] = {0,0,0,0,0,0};

//multiplier for value. default is 1.
int valMultiplier = 1;

void setup() {
  while (!Serial);

  Serial.begin(9600);
  Sensor_Serial.begin(9600);    //Opens the virtual serial port with a baud of 9600
  Serial.println(F("FONA basic test"));
  Serial.println(F("Initializing....(May take 3 seconds)"));

  fonaSerial->begin(4800);
  if (! fona.begin(*fonaSerial)) {
    Serial.println(F("Couldn't find FONA"));
    while (1);
  }
  type = fona.type();
  Serial.println(F("FONA is OK"));
  Serial.print(F("Found "));
  switch (type) {
    case FONA800L:
      Serial.println(F("FONA 800L")); break;
    case FONA800H:
      Serial.println(F("FONA 800H")); break;
    case FONA808_V1:
      Serial.println(F("FONA 808 (v1)")); break;
    case FONA808_V2:
      Serial.println(F("FONA 808 (v2)")); break;
    case FONA3G_A:
      Serial.println(F("FONA 3G (American)")); break;
    case FONA3G_E:
      Serial.println(F("FONA 3G (European)")); break;
    default:
      Serial.println(F("???")); break;
  }

}
void loop()
{
    sendRequest(readCO);
    float valCO = getValue(response);
    static unsigned long startTime = 0;
    if (valCO < 500)

   dtostrf(valCO, 3, 2, r); // I don't know how to covert the unsigned long variable to string and I know //this part does the float to string conversion
    sprintf(buffer, "%s High  Level", r);
    Serial.print("CO  = ");
    Serial.println(valCO);
    if (millis() - startTime > 1UL*60UL*1000UL) {  // Has it been 1 minute since the value was below 500?

      startTime = millis();
      fona.sendSMS("0XXXXXXX", buffer);
     }
  }

void sendRequest(byte packet[])
{
  while(!Sensor_Serial.available())  // If this part works the entire code works I think!!
//keep sending request until we start to get a response
  {
    //Sensor_Serial.write(readCO,9);
    delay(50);
  }

  int timeout=0;  //set a timeoute counter
  while(Sensor_Serial.available() < 9 ) //Wait to get a 9 byte response
  {
    timeout++;
    if(timeout > 10)    //if it takes to long there was probably an error
      {
        while(Sensor_Serial.available())  //flush whatever we have
          Sensor_Serial.read();

          break;                        //exit and try again
      }
      delay(50);
  }

  for (int i=0; i < 9; i++)
  {
    response[i] = Sensor_Serial.read();
  }
}

unsigned long getValue(byte packet[])
{
    int high = packet[2];                        //high byte for value is 3rd byte in packet in the packet
    int low = packet[3];                         //low byte for value is 4th byte in the packet

    unsigned long val = high*256 + low;                //Combine high byte and low byte with this formula to get value
    return val* valMultiplier;
}

OUTPUT:
.
.
.
.
FONA is OK
Found FONA 3G (European)
    ---> AT+GSN
    <--- 8XXXXXXXXXXXXXX
Module IMEI: 8XXXXXXXXXXXX
I guess this part of the is waiting for like ever and not returning any response
while(!Sensor_Serial.available())  //keep sending request until we start to get a response
  {
    Sensor_Serial.write(readCO,9);
    delay(50);
  }

Any help guys?

If I was you I would add a few more print statements to your code to prove that's where it is stopping.  It might be worth checking if pins 12 and 13 are reserved by the shields for something.

Yes inside the while loop it printed a statement.  I mean after  Sensor_Serial.write(readCO,9); Serial.print("CO ppm = "); OUTPUT: I can see the CO ppm=  and I have tested myself pin 12 and 13 they don't seem reserved by the GSM as I got the sensor output. But the code doesn't seem to work with the UART and SMS together...

You have multiple software serial ports and are expecting them to work like real ones.
They don't.
You can only have one of them "active" at a time (that is, ready to receive data). You need to switch between them with Sensor_Serial.listen() and fonaSerial->listen().
In general it is bad to have more than one SoftwareSerial (and personally I think even one is bad) since they are very heavyweight and block all other operations while they are either sending or receiving data (which means your listening one cannot operate at all while your non-listening one happens to be sending).
If you have a requirement for more than one serial port you should really be using a board that has more than one serial port.

In that case, to not use software serial ports I tried one of the four UART's on Arduino Mega for sensor. Can please tell me how do I connect my sensor to the RX0 and TX0. As I have tried assigning sensor pins as: SoftwareSerial Sensor_Serial(0,1); But that didn't make any difference. Please, any fix for this line of code as it is stopping the functioning of sensor's part - while(!Sensor_Serial.available())  as nothing works from this part on.

If you are using a real serial port then you do not try and map it to SoftwareSerial.  I believe T/Rx0 are called Serial, T\Rx1 is called Serial1 etc.

@LD_959 Firstly: do not use pins 0/1 - they are used by your existing Serial connection. Secondly: you must not use SoftwareSerial on pins you expect to be using as a real UART. That is just plain daft. Why use hardware serial pins as GPIO and then slap SoftwareSerial over the top? All UART pins have SerialX objects assigned to them. TX0/RX0 is Serial, TX1/RX1 is Serial1 etc.

Using Serial1 for the sensor worked perfectly. Thank you guys...!!

I have 3 sensors connected to other UART's of Arduino.. can you please tell me how do I print the output sensor readings in this format: CO1= val1   CO2=val2   CO3=val3

With multiple Serial.print() calls.


text:
How to map sensor analog output voltage
My sensor output voltage values ranges from 0.6 V - 3 V. How can I convert this voltage values to ppm in the range 0-1000? Upon exposure to CO gas: 0 ppm = 0.6 V , 500 ppm = 1.52 V and 1000 ppm = 3.01 V. Which means that the sensor cannot detect under 214 ppm (approx). Can you please help with mapping the sensor output values as ppm in the serial monitor? thnk u
// the setup routine runs once when you press reset:
    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue = analogRead(A0);
      // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
      float voltage = sensorValue * (5.0 / 1023.0);

      // print out the value you read:
      Serial.println(voltage);

    }

What do you mean by "sensor cannot detect under 214 ppm"? Do you have the link to the sensor's data sheet? If you are using the MQ-7 sensor, are you using a standalone unit, or with a breakout board? Have you calibrated the sensor?

link if you have a look at the data sheet, they said the analog output voltage is from 0.6-3V and sensor range is 0-1000. According to that, the sensor cannot read anything below 200ppm (0.6=20% of 3V). And I have calibrated the sensor and its giving me 1.52V for 500pm and 3.01 for 1000ppm. How can I print the ppm values equivalent of output voltages?

Fyi:  The value can be between 0 and 1023 so you want to divide by 1024, not 1023.

On page 4 of the datasheet,

Left side value of detection range (zero point) is corresponding to left side value of voltage output range,but right side value of detection(max detection value) is not corresponding to the right side value of voltage output range.

Thus, 0ppm would correspond to 0.6V, for CO. And 1000ppm does not necessarily correspond to 3V.
Assuming that 500ppm = 1.52V was obtained from the "inspection report", you now have two reference points, (0, 0.6) and (500, 1.52).
Further below on the same page, a formula for N is given, which, points towards a linear response of Vo with respect to ppm. Thus, you can use the map() function to do the linear mapping from voltage to ppm.
Note that map() only works with integers, so instead of mapping voltage (0.6 - 1.52) to ppm, you should directly map the analogRead value (123 - 311) to ppm to get better accuracy. Other wise, implement your own mapping using floats.

So are suggesting that I use expression like this: ppm= map (voltage, 0.6, 3, 0, 1000)? Based on my code. Also with regards to the formula mention in pg.4, for example say my Vo=1.5V then if I do the math value of N=600ppm rather than 500ppm that I tested with. Can you please write down your version of mapping voltage to ppm?

No. Use map(voltage, 0.6, 1.52, 0, 500). But since map() uses integer math, better use map(sensorValue, 123, 311, 0, 500).
Note that 123 * (5.0 / 1023.0) = 0.6 and 311 * (5.0 / 1023.0) = 1.52.

Your mapping function is working. Thank you so much!!!

In the main loop, sensorValue is assigned to store the raw analog value read from the potentiometer. Arduino has an analogRead range from 0 to 1023, and an analogWrite range only from 0 to 255, therefore the data from the potentiometer needs to be converted to fit into the smaller range before using it to dim the LED.
In order to convert this value, use a function called map():
outputValue = map(sensorValue, 0, 1023, 0, 255);

outputValue is assigned to equal the scaled value from the potentiometer. map() accepts five arguments: The value to be mapped, the low range and high values of the input data, and the low and high values for that data to be remapped to. In this case, the sensor data is mapped down from its original range of 0 to 1023 to 0 to 255.
The newly mapped sensor data is then output to the analogOutPin dimming or brightening the LED as the potentiometer is turned. Finally, both the raw and scaled sensor values are sent to the Arduino Software (IDE) serial monitor window, in a steady stream of data.
// These constants won't change. They're used to give names to the pins used:
const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0;        // value read from the pot
int outputValue = 0;        // value output to the PWM (analog out)

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
}

void loop() {
  // read the analog in value:
  sensorValue = analogRead(analogInPin);
  // map it to the range of the analog out:
  outputValue = map(sensorValue, 0, 1023, 0, 255);
  // change the analog out value:
  analogWrite(analogOutPin, outputValue);

  // print the results to the Serial Monitor:
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\t output = ");
  Serial.println(outputValue);

  // wait 2 milliseconds before the next loop for the analog-to-digital
  // converter to settle after the last reading:
  delay(2);
}

Few useful commands while mapping any analog output values:

map()
analogRead()
analogWrite()
serial()
AnalogInput - Use a potentiometer to control the blinking of an LED.
AnalogWriteMega - Fade 12 LEDs on and off, one by one, using an Arduino or Genuino Mega board.
Calibration - Define a maximum and minimum for expected analog sensor values.
/*
  Calibration

 Demonstrates one technique for calibrating sensor input. The sensor readings
  during the first five seconds of the sketch execution define the minimum and
  maximum of expected values attached to the sensor pin.

  The sensor minimum and maximum initial values may seem backwards. Initially,
  you set the minimum high and listen for anything lower, saving it as the new
  minimum. Likewise, you set the maximum low and listen for anything higher as
  the new maximum.

  The circuit:
  - analog sensor (potentiometer will do) attached to analog input 0
  - LED attached from digital pin 9 to ground

  created 29 Oct 2008
  by David A Mellis
  modified 30 Aug 2011
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Calibration
*/

// These constants won't change:
const int sensorPin = A0;    // pin that the sensor is attached to
const int ledPin = 9;        // pin that the LED is attached to

// variables:
int sensorValue = 0;         // the sensor value
int sensorMin = 1023;        // minimum sensor value
int sensorMax = 0;           // maximum sensor value

void setup() {
  // turn on LED to signal the start of the calibration period:
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);

  // calibrate during the first five seconds
  while (millis() < 5000) {
    sensorValue = analogRead(sensorPin);

    // record the maximum sensor value
    if (sensorValue > sensorMax) {
      sensorMax = sensorValue;
    }

    // record the minimum sensor value
    if (sensorValue < sensorMin) {
      sensorMin = sensorValue;
    }
  }

  // signal the end of the calibration period
  digitalWrite(13, LOW);
}

void loop() {
  // read the sensor:
  sensorValue = analogRead(sensorPin);

  // apply the calibration to the sensor reading
  sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);

  // in case the sensor value is outside the range seen during calibration
  sensorValue = constrain(sensorValue, 0, 255);

  // fade the LED using the calibrated value:
  analogWrite(ledPin, sensorValue);
}

Fading - Use an analog output (PWM pin) to fade an LED.
Smoothing - Smooth multiple readings of an analog input.

This Codes works for you :)
int SensorPin = A0;
int Readings;
int Min = 0;    // This is the Min reading of the sensor
int Max = 614; // This is the Max reading of the sensor
int Desired_Min = 0; // this is the desired number that you want converted with min reading of the sensor
int Desired_Max = 1000; // this is the desired number that you want converted with max reading of the sensor

void setup(){
 Serial.begin(9600);
 pinMode(SensorPin, INPUT);
 }

void loop(){
  Readings = analogRead(SensorPin);
  Readings = map(Readings, Min , Max, Desired_Min, Desired_Max);
   Serial.println("Mapped Value:"+Readings);

}

I Strongly prefer you to note the min and max reading Value of your sensor with arduino and replace the 'Min' and 'Max' according to that in the programm....


text:
GPS Receiver SKG13BL + Arduino - Having trouble receiving data
Here is my setup:
I'm trying to read the GPS data from SKG13BL which is connected to an Arduino Uno.
The GPS seems to be working fine as I could see the green status light blinks after a while (I think it takes time to fix the position).
I connected TTL of SKG13BL to UNO Digital pins 2 & 3 and connected the ground as well.
Here is the image of the connection:

I'm using the TinyGPS test with GPS device sketch to read the data. but I always get something like this,

**** **** *******  *******   **** *******    *******    **** ******* ****** ***** *   0        0.00   *   30862 0         116
  **** **** *******  *******   **** *******    *******    **** ******* ****** ***** *   0        0.00   *   30885 0         116
  **** **** *******  *******   **** *******    *******    **** ******* ****** ***** *   0        0.00   *   30929 0         117
  **** **** *******  *******   **** *******    *******    **** ******* ****** ***** *   0        0.00   *   30952 0         117
  **** **** *******  *******   **** *******    *******    **** ******* ****** ***** *   0        0.00   *   30985 0         117
  **** **** *******  *******   **** *******    *******    **** ******* ****** ***** *   0        0.00   *   31019 0         117
  **** **** *******  *******   **** *******    *******    **** ******* ****** ***** *   0        0.00   *   31041 0         117
  **** **** *******  *******   **** *******    *******    **** ******* ****** ***** *   0        0.00   *   31086 0         117
  **** **** *******  *******   **** *******    *******    **** ******* ****** ***** *   0        0.00   *   31109 0         117

I tried swapping the pins, using external power source instead of Arduino's  3.3, but there is no change in the result, any advice would greatly help.
Update 2/26
I changed the pin here to 10 & 11, and using this code
#include <SoftwareSerial.h>
#include <TinyGPS.h>

SoftwareSerial mySerial(10, 11); // RX, TX
TinyGPS gps; // create gps object

long lat,lon; // create variable for latitude and longitude object

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
    //gps.encode(mySerial.read());
    if(gps.encode(mySerial.read()))
      { // encode gps data
      gps.get_position(&lat,&lon); // get latitude and longitude
      // display position
      Serial.print("Position: ");
      Serial.print("lat: ");Serial.print(lat);Serial.print(" ");// print latitude
      Serial.print("lon: ");Serial.println(lon); // print longitude
      }

  }

}

But this only displays the below, lon and lat not coming up in the feed even after waiting for an hour.

$GPRMC,043721.000,A,1301.6666,N,07740.9169,E,0.13,343.86,260216,,,D*61
  $GPGGA,043722.000,1301.6666,N,07740.9169,E,2,7,1.36,902.9,M,-88.1,M,0000,0000*72 $GPGSA,A,3,10,31,18,11,193,14,22,,,,,,1.62,1.36,0.88*37
  $GPGSV,4,1,13,41,73,157,43,31,72,187,37,10,47,048,33,14,41,003,28*71
  $GPGSV,4,2,13,18,32,088,16,193,30,107,29,22,27,330,21,21,26,154,*46
  $GPGSV,4,3,13,27,18,238,12,25,15,087,16,26,13,180,,08,11,268,*7A
  $GPGSV,4,4,13,11,09,311,20*43
  $GPRMC,043722.000,A,1301.6666,N,07740.9169,E,0.26,343.86,260216,,,D*64
  $GPGGA,043723.000,1301.6665,N,07740.9169,E,2,7,1.36,902.9,M,-88.1,M,0000,0000*70 $GPGSA,A,3,10,31,18,11,193,14,22,,,,,,1.62,1.36,0.88*37
  $GPGSV,4,1,13,41,73,157,43,31,72,187,37,10,47,048,33,14,41,003,28*71
  $GPGSV,4,2,13,18,32,088,16,193,30,107,29,22,27,330,21,21,26,154,*46
  $GPGSV,4,3,13,27,18,238,12,25,15,087,16,26,13,180,,08,11,268,*7A
  $GPGSV,4,4,13,11,09,311,20*43
  $GPRMC,043723.000,A,1301.6665,N,07740.9169,E,0.33,343.86,260216,,,D*62
  $GPGGA,043724.000,1301.6664,N,07740.9170,E,2,7,1.36,902.9,M,-88.1,M,0000,0000*7E $GPGSA,A,3,10,31,18,11,193,14,22,,,,,,1.62,1.36,0.88*37
  $GPGSV,4,1,13,41,73,157,43,31,72,187,37,10,47,048,33,14,41,003,28*71
  $GPGSV,4,2,13,18,32,088,16,193,30,107,29,22,27,330,21,21,26,154,*46
  $GPGSV,4,3,13,27,18,238,,25,15,087,16,26,13,180,,08,11,268,*79
  $GPGSV,4,4,13,11,09,311,20*43

Updated code on 3/1
This one works perfectly and provides the latitude and longitude.
Thank you @slash-dev and @altinturk
#include <SoftwareSerial.h>
#include <TinyGPS.h>

SoftwareSerial mySerial(10, 11); // RX, TX
TinyGPS gps; // create gps object

long lat,lon; // create variable for latitude and longitude object

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {

char c = mySerial.read();
Serial.write( c );
if (gps.encode( c ))
      { // encode gps data
      gps.get_position(&lat,&lon); // get latitude and longitude
      // display position
      Serial.print("Position: ");
      Serial.print("lat: ");Serial.print(lat);Serial.print(" ");// print latitude
      Serial.print("lon: ");Serial.println(lon); // print longitude
      }

  }

}

Here is the output

$GPGSA,A,3,14,20,21,18,29,15,10,,,,,,2.59,1.13,2.33*0E
  $GPGSV,4,1,13,29,63,172,35,40,59,241,34,15,45,039,43,18,44,324,51*7A
  $GPGSV,4,2,13,21,42,350,46,10,27,284,46,24,27,116,19,14,25,209,17*76
  $GPGSV,4,3,13,20,24,037,46,193,23,064,39,25,10,180,16,26,08,268,*44
  $GPGSV,4,4,13,16,01,294,*42
  $GPRMC,003218.000,A,1301.6703,N,07740.9225,E,0.02,0.00,010316,,,D*6D
Position: lat: 1******8 lon: 7*****42

Seems you are able to receive data properly (according to your the update.) I was using TinyGPS++, an advanced version of TinyGps (http://arduiniana.org/libraries/tinygpsplus/), maybe those can help you:
Try
Serial.print("LAT=");  Serial.println(gps.location.lat(), 6);
Serial.print("LONG="); Serial.println(gps.location.lng(), 6);

GPS cannot get any data indoors. Put your gps close to a window or better -directly outside. First of everything you will get a date&time data on the output, then number of satellites, then the Lat/lon data. But GPS has to receive data indoors.
On some chips there is a LED starts blinking once it gets a fix from any satellite. Keep an eye on it.
I realized this small issue when my phone (used for "calibration") couldn't get a fix by its embedded GPS without any cell/network assistance. You should try if you get any signals where you put your device.

Hi Thank you for your response, Yeah I could see the Status LED starts blinking in green and the I kept the antenna outside of the window looking up to the sky. I believe I'm doing something wrong in the way I read the data.. or connecting the wires.

Check the answer :) I added some piece of code. I used tinyGPS++ but I guess these two are quite relevant.

Sorry about the late reply, Thanks a lot for your response, i will try with the tinygps++,

You are consuming the received characters with the debug print:
Serial.write(mySerial.read());
//gps.encode(mySerial.read());
if(gps.encode(mySerial.read()))

Instead, do this:
char c = mySerial.read();
Serial.write( c );
if (gps.encode( c ))

Also, SoftwareSerial is a real CPU-killer.  Try NeoSWSerial instead.  It's much more efficient and reliable.  Sometimes other interrupts, like Serial.print, can cause SoftwareSerial to be unreliable.  Echoing the received characters may be enough to cause characters to be lost.  NeoSWSerial is not nearly as susceptible.
And while you're at it, take a look at another library I wrote, NeoGPS.  It's the fastest and smallest library out there, especially when you configure it to only parse the fields and messages that you use.  For example, if you only need lat/lon, disable all the other fields (time, alt, speed, sats, etc.) and all the other messages (just RMC, no GGA, no GSA, no GSV).  Saves lots of RAM and CPU time!

Thank you , you nailed it down, i was loosing the information in the debug print, after correcting that able to get the lat and lan, posted the updated code. i will try with the NeoSWSerial as well,

@RamS: LOL, that green check is supposed to be for the answer that worked for you, so I'm not sure why you checked altinturk's answer.   The up and down arrows can be used by anyone like a vote.  The check is reserved for the Original Poster.  Cheers!


text:
Arduino Mega connect to 2.1 speakers
I am new to Arduino and I want to connect it to my 2.1 speakers and later to a 5.1 surround system.
The purpose is to play some wav sounds when a button is clicked or when a trip laser is cut. What should I do in order to play those wav around through the speakers? I also have an SD shield.

What have you tried so far? You need to divide your project into manageable blocks: Input, sound generation, reading wavs from SD card, etc. Which part(s) are you having trouble with?

i am having trouble making the speaker play the wav files i have in my SD. the speaker i have for test is an 8 Ohm speaker and when i finish with that i want to connect it to my 2.1 speaker system.

First, you need to figure out the bandwidth requirements and if this is possible at all. You need to do some basic calculations and answer the question if the Arduino and the different components have the bandwidth (byte/second) that is required.
The Arduino MCU (AVR) is too "weak" to do this on it's own. A special shield is required. Such as https://www.adafruit.com/products/1788
The Arduino Due has more processing power but still not stereo quality; https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer
More info to be googled.
Cheers!


text:
Problem with sending DMX
I want to send DMX with my Arduino Mega 2560. I'm using the IDE 1.6.7
I tried the AVR -> DMX source code from Ulrich Radig and also the layout for the RS-485 transmission.
I modified the code to fit the ATMega2560 but when I upload the code nothing happens.
The only thing I didn't do is to use the 22 Ohm resistors, is that a problem?
Any idea?
Here is my circuit:

Here is the source
#include <avr/interrupt.h>
#include <avr/io.h>
#include <stdio.h>

#define F_CPU 16000000
#include <util/delay.h>

#define DMX_BAUD 250000
#define DMX_BAUD_BREAK 80000
#define DMX_BAUD_BREAK_UBBR ((F_CPU+DMX_BAUD_BREAK*8)/(DMX_BAUD_BREAK*16)-1)
#define DMX_BAUD_UBBR ((F_CPU+DMX_BAUD*8)/(DMX_BAUD*16)-1)

volatile unsigned char dmx_buffer[512];

//############################################################################
//DMX Senderoutine
ISR (USART_TX_vect)
//############################################################################
{
  static unsigned int  dmx_channel_tx_count = 0;
  static unsigned char dmx_tx_state = 0;

  switch (dmx_tx_state)
  {
    case (0):
      UBRR0   = DMX_BAUD_BREAK_UBBR;
      UDR0 = 0; //RESET Frame
      dmx_tx_state = 1;
      break;

    case (1):
      UBRR0   = DMX_BAUD_UBBR;
      UDR0 = 0; //Start Byte
      dmx_tx_state = 2;
      break;

    case (2):
      _delay_us(10);
      //Ausgabe des Zeichens
      UDR0 = dmx_buffer[dmx_channel_tx_count];
      dmx_channel_tx_count++;

      if(dmx_channel_tx_count == 512)
      {
        dmx_channel_tx_count = 0;
        dmx_tx_state = 0;
      }
      break;
  }
}

void setup() {
 //Init usart DMX-BUS
 UBRR0   = DMX_BAUD_UBBR;
  DDRE |= (1<<PE1); //Output TXD Pin ATmega2560
  UCSR0B|=(1<<TXEN0)|(1<<TXCIE0); // TXEN0 Transmitter enable / TXCIE0 TX complete interrupt enable
  UCSR0C|=(1<<USBS0); //USBS0 2 Stop bits
  sei();//Globale Interrupts Enable
  UDR0 = 0;//Start DMX

}

void loop() {
  // put your main code here, to run repeatedly:
    dmx_buffer[4]=255;
    _delay_ms(1000);
    dmx_buffer[5]=255;
     _delay_ms(1000);
    dmx_buffer[6]=255;
    _delay_ms(1000);
    dmx_buffer[4]=0;
    _delay_ms(1000);
    dmx_buffer[5]=0;
     _delay_ms(1000);
    dmx_buffer[6]=0;
     _delay_ms(1000);

}

The resistors are probably required, as they are shown in the original circuit. When you say it does not work, what doesn't work exactly? Maybe try putting some debug statements in your code, which write to the serial monitor, to ensure that the setup(), loop() and ISR() functions are being called, as well as the expected case statements being executed.

The only thing I didnt do is to use the 22 Ohm resitors, is that a problem?

Yes, that's a huge problem. The resistors are there to prevent reflections from distorting the signal. Without them the best you can hope for is a garbled mess.

Well but it doesnt matter if I only use one  DMX device if i remember correcetly, right? I just want to get an output somehow for now.


text:
How can I make Arduino IDE use Atmel's provided toolchain? (Linux/Ubuntu)
I have an Arduino based board using ATmega168PB, but so far only Atmel's provided toolchain supports this microcontroller. I can download the toolchain from Atmel's website, but I am not sure how to make the Arduino environment use it.

In the directory for the new core create a new platform.txt and give the entry for compiler.path the location of the bin/ directory containing the Atmel toolchain.
compiler.path=/path/to/bin/


text:
Another traffic light project
I have a school project, where I'm going to make a traffic light system on a pls. I want to try it out on an Arduino first, just to get the hang of it.
To make it a little bit more advanced than I have found on the internet, I want to make the lights go in "emergency mode" if the green lights in both directions are on at the same time. It will then go into a yellow blink.
My idea is something like this:
// Yellow blinking if fault in the system or operator activates it
int killState = digitalRead(Kill);
int resState = digitalRead(Res);
if (killState == HIGH /*|| greenlights in both directions */) {
 while (resState == LOW;) { // Yellow blink as long as system is not reset
  BLINK();
 }
}

I guess I need a variable or two that tells what state the lights are in, but I'm stuck. Any good solutions out there?
Another thing is the reset button. I haven't put much effort in it, but I want it to go into the starting point.
The link to the complete script can be found here.

For starters, take a close look at this line:
while (resState == LOW;)

That is not the correct syntax. But the real issue is how is this while loop terminated? The value is never set again?
Cheers!

I guessed so. As I said, I haven't put much effort in it yet. I need to take one step at a time. Thanks for the quick reply, though!
The idea is that the state will not change until the reset button is activated. And the ' ; ' was a type-o.
I am new to 'while' and 'for' loops, but i think I'm starting to get the hang on 'if' and 'else' criterias.

You could do something simple to test if both red and green are on,  eg.
if (digitalRead (RED_PIN) == HIGH && digitalRead (GREEN_PIN) == HIGH)
  {
  digitalWrite (RED_PIN, LOW);  // turn off red
  digitalWrite (GREEN_PIN, LOW);  // turn off green
  while (true)
    {
    digitalWrite (YELLOW_PIN, HIGH);
    delay (500);
    digitalWrite (YELLOW_PIN, LOW);
    delay (500);
    }  // end of while
  }  // end of it

If you have other questions please post your code and not a snippet - however I suggest you try to get further on your own. This is obviously an exercise, and the more you try to work it out yourself the more you will learn.

Thanks! That was a good idea. I will add this to the script. I will add the full code next time. I added it as a link, though.

What is it that is true in the while (true) part?

true is true. That particular loop loops indefinitely. In other words, if there is some failure in the traffic lights, it will flash yellow ... forever. (Kind of a scary thought, eh?)

I could have written while (5 == 5) - it just means to do something forever.


text:
Adding fade to this RGB LED IMU
I've built an accelerometer based dice. It changes colour based on what side of the dice faces up. All is well and good, except I'd like the RGB to fade from one colour to the next instead of changes instantly.
Here's the code:
include <Wire.h>
include <Adafruit_Sensor.h>
include <Adafruit_LSM303_U.h>
include <Adafruit_9DOF.h>
include <Adafruit_L3GD20_U.h>

/* Assign a unique ID to the sensors */
Adafruit_9DOF                 dof   = Adafruit_9DOF();
Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);
Adafruit_LSM303_Mag_Unified   mag   = Adafruit_LSM303_Mag_Unified(30302);

// OUTPUT: Use digital pins 9-11, the Pulse-width Modulation (PWM) pins
// LED's cathodes should be connected to digital GND
int redLEDPin = 11;   // Red LED,   connected to digital pin 9
int greenLEDPin = 10;  // Green LED, connected to digital pin 10
int blueLEDPin = 9;  // Blue LED,  connected to digital pin 11

// Program variables
int red = 255;   // Variables to store the values to send to the pins
int green = 255;
int blue = 255;

int lastOrientation = -1; // previous orientation

void initSensors()
{
  if(!accel.begin())
  {
    Serial.println(F("No LSM303 detected"));
    while(1);
  }
  if(!mag.begin())
  {
    Serial.println("No LSM303 detected");
    while(1);
  }
}

void setup() {

  Serial.begin(115200);
  Serial.println(F("RGB Dice... go!")); Serial.println("");

  /* Initialise the sensors */
  initSensors();

  pinMode(redLEDPin, OUTPUT);   // sets the pins as output
  pinMode(greenLEDPin, OUTPUT);
  pinMode(blueLEDPin, OUTPUT);

  int lastOrientation = -1; // previous orientation
}

void loop() {

  /* Get a new sensor event */
  sensors_event_t event;
  accel.getEvent(&event);

  int orientation = - 1; // dice orientation
  String orientationString; // string for printing orientation
  /*
   * orientation:
   * 1: cyan
   * 2: blue
   * 3: green
   * 4: magenta
   * 5: yellow
   * 6: red
   */

  // read accelerometer
  int x = event.acceleration.x;
  int y = event.acceleration.y;
  int z = event.acceleration.z;

  // calculate absolute values, and determin largest
  int absX = abs(x);
  int absY = abs(y);
  int absZ = abs(z);

  if ( (absZ > absX) && (absZ > absY)) {

    //base orientation Z
    if (z > 0) {
      orientationString = "1, cyan";
      orientation = 1;
      red = 255;
      green = 0;
      blue = 0;

    } else {
      orientationString = "6, red";
      orientation = 6;
      red = 0;
      green = 255;
      blue = 255;
    }

  } else if ( (absY > absX) && (absY > absZ)) {

    //base orientation Y
    if (y > 0) {
      orientationString = "2, blue";
      orientation = 2;
      red = 255;
      green = 255;
      blue = 0;

    } else {
      orientationString = "5, yellow";
      orientation = 5;
      red = 0;
      green = 0;
      blue = 255;
    }
  } else {
    //base orientation X
    if (x > 0) {
      orientationString = "4, magenta";
      orientation = 4;
      red = 0;
      green = 255;
      blue = 0;

    } else {
      orientationString = "3, green";
      orientation = 3;
      red = 255;
      green = 0;
      blue = 255;

    }
  }

  // if orientation changes, print out a description
  if (orientation != lastOrientation) {
    Serial.println(orientationString);
    lastOrientation = orientation;
  }

  analogWrite(redLEDPin, red);   // Write values to LED pins
  analogWrite(greenLEDPin, green);
  analogWrite(blueLEDPin, blue);
  delay(100);

}

Every fading example I have adopted has broken the code so far. I guess my initial code isn't set up for it. Any ideas for a workaround?

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.

What have you tried so far? In each case, how did it break your code? What prevented you from modifying your code to get it to work?

You might get some inspiration here: https://hackingmajenkoblog.wordpress.com/2016/10/02/flexible-led-fading/

You need to be a little clearer about the time that can exist between the sensor values changing. If you fade to slowly the correct value might never be reached before the sensor changes again. Maybe that's what you want?
You can't use a delay().
You need a currentRed, currentGreen and currentBlue so you can fade to the values of red, green and blue.
unsigned long last_reading_ms;
int red = 255;   // Variables to store the TARGET rgb target values for each pin
int green = 255;
int blue = 255;
int currentRed = 0;   // Variables to store the current rgb values of the pins
int currentGreen = 0;
int currentBlue = 0;

void setup()
{
   last_reading_ms=millis();
}

void loop()
{
  /* read sensor every 100ms and set red, green,blue if changed */
  if (millis()-last_reading_ms > 100)
  {
    /* Get a new sensor event */
    sensors_event_t event;
    accel.getEvent(&event);
    //the rest of your sensor reading code here

    last_reading_ms=millis()
  }

  /* if orientation changes, print out a description */
  if (orientation != lastOrientation) {
   Serial.println(orientationString);
   lastOrientation = orientation;
  }

  calculateRGBFadeTo();

  analogWrite(redLEDPin, currentRed);   // Write values to LED pins
  analogWrite(greenLEDPin, currentGreen);
  analogWrite(blueLEDPin, currentBlue);

  //*** do not use a delay or use a very small one to slow the transition ***
  //delay(100);

}

/* get values 1 step closer to target red, green, blue */
void calculateRGBFadeTo()
{
  /* fade to required rgb values */
  if (currentRed<red)
   currentRed ++;
  else if (currentRed>red)
   currentRed --;

  if (currentGreen<green)
    currentGreen ++;
  else if (currentGreen>green)
    currentGreen --;

  if (currentBlue<blue)
    currentBlue ++;
  else if (currentBlue>blue)
    currentBlue --;

}

Notes:
The fade can be slowed down either with a small delay such as 5 ms. or by using another millis() variable to determine the time since the led was last set.
For example: if (millis()-last_rgb_write_ms > 5)
It's also possible to speed up the fade by using a larger increment. An increment of two, for example, currentRed+=2; instead of currentRed++;
Reminder, the comparison of when the target red, green, blue has been reached will be more complex with an increment greater than 1.
An increment of 2 and a sensor read frequency of 128ms (instead of 100) would ensure the correct RGB values are always reached. Alternatively reading the sensor every 255ms (4-5 times per second) would also ensure the correct RGB values has been reached.
Using millis() and avoiding delays allows many more tasks to be performed with more accurate timings.


text:
How to detect an read buttons pressure on touchscreen
I made simple 3 red buttons like this:
#include <SPI.h>

#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#include "URTouch.h"

#define TFT_DC 9
#define TFT_CS 10
#define TFT_RST 8
#define TFT_MOSI 11
#define TFT_CLK 13
#define TFT_IRQ  7

Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK,

#define t_SCK 3
#define t_CS 4
#define t_MOSI 5
#define t_MISO 6
#define t_IRQ 7

URTouch ts(t_SCK, t_CS, t_MOSI, t_MISO, t_IRQ);

void setup() {

  tft.begin();
  tft.fillScreen(BLACK);

  tft.fillRoundRect (12,15,30,80,5,RED);//50,100,30,80,5,RED
  tft.fillRoundRect (50,15,30,80,5,RED);
  tft.fillRoundRect (88,15,30,80,5,RED);

  delay(500);
}

And this the part where I need help:
void loop()
{
  int x, y;

  while(ts.dataAvailable())
  {
    ts.read();                //-----------> this is the whole thing
    x = ts.getX();
    y = ts.getY();

  }

What I need is, to know how to detect and read the pressure of the button area, so that I can run different tasks.

The fillRoundRect function format is (initial_Xpoint,initial_Ypoint,length,width,corner_radius,color)
Therefore, you already have the information about the location of the button itself. Next, check if the x and y value is within the button area.
void setup() {

  tft.begin();
  tft.fillScreen(BLACK);

  tft.fillRoundRect (12,15,30,80,5,RED);  //button1
  tft.fillRoundRect (50,15,30,80,5,RED);  //button2
  tft.fillRoundRect (88,15,30,80,5,RED);  //button3

  delay(500);
}

void loop()
{
  int x, y, pressedbutton=0;

  if(ts.dataAvailable())
  {
    ts.read();                //-----------> this is the whole thing
    x = ts.getX();
    y = ts.getY();

    if ((x>=12) && (x<=12+30) && (y>=15) && (y<=15+80)) pressedbutton = 1; else
    if ((x>=50) && (x<=50+30) && (y>=15) && (y<=15+80)) pressedbutton = 2; else
    if ((x>=88) && (x<=88+30) && (y>=15) && (y<=15+80)) pressedbutton = 3;
  }

  ...
  ...
  ...
 }

I'm not 100% sure what you ask, but I assume you want to perform a task depending on what button has been pressed.
You can do this by checking x and y, e.g.
switch (x)
{
case 0:
   switch (y)
   {
   case 0: // Button (0,0) is pressed)
      perform_task_A();
      break;
   case 1:
      perform_task_B();
      break;
   ... // etc.
   }
   break;
case 1:
   switch(x)
       // Etc. as above but use different tasks.

Than create for each task a function
void perform_task_A()
{
   // Do your code
}

If you want to change 'functionality' depending on a button press, e.g. assume perform_task_A should read a digit, than create a new switch statement there to read a digit key.
If you want more complicated menu structures/input entering, check into state diagrams to keep track where you are in the UI-flow and act on the current state AND the pressed button.