text:
Why can't the Atmel ATtiny family delay over a minute?
I have some really simple code and tested on an 8 MHz ATtiny85 and ATtiny2313. It's basically a blocking blink:
int relayPin = 7;

long offPeriod = 1 * 60 * 1000;
long onPeriod = 1 * 60 * 1000;

void setup()
{
  pinMode(relayPin, OUTPUT);
}

void loop()
{
  digitalWrite(relayPin, LOW);
  delay(onPeriod);
  digitalWrite(relayPin, HIGH);
  delay(offPeriod);
}

When I assign onPeriod and offPeriod to be 1 * 1000 (1 second), the LED will blink as expected. When I add the 60 second multiplier in, it seems to fail.
For the ATtiny85 I use Arduino Pin 4 (physical pin 3) and for the ATtiny2313, I use Arduino pin 7 (physical pin 9).
I program through the Arduino IDE using boards manager to install the ATTinyCore library for the ATtiny2313 and this for the ATtiny85.
Am I doing something wrong here?
It looks like if I throw the delay in a function, and then invoke it with however many seconds I want, it will work. This is not good as it remains blocking. So perhaps the correct way to do this is to grab timestamps.
Here's the somewhat working code:
int relayPin = 4;
unsigned long offPeriod = 60;
unsigned long onPeriod = 60;

void setup()
{
  pinMode(relayPin, OUTPUT);
}

void loop()
{
  digitalWrite(relayPin, LOW);
  delaySeconds(onPeriod);
  digitalWrite(relayPin, HIGH);
  delaySeconds(offPeriod);
}

void delaySeconds(int s) {
  for (int i = 0; i < s; i++) {
    delay(1000);
  }
}

The type for the delay value is an "unsigned long" according to this. But I don't think that's your problem.  Could the Delay code not be compatible with your processor?  Also, it is likely you can call delay(1000) in a loop driven by the number of seconds (for instance 6) you wish to delay.

The delay() library works with times below a minute (I haven't tested exactly what but I've done <10 seconds, and then went to test 60 seconds, the latter of which does not work). I would think that if the library isn't compatible, any calls to it won't work, but maybe it's a small bug with it and my MCU?
I just tried unsigned long and it doesn't work. Let me try throwing a delay(1000) in a function.

Looks like throwing it into a delay function works. I'm thinking maybe it's an overflow issue now.

Overflow issue seems weird, because unsigned long is 32-bit which is way more than the 15 * 60 * 1000 = 900000 I require.

This is absolutely nothing to do with "why can't the atmel attiny family delay over a minute?". It is all to do with the way that C++ works.
See my page about Integer arithmetic and overflow.
To excerpt from that:

On the Arduino (Uno) platform, what do you think will be printed here?
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  Serial.println (30000 + 30000); // twice 30000
  Serial.println (60 * 60 * 24);  // seconds in a day
  Serial.println (50 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

Did you guess:
60000
86400
500

Nope!
It prints:
-5536
20864
0

This is because of integer arithmetic. If the compiler can, it treats an numeric literal (like 60) as an int type, which means it has the range -32768 to +32767.
And, arithmetic is done using the type of the largest argument, which means the arithmetic in each case is done as 16-bit arithmetic, and thus it overflows once it reaches 32767.
For example, 30000 + 30000 = 60000 which is 0xEA60 in hex. Unfortunately, 0xEA60 is exactly how -5536 is stored in an int type, which is why it prints -5536.
Meanwhile, 60 * 60 * 24 = 86400 which is 0x15180 in hex. As that doesn't fit in 16 bits, it is truncated to 0x5180 which is 20864 in decimal (as printed).
Finally, in integer arithmetic 50/100 is zero, multiply zero by 1000 and you still get zero, which is why the final result is zero.

Solution
First, you can add a suffix to numeric literals (eg. L for long, or UL for unsigned long), and add a decimal place to floats, like this:
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  Serial.println (30000L + 30000); // twice 30000
  Serial.println (60L * 60 * 24);  // seconds in a day
  Serial.println (50.0 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

Now we get:
60000
86400
500.00

You only need to help out with the first literal, once the compiler knows we are using longs (or floats) it sticks with them for the expression.*

* It's actually somewhat more complex than that as this link explains: Understand integer conversion rules.
The compiler "promotes" a value in an expression to match another "higher-ranked" type, under certain circumstances. For example, adding an int and a long will result in the int being promoted to a long (regardless of whether it appears first in the expression or not). However if an int is being added to another int, it will not promote them to a long, even though the result may not fit into an int.

Thanks for all the information. I was suspecting overflow but have forgotten all the C++ I've learned in university since it's been so long. I had remembered arithmetic is done on largest type, but oversight made me blind to the fact that all the individual numbers are INT. You mentioned at the beginning of your answer "on the Arduino (Uno) platform", but from the diction used in your answer, this seems to be general C++ behaviour. Any reason to keep thinking it's for Arduino only?

The distinction is because on this platform an int is 16 bits. If you try the same code on your PC an int will probably be 32 bits or even 64 bits. If you have come from programming PCs the problem is still there, but masked by the larger integer size. 16-bit ints would be used on other platforms with small processors (8-bit processors) - probably such as PIC etc.

My copy of Kernighan and Ritchie (The C Programming Language) mentions on page 9: The range of both int and float depends on the machine you are using; 16-bit ints, which lie between -32768 and +32767, are common, as are 32-bit ints.

These are the problem lines:
long offPeriod = 1 * 60 * 1000;
long onPeriod = 1 * 60 * 1000;

Even though long should hold the result, integer operations in C++ are still done in int by default. And on AVR int is 16 bits. The fix is to tell the compiler what size the intermediate result should be:
long offPeriod = 1 * 60L * 1000;
long onPeriod = 1 * 60L * 1000;

According to AVR libC the implementation of the delay function has a limited value range that varies with the F_CPU macro definition. So your delaySeconds(int) function is the only solution.

He is using delay, not _delay_ms


text:
How to use relay shield to control dc motor speed and direction?
I tried l298n before but its output voltage wasn't high
so I use relay shield but  it seems that the car can only go forward or stop
Can I control the speed and direction of dc motors?

Please can you expand on your question?  What do you motors need V and A?

You can change the polarity of the power going to the motor using only a single DPDT relay. You'd need a second relay to turn the motor on and off. Using a relay to control speed will wear out the relay pretty fast.

Using a mechanical relay to control the speed is not a good idea. But you can control the directions.
I prefer you to use Solid state relays (SSR) to do this. Arrange 4 SSR as Hbridge and Use PWM to control the speed.
refer this
or you can use the devices like this which has direction control as well.

Yes you can, but the easiest way is by using a "motor shield".  There are more options than just L298N.
Are you sure it was the voltage that wasn't high enough, its normally the current (Amps)?
To do it with a relay you need to change the polarity of the feeds to the motor.  You could do this with 2 relays both connected all the time, but if you close the wrong one, you will short everything.  It would be better using a motor controller.

When I used l298n the output  voltage  was about 4.6V current was
about 120~130mA

the fast speed occurred when I connect 5V pin of arduino to the
positive of motor and GND pin to the negative of motor
I measured the current was about 120~130mA

But I used  the 9V battery to connect logic 5V of l298N ,the speed
didn't increase. I am sure I connected I don't know why it didn't work

Would this be better?
https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/library-reference?view=all

9V batteries can't provide a lot of power/current.

But i use 9V series 9V (18V)  it also seemed no difference to speed

Most refer to relays when talking about mechanical devices which are either closed or open.  If you arrange several in an H-bridge configuration, you can make you car go forward, stop and reverse.  But controlling speed is not possible.

Ok thank you it seems the only choice is l298n

source: Stack Exchange

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

sort: votes


text:
SIM900 random shutdowns
I have a SIM900 GPRS/GSM Shield and an Arduino Mega. Now for the past week I have been using USB as power to send and receive GPRS data with no issue. Today the SIM900 module is continually randomly turning off, not even turning of at specific stages of communication.
I thought this could be power related, so have external power (5V 5A UBEC) into the 5V pin of the Mega, which I believe should cover the voltage and current requirements of the SIM900 shield. However this has not solved the problem.
Any ideas on what could be causing the random shutdowns?
EDIT:
Is it safe for me to wire power up like this:

Are the mega and the PSU sharing a common ground?

Cool, an UBEC is indeed a smart choice for powering a SIM900.
I could get away with a small switching power supply and just putting in a big capacitor (since the sim900 only draws high current in very short peaks).
But, the limiting factor in this case would be the 6AA batteries. Your UBEC may be able to supply 5A's but those AA's may not.
Also, look up "transient response" (related) according to the related article, you can have an 20A power supply, but still have the voltage drop out when the sim900 starts to transmit. This is because your supply needs to be able to deliver the required 2A in a very short period of time, so basically if your supply can't go from 100ma to 2A fast enough, it'll dip.
I suggest finding a more optimal source as AA's and adding a "big ass capacitor" close to the sim900's input.

Pumping 5Amps into the Mega isn't going to make a difference to the current the SIM900 is receiving (needs >2A)  it will still get 500mA (?).
You need to feed the power directly into the SIM900 from the PSU, because when it transmits it needs a nuclear reactor to power it.  Don't forget the common ground.

Ok, i'm not massively clued up on the power side of things. I have this UBEC. How can I safely power the Arduino AND the SIM900 with this?

Is it safe for me to wire power up as shown in the main post edit?

Hold on, even though I am plugging into the 5v pin, then current is still limited 500mA?

Looking at you diagram (could see it yesterday).  Does the "Turnigy" have two separate outputs?  You description seems to say that the SIM900 is powered from the Mega, but you picture seems to say the wire splits and goes separtly to each.
Rereading the description it looks like you have flat batteries, "worked last week but has stopped working", have you tried changing the bat's? (Sorry to ask a dumb question, I'm sure you have, but...)

You could always try adding a large electrolytic capacitor 10000uF to the power rail (- to GND and + to +5V), it might be that SIM900 resets when it just browns out due to transmission power usage.

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


text:
Arduino servo motor on pushbutton
I'm working on my first arduino project and i have my first problem dealing with servo motor , i'm trying to control the servo from my pc with this code but it just spining :
  #include <Servo.h>

Servo servo1;
long num;

void setup()
{
   servo1.attach(7);
   Serial.begin(9600);
   Serial.print("Enter Position = ");
}

void loop()
{
  while(Serial.available()>0)
  {
    num= Serial.parseInt();
    Serial.print(num);
    Serial.println(" degree");
    Serial.print("Enter Position = ");
  }
  servo1.write(num);
  delay(15);
}

this is my setup

I have reformatted your code and the problem becomes very clear (to me).
void loop()
{
  while(Serial.available()>0)
  {
    num= Serial.parseInt();
    Serial.print(num);
    Serial.println(" degree");
    Serial.print("Enter Position = ");
  }
  servo1.write(num);
  delay(15);
}

You are getting some input from the user and then setting the servo to that point.
When there is no data in the Serial buffer you set the servo to the value of write and delay 15ms before checking the buffer again.
I think what you want to do is if there is no data then you don't want to change the Servo position.  In short move the servo1.write(num); line inside the } of the while loop.
Now much more importantly the first time you enter loop() you won't have any data there so the servo will be moved to the number held in num which is? Undefined, it could be anything at all from 0 to 4294967295 and if its the upper end of that it will take a while for the servo to get there, it might seem like all it does is spin.  ALWAYS INITIALIES VARIABLES BEFORE USE :)
A minor point, your while loop could be, probably should be an if statement.  That will prevent a cat sitting on the keyboard and blocking the servo movement.

i changed the while with if and moved servo1.write(num) and initiales num but as soon as i upload it it starts moving slowly and when i enter a position it just spins faster...

What about long num = 0;

What happens if you take the wire out of pin 7 and leave it disconnected?


text:
Arduino audio output circuit
I am looking to build my own arduino-based board that, when triggered, will play a file (line out, not amped to a speaker). Most of the audio shields I see are more complicated than I need, so what I'm wondering is what is the barebones circuit I would need for audio output? I've got the atmega and SDcard side fine, I'm just not sure what IC's are involved in audio output. WAV's are fine so I don't have to deal with mp3 decoding.
PS feel free to move this to electronics instead of arduino, I'm not sure where it belonged since it's built into an arduino board but is more the electronic circuitry.

If you don't care much about quality then all you need is two capacitors and a resistor. Use PWM to create the audio (there is a timerpcm pr something library that will do it). The resistor and pne capacitor form a low pass filter for the PWM, and the other capacitor removes the dc offset.
----/\/\/\----+----||------
              |
             ---
             ---
              |
              _
              -

Kudos for a text-based LPF but why couldn't you upload a picture of the filter in your answer?

Because at the time i didn't have one to hand and the question wasn't worth spending the time making one. Also we didn't have the schematic editor enabled back then.


text:
Using logical operators
This is a snip it of code from a program I am writing. I have the program turn an LED on and if a button is pressed when the LED is on I want it to add to a counter and print the counter value. The problem seems that my if statement is skipped. Right now the while loop is setup for 5 seconds using millis() and stays off using a short delay. This part (button_press_9())) is a function call to a Boolean I have setup for debouncing. If I put the function call in an if statement by its self for example to test it. It works and will turn an LED on and off. It seems the combination of the two is incompatible.
Thank you in advance.
unsigned long previousMillis = millis();
unsigned long currentMillis = millis();

while ((currentMillis - previousMillis) < onTime)
{
    digitalWrite(ledPin4, HIGH);
    if (ledPin4 == HIGH && (button_press_9()))
    {
        counter++;
        Serial.println(counter);
        currentMillis = onTime * 100;
    }
    currentMillis = millis();
}
digitalWrite(ledPin4, LOW);
delay(1000);

ledPin4 == HIGH? Guess you mean something else.

Also, currentMillis = onTime * 100; makes little sense. What did you actually mean?

@EdgarBonet I put it in there so if the LED was HIGH and there button pushed it would end the timer in the while loop

@MikaelPatel I set the LED to HIGH and then used an if statement to check if it's HIGH and the button was pressed at the same time. I didn't use there == to assign the HIGH state

Then you mean currentMillis = previousMillis + onTime, but that won't work because you assign currentMillis = millis(); right after. Instead, you can simply break out of the while loop.

ledPin4 == HIGH does not check if the LED is high. For instance, if ledPin4 is defined as int ledPin4 = 4; then the statement is 4 == 1.

You should use
if (digitalRead(ledPin4) == HIGH && (button_press_9()))

instead of
if (ledPin4 == HIGH && (button_press_9()))

Since the pin has been set to HIGH right before, the first part of the test seems useless. You can just do if (button_press_9()).


text:
Pneumatic cylinders with sensors with Arduino Uno
I'm working on my own project with Arduino Uno. There are controlled 4 pneumatic cylinders via 4 coils. Every pneumatic cylinder has got their own coil which switch air to the pneumatic cylinder. Every pneumatic cylinder has got 2 magnetic sensors (when the pneumatic cylinder is retracted and extended).
I created a program for arduino but it doesn't work correctly. When I write there that I want to control only 2 pneumatic cylinders, it works correctly. If I write there the others, it skip the second if statement, do the third if statement and then do the previous if. I don't know why. The behaviour is random. What's wrong with my code? Thank you for help!
// Constants for pneumatic valves
   const int dvere = 2;
   const int davkovani = 3;
   const int lisovani = 4;
   const int vyhazovani = 5;
// ----------------------------------------
// Constants for sensors
   const int vyhazovaniZasunute = 6;
   const int vyhazovaniVysunute = 7;
   const int lisovaniVysunute = 8;
   const int lisovaniZasunute = 9;
   const int dvereZasunute = 10;
   const int dvereVysunute = 11;
   const int davkovaniVysunute = 12;
   const int davkovaniZasunute = 13;

void setup() {
  // Pneumatic cylinders set as output
  pinMode(dvere, OUTPUT);
  pinMode(davkovani, OUTPUT);
  pinMode(lisovani, OUTPUT);
  pinMode(vyhazovani, OUTPUT);

  // Sensors set as input
  pinMode(vyhazovaniZasunute, INPUT);
  pinMode(vyhazovaniVysunute, INPUT);
  pinMode(lisovaniVysunute, INPUT);
  pinMode(lisovaniZasunute, INPUT);
  pinMode(dvereZasunute, INPUT);
  pinMode(dvereVysunute, INPUT);
  pinMode(davkovaniVysunute, INPUT);
  pinMode(davkovaniZasunute, INPUT);

  // Set pneumatic cylinders as they are retracted
  digitalWrite(dvere, HIGH);
  digitalWrite(davkovani, HIGH);
  digitalWrite(lisovani, HIGH);
  digitalWrite(vyhazovani, HIGH);
}

void loop() {

  if(digitalRead(dvereZasunute) == HIGH)
  {
      digitalWrite(dvere, LOW);      // extend the first pneumatic cylinder when the sensor is lighted on because the pneumatic cylinder is retracted
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH
  )
  {
      digitalWrite(davkovani, LOW);      // extend the second pneumatic cylinder
      delay(4000);
      digitalWrite(davkovani, HIGH);    // retract the second pneumatic cylinder after 4 seconds,
      // this code works when it is alone there, the next if statements not
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH)
  {
      digitalWrite(lisovani, LOW);    // extend the third pneumatic cylinder
      delay(3000);
      digitalWrite(lisovani, HIGH);   // retract the secondthird pneumatic cylinder after 3 seconds
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH)
  {
      digitalWrite(dvere, HIGH);      // retract the first pneumatic cylinder
  }

  if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH && digitalRead(vyhazovaniZasunute) == HIGH)
  {
      digitalWrite(vyhazovani, LOW);    // extend the fourth pneumatic cylinder
  }

  if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH&& digitalRead(vyhazovaniVysunute) == HIGH)
  {
      digitalWrite(vyhazovani, HIGH);    // retract the fourth pneumatic cylinder
  }

  // sensors - HIGH - light on, LOW - light off,
  // pneumatic cylinders - HIGH - retracted, LOW - extended.
}

This is what I refer article. But, the language may be barrier for you to read. There is an alternative method this article's author mentions a library, TimeAction.h. The library has the same method as I mentioned. You can google it. Otherwise, the "interrupt controlling" about Arduino you may interest. Please refer to the relative articles. I don't know your practical hardware architecture. Here just want to provide what I know information for you. Hope these are helpful. TimeAction.h
[interrupt contrlling](https://www.arduino.cc/en/

If you're using multiple conditions, i.e. &&, you need to watch the parentheses.

this code works - please define "works". What actually happens?

The pneumatic cylinder takes time to extend/retract. How do you manage that?

can i get your configuration on board. I am designing same project but with single solenoid valve.
Please share your Circuit configuration if possible.

void loop() {

...

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH
  )
  {
      digitalWrite(davkovani, LOW);      // extend the second pneumatic cylinder
      delay(4000);
      digitalWrite(davkovani, HIGH);    // retract the second pneumatic cylinder after 4 seconds,
      // this code works when it is alone there, the next if statements not
  }

...
}

If the condition is met, then davkovani is going to be LOW 99.999% of the time. It will only briefly go HIGH, as there is no delay there. The loop will iterate and set it LOW again. So it may seem to be "not working" whereas the problem is that it "works" very briefly.

Why the delay doesn't work there?

The delay works, but you need two delays. You need: LOW / delay / HIGH / delay if you are going to have any hope of noticing the HIGH state.

Hi~ The synchronized method is below. The function millis() you can refer Arduino.org. It is a function to show you current time. Here I use it to create a time interval to run synchronization.
Declaration the variables are below:
/* Declaration time interval variables for synchronizing pneumaticValve1 and pneumaticValve2. The interval is 1000ms.  */
long perviousTimepneumaticValve1 = 0;
long perviousTimepneumaticValve2 = 0;
long previousTimeLocal = 0;
long interval = 1000;

The loop() function is below:
void loop() {
checkPneumaticValve1();
checkPneumaticValve2();
}

void checkPneumaticValve1() {
  if (millis()-previousTimeLocal>interval) {
    printPneumaticValve1();
    previousTimeLocal=millis();
   }
 }

void printPneumaticValve1() {
     //Here write your code for PneumaticValve1
   }

void checkPneumaticValve2() {
   if (millis() - previousTimeLocal > interval) {
     printPneumaticValve2();
     previousTimeLocal=millis();
   }
  }

void printPneumaticValve2() {
  //Here write your code for PneumaticValve2
  }

Neither of the ways doesn't work.

Your code's variable names must be meaningful. You mention "2 magnetic sensors (when the pneumatic cylinder is retracted and extended)"-I guess it is solenoid valve. I hope I don't guess wrongly. This help us to understand your code. Otherwise, do you have any procedure diagram-it is like square and prismatic shape to illustrate your programing and its sequence.

Yeah, they are solenoid valves. You're right.

Hello,
Sorry for that I just see you have comment on this program, so I review the code. Otherwise, I have a bit longer not to contact Arduino. What I say it's just for a reference. I wish I can help you.

Hello, Sorry for that I just see you have comment on this program, so I review the code. Otherwise, I have a bit longer not to contact Arduino. What I say it's just for a reference. I wish I can help you. Your evert statements are all clear. The problem you mention it's on loop function. I see on No.4 if  statement the "dvere"  this pneumatic valve is extended. But, the No.1 if statement is already on LOW to extend. I also see in No.4 statement you add a logical operation on "lisovaniZasunute" this sensor if it is "HIGH" level. No.3 and No.4 if statement are same description on its writing.

I continue to say that the No.3 and No.4 statement is same as its condition.
if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH){}
Do you want to use a nest loop to write your code? The No.5 and No.6 are similar to NO.3 and No.4..

Yeah, in the if statement no. 4 should be HIGH, because I need retract the pneumatic valve. Statements no. 5 and no. 6 aren't the same. The last operation is different there.

Sorry I miss the last item. No. 5 and No. 6 are different. No. 4 and No. 3 are the same. You can combine them together. You can combine No. 5 and No. 6 together also.
if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH) {
if (digitalRead(vyhazovaniZasunute) == HIGH)
digitalWrite(vyhazovani, LOW);
if (digitalRead(vyhazovaniVysunute) == HIGH)
digitalWrite(vyhazovani, HIGH);}
The method get rid of many codes.

Okay, thanks. But there is problem when the program go to if no. 3 the valves are extended all 3 in one moment. When I comment the rest and leave there only the if no. 1 and no. 2 it is works correctly.

Okey~
Why do you delay 4 seconds on No.2 if statement before pneumatic retract? Does this pneumatic cylinder trigger any sensors? The No.3 and NO.4 if statement are exactly same and just only different inside of their content statement. "The valves are extended all 3 in one moment," said you. Are these three valves deere, davkovani and lisovani? "I comment the rest and leave," said you. What do you want to specify "the rest" ?

Because I need to pneumatic valves "davkovani" and "lisovani" stay extended some time. If I write only the first two if statements, it works correctly, but when I write there the third condition, all 4 valves are extended at the same time. The Arduino ignore the if statements.

Hi~
The synchronized method is below.
Declaration the variable below:
long your_pneumatic_valve_1 = 0;
long your_pneumatic_valve_2 = 0;
long previousTimeLocal = 0;
long interval = 1000;
void loop()
{
checkPneumaticvalve1();
checkPneumaticvalve2();
}

Thank you, I will try it. But why the function "delay()" doesn't work there?

Hi~
The synchronized method is below.
Declaration the variables are below:
long perviousTimepneumaticValve1 = 0;
long perviousTimepneumaticValve2 = 0;
long previousTimeLocal = 0;
long interval = 1000;
The loop() function is below:
void loop()
{
checkPneumaticValve1();
checkPneumaticValve2();
}
void checkPneumaticValve1()
{
if (millis()-previousTimeLocal>interval)
{
printPneumaticValve1();
previousTimeLocal=millis();
}
}
void printPneumaticValve1()
{
//Here write your code for PneumaticValve1
}
continuing on next ~~


text:
Circuit with buzzer not working :(
so I have a circuit with a buzzer and a resistor:

This circuit should be working, but for some reason the buzzer doesn't sound. I pushed the buzzer into the breadboard as hard as I could, I put the + side to positive and the - side to negative but it still doesnt work :(. How can I fix this?
Quick curiosity question: When I was doing electricity in school, the teacher just called the buzzers 'buzzers' but when I started doing arduino I noticed that the arduino community seems to call them 'Piezo buzzers/piezo speakers'. Is there any significance in the word 'Piezo' and should I start referring to them as 'Piezo buzzers' myself?

A buzzer that is not a piezo based device is a coil relay in which the coil circuit is normally closed. When the buzzer is energized, the relay activates and then opens the circuit, deactivating itself. The cycle repeats, creating vibration in the moving part of the relay. Piezo devices use a crystal material which vibrates when electricity is applied. The crystal is often attached to a membrane to amplify the sound.

In the image you provide, you've properly connected the GND and 5V power from the Arduino to your "buzzer". When you apply power to the Arduino board if you have an active beeper it will begin beeping. If instead you have a passive beeper (aka speaker, headphone) you might hear a slight click or pop. As others have said, you need to connect the positive lead of your buzzer to an I/O pin on the Arduino if you wish to control the buzzer.

There is two kinds of buzzers - active and passive

Passive buzzer means they can be operated by applying  just logic high to + and low to ground.

Digitalwrite function will do this job

Active buzzers needs pulses to make sound. Sound produced depends on the frequency.  Your buzzer might be a passive one. You can make a symphony by applying different frequencies..

'tone' function will help you for this

It may be difficult to detect, but if the buzzer in question is a passive buzzer, you should be able to hear a click when it is activated and possibly one when it is deactivated.

Yes.. fred is right.. you can hear a dup dup sound...

are you saying that rather than connecting the wire on the positive side of the buzzer to the power, I should connect it to one of the pins instead and control it with code to make it work? Also, how can I tell if my buzzer is active or passive without making it work?

Thats a hard question. Generally active buzzer comes with a paper cap on top. But this wont b true always. Yes.you should connect + of buzzer to a pin of arduino and - of buzzer to ground

You've already tried using it as an active buzzer. It didn't buzz, so it is either passive or faulty. The next test would be to connected to an output pin and set it alternately high and low, delaying a few milliseconds after each change. If it buzzes, it's passive (all Piezo's I've used have been passive). If not there is a fault, which could mean a broken piezo or it could be one that needs a higher voltage than your board supplies.

Recently, I was trying to find the difference between an active and passive buzzer. I connected a passive buzzer to voltage. It started heating up and smelling. I do not recommend connecting it like that anymore. Below, I am posting a link to ebay where you can buy 5 active 5V buzzers at a very affordable price. http://www.ebay.com/itm/172078418182?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

Try the toneAC library if it is a two pin piezo speaker... It generates weak alternating current, using two arduino pins. Your piezo will last longer. Works like old tone library. Remember to put a 100 ohm resistor in series :)

Buzzer coils get locked if a higher voltage is applied to the terminals - it could be 5-9 V. Once it gets locked it won't work even if you put direct battery to it. The only solution is to first take out your buzzer and give it a reverse voltage that will get the coil out of the lock position, then put 180 Ω resistor and run. It will work and it will never lock again.

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


text:
Arduino round to nearest 0.5
I am having a double value for example: 34.26 or 11.92 or 2.51. It should be rounded to the nearest 0.5 so 1.34 -> 1.50 and 32.78 -> 33 and 21.09 -> 21.00
How do to do this?

I'd suggest not even using floats. 0.5 = 50, 1.34 = 134, 32.78=3278, should make the calculations faster/more efficient.

Also, let's say you have 134, you can do 134%50, which will return 34 and then you can check if it's above 24 (under = round to 0) and above 74 (under is round to 50) and else you round to 100.

It is a very bad idea to use float.
That being said. multiply by 2 and do a standard round.
Then divide back by 2.
For example:
1.34     *2 = 2.68
round(2.68) = 3
3        /2 = 1.5

and
32.78    *2 = 65.56
round(65.56)= 66
66       /2 = 33

The multiply by 2 is actually very clever I already felt like such a simple way should exist.

Commonly used for nearest 0.10 and 0.05 in cash registers, too (using 10, 20).

I made a little algorithm from the first thing that popped into my mind.
I'm using integers, since I believe it works better as floats.
For example, you can represent euro's (with floating points) by expressing them in cents.
unsigned int roundToFifty(unsigned int nonRound){
    unsigned int rest = nonRound % 50;
    unsigned int fits = floor(nonRound / 50);
    unsigned int add = 0;
    if(rest >= 25){
        if(rest >= 75){
            add = 100
        }else{
            add = 50
        }
    }
    return fits*50+add
}

I actually think the algorithm is a tad weird and something simpler/more effective could also exist. It was just the first thing that popped into my mind.

float i=1.5237475984328953;
#include "math.h"
void setup()
{
 Serial.begin(9600);
}

void loop() {
 Serial.println(i,6);
 float price = i*1000;
 Serial.println(price,2);

 float roundNearest = roundf(i*1000) ; // x 100 for two decimal place
  roundNearest = roundNearest/1000;
 Serial.println(roundNearest,6);

 price = (roundNearest*1000);
 Serial.println(price,2);
 while(1){}
}

you u can use roundf()
like in this video Demo Video


text:
Problem with code for IR remote controlled robot
I recently wrote the code for this project but it's weird because when I press button on the remote nothing shows up on the Serial Monitor and consequently the robot doesn't respond. I know it's not a hardware issue because when I used the IRrecv Demo sketch values were displayed on the serial monitor
Please tell me what's wrong! I'm sure there are a lot of talented programmers out there!!
#include <IRremote.h>
#include <AFMotor.h>
AF_DCMotor rightMotor(1); // Right motor connected to port 1
AF_DCMotor leftMotor(2); // Left motor connected to port 2
IRrecv irrecv(A2);// IR receiver connected to pin A2(ANALOG PINS ON MOTOR             SHIELD USED AS DIGITAL INS!)
decode_results results;
#define Straight 0xC1CC42BD
#define Right 0xC1CCA25D
#define Left 0xC1CC22DD
#define Back 0xC1CCC23D

void setup(){
  Serial.begin(9600); // Establishing Serial Communication, THIS IS     IMPORTANT!!
  irrecv.enableIRIn(); // Start the receiver
}
void loop() {
  if (irrecv.decode(&results))
  {
      Serial.println(results.value, HEX);

      if((results.value)== Straight)
      {
      moveForward();
      }
      if((results.value)== Right)
      {
        turnRight();
       }
      if((results.value)== Left)
      {
        turnLeft();
      }
      if((results.value)== Back)
      {
        moveBackward();
      }
      else
      {
        Stop();
      }
      irrecv.resume();
  }
  delay(100);
}

void moveForward() {

    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
    leftMotor.run(FORWARD);
    rightMotor.run(FORWARD);
}

void turnRight(){

  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(FORWARD);
  rightMotor.run(BACKWARD);
  delay(400);

  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}

void turnLeft() {

  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(BACKWARD);
  rightMotor.run(FORWARD);
  delay(400);

  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}
void moveBackward() {

    leftMotor.setSpeed(200);
    rightMotor.setSpeed(200);
    leftMotor.run(BACKWARD);
    rightMotor.run(BACKWARD);
}

void Stop(){
    leftMotor.setSpeed(0);
    rightMotor.setSpeed(0);

}

You are using two libraries (Arduino-IRremote & Adafruit-Motor-Shield-library) which both use Timer2 on the microcontroller.
The motor library actually changes the setup of timer 2 (see line 92 of AFMotor.cpp) which will disrupt the timing that the IR sensor uses to determine the IR code received.
As far as I can see, the IR library is using Timer2 only. This means you should be able to change your motors over to port 3 & 4 which use Timer0 instead.
AF_DCMotor rightMotor(3); // Right motor connected to port 3
AF_DCMotor leftMotor(4); // Left motor connected to port 4

Try replacing you loop function with this one.  It won't fix it.
void loop()
{
    if (irrecv.decode(&results))
    {
        Serial.println(results.value, HEX);

        switch (results.value)
        {
        case Straight:
            moveForward();
            break;
        case Right:
            turnRight();
            break;
        case Left:
            turnLeft();
            break;
        case Back:
            moveBackward();
            break;
        default:
            Stop();
        }
        irrecv.resume();
    }
    else
    {
        Serial.println ("Nothing received");    // This message will annoy you so comment it out as soon as you are happy with what is happening.
    delay(100);
}

The switch statement is just a neater way of doing your ifs.  The Nothing received message will show you if decode is ever returning.  If it is returning you need to work out why it is returning false, by looking in the library code.  If it isn't returning then you need to look in the library code and see why.  If it is returning, but not giving you an expected value, you need to look in the library code and see why.
Sorry but from what you describe it seems to be an issue with the library or your use of it, could be anything, but when you can get some more info post it back here.


text:
How to turn servo to a specific location and then turn over
I work on my first arduino car project and i want to turn my servo to a position with a letter input
This is my code so far
 #include <Servo.h>
Servo servo;

 void setup() {
 Serial.begin(9600);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
 }

 void loop() {

 if(Serial.available()>0){
 int  caz=Serial.read();
 switch(caz)
{
  case 'w':
      digitalWrite(8,LOW);
      digitalWrite(7,HIGH);
      break;
  case 's':
      digitalWrite(7,LOW);
      digitalWrite(8,HIGH);
      break;
  case'd':
       servo.attach(12);
       servo.write(0);
       break;
  case'a':
       servo.attach(11);
       servo.write(180);
       break;
   default:
       digitalWrite(7,LOW);
       digitalWrite(8,LOW);
       servo.attach(0);
  }
}

when i input 'a' or 'd' it starts turning until i input something else and i want it to stop after 10-30 degree .
And also i would like to do that to my motor , moving a bit when i input the key.

Nice use of a switch statement :D

I found out that my servo 360 Parallax has continuous rotation

You should get a 180 degree servo. You code looks fine and it should work with a 180 degree servo. Read my comment under the answer by Matt. Using .write command on continuous servos tells them the speed and direction in which to rotate, not the angle.

@user6317433 are you still in need of an answer?

Rather than writing to 180 and 0 write to a variable.
static const int MovementAmount = 30; //degrees
int position = 90;  // 90 is the start position.
...
case 'd':
   servo.attach(12);
   position += MovementAmount;
   if (position > 180)
   {
     position = 180;
   }
   servo.write(position);
   break;

Doesn't the servo.write need to be outside of the if statement?

'MovementAmount' it should be the position ,number?

@Matt does it matter what kind of servo i have ?

@Gerben - Doh :)  That would help wouldn't it, I'll edit it.

@user6317433 - The movement amount is the amount you want it to move by every time you press the relative key.  You will need a block of code like this for case 'a'.
I don't think a continuous servo will affect the code, but you will have to remember to use -MovementAmount and +MovementAmount. otherwise it will turn around where you don't want it to go.

@Matt I actually believe that it won't work with continuous servos. When saying servo.write(180), that means rotate full speed one way. write(0) is full speed the opposite way. 90 is stop. I do not think that there is a way to get precise angles with continuous servos.


text:
POST data from Arduino to website
I am working on a project where I am trying to send data using HTTP and POST method from my Arduino Mega2560 to a website which I host on localhost. I am living to a students' accommodation and thus, I do not have access to the router. However, I have bought a router and have connected it to the wall via the WAN. Also, the Arduino is connected to one of the ethernet plugs of the router via an Ethernet shield and my laptop to another ethernet plug. I am trying to retrieve the data from the website, but I cannot seem to load them.
Arduino Code
#include <dht.h>
#include <SPI.h>
#include <Ethernet.h>

dht DHT1;
int temperatureSensorPin1 = 25;

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
EthernetClient client;
EthernetServer server(80);

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000;
String data;

long lastUpdate = 0;

void setup() {

  Serial.begin(9600);
  if(Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
  }

  data = "";

  pinMode(temperatureSensorPin1, INPUT);
}

void loop() {

int temp1 = DHT1.read11(temperatureSensorPin1);

switch (temp1)
  {
    case DHTLIB_OK:
        Serial.print("OK,\t");
        break;
    case DHTLIB_ERROR_CHECKSUM:
        Serial.print("Checksum error,\t");
        break;
    case DHTLIB_ERROR_TIMEOUT:
        Serial.print("Time out error,\t");
        break;
    case DHTLIB_ERROR_CONNECT:
        Serial.print("Connect error,\t");
        break;
    case DHTLIB_ERROR_ACK_L:
        Serial.print("Ack Low error,\t");
        break;
    case DHTLIB_ERROR_ACK_H:
        Serial.print("Ack High error,\t");
        break;
    default:
        Serial.print("Unknown error,\t");
        break;
  }

  currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
  }
  String data="temp1="+String(DHT1.temperature, 0)+"&temp2="+String(DHT2.temperature, 0)+"&temp3="+String(DHT3.temperature, 0)+"&temp4="+String(DHT4.temperature, 0)+"&temp5="+String(DHT5.temperature, 0)
                  +"&hum1="+String(DHT1.humidity, 0)+"&hum2="+String(DHT2.humidity, 0)+"&hum3="+String(DHT3.humidity, 0)+"&hum4="+String(DHT4.humidity, 0)+"&hum5="+String(DHT5.humidity, 0)+"&gas="+gasValue;

  Serial.println(Ethernet.localIP());
  if(client.connect("192.168.0.1", 80)) {
    client.println("POST /home/visualisation.php HTTP/1.1");
    client.println("Host:  192.168.0.1");
    //client.println("User-Agent: Arduino/1.0");
    //client.println("Connection: close");
    client.println("Content-Type: application/x-www-form-urlencoded;");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.print(data);
    //Serial.println(data);
    Serial.println("We have connection");
  }

  if(client.connected()) {
    Serial.println("We have abc");
    client.stop();
  }

  delay(4000);
}

PHP Code
<?php
$temp1 = "";
if(isset($_POST['temp1'])) {
    $temp1 = $_POST['temp1'];
}
echo $temp1;
?>

Windows ip configuration
[Router ip configuration][2]
Is the connection that I have made the appropriate one? How should I do it in order to work?
P.S.: I would like to clarify that I do not have an extended knowledge regarding networking.
Router ip configuration
LAN
MAC Address: 60-E3-27-E7-70-7A
IP Address: 192.168.0.1
Subnet Mask: 255.255.255.0
Wireless
Wireless Radio: Enable
Name (SSID): TP-LINK_707A
Mode: 11bgn mixed
Channel Width: Automatic
Channel: Auto (Current channel 3)
MAC Address: 60-E3-27-E7-70-7A
WDS Status: Disable
WAN
MAC Address: 60-E3-27-E7-70-7B
IP Address: 100.66.166.2    Dynamic IP
Subnet Mask: 255.255.255.192
Default Gateway: 100.66.166.1
DNS Server: 77.244.128.44 , 77.244.128.45

Since the php script isn't doing anything you can detect it might already be working. Could you post the serial output of the Arduino? Can you check the access log of the web server you are running on your PC?

It is working! I had to make a PHP script to store the values to a database. One change that I needed to do is to make the Arduino send the values to 192.168.0.100

If you have found a solution to your question, then please answer the question and accept it.

Great to hear. Best of luck.

The ip that I have Arduino send data to is the router's and thus, I should have used the 192.168.0.100 ip which is the one of my computer.
I also needed to save the value to a database to notice the changes because echo $temp1; did not seem to work, probably I should have it included into HTML label tags. Anyway, I just loaded the value from the database into a PHP variable and I was able to accomplish the task.


text:
connecting 3.3V to +3V
Well, I hope this question won' t be buried to the dark depths of this forum as my previous q' s:) But I suppose it won' t this time cause it's pretty short without this introduction part...
I have an Arduino pro mini works with 3.3V and in the other hand, I have a DS1307 DIP ic, works with +3V. I was wondering if I could connect the ic to my Arduino directly.
Thats all. Thanks already:)

The 3V input on the DS1307 is for a 3V battery, usually a CR2032 or similar. The supply voltage of the DS1307 is 5V, which means that it won't work with a 3.3V Arduino without a separate supply and level shifter.

Seems like Konko would be better off finding an RTC capable of operating on a 3.3v supply.  The present device might be usable with the upsteam source if the 3.3v Arduino is regulating down from something around 5v, but then an I2C level shifter would be needed, probably MOSFET-based.

Minimal supply voltage for the DS1307 is 4.5V

The supply voltage is specified as 5V±10%, but it's really intended to be used with as reasonably precise a 5V supply as you can get.

Thank you all, I have a 5v to 3.3v converter, I' m probably gonna use ic with that. I' m happy that I' ve learnt that DS1307 works with 5 volts...


text:
Voice recognition module: avrdude: stk500_getsync(): not in sync: resp=0x00
I am using a GeeeTech voice recognition module, I have recorded my voices using CoolTerm, and imported these voice commands in my sketch. However, when I plug in that voice recognition module, an error gets thrown: avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00; otherwise, it uploads normally. How can the computer and the Arduino lose connection when the voice recognition module gets plugged in? . I have checked my com ports, and checked the everything that it is connected to is correct.
#include <avr/sleep.h>
#include <avr/power.h>
//#include "math.h"
//This sketch is a metronome, in which each led pin shows one beat.
/**************************************/
const int speaker = 13;//speaker at pin 13
int ts = 6;//highest led pin
int count = 3;//"beat 1 pin"
const int keyPin = 11;//button to change time signature
const int keyPinR = 10;//button to change rhythm
const int keySwitch = 2;//sleep mode/wake up button

//All pins below use a pull-up resistor, so the states are inverted
int buttonState = LOW;
int buttonState2 = LOW;
int switchState = LOW;
int silentState = LOW;

int bpm = 120;//you do not need to know this,
//it's just a variable for the potentialmeter to change the tempo
int comdata;

int rthm = 1;//rhythm
int pressed = 0;//
long silent = 0;

byte com = 0; //reply from voice module
/**************************************/

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

 for(int thisPin = 3;thisPin <= ts;thisPin++)
  {
     pinMode(thisPin,OUTPUT); //initialize thisPin as an output
     pinMode(12, INPUT); //potentialmeter for changing tempo

   //Pin 9 to 11, along with pin 2, are all push buttons with pull-up resistors
    for(int i = 9; i<=11; i++)
    {
      pinMode(i, INPUT);
      digitalWrite(i, HIGH);
    }
    pinMode(2, INPUT);
    digitalWrite(2,HIGH);
  }
delay(2000);

//imported voice commands
Serial.write(0xAA);
Serial.write(0x37);
delay(1000);
Serial.write(0xAA);
Serial.write(0x21);

 Serial.print("Type in beats per minute");

}

/****************************************/
void loop()
{
  turnOn();
  getTS();
  getVoiceCommand();
}

void turnOn()
{
    buttonState = digitalRead(keyPin);//key for
    buttonState2 = digitalRead(keyPinR);
    switchState = digitalRead(keySwitch);
    silentState = digitalRead(9);

    if(switchState==LOW) pressed++;

    if(pressed!=0)
    {
      sleep_enable();
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      attachInterrupt(0, interrupt, LOW);
      sleep_cpu();
    }

  else{
    //The beat starts at pin 3, runs in consecutive pins, and ends at pin 8 at maximum

     if(buttonState==LOW){//changing time signature - up to 5 beats
            ts++;
          if(ts==8) ts = 3;  //8 - 3 = 5 beats max
     }
     if(buttonState2==LOW){//changing rhythm - quarter note to eighth, then
             //triplets and sixteenths, back to quarter notes
           rthm++;
          if(rthm==5) rthm = 1;
     }
     if(silentState==LOW) silent++; //if silent key pressed, go to silence (only LED's showing)

      runMetronome();//Run the metronome
     }
  }

  void runMetronome(){
    for(int thisPin = 3;thisPin <= ts;thisPin++)
      //LED's blinking beats (thisPin - LED pin (beat number + 2))
      {
           for(int r = 1; r<=rthm; r++){//nested loop for the rhythm
               bpm = pulseIn(12, HIGH);//pin 12 - tempo potentialmeter
               digitalWrite(thisPin,HIGH);//each LED blinks
               pinMode(13,OUTPUT); //pin 13 - speaker

              silent%2==0 ? noTone(13) : (count==3 && r==1 ? tone(13,4400,80) :
                   r==1 ? tone(13,2500,80) : tone(13,2200,60));
              delay((bpm-52)/rthm);
              digitalWrite(thisPin,LOW);//turn each off as we proceed to the next beat (LED)
              pinMode(13,INPUT);//speaker input
            }
          count++;//beat++

          if(count>ts) count = 3; //go back to beat 1
        }
    }

  void interrupt()  {
      sleep_disable();
      detachInterrupt(0);
  }

   void getTS(){
      if(Serial.available()>0){
          comdata = Serial.read();
          switch (comdata){
              case '1': ts = 3; break;
              case '2': ts = 4; break;
              case '3': ts = 5; break;
              case '4': ts = 6; break;
              case '5': ts = 7; break;
            }
     }
   }
     void getVoiceCommand(){
        while(Serial.available()){
            com = Serial.read();
            switch(com){
                case 0x11: ts = 3; break;
                case 0x12: ts = 4; break;
                case 0x13: ts = 5; break;
                case 0x14: ts = 6; break;
                case 0x15: ts = 7; break;
              }
          }
      }

It's not loosing connection, there just can't be two devices on the same serial port (I suppose this setup)
You can use software serial for VR module, arduino with more hardware serials (=mega) or you can use another arduino as ISP programmer.

There is a arduino SoftwareSerial library to use another serial on almost any two pins.

Pins 0 and 1 are usually used for hardware serial port (and bootloader too). Try some other pins..

Actually, I got it working as I tested it out, by using English commands: '2', '3', '4', '5', and '6'. But, sometimes, when I say: '8', '1', the wrong messages get printed out in the serial monitor.


text:
millis() function always returns same value
I'm trying to program an Arduino MKR1000 and I am using the millis() function to emulate a traditional timer.  The problem is that any call to millis() inside the debounceTimer() function returns the same value.  I only added the Serial.print to debug.
I left out a decent bit of the code to simplify your reading of it.  It works by waiting for an interrupt on pin 4 which then calls the runTimers() function and that calls the debounceTimer() function and within that the millis() function is called. The debouncetimer() function keeps getting called until the 10 ms has elapsed and then should end the timer.  The problem is that the millis() function stops returning a value that goes up.
#define doorIntPin 4
unsigned char sysEnabled = 0;
unsigned long debounceTimerPlace =0;
unsigned char debounceTimerOn =0;

void setup() {
  Serial.begin(9600);
  attachInterrupt(doorIntPin, doorOpens, LOW);
  interrupts();
}

void loop() {

}
void runTimers(){
  Serial.print('r');
  while(alarmTimerOn || debounceTimerOn || enablingTimerOn){
     if(alarmTimerOn)
      alarmTimer();
    if(enablingTimerOn)
      enablingTimer();
    if(debounceTimerOn)
      debounceTimer();
  }
}

void debounceTimer(){
  unsigned long time = millis()- debounceTimerPlace;
  Serial.println(millis() & 0xFFFF, DEC);
  if(sysEnabled && time> 10){
    debounceTimerOn=0;
  }
}
void doorOpens() {
  Serial.print('o');
  if(!debounceTimerOn){
      debounceTimerPlace = millis();
      debounceTimerOn=1;
  }
  runTimers();
}

I suspect that in the background an interrupt is being called than increments the value millis() returns and somehow my external interrupt is disabling that.  I don't know why this is happening or how to fix it.
Any ideas?

You never exit the ISR, hence all interrupts are disabled. Do the minimum work possible within an ISR, and have the main loop outside.

Thanks.  The thing is I'm trying to get the mkr1000 to sleep when not in use.  I've tried to execute the wait for interrupt function but i dont see how to.  Do you know how i could do this in the Arduino IDE?

To answer your question about millis(), it uses interrupts to function, and so you can't call it within an ISR.  According to this: https://www.arduino.cc/en/Reference/AttachInterrupt, you should be able to use delayMicrosconds() within an ISR, since it (reportedly) doesn't use interrupts.

The problem is that the millis() function stops returning a value that goes up.

That's right. The value returned by millis() is incremented by an ISR which won't be called inside your other ISR.
You can use micros() which will increment. However that will only be good up to approximately 1 ms. The main rule of ISRs is that you don't attempt to do delays inside them.


text:
Arduino MCP23S17 I/O Expander (SPI)
I found this post and I am having almost the exact same issue. Nick Gammon (the god of arduino) has an excellent answer but I can't for the life of me implement it myself. I am not an advanced user like the initial question asker.
So What I want to do is use 2 MCP23S17's (picture here).
I have been messing with one of them all week and have it reading like a charm. I am using the githib library by n0mjs710 to do this. But writing to one will not work.
Along with the zipped library is a few examples. I am trying to read some BCD switches off of one "input MCP" and then display the digits on the "output MCP"
I have used external pullups so I did make one change to the code by commenting out the call for pullups. Here is what Doesn't work:
#include <SPI.h>              // We use this library, so it must be called here.
#include <MCP23S17.h>         // Here is the new class to make using the MCP23S17 easy.

MCP inputchip(1, 10);             // Instantiate an object called "inputchip" on an MCP23S17 device at address 1
                                  // and slave-select on Arduino pin 10
MCP outputchip(2, 10);            // Instantiate an object called "outputchip" on an MCP23S17 device at address 2
                                  // and slave-select on Arduino pin 10

void setup() {
  inputchip.begin();
  outputchip.begin();
  inputchip.pinMode(0xFFFF);     // Use word-write mode to set all of the pins on inputchip to be inputs
  //inputchip.pullupMode(0xFFFF);  // Use word-write mode to Turn on the internal pull-up resistors.
  inputchip.inputInvert(0xFFFF); // Use word-write mode to invert the inputs so that logic 0 is read as HIGH
  outputchip.pinMode(0x0000);    // Use word-write mode to Set all of the pins on outputchip to be outputs
}

void loop() {
  int value;                        // declare an integer to hold the value temporarily.
  value = inputchip.digitalRead();  // read the input chip in word-mode, storing the result in "value"
  outputchip.digitalWrite(value);   // write the output chip in word-mode, using our variable "value" as the argument
  // outputchip.digitalWrite(inputchip.digitalRead()); // this one line replaces the three above, and is more efficient
}

I have tried:

slowing the SPI bus by changing the library to SPI_Divide the clock by 2
changing the ss line and even splitting the lines so one chip uses pin 10 and the other uses pin 9

So after reading Mr. Gammon's post I have made some changes to the code attempting to rid myself of the old slave select pin low trick he mentioned. Here is my attempt:
MCP inputchip(1, 10);             // Instantiate an object called "inputchip" on an MCP23S17 device at address 1
                                  // and slave-select on Arduino pin 10
MCP outputchip(2, 9);            // Instantiate an object called "outputchip" on an MCP23S17 device at address 2
                                  // and slave-select on Arduino pin 10
int ssPin = 9;

void setup() {
  pinMode(ssPin,OUTPUT);

  inputchip.begin();
  digitalWrite(ssPin, HIGH);
  digitalWrite(ssPin, LOW);
  outputchip.begin();
  inputchip.pinMode(0xFFFF);     // Use word-write mode to set all of the pins on inputchip to be inputs
  //inputchip.pullupMode(0xFFFF);  // Use word-write mode to Turn on the internal pull-up resistors.
  inputchip.inputInvert(0xFFFF); // Use word-write mode to invert the inputs so that logic 0 is read as HIGH
  digitalWrite(ssPin, HIGH);
  digitalWrite(ssPin, LOW);
  outputchip.pinMode(0x0000);    // Use word-write mode to Set all of the pins on outputchip to be outputs
}

void loop() {
  int value;
  // declare an integer to hold the value temporarily.
  value = inputchip.digitalRead();  // read the input chip in word-mode, storing the result in "value"
  digitalWrite(ssPin, HIGH);
  digitalWrite(ssPin, LOW);
  outputchip.digitalWrite(value);   // write the output chip in word-mode, using our variable "value" as the argument
}

So any advice would be great to get this working. Help me Obi wan Gammon your me only hope.

Try my library instead. That one looks horrible. https://github.com/MajenkoLibraries/MCP23S17

I agree with Majenco...that one looks hard...I am no expert but i used the Adafruit library and found it very friendly... https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library

I will try yours now Mr. Majenko. Doug the library you posted is for the I2C version of the chip. I have worked with it  before and found it excellent but must use the SPI for some applications.

I have one question. Once you set the PinMode of an expander then can you change the mode without giving a reset? I mean, I have to use 3 expanders for controlling an SRAM: on one MCP I have the data lines, on the second one I have the control signals and on the last one I have the address lines. Firstly, I do a SRAM_WRITE, so I need the pins of the first expander to be OUTPUTs,then I do a READ_SRAM so a need the pins of the first expander to be INPUTs. Can I change the mode from output to input? Then I am trying to check the signals with an oscilloscope. When a do a pinMode OUTPUT of the expa

Majenko's library works. All praise to Majenko https://github.com/MajenkoLibraries/MCP23S17

Nick is only a Demi-god :P I am Zeus and Odin rolled into one. Maybe I should change my name to Zein ... or Odus...? ;)

This sketch uses the Majenko Library with two MCP23S17 chips to demonstrate the library functions.
It was tested on an Arduino Uno with IDE 1.6.5.
/*
 * MultiTest_Majenko_02.ino
 * Library Ref: github.com/MajenkoLibraries/MCP23S17
 *
 * Lowell Bahner
 * 2016-12-11
 *
 * Hardware: Arduino UNO
 * IDE: Arduino 1.6.5
 *
 * Useful SPI Ref: gammon.com.au/spi
 *
 * Wire the SPI Interface common lines (Mega2560 SPI pins shown in [ ]):
 * Arduino SPI_MOSI pin 11 [51] <->   SI  MCP23S17 pin 13
 * Arduino SPI_MISO pin 12 [50] <->   SO  MCP23S17 pin 14
 * Arduino SPI_CLOCK pin 13 [52]<->   SCK MCP23S17 pin 12
 * Arduino SPI_CS pin 10 [53]   <->   SS  MCP23S17 pin 11
 * MCP23S17 VDD pin 9 to +5V
 * MCP23S17 VSS pin 10 to Gnd
 * MCP23S17 Reset pin 18 to +5V
 * MCP23S17 Interrupt pins 19-20
 * MCP23S17 A0,A1,A2 pins connect to Gnd or +5V (000 = Address 0, 100 = Address 1, 010 = Address 2, etc)
 * MCP23S17 Port A pins are chip pins 21-28
 * MCP23S17 Port B pins are chip pins 1-8
 *
 * This sketch runs a series of functions to demonstrate library capabilities.
 * This sketch does not demonstrate interrupt functionality.
 *
 * This sketch instantiates 2 MCP23S17 chips.
 * Bank2 (MCP23S17 address 1) pins are set as INPUT or INPUT_PULLUP.
 *    Normally HIGH, use switch to set a pin LOW.
 * Bank1 (MCP23S17 address 0) pins are set as OUTPUT.
 *    MCP23S17 outputs will power LEDs up to 25ma through 1000ohm resistor to ground.
 *
 * Majenko MCP23S17 library functions (see .h,.cpp files for details):
 *
 *  bank.pinMode(uint8_t pin, uint8_t mode)
 *    where modes are:
 *      OUTPUT - sets pin HIGH
 *      INPUT  - sets pin LOW for sensing change to HIGH +V
 *      INPUT_PULLUP - sets pin HIGH for sensing change to LOW 0V
 *
 *  bank.digitalWrite(uint8_t pin, uint8_t value)
 *    if mode=OUTPUT, pin value = LOW (0) or HIGH (1)
 *    if mode=INPUT, value LOW disables pullup on pin, value HIGH enables pullup on pin
 *
 *  uint8_t value = bank.digitalRead(uint8_t pin)
 *    read the state of the pin
 *
 *  uint8_t value = bank.readPort(uint8_t port)
 *    read entire 8-bit port of all INPUT pins on Port A (port=0) or Port B (port>=1)
 *
 *  uint16_t longValue = bank.readPort()
 *    read both ports as 16-bit combined
 *
 *  bank.writePort(uint8_t port, uint8_t val)
 *    write val (0 or 1, hex example 0x55) to all OUTPUT pins on Port A (port=0) or Port B (port>=1)
 *
 *  bank.writePort(uint16_t val)
 *    write val (hex example 0x55AA) to all OUTPUT pins on Port A and Port B
 *
 *  Also, interrupt functions are defined:
 *      enableInterrupt(uint8_t pin, uint8_t type);
 *      void disableInterrupt(uint8_t pin);
 *      void setMirror(boolean m);
 *      uint16_t getInterruptPins();
 *      uint16_t getInterruptValue();
 *      void setInterruptLevel(uint8_t level);
 *      void setInterruptOD(boolean openDrain);
 *
 *
 *
 *
Run Sketch: Serial Monitor Output

 -- RWpins() --

Bank2: Switch i15: 1 (Push button switch not pushed, Bank2 INPUT pin 15 is HIGH +5V)
Bank1: Output j4:  1 (Bank1 OUTPUT pin 4 is HIGH.
                      Arduino pin 7 is set HIGH.
                      LED on pin 4 is ON. LED on pin 7 is ON.)

Bank2: Switch i15: 0 (Push button switch pushed, grounds Bank2 INPUT pin 15)
Bank1: Output j4:  0 (Bank1 OUTPUT pin 4 switches to LOW.
                      Arduino pin 7 is set LOW.
                      LED on pin 4 is OFF. LED on pin 7 is OFF.)

 -- RWport() --

Bank1: Port A BIN: 00000000
Bank1: Port B BIN: 00000000

Bank1: Port A BIN: 11110100  DEC: 244
Bank1: Port B BIN: 00001011  DEC: 11

 -- RWlongPortValue() --

Bank1: Port A & B BIN: 0000101111110100  HEX: 0x0BF4    DEC: 3060

 -- RWlongPort() --

Bank1: Port A & B BIN: 1011100101000010  HEX: 0xB942    DEC: 47426

 -- CyclePins() --

Bank1: Port A & B BIN: 0000000000000000  HEX: 0x0000    DEC: 0
Bank1: Port A & B BIN: 0000000000000001  HEX: 0x0001    DEC: 1
Bank1: Port A & B BIN: 0000000000000011  HEX: 0x0003    DEC: 3
Bank1: Port A & B BIN: 0000000000000111  HEX: 0x0007    DEC: 7
Bank1: Port A & B BIN: 0000000000001111  HEX: 0x000F    DEC: 15
Bank1: Port A & B BIN: 0000000000011111  HEX: 0x001F    DEC: 31
Bank1: Port A & B BIN: 0000000000111111  HEX: 0x003F    DEC: 63
Bank1: Port A & B BIN: 0000000001111111  HEX: 0x007F    DEC: 127
Bank1: Port A & B BIN: 0000000011111111  HEX: 0x00FF    DEC: 255
Bank1: Port A & B BIN: 0000000111111111  HEX: 0x01FF    DEC: 511
Bank1: Port A & B BIN: 0000001111111111  HEX: 0x03FF    DEC: 1023
Bank1: Port A & B BIN: 0000011111111111  HEX: 0x07FF    DEC: 2047
Bank1: Port A & B BIN: 0000111111111111  HEX: 0x0FFF    DEC: 4095
Bank1: Port A & B BIN: 0001111111111111  HEX: 0x1FFF    DEC: 8191
Bank1: Port A & B BIN: 0011111111111111  HEX: 0x3FFF    DEC: 16383
Bank1: Port A & B BIN: 0111111111111111  HEX: 0x7FFF    DEC: 32767
Bank1: Port A & B BIN: 1111111111111111  HEX: 0xFFFF    DEC: 65535

Bank1: Port A & B BIN: 1111111111111111  HEX: 0xFFFF    DEC: 65535
Bank1: Port A & B BIN: 0111111111111111  HEX: 0x7FFF    DEC: 32767
Bank1: Port A & B BIN: 0011111111111111  HEX: 0x3FFF    DEC: 16383
Bank1: Port A & B BIN: 0001111111111111  HEX: 0x1FFF    DEC: 8191
Bank1: Port A & B BIN: 0000111111111111  HEX: 0x0FFF    DEC: 4095
Bank1: Port A & B BIN: 0000011111111111  HEX: 0x07FF    DEC: 2047
Bank1: Port A & B BIN: 0000001111111111  HEX: 0x03FF    DEC: 1023
Bank1: Port A & B BIN: 0000000111111111  HEX: 0x01FF    DEC: 511
Bank1: Port A & B BIN: 0000000011111111  HEX: 0x00FF    DEC: 255
Bank1: Port A & B BIN: 0000000001111111  HEX: 0x007F    DEC: 127
Bank1: Port A & B BIN: 0000000000111111  HEX: 0x003F    DEC: 63
Bank1: Port A & B BIN: 0000000000011111  HEX: 0x001F    DEC: 31
Bank1: Port A & B BIN: 0000000000001111  HEX: 0x000F    DEC: 15
Bank1: Port A & B BIN: 0000000000000111  HEX: 0x0007    DEC: 7
Bank1: Port A & B BIN: 0000000000000011  HEX: 0x0003    DEC: 3
Bank1: Port A & B BIN: 0000000000000001  HEX: 0x0001    DEC: 1
Bank1: Port A & B BIN: 0000000000000000  HEX: 0x0000    DEC: 0
 *
 *
 *
 */

// Majenko MCP23S17 Library
#include <MCP23S17.h>

// Arduino Library SPI.h
#include <SPI.h>

// SPI CS/SS chipselect pin can be changed by user as desired
const uint8_t chipSelect = 10;

// example Arduino board pin
uint8_t pin7 = 7;

// Create an object for each chip
// Bank1 is address 0. Pins A0,A1,A2 grounded.
// Bank2 is address 1. Pin A0=+5V, A1,A2 grounded.

MCP23S17 Bank1(&SPI, chipSelect, 0);
MCP23S17 Bank2(&SPI, chipSelect, 1);

void setup() {

  // Slow down the master a bit if desired
  SPI.setClockDivider(SPI_CLOCK_DIV8);

  Serial.begin(9600);

  Bank1.begin();
  Bank2.begin();

  // LED connected to Arduino pin 7 to test inter-device communication
  pinMode(pin7, OUTPUT);

  //
  // Set MCP23S17 pin modes:
  // example set one pin: chip.pinMode(0, OUTPUT); // sets chip pin 0 (Port A 0) to OUTPUT mode
  //
  // setChipPins(); // use loop to set individual pins
  // or, since this library does not have a setPortPinMode, do 8 pin loops
  setPortPins(); // example: set pins on each Port on each chip to different modes.
  //

}

// Set all Chip pins to desired mode
void setChipPins() {
  // Example usage

  // Set all Bank1 pins to be OUTPUT
  for (uint8_t i = 0; i <= 15; i++)
    Bank1.pinMode(i, OUTPUT);

  // Set all Bank2 pins to be INPUT_PULLUP
  for (uint8_t i = 0; i <= 15; i++)
    //Bank2.pinMode(i, INPUT);  // unswitched pin voltages about +0.1V, switch must pull pin to +5V
    Bank2.pinMode(i, INPUT_PULLUP);  // unswitched pin voltages about +4.9V, switch must ground pin
}

// Set Port pins to desired mode
void setPortPins() {
  // Example usage

  // Set all Bank1 Port A pins to OUTPUT
  for (uint8_t i = 0; i <= 7; i++)
    Bank1.pinMode(i, OUTPUT);

  // Set all Bank1 Port B pins to OUTPUT
  for (uint8_t i = 8; i <= 15; i++)
    Bank1.pinMode(i, OUTPUT);

  // Set all Bank2 Port A pins to be INPUT
  for (uint8_t i = 0; i <= 7; i++)
    Bank2.pinMode(i, INPUT);

  // Set all Bank2 Port B pins to be INPUT_PULLUP
  for (uint8_t i = 8; i <= 15; i++)
    Bank2.pinMode(i, INPUT_PULLUP);
}

//
// Change LED On/Off with button push
// 1) Switch an INPUT_PULLUP pin to ground
// 2) Read the pin value
// 3) Write the value to an OUTPUT pin
// 4) Turn LED On/Off
// Use functions digitalRead(pin) and digitalWrite(pin,value)
//
void RWpins() {

  Serial.print("\n -- RWpins() --"); Serial.println("");

  uint8_t b15 = 0;  // Bank2 input pin value (0 push LOW, 1 normally open HIGH) with push button switch to gnd
  uint8_t i = 15;   // Bank2 pin number
  uint8_t a4 = 0;   // Bank1 output pin value
  uint8_t j = 4;    // Bank1 pin number

  // read the switch value into b15
  b15 = Bank2.digitalRead(i);
  Serial.print("\nBank2: Switch i"); Serial.print(i); Serial.print(": ");  Serial.println(b15);

  // write the switch pin i, value b15, to the output pin j
  Bank1.digitalWrite(j, b15);

  a4 = Bank1.digitalRead(j);
  Serial.print("Bank1: Output j"); Serial.print(j); Serial.print(": ");  Serial.println(a4);

  // Turn on/off LED connected to Arduino pin 7 through resistor to ground
  digitalWrite(pin7, a4);
}

//
// Read and Write Port values
//
void RWport() {

  Serial.print("\n -- RWport() --"); Serial.println("");

  // set the port pin modes
  setPortPins(); // all Bank1 pins are OUTPUT but set as Ports

  // clear the port pin values to 0
  uint8_t port = 0; // Port A
  uint8_t val = 0x00; // set to 0000 0000
  Bank1.writePort(port, val);
  port = 1; // Port B
  Bank1.writePort(port, val); // set to 0000 0000

  // read the port pin values
  uint8_t valueA = Bank1.readPort(0);
  Serial.print("\nBank1: Port A BIN: "); print8Bits(valueA); Serial.println("");
  uint8_t valueB = Bank1.readPort(1);
  Serial.print("Bank1: Port B BIN: "); print8Bits(valueB); Serial.println("");

  // set the port pin values
  port = 0; // Port A
  val = 0xF4; // set to 1111 0100
  Bank1.writePort(port, val);
  port = 1; // Port B
  val = 0x0B; // set to 0000 1011
  //val = 0xB0; // set to 1011 0000
  Bank1.writePort(port, val);

  // read the port pin values
  valueA = Bank1.readPort(0);
  Serial.print("\nBank1: Port A BIN: "); print8Bits(valueA);
  Serial.print("  DEC: "); Serial.println(valueA, DEC);

  valueB = Bank1.readPort(1);
  Serial.print("Bank1: Port B BIN: "); print8Bits(valueB);
  Serial.print("  DEC: "); Serial.println(valueB, DEC);
}

void RWlongPortValue() {

  Serial.print("\n -- RWlongPortValue() --"); Serial.println("");

  // Read the Bank1 Port pin values as a combined long value
  uint16_t valueLong = Bank1.readPort();
  Serial.print("\nBank1: Port A & B BIN: "); print16Bits(valueLong);
  Serial.print("  HEX: "); crPrintHEX(valueLong, 4);
  Serial.print("  DEC: "); Serial.println(valueLong, DEC);
}

void RWlongPort() {

  Serial.print("\n -- RWlongPort() --"); Serial.println("");

  // Write the Bank1 Port pin values as a combined long value
  uint16_t valueLong = 0xB942;
  Bank1.writePort(valueLong);

  // Read the Bank1 Port pin values as a combined long value
  uint16_t valueLongIn = Bank1.readPort();
  Serial.print("\nBank1: Port A & B BIN: "); print16Bits(valueLongIn);
  Serial.print("  HEX: "); crPrintHEX(valueLongIn, 4);
  Serial.print("  DEC: "); Serial.println(valueLongIn, DEC);
}

//
// Cycle through OUTPUT pins with count-up count-down
//
void CyclePins() {

  Serial.print("\n -- CyclePins() --"); Serial.println("\n");

  // Set all Bank1 pins to be OUTPUT
  for (uint8_t i = 0; i <= 15; i++)
    Bank1.pinMode(i, OUTPUT);

  // clear Bank1 using writePort
  uint16_t valueLong = 0x0000;
  Bank1.writePort(valueLong);

  // Read the Bank1 Port pin values as a combined long value
  for (int8_t i = -1; i <= 15; i++) {
    if (i >= 0) Bank1.digitalWrite(i, 1); // i=-1 allows print of 0 data
    valueLong = Bank1.readPort(); // read 16 bits
    Serial.print("Bank1: Port A & B BIN: "); print16Bits(valueLong);
    Serial.print("  HEX: "); crPrintHEX(valueLong, 4);
    Serial.print("  DEC: "); Serial.println(valueLong, DEC);
  }

  Serial.println("");

  for (int8_t i = 15; i >= -1; i--) { // i=-1 allows print of 0 data
    // decrement after the read while reading down the values
    valueLong = Bank1.readPort(); //  read 16 bits
    Serial.print("Bank1: Port A & B BIN: "); print16Bits(valueLong);
    Serial.print("  HEX: "); crPrintHEX(valueLong, 4);
    Serial.print("  DEC: "); Serial.println(valueLong, DEC);
    Bank1.digitalWrite(i, 0);
  }
}

void loop() {

  // Change LED On/Off with button push
  RWpins();

  // Read and Write Port pins as a group
  RWport();

  // Read the Bank1 Port pin values as a combined long value
  RWlongPortValue();

  // Read and Write Chip 16 pins as a group
  RWlongPort();

  // Cycle through OUTPUT pins with count-up count-down
  CyclePins();

  delay(1000);

}

// print 8-bit byte as 8 bit binary string
void print8Bits(uint8_t myByte) {
  for (byte mask = 0x80; mask; mask >>= 1) {
    if (mask  & myByte)
      Serial.print('1');
    else
      Serial.print('0');
  }
}

// print 16-bit word as 16 bit binary string
void print16Bits(uint16_t myWord) {
  for (uint16_t mask = 0x8000; mask; mask >>= 1) {
    if (mask  & myWord)
      Serial.print('1');
    else
      Serial.print('0');
  }
}

//---------------------------------------------------------------------------------
// crPrintHEX print value as hex with specified number of digits
//---------------------------------------------------------------------------------

void crPrintHEX(unsigned long DATA, unsigned char numChars) {
  unsigned long mask  = 0x0000000F;
  mask = mask << 4 * (numChars - 1);
  Serial.print("0x");
  for (unsigned int i = numChars; i > 0; --i) {
    Serial.print(((DATA & mask) >> (i - 1) * 4), HEX);
    mask = mask >> 4;
  }

  Serial.print("  ");
}


text:
Powering Down Arduino MKR1000
The MKR1000 is still pretty new and I'm having a hard time getting good information on it. I'm using the Arduino IDE but don't find any functions to sleep the MKR1000. Most libraries I encounter are for AVR chips while the MKR1000 has an ARM chip. I want to put it to sleep until an external interrupt is called. I also use the millis() function, will this function be rendered useless if it goes to sleep?
In the data sheet for the ATSAMD21 it talks about the Wait for Interrupt instruction which puts the machine to sleep but it doesn't say how to call the instruction. How can I do this in the Arduino IDE?

The rocketscream low power library looks like it supports the ATSAMD21.


text:
How come my code does not wait for a specific time before going into an if statement?
I have an HC-SR04 attached to a servo. When the 90 degree reading is less than 30 cm, I want the motor to take 2 seconds to turn to 130 degrees, get a measurement on the right, and turn back to 90 degrees. My code does not seem to work. Even though I tell it to wait for 2000 ms, it skips directly to the if statement where the turning to 90 degrees is done. Here is the main code:
 #include <Servo.h>
#define trig 22
#define echo 24
long duration;
boolean turned130 = false;
int cm50, cm, cm130;
Servo servo;
boolean checkRight = false;
boolean mainPing = true;
unsigned long counter;
unsigned long servoTimer = millis();
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(echo, INPUT);
pinMode(trig, OUTPUT);
servo.attach(12);
servo.write(90);
delay(2000);

}

void loop(){
counter=millis();//my timer
  if(((counter-servoTimer) >= 250) && mainPing){//distance measured 4 times a second
    ping();
    cm=duration/29.1/2;
    Serial.println(cm);
    servoTimer=counter;//this if statement works fine
  }
  if((cm<30) && mainPing){

    mainPing=false;//makes the 90 degree ping and this if statement unable to run
    checkRight = true;//enables next if statement to run
    servoTimer=millis();
    servo.write(130);
    cm=30;//so that this if statement does not get called again until distance is obtained
    Serial.println("Inside less than 30 loop");//I added this for debugging, to let me know when the loop is called

  }
  if(checkRight && ((counter-servoTimer) >= 2000)){//after 2 seconds passes

    checkRight=false;
    ping();
    cm130 = duration/29.1/2;
    mainPing = true;//enable to other 2 if statements to run
    servoTimer=millis();
    Serial.println(cm130);
    servo.write(90);//turn motor back
    Serial.println("Inside other loop");//for debugging

  }

  delay(2);
  }

void ping(){

    digitalWrite(trig, LOW);
    delayMicroseconds(2);
    digitalWrite(trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig, LOW);
    duration = pulseIn(echo, HIGH);

}

This is what I got in the Serial monitor:
25//distance triggers 2nd if statement
Inside less than 30 loop
261
Inside other loop
13
Inside less than 30 loop
14
Inside other loop
14
Inside less than 30 loop
14
Inside other loop
3242
13
Inside less than 30 loop
14
Inside other loop

This all happened within milliseconds. There was no 2 second pause and the servo never turned. What is wrong with my code that prevents the motor from turning and waiting 2 seconds? The order of the Serial messages is correct, but it is happening fast.
EDIT:
When I remove the Serial messages and disconnect from the computer, it kind of works. By that, I mean it turns and waits for 2 seconds 50% of the time. Other times, the servo just shakes a little bit and stops.
Another thing I noticed is that if I leave only Serial.println(cm) message and Serial.println("Inside less than 30 loop"), this is the result that I observe.
    12
    13
    Inside less than 30 loop

    15
    3
    Inside less than 30 loop

For some reason the loop does not get triggered the first time. Is there a possibility that I have a defective Arduino Mega?
EDIT 2:
I tested the same setup on an official Arduino Uno and it did not work either. This means that I do not have a broken Arduino. Could the servo motor be broken? That won't explain the Serial messages though.

Try adding some parentheses; if( checkRight && ((counter-servoTimer)>=2000) )

@Gerben I added parentheses. When I removed the Serial messages, it kind of worked like 50% of the time. When I add them back in, the same thing happens. There is no interval between the messages and the servo just shakes, but does not rotate.

Could you post the entire sketch? Make sure servoTimer isn't a local variable.

@Gerben I posted the entire sketch.

That isn't the whole sketch. The lines counter=millis();//my timer onwards are outside any function. Try compiling what you posted.

@NickGammon When I was copying/pasting, I forgot the void loop(). I added it in. I still have it in my code like it should be.

Could it be that the arduino is reseting, because the servo uses too much power? Try adding  something like Serial.println("start"); to the setup function, so you can detect resets.

@Gerben I will try that. Do you think a 4AA battery pack of rechargeable batteries will work for a 5v servo? Because on full charge, they can be nearly 6 volts.

@Gerben I tried and the Arduino does not reset.

I added some more debugging, and I think I have your issues detected.
Amended code:
#include <Servo.h>
#define trig 22
#define echo 24
long duration;
boolean turned130 = false;
int cm50, cm, cm130;
Servo servo;
boolean checkRight = false;
boolean mainPing = true;
unsigned long counter;
unsigned long servoTimer = millis();
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(echo, INPUT);
  pinMode(trig, OUTPUT);
  servo.attach(12);
  servo.write(90);
  delay(2000);
}

void loop() {
  counter = millis(); //my timer
  if (((counter - servoTimer) >= 250) && mainPing) { //distance measured 4 times a second
    Serial.print ("Doing ping at time ");
    Serial.println (counter);
    ping();
    cm = duration / 29.1 / 2;
    Serial.println(cm);
    servoTimer = counter; //this if statement works fine
  }
  if ((cm < 30) && mainPing) {

    mainPing = false; //makes the 90 degree ping and this if statement unable to run
    checkRight = true;//enables next if statement to run
    servoTimer = millis();
    servo.write(130);
    cm = 30; //so that this if statement does not get called again until distance is obtained
    Serial.println("Inside less than 30 loop");//I added this for debugging, to let me know when the loop is called
  }
  if (checkRight && ((counter - servoTimer) >= 2000)) { //after 2 seconds passes
    Serial.print ("counter = ");
    Serial.println (counter);
    Serial.print ("servoTimer = ");
    Serial.println (servoTimer);
    checkRight = false;
    ping();
    cm130 = duration / 29.1 / 2;
    mainPing = true;//enable to other 2 if statements to run
    servoTimer = millis();
    Serial.print ("cm130 = ");
    Serial.println(cm130);
    servo.write(90);//turn motor back
    Serial.println("Inside other loop");//for debugging
  }
  delay(2);
}

void ping() {
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
}

With no server (or anything) attached I get this output:
Doing ping at time 1999
0
Inside less than 30 loop
counter = 1999
servoTimer = 2693
cm130 = 0
Inside other loop

First note that servoTimer is somewhat higher than counter because the pulseIn function takes a while to execute (times out after 1 second allegedly, although that was less than a second).
Now we come to the problem "if" statement.
  if (checkRight && ((counter - servoTimer) >= 2000)) { //after 2 seconds passes

That can't be right, eh? counter is 1999 and servoTimer is 2693, and there is not 2000 difference. However you are doing the maths the other way:
counter - servoTimer =  1999 - 2693 = -694

Since we are using unsigned long, it cannot hold negative numbers so the result of the subtraction is 4294966602.

That is much larger than 2000, so the "if" branch is taken.

Your answer makes a lot of sense. What I did to address the issue is put counter=millis(); after each ping before I set the servoTimer. This seemed to fix the issue. Works really well now! Now I have to make it turn left as well and record distances. It should not be a problem with this issue taken care of. Quick question, what is "" for? Is it necessary? Thank you for your help!

The language tag is just a hint to Stack Exchange to syntax-colour the code. Look at the posts. Mine is coloured, yours isn't. :) However I notice now that I put it in the wrong place. I must have hit "paste" at the wrong time. I've edited it out of the code.


text:
Gas Sensor Library for Proteus
Does any one know how to use Gas Sensor module in Proteus. I wanna use Gas Sensor but I am unable to find it in Proteus. So, does anyone know any way of adding Gas Sensor Library for Proteus software. Thanks in advance.

I have found the Gas Sensor Library for Proteus, so I thought to share it here so that others can also get benefit out of it. They have also posted the complete method of How to use this Gas Sensor Library and have also given an example to download.
Thanks.


text:
TCS230 Low Pulse Length with Arduino
My son and I are attempting to connect a TCS230 Color Sensor to an Arduino Nano using the tutorial at TopTechBoy.com (http://www.toptechboy.com/arduino/lesson-15-super-cool-arduino-color-sensor-project/) as guidance.
Everything seems to be working except that the conversion from pulseIn to RGB used on TopTechBoy is expecting a maximum pulse count of 102,400. Instead I am receiving pulseIn readings with a maximum of 2000.
Our Wiring
S0  - GND
 S1  - 5V
 OE  - No Connection (Tried GND)
 GND - GND
 S2  - D8
 S3  - D7
 OUT - D4
 VCC - 5V
Our Code:
int S2 = 8;
int S3 = 7;
int OUT = 4;

void setup() {

Serial.begin(9600);
pinMode (S2, OUTPUT);
pinMode (S3, OUTPUT);
pinMode (OUT, INPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  int red , green, blue;

  red = getRed();
  Serial.print("Red : "); Serial.println(red);
  Serial.println("**********************");
  Serial.println();

  blue = getBlue();
  Serial.print("Blue : "); Serial.println(blue);
  Serial.println("**********************");
  Serial.println();

  green = getGreen();
  Serial.print("Green : "); Serial.println(green);
  Serial.println("**********************");
  Serial.println();

  delay(3000);

}

int getRed(void){ return getColor(0, 0, 19000, 24000); }

int getGreen(void){return getColor(1, 1, 13600, 19200);}

int getBlue(void){return getColor (0, 1, 16400, 21600);}

int getColor(int s2Value, int s3Value , int typicalPulseWidth, int maxPulseWidth){

  long divideForScale = typicalPulseWidth / 255 ;

  digitalWrite(S2, s2Value);
  digitalWrite(S3, s3Value);

  unsigned int pulseWidth = pulseIn(OUT,LOW);

  Serial.print("Pulse Width : "); Serial.println(pulseWidth);

  unsigned int rColor = pulseWidth / divideForScale ; //401.5686274509804
  Serial.print("Response Color - Inverted : "); Serial.println(rColor);

  rColor = 255 - rColor ;
  Serial.print("Response Color - Final : "); Serial.println(rColor);

  delay(500);

  return rColor ;

}

The pulses appear correct, just out of scale. Red items produce short Red pulses and so on.
I tried to correct for the shorter pulses by using the Typical Output Frequency (f0) found on page 4 of the data sheet. I'm not sure if this is the right use of this frequency output spec.
http://www.unihedron.com/projects/darksky/tcs230-e33.pdf
Lowering the max possible pulses per second from 100,400 to around 20,000 gave us a little more variation between RGB values, but still the output is nothing like the expected color.
Can anybody offer some insight as to why the TCS230 pulse count is far fewer than the TTB code expects and what can I do to fix either the pulse count or the scale? Kind regards.
Output from Measuring a Blue RFID Keyfob:
    divideForScale : 74
    Pulse Width : 673
    Response Color - Inverted : 9
    Respponse Color - Final : 246
    Red : 246
    **********************
divideForScale : 64
Pulse Width : 376
Response Color - Inverted : 5
Respponse Color - Final : 250
Blue : 250
**********************

divideForScale : 53
Pulse Width : 737
Response Color - Inverted : 13
Respponse Color - Final : 242
Green : 242
**********************

Do you have an oscilloscope? I think the first step is to fully read the technical documentation on the device (your link) and understand the information on the typical frequency at full resolution (which is pretty high.) It's easy to protoboard this device with a power supply and NO Raspberry pi 3 attached. Just hook up some selector switches so you can play with S1 to S4 and see what the scope sees. If you've done that, know it works okay without the Pi, then this is either an interfacing problem (good here) or a software problem (good elsewhere.)

No oscilloscope - I've never touched any of this stuff before this summer so please feel free to correct what I may not understand about the datasheet.
We tried all of the S0 and S1 setting and it makes sense that 2% resolution would generate the longest pulse so that is what we are using - but even at 2%, pulseIn maxes out at 2000 or so.
Why are the pulses so short? Is the 102,400 max pulse width from TTB.com correct? How can I find the correct max pulse width from the datasheet info?

Connect S0 to 5V to get 100% OUTPUT FREQUENCY SCALING.
Currently, with S0 LOW and S1 HIGH, you get 2% OUTPUT FREQUENCY SCALING. Which would explain the 50 times to low values you get (100% / 2% = 50).

I tried increasing the resolution but the pulse width decreases as the resolution increases. S0 - Low and S1 - High for 2% resolution provides the longest pulses.

I'm not really following, but the fact that you tried different S0, S1 combinations, means this isn't the solution. Maybe someone else knows. Best of luck.

The  reading from pulseIn was about 30 - 50 when S0 and S1 were both set to High. Perhaps resolution is not the correct word, but a higher output frequency seems to require a shorter pulse rate. The 2000 reading from pulseIn at 2% is the longest pulse we were able to get back from the unit.

From the project page (a comment by Marius David) it seems some integer datatypes may not be the same on different platforms. If he is correct, you may be working with a 16 bit pulseWidth while 32 bits are needed.
Try using an unsigned long for the pulseWidth variable.

Good idea but no such luck. Issue persisted after changing pulseWidth type to unsigned long


text:
Arduino Leonardo isn't detected by Linux Mint on serial port /dev/ttyACM0
I'm working on Linux Mint 18 Sarah (earlier Ubuntu 16.04 LTS) system. I've installed Arduino IDE using command sudo apt-get install arduino and I've added me dialout group using sudo usermod -aG dialout $(whoami). This is results of executing groups command:
hubert@hubert-SATELLITE-C660D ~ $ groups
dialout adm cdrom sudo dip plugdev lpadmin sambashare hubert

When I try upload following code to Arduino Leonardo:

/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.

  This example code is in the public domain.
 */

// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(500);               // wait for a second
}

orange LED marked with L letter on my board blinks and next I get following error:
Wielkość binarna szkicu: 4 736 bajtów (maksymalnie: 28 672 bajtów)
processing.app.debug.RunnerException: Couldn’t find a Leonardo on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.
    at processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:153)
    at processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)
    at processing.app.Sketch.upload(Sketch.java:1671)
    at processing.app.Sketch.exportApplet(Sketch.java:1627)
    at processing.app.Sketch.exportApplet(Sketch.java:1599)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)
    at java.lang.Thread.run(Thread.java:745)

On my IDE Arduino shows on /dev/ttyACM0 serial port. When I try running this IDE on root privileges, I get the same error. On root privileges serial port is changing from /dev/ttyACM0 to /dev/ttyACM1, from /dev/ttyACM1 to /dev/ttyACM2 etc. I tried different USB cabels and reset Arduino but these ways nothing help. On Windows 7 my Arduino works and Arduino IDE uploads code without problems. Can anybody help me?

Read this: https://hackingmajenkoblog.wordpress.com/2016/08/24/diagnosing-arduino-problems-in-linux/

FWIW my money is on ModemManager.

Are you create ModemManager app?

No. "my money is on..." is a British idiom meaning "If I were a gambling man and I placed a bet on the cause, I would bet on it being ModemManager".

What exactly is ModemManager?

It's explained in the link I posted above.

Let us continue this discussion in chat.

Have you read that article? Have you tried the things in it? Until you do I cannot help you further.

Yes, I executed these instructions.

I've one more question. Did you write this guide for only Linux Mint distribution?

That guide is generic for most Linux distros, but I use Debian which is what Ubuntu is based on, which in turn is what Mint is based on.

So what was the outcome of disabling / removing ModemManager?

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


text:
Can I use a DAC with an L293D driver?
I'm trying to provide analog control to a Bluetooth controlled car, via Arduino. I have joystick app (as the pot).
It send values between 0 to 255
So I'm thinking... Whether this flow down here  will work?
Joystick app --> Bluetooth Rx --> DAC --> Vs pin of L293D. Or motor?
Is Arduino required at all? Or is the serial word enough to translate into voltage via DAC?

You need a PWM signal for a motor driver, not a DAC.

@Majenko but I am using a simple dc motor not any servo or stepper motor

So? What difference does that make? A motor driver requires PWM. A DAC (unless it's a very expensive industrial one designed for the purpose) cannot directly drive a motor.

@Majenko that's what... I mean to use the output of the DAC to use with the "motor voltage" pin of l293d.

What "motor voltage" pin? If you mean the pair of VCC pins, I reiterate: a DAC cannot drive a motor.

@Majenko I totally agree that Kotor requires l293D to be driven. I agree.

@Majenko the thing is, the DAC provides variable voltage at its output depending on input bits? Right? So this voltage I'm planning to apply to the Vss pin or the motor voltage pin if l293d. So my idea was to vary the motor's input voltage through l293d via DAC. The variable voltage will alter it's rpm also right?

The power you put into the supply pins of the motor driver is what is used directly by the motor. That supply has to have enough current to drive the motor, which a DAC cannot provide. The motor driver is designed to switch a high current supply on and off to the motor. That is how it controls the speed. To use a DAC you will first have to convert that voltage into a PWM waveform to switch the EN pins of the driver so it can switch a high current source to drive the motor. The driver does not magic extra power from thin air.

@Majenko oh right... So the the current required by the motor is not provided by the DAC(insufficient), unlike a battery supply.

Correct. You need to amplify that some how, and for a motor the most efficient way is with an H bridge (motor driver) and PWM. There are voltage-to-PWM chips available that would do the job, but you may as well just use an ATTiny and lose the DAC.

@Majenko so the voltage level at the DAC output, which is determined by input bits, is converted to a pwm waveform. This is fed to en pins to enable that respective motor.

@Majenko this voltage that varies over say, 8 bits will produce a different waveform for each of the 256 voltage levels? If so, then this will keep on switching the en pin repeatedly depending on wavefrom and thus varying motor speed by determining for how long the motor remains on before giving it another pulse. Right?

Or you can try power amplifier and weep over all of the power turned into heat on it...

@NiranjanDixit Correct. But like I say - easier to just use a small MCU and not worry about the complexity of a DAC and PWM chip.

It seems part of question arises from confusion between the sparse PWM pulses (repeating only about 50 times a second) used as a command to radio control hobby servos and speed controls, vs the kind of continuous PWM needed to cause a simple H-bridge to directly modulate power to a motor itself.  Essentially the poster will be building their own "ESC" where the high rate continous PWM output is controlled by software and messages originating with bluetooth, rather than controlled by sparse PWM from an RC transmitter.

Also, consider getting something better than the antiquated L293D, especially if you want to run on batteries.  It is rather horrible, and there are a number of threads discussing better alternatives.

No, you cannot. A DAC cannot provide enough current to either directly drive a motor or to power a motor driver (which is basically driving the motor directly through a switch anyway).
A motor driver requires a PWM signal to rapidly switch a high current source on and off to set the motor speed.
You could feed the DAC output into the input of a voltage-to-PWM converter chip which would then feed the motor driver's EN pin, but that is pretty pointless when you could just use a small microcontroller to receive the digital speed value and directly generate a PWM signal.
After all, that is the kind of job that small microcontrollers are designed for...


text:
Identify connected PC per Arduino
Question:
Is there a way to collect any data (e.g. MAC addresses, installed devices, driver versions, etc.) from a PC by simply connecting an Arduino via USB to it, so that this PC can be clearly identified?
Background:
Basically, I`m using an Arduino to send some text to a computer by emulating a keyboard, but I don´t want the text to be sent to any computer I connect the Arduino with. That is why I want the PC to be identified first.
To be clear: this should be done without having to install programs on the PC in the first place.

No. The Arduino is a dumb device. It can only receive what you program the PC to send to it.

Ok, but what if could find a way to direct the PC to send the data to me, by sending commands when emulating a mouse and or keyboard.

Then you can possibly tell the PC to tell you things. As long as you already know what the PC is and what/how to instruct it to tell you the right things.

@AstronAUT Yes, if you emulate the keyboard to send keystrokes to run a command (hardcoded or from a network share/trusted network location) you can select a command that reports the desired information to some network server.

http://stackoverflow.com/questions/31165217/avr-usb-detect-os

How about a unique two part cable? Make it impossible to connect the Arduino to normal USB without the special adapter.

Is your USB on the PC generating a container ID?

http://arduino.stackexchange.com/q/1689/26072  May provide some ideas on connection of USB such a Leonardo's Class 1 serial.  Another option is I2c to USB.

While not exactly the thing you're looking for, Gobetwino is a pretty sweet tool. You can emulate what you want your Arduino to do, so for prototyping and concept development it is probably what you want: http://mikmo.dk/gobetwino.html

No you cannot. Arduino communicates to pc via UART so there must be a host which can send or receive the data. You have to install software on the host computer which can send and receive data to the com port to which arduino is connected to.