text:
When a pushbutton and sensor are in a certain state, do something for a certain period of time (15 seconds)
I have a sketch that contains code for an analog input (FSR sensor), a pushbutton, and 6 blinking LEDs.
Currently, the sketch is written to allow the LEDs to blink only when the button is pressed and there is sensor input.
Can someone help me write code to make the LEDs blink for a certain period of time once there is input from the analog sensor and while the button is pressed?  I am trying to make the LED blink for 15 seconds and then turnoff.
thank you!
/*
 6 Flashing LED Lights With A Pushbutton and FSR Sensor
*/

const int buttonPin = 8;
const int LedPin1 = 7;
const int LedPin2 = 6;
const int LedPin3 = 5;
const int LedPin4 = 4;
const int LedPin5 = 3;
const int LedPin6 = 2;

int buttonState = 0;
int SensorPin = A0;
int SensorPinReading;

void setup() {
  Serial.begin(9600);
  pinMode(LedPin1, OUTPUT);
  pinMode(LedPin2, OUTPUT);
  pinMode(LedPin3, OUTPUT);
  pinMode(LedPin4, OUTPUT);
  pinMode(LedPin5, OUTPUT);
  pinMode(LedPin6, OUTPUT);
  pinMode(buttonPin,INPUT);
  pinMode(SensorPin, INPUT);
}

void loop() {
  SensorPinReading = analogRead(SensorPin);
  Serial.print("Analog reading = ");
  Serial.print(SensorPinReading);

if (SensorPinReading < 10) {
  Serial.println(" - No Pressure");
} else if (SensorPinReading < 200) {
  Serial.println(" - Light Touch");
} else if (SensorPinReading < 500) {
  Serial.println(" - Light Squeeze");
} else if (SensorPinReading < 800) {
  Serial.println(" - Medium Squeeze");
} else {
  Serial.println(" - Big Squeeze");
}

  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH && SensorPinReading > 10)  {
  digitalWrite(LedPin1, HIGH);
  digitalWrite(LedPin2, HIGH);
  digitalWrite(LedPin3, HIGH);
  digitalWrite(LedPin4, HIGH);
  digitalWrite(LedPin5, HIGH);
  digitalWrite(LedPin6, HIGH);
  delay(600);
  digitalWrite(LedPin1, LOW);
  digitalWrite(LedPin2, LOW);
  digitalWrite(LedPin3, LOW);
  digitalWrite(LedPin4, LOW);
  digitalWrite(LedPin5, LOW);
  digitalWrite(LedPin6, LOW);
  delay(200);
  }
  else {
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }

}

Please edit your question (click "edit") and mark the 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.

The code shown below is to “make the LEDs blink like the previous sketch during the 15 seconds”.  The  previous sketch (that is, the code in the question) turns the LEDs on for 600 ms and off for 200.  The code below reverses the order – that is, does off for 200 and on for 600 – and repeats that pattern during the first 15 seconds after conditions being met.  The annoyingly complicated if statements in the code are to prevent retriggering; that is, to prevent another 15-second blink session immediately starting up if the trigger conditions are still present.  Your problem statement is not perfectly clear on how that should be handled.
// 6 Flashing LED Lights With A Pushbutton and FSR Sensor

enum { LedPin6=2, LedPin5, LedPin4, LedPin3, LedPin2, LedPin1 };
enum { buttonPin=8, SensorPin = A0};
enum { quantum=200, sessionLength=15000/quantum};

byte buttonState = 0;
byte SensorPinReading;
byte blinkLEDs=false, sessionDone=false;
unsigned long baseMilli;

void setLEDlevels(byte level) {
  digitalWrite(LedPin1, level);
  digitalWrite(LedPin2, level);
  digitalWrite(LedPin3, level);
  digitalWrite(LedPin4, level);
  digitalWrite(LedPin5, level);
  digitalWrite(LedPin6, level);
}

void setup() {
  Serial.begin(115200);
  pinMode(LedPin1, OUTPUT);
  pinMode(LedPin2, OUTPUT);
  pinMode(LedPin3, OUTPUT);
  pinMode(LedPin4, OUTPUT);
  pinMode(LedPin5, OUTPUT);
  pinMode(LedPin6, OUTPUT);
  pinMode(buttonPin,INPUT);
  pinMode(SensorPin, INPUT);
}

void loop() {
  SensorPinReading = analogRead(SensorPin);
  Serial.print("Analog reading = ");
  Serial.print(SensorPinReading);

  if (SensorPinReading < 10) {
    Serial.println(" - No Pressure");
  } else if (SensorPinReading < 200) {
    Serial.println(" - Light Touch");
  } else if (SensorPinReading < 500) {
    Serial.println(" - Light Squeeze");
  } else if (SensorPinReading < 800) {
    Serial.println(" - Medium Squeeze");
  } else {
    Serial.println(" - Big Squeeze");
  }

  buttonState = digitalRead(buttonPin);
  // Turn on 15-second blink session if conditions met
  if (buttonState == HIGH && SensorPinReading > 10)  {
    if (!blinkLEDs && !sessionDone) { // Is session eligible?
      blinkLEDs = true;
      sessionDone = false;
      baseMilli = millis();
    }
  } else {               // A condition failed.
    if (sessionDone)             // Has session finished?
      blinkLEDs = sessionDone = false; // Enable next session
  }

  if (blinkLEDs) {
    int age = (millis()-baseMilli)/quantum;
    setLEDlevels((age&3)>0);    // Off for 1 quantum, on for 3 quanta
    // See if blink session has run long enough
    if (age > sessionLength) {
      blinkLEDs = false;        // Stop blinking
      sessionDone = true;   // Prevent retrigger until conditions reset
      setLEDlevels(LOW);    // Turn off lights
    }
  }
}

The statement setLEDlevels((age&3)>0) calls setLEDlevels() with a parameter value of 0 or 1.  It will be 0 if age is a multiple of 4.  In binary, multiples of 4 have their lowest two bits clear.  It will be 1 if age is not a multiple of 4.  This will alternately turn the LEDs off for one quantum (200 ms) and then on for 3 quanta (600 ms).

Edit 1: To  “make the sensor read input while the button is not pressed, and then relay that input once the button is pressed so the LEDs immediately light up when it is pressed”, add a state variable (eg sensorPressed) to use in place of SensorPinReading > 10.  Whenever SensorPinReading is large enough (and any other necessary conditions are met), set sensorPressed.  When you start a blink session, reset sensorPressed (make it false).
Note, from your comment, you've added the following code near the end of loop():
if (buttonState == LOW && blinkLEDs == true) {
  blinkLEDs = false;
  sessionDone = true;
  setLEDlevels(LOW);
}

A minor issue with that code is it leaves sessionDone = true.  It is minor because the next pass through loop() usually will execute the else branch (of the if (buttonState == HIGH && SensorPinReading > 10) if-statement) which will go ahead and set sessionDone = false to enable the next blink session.  Assuming you want to shut down blinking whenever the button is low, what I would do instead of that little code block is this:
if (!buttonState) {
  blinkLEDs = sessionDone = false;
  setLEDlevels(LOW);
}

(The expression !buttonState has the same value as buttonState == LOW and is four syllables shorter.)
Note, the code perhaps can be made more clear by using a state machine to control what happens.  To do so, draw a diagram with nodes representing possible states – such as “idle” or “waiting for inputs”, “enabled”, “blinking”, “after blinking”.  Draw lines between states, each labeled with the condition that triggers the particular state transition.  State machines can be implemented using switch and case statements, or via an if–else sequence.

thank you so much! That is basically what I need, although I made one modification to your code...

if (buttonState == LOW && blinkLEDs == true)  {
blinkLEDs = false;
sessionDone = true;
setLEDlevels(LOW);                                                                                Thank you so much @jwpat7 ! Sorry about the unclear problem statement.  I added the above code at the end.  Now to complicate it a bit more.  I will explain best I can.  Is there any way to make the sensor read input while the button is not pressed, and then relay that input once the button is pressed so the LEDs immediately light up when it is pressed?  Either way thank you again!

@msquirrel, see edit 1

To “make the sensor read input while the button is not pressed, and then relay that input once the button is pressed so the LEDs immediately light up when it is pressed”... I changed the SensorPinReading to sensorPressed, but what type of statement would I use in the loop to meet the condition?  I tried similar if statements that did not work, and I'm unsure of how to set it up.

You still need to set SensorPinReading = analogRead(SensorPin) each pass thru loop.  Turn on sensorPressed whenever  SensorPinReading is high enough; turn sensorPressed off once you have used it to trigger a blink session.

Here below is modified code based on your requirement. There are some changes in your code and I also comment it out. I hope it will help you.
/*
 6 Flashing LED Lights With A Pushbutton and FSR Sensor
*/

const int buttonPin = 8;

const int LedPin1 = 7;
const int LedPin2 = 6;
const int LedPin3 = 5;
const int LedPin4 = 4;
const int LedPin5 = 3;
const int LedPin6 = 2;

const int kDelay = 1000; // Take one varible "kDelay" and value = 1000

int buttonState = 0;
int SensorPin = A0;
int SensorPinReading;

void setup()
{
  Serial.begin(9600);
  pinMode(LedPin1, OUTPUT);
  pinMode(LedPin2, OUTPUT);
  pinMode(LedPin3, OUTPUT);
  pinMode(LedPin4, OUTPUT);
  pinMode(LedPin5, OUTPUT);
  pinMode(LedPin6, OUTPUT);

  pinMode(buttonPin,INPUT_PULLUP); // Provide PULLUP
  pinMode(SensorPin, INPUT);
}

void loop()
{
  SensorPinReading = analogRead(SensorPin);
  Serial.print("Analog reading = ");
  Serial.print(SensorPinReading);

  if(SensorPinReading < 10)
  {
    Serial.println(" - No Pressure");
  }
  else if (SensorPinReading < 200)
  {
    Serial.println(" - Light Touch");
  }
  else if (SensorPinReading < 500)
  {
    Serial.println(" - Light Squeeze");
  }
  else if (SensorPinReading < 800)
  {
    Serial.println(" - Medium Squeeze");
  }
  else
  {
    Serial.println(" - Big Squeeze");
  }

  buttonState = digitalRead(buttonPin);

  if(buttonState == HIGH && SensorPinReading > 10)
  {
    digitalWrite(LedPin1, HIGH);
    digitalWrite(LedPin2, HIGH);
    digitalWrite(LedPin3, HIGH);
    digitalWrite(LedPin4, HIGH);
    digitalWrite(LedPin5, HIGH);
    digitalWrite(LedPin6, HIGH);
    delay(15 * kDelay);            // You need 15 Sec, multiply kDelay with 15
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }
  else
  {
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }
}

is there any way to make the LEDs blink like the previous sketch during the 15 seconds? @Hasan


text:
Issue with HC-SR505 sensor
I have been using a HC-SR501 PIR module with my Arduino Mega and it was tracking presence pretty well.
Because of cost constraints, I decided to go with HC-SR505 sensor - bought a bunch of them. The performance is very bad. It almost seems like it is giving random HIGH and LOW values. Out of the 20 odd sensors I bought, may be one or two are fairly ok - others are all behaving weird. Have someone experienced this kind of behavior with HC-SR505?
Are they highly sensitive to noise in the power supply - is there any workaround to mitigate the effect? Help?
Code:
const int buttonPin = 4;

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

   pinMode(buttonPin, INPUT);
 }
 void loop()
 {
    if (digitalRead(buttonPin) == HIGH)
    {

      Serial.println("Presence Detected");
    }
    else {

      Serial.println("No Presence Detected");
    }

 delay(2000);

 }

You asked if anyone else has experienced this behavior, and from the documentation I can find the answer must be yes.
The 505 holds the HIGH output for a certain amount of time.  None of the documentation I can find on it specifies the amount of time.  So it is very possible that you are operating right near that limit.  If their quality control is not perfect, some might work correctly and some might not.
In other words, I believe the problem is that you are not allowing for the built-in time delay in the SR505.
That is the main difference between the 501 and the 505.  On the 501 it is adjustable in both sensitivity and time delay.  With the 505 those values are preset.
As a workaround, you can try increasing your delay upwards from 2000ms until you find the right value that will work consistently with your batch of them.
The sensitivity cannot be adjusted, either, but this can be an advantage if you are trying to cover a smaller area than you would try with the 501.  They both have the same 90-100 degree width of view, but the 505 is made for shorter range like a doorway, as opposed to the 501 which can cover an entire room.

By shining with a bright light through the PCB, I came up with this reverse-engineered circuit diagram. From my understanding, the IC is some sort of special OP amp. I suppose one can change the timing by adjusting the 154 (150k) resistor and the sensitivity by adjusting the 335 (3.3Meg) and/or the 103 (10k) resistor.

According to this wiki: https://www.elecrow.com/wiki/index.php?title=HC-SR505_Mini_PIR_Motion_Sensor, there is an 8 second +/-30% delay.
The sensor is very sensitive to motion. Waving your hand in front of it "as fast as you can" (at close range) will trigger the sensor. While testing the two I had purchased, they had to be pointed away from me or there were "false alarms".

I had the same problem of the sensor giving random 1/0 values. I then looked at the circuit closer.
The PINs are badly marked which doesn't tell great detail, PIN-1 is marked with "+", however the word "OUT" is sitting between PINs 2 and 3.
If you connect + to the +5V, and then the middle PIN into the GND and then OUT into your Arduino (say PIN-10 of your Arduino), then you will notice ups and downs that does not correspond to any movements, (i.e. telling you "Bad Sensor")... however:

Part-1 of the solution:

Swapping PINs 2 and 3 of the sensor (i.e. + goes into +5V of Arduino, Ground is PIN-3 of the sensor, and Middle is what you should be reading (i.e. PIN-10 of Arduino)) then this should start to work, but we're not finished yet, you would still get bad results...

Part-2 of the solution:

If you are reading from PIN-10 of Arduino, then on your setup() function would usually be like this:
setup()
{
 pinMode(10, INPUT);
}

This is NOT enough for that sensor!... I know,... should be right?!...
Anyway, you MUST tell that PIN to be ZERO at the start, otherwise, it's hell brake loose... Therefore, please write the PIN with 0 and then it should all work fine after that:
setup()
{
    pinMode(10, INPUT);
    digitalWrite (10, LOW);
}

Following the above does resolve the issue, the sensor worked absolutely fine.
One annoying issue however which I am currently trying to work on is to reduce the sensor delay timer from 8 seconds into just 1-2 seconds, i.e. once someone is in-front of the sensor I don't want it to tell me that the person was there still when he left the area almost 7 seconds ago... I might post another article on how to do this later.
In the mean time, I hope this helps to resolve this problem
Regards
Heider

source: Stack Exchange

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

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

sort: votes


text:
How do I change number and bracket colors in the arduino IDE?
I recently personalized my arduino IDE (changed the background color, input text color, etc....) by going into the theme.txt file and replacing some hexadecimal values. I made the background black and the text lime green, but for some reason numbers and brackets still remain black, thus I can't see them against a black background. Anyone know how to fix this? I would really appreciate the help, got sick of looking at a white background when making sketches.
Sal

Inside path C:\Program Files (x86)\Arduino\lib\theme\syntax there is file default.xml where I made some changes and the following lines are as follows:
  <style token="SEPARATOR" fg="ffffff" />
  <style token="LITERAL_NUMBER_DECIMAL_INT" fg="ffffff"/>
  <style token="LITERAL_NUMBER_FLOAT" fg="ffffff"/>
  <style token="LITERAL_NUMBER_HEXADECIMAL" fg="ffffff"/>

After this brackets and numbers occur white.

Ok i found the file and what I need to change. However, my computer opens the file in internet explorer. Do I need some software to open and edit xml files? If so, any suggestions?

Copy file and paste it to your desktop. Right click and select open with WordPad. Save after edit. Copy and  paste to original place. You are asked for admin rights. Give right by clicking option. Restart IDE.

In some windows you can select right click on file and edit as admin user.

I figured it out, wish I would have read your comment just above first haha would have saved me some trouble. I wound up using Visual Studio to change it. Thank you so much though for all the help

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


text:
Evaluating delay for Xbee
I will explain my task in a simplified way. I'm communicating among 3 Xbee's.
The attached code is for the sender Xbee. This Xbee actually sends multiple values of value1 (here for simplification I assigned it to constant value 10). For finding the value1 it does some other calculations as well and then assigns it.
But I find that if I reduce or remove the delay(100) I end up receiving improper values. I guess delay gives a buffer time for data transmission but my question is how to do I calculate the minimum delay or how can justify that this is the delay needed ?
I hope you can understand my question. If not please comment I will give some more pertinent details.
  // Sender Xbee
    void setup()
    {
    Serial.begin(9600);
    }
    void loop()
    {
    int value1 = 10; // some hardcoded values to send
    Serial.print('H'); // unique header to identify start of message
    Serial.print(value1,DEC);
    Serial.print(","); // note that a comma is sent after the last field
    Serial.print('\n'); // send a cr/lf
    delay(100);
    }

If timing is critical (and assuming you do not want to loose any message), you probably need some notification back that the message has been received correctly (possibly with a checksum value).

Based on my experience with Xbee, I would say the limit is 50ms as Xbee can do the lowest sampling rate of 50ms.


text:
Arduino Due vs Mega 2560
What can an Arduino Due do that a Mega 2560 can't? What can a Mega 2560 do that a Due can't? I've heard the Due is 3.3V so it can't work with most shields.

Since the due uses a ARM chip instead of an AVR you might run into problems with certain libraries that only support AVR.

people like the mega because it's "more uno", while the due is trying to be a "faster uno" but jettisons much of the beloved uno cargo in doing so.

The 'R3' version boards and shields are compatible with 3.3V and 5V. For example the Ethernet Shield V1 version 'R3' can be used with the Due. The new Arduino Ethernet Shield 2 is also compatible with the Due.
Many older shield are not compatible with the Due, but do you really need to use an old shield ?
Most sensors are 3.3V, and also a SD memory card is 3.3V. That is a lot easer with the Arduino Due which runs at 3.3V.
The Arduino Mega 2560 board is the only board with 10k pullup resistors at SDA and SCL, therefor it has a 5V I2C bus. When a 3.3V sensor with I2C is used, you need a I2C level shifter. When a 3.3V with SPI is used, you need more hardware.
The Arduino Mega pins can drive more than 20mA, it can be used to drive 10 leds with 20mA simultaneously, the Arduino Due can't do that.
My suggestion is to use an Arduino Uno for all kind of testing. It's always good to have one lying around. Start with an Arduino Uno if you want to learn programming and have fun with leds and buttons.
The Arduino Zero or MKRzero or M0 have a M0+ processor at 3.3V and they can be used for all kind of nice projects. When you already know a little about programming and electronics, this is a very good choice.
The Arduino Due has more processing power then the M0+.
The Arduino Mega 2560 is still used, because there are many libraries and shields that are compatible with the Arduino Mega 2560.

The Due can do a lot of things much faster. It has more memory and far more processing power. It has more flexible and more powerful built-in peripherals.
It can't easily interface with 5V devices though.
The Mega2560 has less memory and far less processing power, but interfacing with legacy 5V devices is far easier. It's also more forgiving to the novice user than the more complex SAM3X chip.
From an Arduino programming point of view both boards are pretty much programmed the same. The language is, excepting a few esoteric anomalies, largely the same. However when you come to do low-level programming instead if relying on the Arduino API you would find that the ATMega2560 is a much simpler chip to program.  Power comes at a price. The more powerful SAM3X chip is much harder to get to grips with and program.
It's like comparing a Ford Escort with a Boeing 737. They're both vehicles, and they can both get you from A to B. The Boeing does it much faster and can carry more people, but flying it is a lot harder than driving a Ford Escort, and you can't fly it on an old-fashioned road.

Ahhhh... There is a more profound problem than these mentioned because the MEGA treats double precision declarations as floating point ( far less precision ).  I was working with 1 CM GPS Location coordinates requiring double precision variables.  It took a while for me to discover that ONLY the DUE compiles to a true double precision variable.  The MEGA and most others do not.  They convert double to float at compiler level.  This is only meaningful if extremely precise math must occur.
Donald


text:
How do I send HTTP request using ESP8266 to other port than 80?
I currently have a working connection to my ESP8266 module.
However, I can only connect to a server using the port 80, is it possible to choose a different port?
I can connect using AT+CIPSTART="TCP","192.168.122.46",80,
but I get an ERROR CLOSED when using AT+CIPSTART="TCP","192.168.122.46",8090 for example
Also, how do I send an HTTP request using the AT+CIPSENDcommand?
UPDATE: Stupid me, it was just Firewall blocking it...

Are you certain there is a port open and listening on 8090 at the target machine, and it's bound to the right outward-facing interface?

It was just firewall blocking in


text:
Arduino Nano, nodeJS serial
I tried to make a 2 way communication between my Arduino and a PC(running linux mint) using NodeJS:
My Arduino code:
void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()) Serial.println(Serial.readString()+"\r");
}

My NodeJS code:
var SerialPort = require('serialport');
var port = new SerialPort('/dev/ttyUSB0',{
  baudRate: 9600,
  parity: 'none',
  stopBits: 1,
  flowControl: false,
  parser: SerialPort.parsers.readline('\r\n')
});

port.on('open',function(){
  setInterval(() => port.write('Test'),1000);
});

port.on('data',(data) => console.log(data.toString()));

There is possible encoding error, but I cannot seem to find and fix this. Thanks in advance

What error do you get?

Basicly it outputs "TestTestTest" with random length

What's more if I use Arduino code to send the data like Serial.println("Test"), and use readline('\n') I get correct results

Weird. For me, Arduino's Serial.println() plays well with serialport's readline("\r\n").

Is this your code, or the above?

You don't need to revert to sending single bytes. Line oriented
protocols work well with both Arduino and Node.js. The only difficulty
is that you have to decide what line terminators you want to use, and
then consistently use them.
I tend to use CR for the PC → Arduino stream and CRLF for Arduino
→ PC. Using different line terminators is kind of odd, but this
convention plays well with terminal emulators: the emulator usually
sends CR when you hit <Enter>, and expects CRLF in return. Also,
Arduino's Print::println() sends CRLF.
Here is a simple test demonstrating this convention. Node.js side:
var SerialPort = require('serialport'),
    port = new SerialPort('/dev/ttyACM0', {
        baudRate: 9600,
        parser: SerialPort.parsers.readline('\r\n')
    });

port.on('open', () => setInterval(() => port.write('Test\r'), 1000));
port.on('data', console.log);

Notice the different line terminators in readline() and write().
The Arduino side:
void setup() {
    Serial.begin(9600);
}

void loop() {
    static char buffer[128];
    static size_t pos;

    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\r') {                       // line terminator
            buffer[pos] = '\0';                // terminate the string
            Serial.print(F("Arduino received: "));
            Serial.println(buffer);            // echo received message
            pos = 0;                           // reset buffer position
        } else if (pos < sizeof buffer - 1) {  // regular character
            buffer[pos++] = c;                 // buffer it
        }
    }
}

Here you may notice that Arduino has no equivalent of
parsers.readline(), so I had to implement it (comparing the incoming
character to '\r'). Note that explicit buffering of the incoming
message is a standard way of handling line-oriented protocols on
Arduino. Stream::readString() does not work well for this purpose, as
it waits for incoming bytes until it times out.
Stream::readStringUntil() may work better, but I prefer to avoid it
just because it returns a String, which relies on heap allocation.

Well, this code works great, but you forget that the content of the "previous" buffer stays in the array, which results in results like: "Arduino received: Testest"

@Berrigan: Oops! I forgot to properly terminate the string. Fixed. Now it works. The previous content of the buffer is now irrelevant, as only the contents before the first '\0' is considered to be part of the "string". After a complete string is received, the buffer is reset by the statement pos = 0;.

Ok, I solved the issue by using pure bytes, and then casting the response to the string in nodeJS, I post the codes in case anyone needs them:
var SerialPort = require('serialport');
var port = new SerialPort('/dev/ttyUSB0',{
  baudRate: 9600,
  parity: 'none',
  stopBits: 1,
  flowControl: false,
//  parser: SerialPort.parsers.readline('\r\n')
});

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}

port.on('open',() => {
  setInterval(() => port.write('Test'),500);
});

port.on('data',(data) => {
  console.log(ab2str(data));
});

And the Arduino code:
void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()) Serial.write(Serial.read());
}


text:
Middle school Student stuck and needs help
I have a middle school student who is having problems getting her pollution sensor to work when asked to. I have attached her document to this post. Can anyone help her fix the issue?
int conductivitySensorValue; //initialize an integer variable to hold the sensor reading

void setup() {
Serial.begin(9600); //start serial communications so we can print the reading out

}

void loop() {
  conductivitySensorValue = analogRead(A0); //gat the integer representation of the sensor reading

  float voltage = conductivitySensorValue*(5.0/1023.0); //put the data in terms of our voltage (5 volts)

  Serial.println("The Conductivity is" + voltage); //print the current reading to the serial port
}

Arduino: 1.8.2 (Windows 7), Board: "Arduino/Genuino Uno"

C:\Users\sushmit\Documents\Arduino\sketch_apr19a\sketch_apr19a.ino: In function 'void loop()':

sketch_apr19a:13: error: invalid operands of types 'const char [20]' and 'float' to binary 'operator+'

   Serial.println("The Conductivity is" + voltage); //print the current reading to the serial port

                                          ^

exit status 1
invalid operands of types 'const char [20]' and 'float' to binary 'operator+'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

End copy.......

Please edit your question (click "edit") and mark the 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. ¶ Add a few blank lines between the end of the code and the beginning of the error messages.

Try Serial.println(String("The Conductivity is ") + voltage); or simply Serial.print(F("The Conductivity is ")); Serial.println(voltage);

Welcome to Arduino SE.  Please take a minute to view the tour:  https://arduino.stackexchange.com/Tour - there are tips in there about how to format your questions.

Your post reads as if you are a teacher.  I would have expected a teacher to understand this issue, maybe you ought to do some revision.  If you are the student why hide?

Serial.println("The Conductivity is" + String(voltage)); works and is readable, though there's more efficient ways with lower level code.

You can't add a string literal and a number together.
Instead you either have to convert one or both into a format that can be joined, or just treat them as separate entities. The simplest way is:
Serial.print(F("The Conductivity Is: "));
Serial.println(voltage).

Note the use of F(...) around the string literal - that forces it to stay in Flash so it doesn't waste RAM. Maybe not an issue with this project, but a good habit to get into nonetheless.

This is how I do it (although I didn't know about the F part) - Serial.print will do the conversion implicitly.  No need to do any conversions in your code.


text:
Arduino Mega 2560 SoftwareSerial Not Working
We have an xBee Pro S2C that is using this library (https://github.com/andrewrapp/xbee-arduino) very well on a Software Serial connection to ports 2 and 3 on an Arduino Uno. However, when we take the same setup and try it on a Arduino Mega 2560 using any of the ports specified here:
*
https://www.arduino.cc/en/Reference/SoftwareSerial

Not all pins on the Mega and Mega 2560 support change interrupts, so
  only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51,
  52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14
  (68), A15 (69).

*
We cannot get this setup to work on the Arduino Mega 2560. We did not try every combination of these ports but tried most of them and it continues to fail. We can get successful packets on an Uno on pins 2 and 3.
Code is as follows:

#include "Arduino.h"
#include "laser_essentials.h"
#include "XBee.h"
#include <SoftwareSerial.h>
#define IS_STAR 1
#if IS_STAR

#define rxPin 10 //input
#define txPin 11 //output
#else
#define rxPin 2 //input
#define txPin 3 //output
#endif
#include "SoftReset.h"

///setup xbee object

XBee xbee = XBee();
SoftwareSerial xBeeSerial = SoftwareSerial(rxPin, txPin);

//Setting up class & contructors

Laser::Laser () {

        pinMode(rxPin, INPUT);
        pinMode(txPin, OUTPUT);
        xBeeSerial.begin(9600);
        xbee.setSerial(xBeeSerial);
        Serial.begin(9600);

Any thoughts as to why this might not work on a Arduino Mega?

Does the Mega work at all? Can you flash an LED with it?

Yes, we have tried some basic sketches and all seem to perform fine on it.  In addition, we have the same issue on a completely different Mega, so we must be doing something wrong.

Why use software serial in the first place? A Mega has multiple hardware serials.

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


text:
SoftwareSerial response is semi-gibberish using ESP8266
I have a working SoftwareSerial connection to my ESP8266 module on my Arduino UNO board. However, the response I get from the ESP8266 using the SoftwareSerial library is semi-gibberish.
So I do get the correct response, but some characters are changed.
For example when I ask the IP of the module, it sometimes returns the right IP, but most of the times just alters the IP, for example 092.168/123.5.
So what am I doing wrong?
This is the code I'm currently using:
#include <SoftwareSerial.h>

SoftwareSerial esp8266(10, 11);

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Started");
}

void loop() {
  if (esp8266.available()) {
    Serial.println(esp8266.readStringUntil("\n"));
  }
  if (Serial.available()) {
    esp8266.write(Serial.read());
  }
}

When I send the AT command, I sometimes get OK□ or some other extra random characters.
So how do I make the SoftwareSerial show (or receive) the correct response?

You never call begin on software serial.

How do you convert logic level Arduino UNO (5V) and ESP8266 (3.3V)?

@AltAir, I don't, the board accepts a logic level of 5V

Try lowering your baudrate to 9600.
https://blogs.msdn.microsoft.com/abhinaba/2016/01/23/esp8266-wifi-with-arduino-uno-and-nano/

Thank you, however I tried chaning the baudrate to 9600 by sending AT+IPR=9600 but I couldn't talk to it on rate 9600. I can't talk to it on any rate anymore... So what would the best way be to change that modules baud rate?

You need to send that command at the baud rate the ESP8266 is expecting. The default is 115200.

The command I used AT+IPR=9600 bricked the flash, but I tried it on a different ESP8266, used the AT+CIOBAUD=9600 and everything started to work! I can now read it without any gibberish, thanks!


text:
How can I learn to use Generic ESP8266 boards Libraries in Arduino?
I am new to ESP8266. I am using the Arduino IDE to program the ESP8266-01 module. How can learn to make my own codes for ESP using Arduino?
I am going through the example programs and learning which part of the code does what. But, is there a better way to understand the syntax of those libraries.
Thanks!!

there's not much to learn; it's like an UNO with some extra libs built-in...

They publish a reference page for the included libraries at each release of the ESP8266 core for Arduino. The latest at this time is here:
http://esp8266.github.io/Arduino/versions/2.3.0/doc/libraries.html
You can adjust that URL for the release version you're using.
The libraries try to follow the API of the standard Arduino libraries and that documentation mostly focuses on the differences. So you will also find some documentation for these libraries in Arduino's library reference pages:
https://www.arduino.cc/en/Reference/Libraries
and the reference pages for the Arduino core API:
https://www.arduino.cc/en/Reference/HomePage
Of course the definitive (albeit less beginner friendly) reference will always be the source code. There are two ways to quickly determine the location of the source code for a library:
Option 1:

Select the appropriate board from the Tools > Board menu. The Arduino IDE may select the library to be used based on which board is selected.
File > Examples > {library name} > pick any example
Sketch > Show Sketch Folder. This will open the {library name}/examples/{example name} folder. The source files for the library will be found in the library root folder, src folder, or utilities folder.

Option 2:

File > Preferences > Show verbose output during: > compilation (check) > OK
Write or open a sketch that includes the library.
Sketch > Compile/Verify
Wait for the compilation to finish.
Examine the contents of the black console window at the bottom of the Arduino IDE window. The path to any library used by the sketch will be found in that output.


text:
High power consumption of ATmega32u4 when connected to iOS device
Just wondering if I can get some help here.
I have a simple scheme of MIDI controller based on ATmega32u4:
ATmega32U4 with TXLED and RXLED as output pins and USB functionality
And my team wants me to make this device Android/iOS compatible (because our Arduino prototypes worked fine with iPads and even iPhones).
I am experiencing a high power consumption of ATmega32u4 when connected to iOS devices. When we connect our device to iOS we get the following message:

Meanwhile, when I make almost the same scheme and run the identical sketch on ATmega328 chip it works just fine!
I tried running all the stuff on Arduino boards, and the result is stable:

works on Arduino Uno and Arduino Mega (based on ATmega328 chip);
doesn't work on Arduino Micro and some of its Chinese clones like Arduino Micro Pro (based on ATmega32u4).

We've found a small trick/workaround: connect even two our ATmega32u4 devices through an active USB hub with additional power supply to one iPad, and they both work perfectly, then we switch off the additional power on the hub, and devices continue to work fine using the power from this single iPad without any messages about high power consumption.
This case leads me to the thought that high consumption of ATmega32u4 chip appears only on the device initialisation stage.
Is there a way to solve this?
Thanks in advance.

It would help if you provide a schematic or summary of the power supply/distribution on your device.  What is connected and how much current does it use? How much capacitance is connected? Also, you could get a lot of useful information about power-on transients with an oscilloscope and a current probe.

The schematic is available through the first link provided. Basically, I have no any power-eager devices, it is just digital inputs, even with no analog inputs available. When I leave only diode matrix, the problem stays the same. That is why I consider that the problem in ATmega32u4 chip rather than schematic (the same schematic with ATmega328 chip works fine).

Moreover. If I disconnect all of the input switches and potentiometers leaving just plain Arduino Micro clone with basic MIDI device sketch, connected iOS device complains about high power consumption. Arduino Uno (ATmega328 based) device is working fine here.

If it's too much trouble for you to add a schematic to your question, I'd guess it'll probably be too much trouble for some to bother trying to answer it.

do you have big caps on there that cause a high inrush current that a powered hub doesn't mind supplying?

The idea of questions on SE is that they are self-contained and meaningful without having to look at external links that may vanish later

The major difference between ATmega32u4 and ATmega328 is that the former has USB functionality built in, while the latter requires an external USB to UART chip. When such UART chips go through enumeration, they will tell the host that they only consume 100 mA or less, because they have no idea what else you have on the board. ATmega32u4 however can potentially consume up to 200 mA (sinking 100 mA through each of the IO banks). Maybe it's requesting that current from the host when you connect it, and your phone refuses to power up a device requesting more than 100 mA of current.
You can connect your controller to a computer and check USB properties to confirm this.


text:
Arduino Due DAC pins with 0V
I know the DACs on the Arduino Due only allow for a range of output voltages from 1/6*Vdd to 5/6*Vdd (see here). This suits my needs, for the most part.
My question is if it is possible to have 0V on the DAC pins by, for example, switching the DACs of completely, or using them as normal digital out pins. I'd like to do this without the need for any external hardware or circuitry.
I googled for solutions but found none.

The DAC is port B15 and B16 so yes, it is possible to disable the DAC and use those pins as normal GPIO pins. Not sure how you would do it though, if the Arduino definitions have those pins set up for GPIO or not (away from my computer at the moment).

It's apparently not possible. This answer covers the topic very precisely. https://arduino.stackexchange.com/a/25843/16623


text:
SAMD21 Programming with Atmel ICE Fail to Write
I am trying to program my Adafruit M0 with the SAMD21G18 chip with Atmel studio and the Atmel ICE programmer. I have pin 1 on the ICE connected to 3.3V on the M0, pin 2 connected to SWDIO, pin 4 to SWDCLK, pin 10 to Reset, and pins 3, 5, and 9 to ground. This was all according to the ARM SWD connection section of the Atmel ICE manual. In Atmel Studio, I can read the device signature, but when I go to program the chip, I get the following error:
Timestamp:      2017-04-20 22:03:32.563
Severity:       ERROR
ComponentId:    20100
StatusCode:     131103
ModuleName:     TCF command: Modules:writeToMemory failed.

Failed to write segment at 0x0 to target for memorytype

I have searched the internet for hours, finding no solution to this problem.

Whats is the fuse setting of NVMCTRL_BOOTPROT?
it should be:
NVMCTRL_BOOTPROT = 0x07
which will set your memory location to 0x00 (no bootloader).
NVMCTRL_BOOTPROT sets the amount of space to allocate for the bootloader in flash memory. Setting this fuse to 0x07 tells the chip you are not allocating space for a bootloader and the programmer will start to write at address 0x00, which is the beginning of flash memory. If you are programming with an Atmel ICE, you are not using a bootloader.

Worked like a charm! Thanks! Did you find this in the Atmel ICE manual?

Happy to help. No in the Samd21 datasheet. There is a whole section on NVM and boot allocation.


text:
Converting a message received in char buffer to integer
I am receiving a message from my mobile to my microcontroller via GSM. The message is in a char buffer, but I want to convert it to an integer as I want to perform some mathematical operations on it. I tried many functions such as atoi, toint but it's not working. Please let me know if there is any way in which I could do this conversion.

int x = String( chars ).toInt() works if nothing else...

You'd better post your char buffer content here. There is a chance it might contain something can't be converted into integer.

i am only sending integer data such as 242,etc

"not working" is not an useful description of a problem.

atoi should have worked.  If it didn't then you have some other mistake.  If you'll post the code that you were using then that would make it possible for someone to try to spot the problem and help you.

atoi() is the simplest way:
int val = atoi(buf);

If that doesn't work then your buffer doesn't start with the number you are after. If that is the case you will have to work out where in the buffer the number is and convert just that portion. How you do that depends on what the format of the data is in your buffer.


text:
Arduino Simon Says with Midi Controller
I altered code for the Simple Simon says to work with a Midi controller instead of push buttons. i am having trouble with the input of the song sequence with the Midi Controller. during the time where the code is waiting for input from the Midi controller waitForButton(int delay) the notes being inputted should sound but it dose not . i need help in figuring this out. any advice would be appreciated. Here's my code :https://pastebin.com/dV73eF9U
const int PLAY = 1;
const int TRYAGIN = 2;
long currentMillis = 0;
long previousMillis = 0;
int state;
void songlearn(int tune);
void showsequence();
void readsequnce();
void incorrect();
int tune;

void loop() {
  if (state == PLAY) {
    showsequence();
    readsequnce();
  }
  else if (state == TRYAGIN) {
    incorrect();
    state = PLAY;
  }
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
  data1 = MIDI.getData1();
  if (data1 == 48) { //C3
    Status[0][0] = 1;
    noteOn(0, data1, 100);
    input[0] = data1;
  }
  if (data1 == 49) { //C3#
    Status[0][1] = 1;
    noteOn(0, data1, 100);
    input[1] = data1;
  }
  if (data1 == 50) { //D3
    Status[0][2] = 1;
    noteOn(0, data1, 100);
    input[2] = data1;
  }
  if (data1 == 51) { //D3#
    Status[0][3] = 1;
    noteOn(0, data1, 100);
    input[3] = data1;
  }
  if (data1 == 52) { //E3
    Status[0][4] = 1;
    noteOn(0, data1, 100);
    input[4] = data1;
  }
  if (data1 == 53) { //F3
    Status[1][0] = 1;
    noteOn(0, data1, 100);
    input[5] = data1;
  }
  if (data1 == 54) { //F3#
    Status[1][1] = 1;
    noteOn(0, data1, 100);
    input[6] = data1;
  }
  if (data1 == 55) { //G3
    Status[1][2] = 1;
    noteOn(0, data1, 100);
    input[7] = data1;
  }
  if (data1 == 56) { //G3#
    Status[1][3] = 1;
    noteOn(0, data1, 100);
    input[8] = data1;
  }
  if (data1 == 57) { //A3
    Status[1][4] = 1;
    noteOn(0, data1, 100);
    input[9] = data1;
  }
  if (data1 == 58) { //A3#
    Status[2][0] = 1;
    noteOn(0, data1, 100);
    input[10] = data1;
  }
  if (data1 == 59) { //B3
    Status[2][1] = 1;
    noteOn(0, data1, 100);
    input[11] = data1;
  }
  if (data1 == 60) { //C4
    Status[2][2] = 1;
    noteOn(0, data1, 100);
    input[12] = data1;
  }
  if (data1 == 61) { //C4#
    Status[2][3] = 1;
    noteOn(0, data1, 100);
    input[13] = data1;
  }
  if (data1 == 62) { //D4
    Status[2][4] = 1;
    noteOn(0, data1, 100);
    input[14] = data1;
  }
  if (data1 == 63) { //D4#
    Status[3][0] = 1;
    noteOn(0, data1, 100);
    input[15] = data1;
  }
  if (data1 == 64) { //E4
    Status[3][1] = 1;
    noteOn(0, data1, 100);
    input[16] = data1;
  }
  if (data1 == 65) { //F4
    Status[3][2] = 1;
    noteOn(0, data1, 100);
    input[17] = data1;
  }
  if (data1 == 66) { //F4#
    Status[3][3] = 1;
    noteOn(0, data1, 100);
    input[18] = data1;
  }
  if (data1 == 67) { //G4
    Status[3][4] = 1;
    noteOn(0, data1, 100);
    input[19] = data1;
  }
  if (data1 == 68) { //G4#
    Status[4][0] = 1;
    noteOn(0, data1, 100);
    input[20] = data1;
  }
  if (data1 == 69) { //A4
    Status[4][1] = 1;
    noteOn(0, data1, 100);
    input[21] = data1;
  }
  if (data1 == 70) { //A4#
    Status[4][2] = 1;
    noteOn(0, data1, 100);
    input[22] = data1;
  }
  if (data1 == 71) { //B4
    Status[4][3] = 1;
    noteOn(0, data1, 100);
    input[23] = data1;
  }
  if (data1 == 72) { //C5
    Status[4][4] = 1;
    noteOn(0, data1, 100);
    input[24] = data1;
  }
}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {
  data1 = MIDI.getData1();
  if (data1 == 48) { //C3
    Status[0][0] = 0;
    noteOff(0, data1, 100);
    input[0] = 0;
  }
  if (data1 == 49) { //C3#
    Status[0][1] = 0;
    noteOff(0, data1, 100);
    input[1] = 0;
  }
  if (data1 == 50) { //D3
    Status[0][2] = 0;
    noteOff(0, data1, 100);
    input[2] = 0;
  }
  if (data1 == 51) { //D3#
    Status[0][3] = 0;
    noteOff(0, data1, 100);
    input[3] = 0;
  }
  if (data1 == 52) { //E3
    Status[0][4] = 0;
    noteOff(0, data1, 100);
    input[4] = 0;
  }
  if (data1 == 53) { //F3
    Status[1][0] = 0;
    noteOff(0, data1, 100);
    input[5] = 0;
  }
  if (data1 == 54) { //F3#
    Status[1][1] = 0;
    noteOff(0, data1, 100);
    input[6] = 0;
  }
  if (data1 == 55) { //G3
    Status[1][2] = 0;
    noteOff(0, data1, 100);
    input[7] = 0;
  }
  if (data1 == 56) { //G3#
    Status[1][3] = 0;
    noteOff(0, data1, 100);
    input[8] = 0;
  }
  if (data1 == 57) { //A3
    Status[1][4] = 0;
    noteOff(0, data1, 100);
    input[9] = 0;
  }
  if (data1 == 58) { //A3#
    Status[2][0] = 0;
    noteOff(0, data1, 100);
    input[10] = 0;
  }
  if (data1 == 59) { //B3
    Status[2][1] = 0;
    noteOff(0, data1, 100);
    input[11] = 0;
  }
  if (data1 == 60) { //C4
    Status[2][2] = 0;
    noteOff(0, data1, 100);
    input[12] = 0;
  }
  if (data1 == 61) { //C4#
    Status[2][3] = 0;
    noteOff(0, data1, 100);
    input[13] = 0;
  }
  if (data1 == 62) { //D4
    Status[2][4] = 0;
    noteOff(0, data1, 100);
    input[14] = 0;
  }
  if (data1 == 63) { //D4#
    Status[3][0] = 0;
    noteOff(0, data1, 100);
    input[15] = 0;
  }
  if (data1 == 64) { //E4
    Status[3][1] = 0;
    noteOff(0, data1, 100);
    input[16] = 0;
  }
  if (data1 == 65) { //F4
    Status[3][2] = 0;
    noteOff(0, data1, 100);
    input[17] = 0;
  }
  if (data1 == 66) { //F4#
    Status[3][3] = 0;
    noteOff(0, data1, 100);
    input[18] = 0;
  }
  if (data1 == 67) { //G4
    Status[3][4] = 0;
    noteOff(0, data1, 100);
    input[19] = 0;
  }
  if (data1 == 68) { //G4#
    Status[4][0] = 0;
    noteOff(0, data1, 100);
    input[20] = 0;
  }
  if (data1 == 69) { //A4
    Status[4][1] = 0;
    noteOff(0, data1, 100);
    input[21] = 0;
  }
  if (data1 == 70) { //A4#
    Status[4][2] = 0;
    noteOff(0, data1, 100);
    input[22] = 0;
  }
  if (data1 == 71) { //B4
    Status[4][3] = 0;
    noteOff(0, data1, 100);
    input[23] = 0;
  }
  if (data1 == 72) { //C5
    Status[4][4] = 0;
    noteOff(0, data1, 100);
    input[24] = 0;
  }
}

//Send a MIDI note-on message.  Like Pressing a piano key
void noteOn(byte channel, byte note, byte attack_velocity) {
  talkMIDI( (0x90 | channel), note, attack_velocity);
}

//Send a MIDI note-off message.  Like releasing a piano key
void noteOff(byte channel, byte note, byte release_velocity) {
  talkMIDI( (0x80 | channel), note, release_velocity);
}

//Plays a MIDI note. Doesn't check to see that cmd is greater than 127, or that data values are less than 127
void talkMIDI(byte cmd, byte data1, byte data2) {
  mySerial.write(cmd);
  mySerial.write(data1);
  //Some commands only have one data byte. All cmds less than 0xBn have 2 data bytes
  //(sort of: http://253.ccarh.org/handout/midiprotocol/)
  if ( (cmd & 0xF0) <= 0xB0)
    mySerial.write(data2);
}

void playNote(int midi, int row, int col, int len, bool short_led = false)
{
  int len1, len2;
  if (short_led) {
    len1 = len * 3 / 4;
    len2 = len * 1 / 4;
  } else {
    len1 = len;
    len2 = 0;
  }
  noteOn(0x90, midi, 100);
  digitalWrite(LedR[row], HIGH);
  digitalWrite(LedC[col], LOW);
  delay(len1);
  digitalWrite(LedR[row], LOW);
  digitalWrite(LedC[col], HIGH);
  delay(len2);
  noteOff(0x90, midi, 0);
}

void songlearn (int tune) {
  if (tune == 1) {

    lcd.clear();
    lcd.setCursor(4, 0);
    lcd.print("Learning Song :");// Print a message to the LCD.
    lcd.setCursor(1, 1);
    lcd.print(menuP1);

    //Plays Mary Had a Little Lamb on a loop at 145 BPM

    //Bar 1
    note[0] = 0x40;
    note[1] = 0x3e;
    note[2] = 0x3c;
    note[3] = 0x3e;
    //Bar 2
    note[4] = 0x40;
    note[5] = 0x40;
    note[6] = 0x40;
    //Bar 3
    note[7] = 0x3e;
    note[8] = 0x3e;
    note[9] = 0x3e;
    //Bar 4
    note[10] = 0x40;
    note[11] = 0x43;
    note[12] = 0x43;
    //Bar 5
    note[13] = 0x40;
    note[14] = 0x3e;
    note[15] = 0x3c;
    note[16] = 0x3e;
    //Bar 6
    note[17] = 0x40;
    note[18] = 0x40;
    note[19] = 0x40;
    note[20] = 0x40;
    //Bar 7
    note[21] = 0x3e;
    note[22] = 0x3e;
    note[23] = 0x40;
    note[24] = 0x3e;
    //Bar 8
    note[25] = 0x3c;
    //End song
  }
}

void (*SongSeq[x])() =
{ //Bar 1
  [] { playNote(0x40, 3, 1, 414); } ,//Quarter note: E
  [] { playNote(0x3e, 2, 4, 414); } ,//Quarter note: D
  [] { playNote(0x3c, 2, 2, 414); } ,//Quarter note: C
  [] { playNote(0x3e, 2, 4, 414); } ,//Quarter note: D
  //Bar 2
  [] {playNote(0x40, 3, 1, 414, 1);} , //Quarter note: E
  [] {playNote(0x40, 3, 1, 414, 1); }, //Quarter note: E
  [] {playNote(0x40, 3, 1, 828, 1); }, //Half note: E
  //Bar 3
  []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
  []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
  []{playNote(0x3e, 2, 4, 828, 1);}, //Half note: D
  //Bar 4
  []{playNote(0x40, 3, 1, 414);}, //Quarter note: E
  []{playNote(0x43, 3, 4, 414, 1);}, //Quarter note: G
  []{playNote(0x43, 3, 4, 828, 1);}, //Half note: G
  //Bar 5
  []{playNote(0x40, 3, 1, 414);}, //Quarter note: E
  []{playNote(0x3e, 2, 4, 414);}, //Quarter note: D
  []{playNote(0x3c, 2, 2, 414);}, //Quarter note: C
  []{playNote(0x3e, 2, 4, 414);}, //Quarter note: D
  //Bar 6
  []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
  []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
  []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
  []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
  //Bar 7
  []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
  []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
  []{playNote(0x40, 3, 1, 414);}, //Quarter note: E
  []{playNote(0x3e, 2, 4, 414);}, //Quarter note: D
  //Bar 8
  []{playNote(0x3c, 2, 2, 1656);}, //Whole note: C
  //End song

};

void showsequence() {
  //Add a new index to the end of the songseq
  SongSeq[largestindex];
  largestindex++;
  //loop through the songseq
  for (int index = 0; index < largestindex; index++) {
    SongSeq[index]();
  }
}

void readsequnce() {
  bool mademistake = false;
  int key;
  for (int index = 0; index < largestindex & mademistake == false; index++) {
    key = waitForButton(5000);
    if (key == -1 | key != note[index]) {
      mademistake = true;
      SongSeq[index]();
      SongSeq[index]();
      state = 2;
    }
  }
}

int waitForButton(int delay)
{
  int keyPressed = -1;
  int check;
  boolean keyBackUp = false;

  currentMillis = millis();      // The number of ms since the program started running
  previousMillis = currentMillis;   // Records the point when we start spinning the loop.

  // Keep spinning the loop until "delay" seconds have passed.
  while (currentMillis - previousMillis < delay & keyBackUp == false)
  {
    // Read the button and record when it has been pushed down.
    for (int i = 0; i < 25 & keyBackUp == false; i++)
    {
      if (input[i] != 0)
      {
        keyPressed = input[i];

        // Show the LED pushed.
        noteOn(0, keyPressed, 100);
        //  digitalWrite(leds[pin], HIGH);

        // It is possible the button is still being pushed.
        // This loop spins until the button is let up.
        while (currentMillis - previousMillis < delay & keyBackUp == false)
        {
          check = input[i];
          if (check == 0)
          {
            keyBackUp = true;
          }
          currentMillis = millis();
        }

        // Turn the LED pushed off.
        noteOff(0, keyPressed, 0);
        // digitalWrite(leds[pin], LOW);

        // See if they took to long.
        if (currentMillis - previousMillis > delay)
        {
          keyPressed = -1; // They took to long to let the button up so they lose.
        }
      }
    }

    currentMillis = millis();

  }

  return keyPressed;
}

Include the properly formatted code into the question. And your incomplete code is missing two }.

the proper code has been added

Please run your code through the formatter in the Arduino IDE. It's very difficult to read right now due to poor formatting, that discourages people from reading enough of it to answer your question. (It certainly discouraged me! I gave up trying to read it.) It's worth spending time on making your posts easy to read if you want people to take the time to answer.

@CurtJ.Sampson thanks for letting me know i set the auto format in the arduino IDE. i hope its easier to read now.

It's considerably better, but there are still some things you should do manually, such as adding blank lines between functions. (I've submitted an edit for that.) Now that I can read it, I can see that the code is incomplete: for example you have no init() function, no definitions of state or Status, PLAY, TRYAGIN, etc. You really need to cut down the program to much smaller size (e.g., by removing most of the keys) and post the complete smaller version. Also, you say you altered some code; where is the original code?

@CurtJ.Sampson the Original code : https://gist.github.com/anonymous/58f817ed9b9b8b155d51a49c015370b9

I notice that nothing in the code you posted calls the MyHandleNoteOn() function, which is the only thing that reads MIDI data in the code you posted.
The waitForButton() function where you say you're having the problem never does any input or output, it simply checks to see if something else has changed the input array. MyHandleNoteOn() above does change it.
This leads me to believe that code you haven't posted sets up an interrupt handler that calls MyHandleNoteOn() (and probably MyHandleNodeOff()). If that doesn't mean anything to you, the main problem here is that the program is a bit beyond your abilities and you need to start learning on something simpler. If it does mean something to you, the problem here is that the program is rather badly written and you need to write something simpler to practice using interrupts and shared memory communication.
Have you written simpler programs before that read MIDI events, do a bit of processing, and play back things based on that? Building a Simon Says game on top of that would be a good learning project.

yes i have written simpler programs for midi. the MyHandleNoteOn() &  MyHandleNodeOff() both are functions from the midi library  and are called when the keys on the midi controller are pressed.

Did your MIDI code use in-memory communication between interrupt handlers and your main loop? If not, you want to write some simpler programs that do that first, if you're going to use that technique. Alternatively, you could write a Simon Says game on top of non-interrupt-driven code that uses wait-loops (which would look quite different from the above). Either way, if you have further questions, pare your code down to the bare minimum that demonstrates the problem so that others can load it up and run it.

maybe my approach is off  how would you go about it ?

Start as small and as basic as I could, and then expand from there.


text:
Molex power with USB serial Communication from the same PSU
Before I begin I just want to apologize for my mediocre understanding of things electrical and arduino. I know there are a lot of topics similar to this but I'm confused by the term external PSU
Question
Do I need to worry about any sort of issues (loops/grounding) if I use the molex connector to supply power to my arduino uno and continue to use the USB for serial communication at the same time? The source of both would be from the same PSU in my PC.
From what I understand the Uno when powered by DC should not exceed 7.5V for maximum efficiency. So it looks like the 5V from the molex would be more suitable than the 12V and sufficient for my needs of roughly 3.6A (60mA per LED * 60). Since USB can only supply a maximum of 2.0A and Molex appears to supply up to 5.0A from what I've read.
And I would connect it like so 5V molex powered Uno?
Background
Currently I'm using the arduino uno to power a single 5V strip of 30 rgb WS2812B leds, which works great when powered through the USB port, but since I need an additional strip of 30 leds and USB alone cannot supply enough amperage to power both I need a better source of current. I also needed the cleanest solution possible as it's for a PC tower and I don't want to use an external power source.
Edit - Alternative solution
If you have an Arduino board with USB, simply power the Arduino from your PC's USB via a standard cable and the LED strips from the Molex. The only connection between these two would need to be GND and led strip data line. No need to share a 5V between the LEDs and the Arduino

I think the Molex and the USB should have a common ground (The PC, The mains, etc), but why not just add one just to make sure?

USB is rated to supply only 500 mA. Some charging adapters, and occasionally computer USB ports, will supply more, but that should not be counted on unless you're doing the proper detection (which is manufacturer-dependent) to confirm that you can do that.

Oh, and I'd forgotten, there's also a 500 mA polyfuse on the USB input of the Uno, so even if your USB port can supply more than 500 mA, it makes no difference.

Post your own solution as an answer, not as an edit to the question.

Two important things first:

The Uno 5 V pin and power bus must never be supplied more than 5.5 V or the MCU may die. The DC power input jack (the barrel jack) and the Vin pin, which are connected together, are not directly connected this bus, which is why you can supply higher voltages to that (see below).
You can not simultaneously supply power via both the USB cable and a power supply to the 5V pin/5 V bus because that would directly connect the two power supplies. That's a very bad thing, and probably not just for the Uno. (But there is a trick you can use here to still connect USB data when you are supplying power to 5V; see below.)

Now on to the details.
You can safely connect Vin (the pin or the barrel jack; they are directly connected) and USB at the same time because there's a switch (T1 on the schematic) on the board that will disconnect the USB power line from the Arduino 5V bus if more than 3.3 V is being supplied to Vin.
However, Vin goes through a regulator which, while it has the advantage of safely handling voltages much higher than 5 V, also causes some voltage drop, so you need to supply it with a minimum of 7 V. (6 V might work if there's very little power draw; 5 V almost certainly will not.) The maximum voltage you should supply is 20 V, but it's recommended that you stick to 12 V or less, since higher voltages mean that the regulator can get rather hot.
Unfortunately for you, this doesn't really help with your problem. While you could take the 12 V power off the molex connector, supply it to Vin and run the Arduino itself quite happily with the USB cable also connected, the regulator on Vin is rated for only 1 A, which is considerably less than you need for the entire system.
There are ways to have some parts of the system powered by one power supply and other parts powered by a separate power supply, but they're not trivial (and also beyond my expertise at the moment :-)).
Probably the easiest solution is to connect the 5 V output from the molex connector to your system power bus, which would be supplying both the 5V pin on the Arduino and your external components, and then build a custom USB cable with only the D+ and D- pins connected, dropping the power and ground pins. (You don't need the ground pin because the USB data signal is actually a differential signal: the difference or similarity in the voltage between D+ and D- pins is what determines whether the signal is a 1 or a 0.)
By the way, just to make sure, you do have some separate switching for all those LEDs, right? You're not trying to provide all their power via the Arduino digital outputs? Because, as per section 32.1 of the ATmega328P datasheet, while you are allowed to sink up to 40 mA from any individual data pin, you cannot sink more than 200 mA in total from the chip.

Wow thank you for such a detailed and well thought out explanation. Really appreciate that since, I know very little. To answer you question about the LEDs I'm not entirely sure how to answer it best. This is the project I'm using as an example for mine. https://github.com/CalcProgrammer1/KeyboardVisualizer right now there is no switching on my led strips connected to the digital output, ground and the 5V pin that I am aware of. Seems to run fine with just the 1 strip of 30 LEDS so I'm assuming that the strip itself is handling this?

I'm marking you answer as the correct answer. But I have discovered an easier way which wouldn't require a custom USB cable, I could simply power the Arduino from my PC's motherboard USB header via a standard cable and the LED strip from the Molex seperately. The only connection between these two would need to be GND and led strip data line I believe. So I would never need to try share a 5Vs connection between the 2 components.

If you have an Arduino board with USB, simply power the Arduino from your PC's USB via a standard cable and the LED strips from the Molex. The only connection between these two would need to be GND and led strip data line. No need to share a 5V between the LEDs and the Arduino


text:
Powering an USB to Serial from USB
I am creating a PCB which is a modification of the Arduino on a breadboard. I am intending to buy an USB to Serial breakout from Adafruit so that I can upload my sketches to the atmega 328 I'll be using.
However, in order to reduce power consumption (later I want to run my circuit by using some AA batteries), I would like to turn off the USB to Serial breakout. I thought originally about adding a SPST switch to disconnect it when not using it, but I wonder if it is possible to power it from the USB (whenever I connect something) instead of having to connect its VCC header to the circuit's 5v power.
Is it possible to do that? Or is there any other way I to accomplish this that I'm not thinking of?
UPDATE: For clarity sake, I will explain my design choices: I want this circuit to power some peristaltic pumps that work on 12V. Thus, I'm providing 12V for the pumps and using a regulator to lower the voltage to the circuit. I don't see this is a huge problem for power consumption because the circuit will be in low-power 98% of the time, only waking up one minute per hour. Sometimes, it will run on batteries, which is the reason I wanna eliminate the USB-to-Serial. However, when connected to a power adaptor, I want the USB to be available.
All the best,
Francis

Why not make it so you can plug in the usb-to-serial, only when you need it? Add some female headers to the breakout, and some male headers to your board. PS if you want good battery life using the 7805 regulator isn't the best.

@CurtJ.Sampson: Thanks. Do I really need the DTR? On the breadboard link above, they are not using it.

@Gerben: That is a very good idea, actually! Simple and nice. My only concern is that the board will get a bit "taller" than it should be, and it will be harder in case I make a custom case to it. But it is definitely worth considering! As for the 7805, you are right, and I considered it, but the circuit will run on LowPower mode most of the time, so I guess it won't make that difference.

The 7805 has a quiescent current of around 5mA. So that alone will drain an AA in around 20 days. As for the headers. There are also right angled headers. So you can plug in the module from the side.

@francisaugusto: You need DTR only if you want to have the PC auto-reset the Arduino when uploading sketches. If you don't mind having to push the reset button manually when you do this, you can leave off DTR.

This is a good, specific question about how to do a particular thing. However, you mention that your general aim is to reduce power consumption and, in a comment below, that you're supplying 12 V power to the Arduino side of the system. This changes things a lot, and rather than try to deal with that here I suggest you ask another question, giving more details about the whole system (including everything connected to it, and ask the general question about how you can reduce its power consumption.

You might be overthinking this. As Gerben points out in the comments, you might want to consider pluging in the USB to Serial breakout board only when required, instead of making it a permanent part of your prototype.
I do this myself in two ways, depending of what I need.
Option 1:
When I foresee a lot of debbuging through the Serial Monitor, I use a permanent pin header so I can attach and dettach the breakout board easily.
In this case I use a right angle pin header so as to keep a low profile. Like in this Arduino Pro Mini:

Option 2:
When I just need to upload the sketch to the Arduino and I know that I won't be using the breakout board from that moment on, I don't solder the pin header in place.
Instead, I've modified another breakout board using pogo pins (spring test probes):

This modified board is what I use to upload the code to the Arduino without any pin header whatsoever. Something like this (I've taken the picture just for illustrative purposes):

Thanks Enric! Those are very good ideas. I think I will do something on those lines, but I still think that maybe using a button to turn the usb on and off can be a better alternative. That, or running the usb chip by, well, using usb power.

That is not easy to do. You could try diodes and mosfets as switches, but one way or the other, there will probably some leakage current. The 6N137 requires power for the receiving signal.
Other common optocouplers might have leakage current in the nA range for the transistor output. That might be possible. Connect the GNDs. The RX and TX via optocouplers. DTR to RESET with 100nF as usual. Maybe you don't need extra inverters when the transistor outputs are used as emitter followers.
Could you make your project with the ATmega328P without the usb-to-serial module ? The Arduino Pro Mini does not have a usb-to-serial either.
Now that I mention the Arduino Pro Mini: Instead of making an Arduino compatible circuit with a ATmega328P, you could also buy a Arduino Pro Mini 8MHz, and remove the voltage regulator and the power led. Then you have the same thing.
That breadboard Arduino tutorial has +5V connected to AREF. Please don't do that. Keep AREF open, or connect a capacitor of 100nF to it to reduce some noise for analogRead.
In the deepest sleep mode, the ATmega328P can run more than a year on three AA batteries. The timer of the WatchDog can be used to wake up.
The voltage of the three AA batteries is directly connected to the VCC of the ATmega328P, without voltage regulator.
A very good tutorial about power saving is this: Nick Gammon about power saving

Thanks @jot! Answering your questions: Yes, I do need the USB-to-serial to be connected, as I'll change the sketches sometimes, and, when connected to power, I want to be able to transfer data from the sensors to a connected RaspPi. When on battery, I want it to be disconnected, and that's why I ask. Since there's some voltage on the USB cable, I wish I could use it instead of the circuit's. My project will use 12V (8AA batteries), so that's why I need the regulator. I will power other connected stuff that requires 12V (before the Voltage Regulator, of course).

As for the AREF, I will do very simple and quick reading. Other than the noise, will it be a problem to connect the 5V to it?

You should have mentioned the 12 V thing in your main post! You definitely want to avoid using the on-board regulator if you're concerned about running for a long time on batteries. That's throwing away far more power than a powered-but-quiescent USB/Serial chip would.

francisaugusto When the internal voltage reference is selected with AREF connected 5V, it will cause an internal shortcut. It's just wrong, don't do it. @CurtJ.Sampson You are so right, powering a ATmega chip with 12V is not low power, and makes this whole question and all answers trivial.

Have a look at this one: https://www.pololu.com/product/2843 It has 200µA quiescent current. I'm not saying that it is a good solution, because we have no know the whole circuit and its function, because everything has changed now that 12V is used.

@CurtJ.Sampson and Jot: I updated the question with a better description. As I explain there, I assume that because I will be running the circuit in lowpower mode 98% of the time, the voltage regulator won't be a big deal.

Using separate power supplies at the same time for different parts of your system is a bad, bad idea; you never want two separate power supplies potentially pushing current at each other. Using separate +5V power sources for different chips but sharing a common ground across the device and connecting just data lines is problematic, too; as far as I know it's not trivial to do safely. Unless you really know what you're doing, full isolation between separately powered components is the way to go.
The two parts of the system we're talking about here, the USB-Serial converter and the rest of the system, exchange digital data only, and that at only three points, all of which are unidirectional: serial TX, serial RX and DTR. (DTR, when pulled low by the PC, resets the Arduino). Therefore if we can isolate these links not to exchange current when they communicate, we can separately power the devices on each side of this isolation barrier.
This is actually a common problem in things like power supplies (where we want data from the high-voltage side sent to the low-voltage side but don't want the risk that someone touching the low-voltage side could get electrocuted) and motor control boards (where the motors often use a separate power supply from the controller logic to reduce noise passed into the controller logic). One common solution is to use opto-isolators (also called optocouplers). Typically these use an LED and a sensor looking at it from across a gap; when the LED is lit up by one side, the other side sees it and generates a current.
The 6N137 (as used in this answer) or similar chip should work for this: 10 MHz is plenty of bandwith to run a 115,200 baud serial link. Each opto-coupler would be powered by the receiving side (Arduino for its RX and DTR, USB-serial for Arduino's TX) and on the other side you'd connect data to the VF+ pin and ground to the VF- pin. As per note 1 on page 4, you'll need caps at the power supply inputs, and you'll have to add inverters as well if you use this particular opto-isolator, since it inverts the signal; a 74HC04 will give you six of those. If you want to save a dollar, you could not bother to connect the DTR line and just reset the Arduino manually when you want to upload a program, if that's not too inconvenient.
Consumer warning here: I've not actually built this circuit (though I'd like to give it a try one day), so there could be something I'm missing here. (Hopefully someone more expert than me will speak up if that's the case.)
If you're going to be spending any significant amount of time connected to USB power and your whole system can run on less than 500 mA (the limit of the USB supply from many PCs), you may want to consider powering the entire system from USB while it's connected. This can be done in a way similar to how the Arduino Uno board disconnects USB power when receiving power on Vin: switch it with a comparator and a MOSFET.

Thanks a lot! I will have that in mind. It seems to be that the best option so far is to just put an SPST button on the circuit to turn the board on and off. But I got curious: how do I get power from USB using the adapter I'm planning to use?


text:
how to move my robot to the assigned coordinates
I am working on an ground surveillance robot using an Arduino mega for programming, am using components like the HMC5883L compass, Adafruit GPS for assigning of coordinates (latitude and longitude) which are the way points, I have written up the code for both the compass and the GPS and am able to get information from them, but now what I want for my robot to move to those specified coordinates (latitude and longitude waypoints) which I don't know how to do please do pardon me for asking such question cause I am new to coding GPS and compass and I would appreciate it if anyone could help me out or explain a bit in details what I need to do please find my code here http://textuploader.com/drqwv

Do you remember your high school trigonometry lessons?

@Majenko yes I do remember

Then you know where you are, and you know where you want to be. Between you is a right angle triangle. Calculate the angle of the hypotenuse turn to that angle, and drive to your destination.

yes I am aware of how to do that cause I have already done it in my code (Turning Calculation) what I need to know is how to write the code that to move the robot in-respect to the coordinates

You have code to turn left and right already. How far to turn I guess is the question. You have the angle you want, and you have a compass. There's multiple ways of working out how long to turn for. Experimentation may give you a specific time-per-degree, or you could turn some amount and see how far it actually turned then use that to calculate how long to turn for the rest of the turn. Then just drive straight until you're there.

You may find Robotics Stackexchange  useful for this question.  If so ask moderator to move it

Due to my robot I have been thinking about this problem quite a few times but I never got to coding.  So this is a purely my thinking no experience.
The problem is not only calculating where you are and where to go. The robot needs to move so it needs to know whether it needs to turn (left or right; slow or fast) to drive into the correct direction.
So basically you want a method that takes the compass direction the 2 gps locations and returns a speed and turn value.
The speed and turn value will be different for a waypoint and the final destination. I thought to do so by switching to the next waypoint before coming in the "slow down area". This should make that only one algorithm can handle both situations.
I think the algorithm is likely to look like this.
Given the 2 gps locations calculate the expected compass reading.
Given the 2 gps locations calculate the distance
Based on the distance and the difference between the expected and actual compass reading decide on the speed and turn.
As to the last step there is no "one size fits all" for instance a skid driven robot may opt to turn on the spot until it hits the expected compass reading.
If you have a slow turning robot and you are close to the waypoint you may opt to drive backwards first (like parking a car)
I hope this helps


text:
reverse 12v motor
I am working on an RC car, and I need to be able to reverse a 12v circuit that powers my main drive motor.
I have a TIP102 transistor and a 5-30v relay for each motor terminal. I assumed that I could open up ground via the transistor on one side, and the power relay on the other, and then switch these to reverse.
My motor runs each direction when hooked directly to the battery, and my relays are definitely outputting the full 12v, but I seem to have a problem with the grounding circuit. Whichever side has the relay switched on, that transistor gets very hot, and my motor doesn't spin. I tested the transistor and can get it to ground when on a single directional circuit with just the relay on one side and the TIP102 on the other.
Here is my wiring. Can anyone tell me where I screwed up?
Ignore the 9v, I just couldnt find a 12v in fritzing

You want a H-bridge motor driver. There's plenty of shields around to do it.

If the diagram correctly represents what you have, it isn't obvious to me what the problem might be.  One possibility is that the base resistors to the TIP102's are too large.  Too little current into a transistor base keeps a transistor out of saturation, ie operating in a linear mode instead of switching mode, leading to high power loss and high heat.  Slightly more likely is that the fairly high voltage drop across the Darlington in the TIP102 is just heating it up a lot.
If, as suggested in a comment, you were to use an H-bridge motor driver, it might include heat sinks or might use MOSFETs with lower voltage drops; thus avoiding so much lost heat, one way or the other.
As it happens, you probably don't need the transistors in the circuit anyway.  Label the relays as A and B.  Hook one of the motor leads to the common terminal of A, and the other motor lead to the common terminal of B.  Hook the NO lead of each relay to V+, and the NC lead of each to ground.  To run one direction, switch A on and B off.  To run the other direction, switch A off and B on.  To stop, switch both off.

Brilliant! That did the trick. I followed your relay wiring and it does exactly what I wanted. Thank you.

@Broom, good deal.  Relays are fine for on-off motor control.  But if you need PWM, buy an H-bridge.  They usually have MOSFETs (reducing heat) and protective diodes (to keep inductive voltage kick from destroying transistors).


text:
Run Servo when detect object on OpenCV Python
I want to connect OpenCV (Python) with arduino Uno when it detects a tennis ball.
OpenCV code:
import numpy as np
import cv2
import serial
face_cascade = cv2.CascadeClassifier('tennisballdetect.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
print(faces)
    for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
detect=(x+y)/2
    print(detect)
cv2.imshow('img', img)
k = cv2.waitKey(30) & 0xff
if k == 27:
    break
cap.release()
cv2.destroyAllWindows()

# Module -2: Trigger Pyserial
if detect > 0:

     ser = serial.Serial('COM1', 9600)
     print(ser)
     ser.write('Y')
else:

   ser = serial.Serial('COM1', 9600)
   print(ser)
   ser.write('N')

My Arduino Code:
#include <Servo.h>
int servoPin = 3;
Servo Servo1;
char incomingBit;    // for incoming serial data

void setup() {
// We need to attach the servo to the used pin number
// Servo1.attach(servoPin);
pinMode(servoPin, OUTPUT);      // sets the digital pin as output
Serial.begin(9600);    // opens serial port, sets data rate to 9600 bps
}
void loop() {
if (Serial.available() > 0) {       // Serial.available(), which detects if
any data has been sent to the
                                   //serial port
 //  Serial.read() will read the incoming character and store it in
incomingBit
    incomingBit = Serial.read();
    Serial.print("I received:  ");
    //if the value of incomingBit is ‘Y’, we need to turn the LED ‘on’, else we turn it ‘off’. So,
    //in a nutshell,if detecting faces from a given image was successful, this will turn on the LED

            if(incomingBit == 'Y' || incomingBit == 'y') {

             // Make servo go to 0 degrees
  Servo1.write(0);
  delay(1000);
 // Make servo go to 90 degrees
   Servo1.write(90);
 delay(1000);
 // Make servo go to 180 degrees
 Servo1.write(180);
 delay(1000);
 //exit(0);
            }
            else {
              digitalWrite(servoPin, LOW);
            }
  }
}

Servo is correctly connected to Arduino and it is moving without serial communication. openCV is also working and detecting tennisball.
But when trying to connect OpenCV to arduino, servo is not moving.
Any kind of help is appreciated.

Put a serial.print incomingBit. Also serial.read returns a byte. Could be that your parse is failing.

Can you be a bit more specific? I am new to this and this is not very clear to me.Sorry for that.

Put Serial.println(incomingBit) after serial.read() to see if you get an incoming command

You need to debug the code. Is the message sent through the COM(serial communication), if so, is it recived on the other end? Anyway put ´Serial.print("I received:  "); Serial.println(incomingBit);´ to se if anything is recived on the other end. Then get back to me! =)

The "detect" value in Python code is >0 but still when I upload my arduino code , I get no value at arduino IDE. Is there any way to solve it? @sigma

If i understand you right, the python code is sending a massage but the Arduino isn't receiving it. It looks right on the arduino side. I cant help you with python code, its not my area. Could be that you are not sending it correctly, just a wild guess. :/


text:
ATtiny85 Timer 1 comparator A interrupt problem
I'm writing a program on attiny85 using interrupts. It is a simple program:
- when rising edge is detected on PCINT0, drive DEBUG_PIN to HIGH
- when TIMER1 counts up to OCR1A, drive DEBUG_PIN to LOW
Problem is that when program detects rising edge on PCINT0, it starts Timer1 comparator A and then immediately calls ISR(TIMER1_COMPA_vect). As an effect, on DEBUG_PIN there is only a little narrow spike instead of a nice square wave of length 50ms (checked it with oscilloscope).
Im using ARDUINO IDE. Here is the code:
/*
 * Movement detection using interrupts instead of linear approach
 *
 * POS_TIMEOUT will be checked using COMPA on TIM0
 * IMP_TIMEOUT will be checked using COMPB on TIM0
 * LOOP_TIME will be chcecked using TIMER1 overflow
 *
 * INT0_PIN_IN  (PB2) is the pin that receives the signal
 * INT0_PIN_OUT (PB4) is the pin used for external interrupt debugging
 * DEBUG_PIN    (PB3) is the pin used for debugging
 * STATUS_PIN   (PB1) - high when awake, low when asleep
*/

#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>
//#include "timers_init.h"

//Watch out! do not use the reset pin (PB5)!

#define INT0_PIN_IN     0
#define INT0_PIN_OUT    4
#define STATUS_PIN      1
#define DEBUG_PIN       3
#define POS_TIMEOUT     50

#define PRE_1     0
#define PRE_2     1
#define PRE_4     2
#define PRE_8     3
#define PRE_16    4
#define PRE_32    5
#define PRE_64    6
#define PRE_128   7
#define PRE_256   8
#define PRE_512   9
#define PRE_1024  10
#define PRE_2048  11
#define PRE_4096  12
#define PRE_8192  13
#define PRE_16384 14

/*******MONITORING*VARIABLES*VOLATILES**************/
/* variable keeping last state of INT0 input */
volatile bool lastState = false;

/*************STATUS FLAGS**************************/
/* flags used for movement detection */
/* all flags are initiated as false */

volatile bool positiveFlag  = false;
volatile bool fallingEdge   = false;
volatile bool risingEdge    = false;
volatile bool positiveTimeoutCheck  = false;
volatile bool impulseTimeoutCheck = false;
/*************UTILS*********************************/
void timerOneCompADisable( void ){
  bitClear(TIMSK, OCIE1A);
}

void timerOneCompAInit( uint8_t compValue  ){
  //set comparatorA value
  OCR1A = compValue;
  //enable compA interrupts
  bitSet(TIMSK, OCIE1A);
}

/******************
 * INTERRUPTS!!!
******************/

/*
 * This interrupt is called every time PCINT0 input state changes
*/
ISR(PCINT0_vect){
  bool readPin = digitalRead( INT0_PIN_IN );

  //falling edge
  if( lastState && lastState != readPin ){
    fallingEdge = true;
    lastState = false;
  }
  //rising edge
  else if( !lastState && lastState != readPin ){
    risingEdge = true;
    lastState = true;
  }
}

//TIMER 1 COMPARE match A
ISR(TIMER1_COMPA_vect){
  positiveTimeoutCheck = false;
  digitalWrite( DEBUG_PIN, LOW );
  timerOneCompADisable();
}

/**********************
 * MAIN CODE!!!!!!!
**********************/

void setup(){

  /* Pin config */
  pinMode( INT0_PIN_IN, INPUT );
  pinMode( DEBUG_PIN, OUTPUT);

  /* Pin initialization */
  digitalWrite( DEBUG_PIN, LOW );

  /* Timers configuration */
  //prescaler is 8192 so one tick is ~1 ms
  TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);

  /* Interrupts initialization */
  bitSet( GIMSK, PCIE );
  bitSet( PCMSK, PCINT0 );
}

/* function resetting flags */
void resetFlags( void ){
   positiveFlag  = false;
   fallingEdge   = false;
   risingEdge    = false;
   positiveTimeoutCheck  = false;
}

int main(){
  cli();
  setup();

  /* Variables initialization */
  lastState = digitalRead( INT0_PIN_IN );
  resetFlags();
  sei();

  while(1){
      /* State machine */

      //if nothing is going on and rising edge is detected
      //reset everything and ignite positive flag
      if( risingEdge ){
        cli();
        resetFlags();
        positiveFlag = true;
        sei();
      } // if

      //INT0 is high, initiate positive timeout check
      else if( positiveFlag && !positiveTimeoutCheck ){
        cli();
        resetFlags();
        timerOneCompAInit( POS_TIMEOUT );
        positiveTimeoutCheck = true;
        digitalWrite( DEBUG_PIN, HIGH );
        TCNT1 = 0;
        sei();
      } //else if

  } //while

  return 0;
}

Thank you guys! All I had to do is disable TIMER1, reset it, set COMPA, reset OCF1A ("bitSet(TIFR,OCF1A)") and set prescaler before sei();.
Here is my final, working code:
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>
//#include "timers_init.h"

//Watch out! do not use the reset pin (PB5)!

#define INT0_PIN_IN     0
#define INT0_PIN_OUT    4
#define STATUS_PIN      1
#define DEBUG_PIN       3
#define POS_TIMEOUT     70

#define PRE_1     0
#define PRE_2     1
#define PRE_4     2
#define PRE_8     3
#define PRE_16    4
#define PRE_32    5
#define PRE_64    6
#define PRE_128   7
#define PRE_256   8
#define PRE_512   9
#define PRE_1024  10
#define PRE_2048  11
#define PRE_4096  12
#define PRE_8192  13
#define PRE_16384 14

/*******MONITORING*VARIABLES*VOLATILES**************/
/* variable keeping last state of INT0 input */
volatile bool lastState = false;

/*************STATUS FLAGS**************************/
/* flags used for movement detection */
/* all flags are initiated as false */

volatile bool positiveFlag  = false;
volatile bool fallingEdge   = false;
volatile bool risingEdge    = false;
volatile bool positiveTimeoutCheck  = false;
volatile bool impulseTimeoutCheck = false;
/*************UTILS*********************************/
void timerOneCompADisable( void ){
  bitClear(TIMSK, OCIE1A);
}

void timerOneCompAInit( uint8_t compValue  ){
  //set comparatorA value
  OCR1A = compValue;
  //enable compA interrupts
  bitSet(TIMSK, OCIE1A);
}

void timerOneDisable(){
  TCCR1 |= (0<<CS13)|(0<<CS12)|(0<<CS11)|(0<<CS10);
}

/******************
 * INTERRUPTS!!!
******************/

/*
 * This interrupt is called every time PCINT0 input state changes
*/
ISR(PCINT0_vect){
  bool readPin = digitalRead( INT0_PIN_IN );

  //falling edge
  if( lastState && lastState != readPin ){
    fallingEdge = true;
    lastState = false;
  }
  //rising edge
  else if( !lastState && lastState != readPin ){
    risingEdge = true;
    lastState = true;
  }
}

//TIMER 1 COMPARE match A
ISR(TIMER1_COMPA_vect){
  positiveTimeoutCheck = false;
  digitalWrite( DEBUG_PIN, LOW );
  TCNT1=0;
  timerOneCompADisable();
}

/**********************
 * MAIN CODE!!!!!!!
**********************/

void setup(){

  /* Pin config */
  pinMode( INT0_PIN_IN, INPUT );
  pinMode( DEBUG_PIN, OUTPUT);

  /* Pin initialization */
  digitalWrite( DEBUG_PIN, LOW );

  /* Timers configuration */
  //prescaler is 8192 so one tick is ~1 ms
  TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);

  /* Interrupts initialization */
  bitSet( GIMSK, PCIE );
  bitSet( PCMSK, PCINT0 );
}

/* function resetting flags */
void resetFlags( void ){
   positiveFlag  = false;
   fallingEdge   = false;
   risingEdge    = false;
   positiveTimeoutCheck  = false;
}

int main(){
  cli();
  setup();

  /* Variables initialization */
  lastState = digitalRead( INT0_PIN_IN );
  resetFlags();
  sei();

  while(1){
      /* State machine */

      //if nothing is going on and rising edge is detected
      //reset everything and ignite positive flag
      if( risingEdge ){
        cli();
        resetFlags();
        positiveFlag = true;
        sei();
      } // if

      //INT0 is high, initiate positive timeout check
      else if( positiveFlag && !positiveTimeoutCheck ){
        cli();
        resetFlags();
        timerOneDisable();
        timerOneCompAInit( POS_TIMEOUT );
        positiveTimeoutCheck = true;
        digitalWrite( DEBUG_PIN, HIGH );
        bitSet(TIFR,OCF1A);
        TCNT1 = 0;
        TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);
        sei();
      } //else if

  } //while

  return 0;
}

You should move the line TCNT1 = 0; from loop() into timerOneCompAInit() function:
void timerOneCompAInit( uint8_t compValue  ){
  TCNT1 = 0;
  //set comparatorA value
  OCR1A = compValue;
  //enable compA interrupts
  bitSet(TIMSK, OCIE1A);
}

Otherwise, during the timelapse between  OCR1A = compValue; and TCNT1 = 0;, it is highly possible that TCNT1 reaches OCR1A and thus sets the OCF1A flag in TIFR, which will generate an interrupt and call ISR(TIMER1_COMPA_vect) immediately after sei() is called in loop().
The fact is Timer1 is always running since it has been enabled at setup(), hence TCNT1 is continuously changing from 0 to 255 and back to 0.
Hence in your current code, at the time you execute OCR1A = compValue;, TCNT1 may have any value between 0 and 255, if its value is >50 (POS_TIMEOUT), then an interrupt will be generated.
Roughly the probability for this interrupt to happen is at least 80% (i.e. (255-50)/255).

the code is a little too long for me to go through but sounds like this is a one-shot compare.
With that, you should turn off the timer1, clear the timer1 compa flag, set the compare match point forward (COMPA = target count if TCNT1 is reset, or COMPA = TCNT1 + target if TCNT1 is NOT reset), enable the timer1 compa interrupt, and start the timer1. All of that in the PCNT1 interrupt (where timer1 is armed).
Some of the actions can be structured in the timer1 initialization routine, or even after timer1 compa isr if you want to improve the code responsiveness.
Otherwise, your timer1 keeps running and once the counter passes COMPA, the flag is set, regardless of if the interrupt is set or not.

Man, youre great!!!! All I had to do was to: 1. Disable TIM1; 2. Reset TIM1; 3. Set COMPA 4.Enable TIM1 5.Enable interrupts . One more question: is there a way to disable timer (make it stop counting) without clearing  its prescaler bits?

there is no "prescaler counter" in the avrs so the answer is no (in general). in some cases, you can read the prescaler -> by externally switching the input to a gpio pin and flip that pin until the counter advances. But that doesn't seem to be the case here.