text:
How to control Keyboard inputs using arduino(serial monitor) and python keyboard libraries?
I am able to control my monitor and most other applications by giving serial input to python through arduino.
Arduino code:
void setup()
 {

  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, INPUT);
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(7, INPUT);
  Serial.begin(9600);

}

void loop()
{
  if(digitalRead(2) == HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("up");
  }
  if(digitalRead(3) == HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("down");
  }
  if(digitalRead(4) == HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("left");
  }
  if(digitalRead(5) == HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("right");
  }
  if(digitalRead(6)== HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("space");//orange
  }
  if(digitalRead(7)==HIGH)
  {
     delay(5);
  }
  else
  {
    Serial.println("nitro");//brown
  }
 }

Python code:
import serial
from pymouse import PyMouse
from pykeyboard import PyKeyboard

k = PyKeyboard()

ser = serial.Serial('COM7', 9600)

#sp.write("AT\r\n".encode('ascii'))

while True:
    p=ser.readline()
    print p
    if ('up' in p):
        k = PyKeyboard()

        k.tap_key(k.up_key)

    if ('down' in p):
        k = PyKeyboard()

        k.tap_key(k.down_key)

    if ('right' in p):
        k = PyKeyboard()

        k.tap_key(k.right_key)

    if ('left' in p):
        k = PyKeyboard()

        k.tap_key(k.left_key)

    if ('space' in p):
        k = PyKeyboard()

        k.tap_key(k.space_key)

    if ('nitro' in p):
        k = PyKeyboard()

        k.tap_key(k.enter_key)

My problem is that..I am not able to play games such as NFS and other similar games using these controls..
What should i do??

This appears to cover much the same ground as http://arduino.stackexchange.com/questions/1148/use-an-arduino-as-a-user-interface-for-the-computer

Your examples of sending input to the Arduino IDE monitor and to Python involve the Arduino sending data via "Serial over USB" convention. However this is not seen by the operating system (Windows, MacOS) as legitimate keyboard/mouse/joystick input.
There are separate USB conventions (device types) for keyboard/mouse/joystick. Only Arduinos where the USB interface is programmable are able to present those conventions, and some more easily than others, and require understanding some USB client libraries.  The link provided by Chris Stratton has some useful background.
A particularly easy way to get into this is with the PJRC Teensy, https://www.pjrc.com/teensy/, which comes with libraries and examples that let you do this out-of-the-box. See the "Teensyduino" section of their website for USB Keyboard, Mouse, Joystick and so on. These pages are useful background even if not using Teensy. It has attracted a small following of users interested in this area. Plus the various Teensies are conveniently small boards that fits nicely in some user-interface device you might want to build.

I'm later, but, I think you should redesign your python and arduino code, to make messages like "start up", "end up", and if message is "start *", hold that key, if "end *", release that key. This should work as intended. I will pin python and arduino code later here. (Also sorry for my english, i'm russian)


text:
Can I simulate a clock without an RTC connected?
I want to program for a timer that works as set timer such as in an oven where user can set their own time. One of the way I know is using an IC(RTC) for the timer. However, I don't have the IC yet only the coding and Arduino.
Is it possible to simulate the Arduino code without having the RTC? Or is there any electrical component that I can use to replace the IC for the time being?
Thank you for your help and comment.I really appreciate that.

You can, by using millis(), if you can tolerate the mediocre frequency accuracy of the ceramic resonator clocking the Arduino.

Yes, if you don't mind if your cake cooks for 1 hour or 1 hour and 5 seconds. :)

Are you referring to a RTC (Real Time Clock) chip?

Reply to Majenko: Yes the RTC chip.

TimeLib.h has a virtual clock that can be updated and corrected from multiple sources, including an RTC chip or an NTP server on the internet (assuming an internet connection).
It doesn't need that clock source, though, but it will drift with time. Once you have set the clock correctly it will keep close to the right time (assuming no reset or power loss of the Arduino). Not perfect (because the Arduino's main clock isn't perfect) but close enough for many simple applications.

There are programs to simulate Arduino code, but they are very limited. To really simulate the circuit the program would have to also know about the IC you are using. You didn't told us what IC this is, so we can only speculate, that it might not be something, that these programs know (though you can try it). And sometimes Arduino Simulators have problems with simulating time sensitive code. If you want to try, just google for Arduino Simulator and check out the possibilities. I cannot suggest one, since I didn't use one until now.
At this point it might be the better option to write time-keeping code using the millis() function, which returns the number of milliseconds since the Arduino started. Save a timestamp from when you started and compare the difference between millis() and your timestamp to the wanted bake time.
You can pack this code in extra functions, that can later be replaced by code managing the "timer IC". With dividing your code this way you can write the rest of the logic without bothering about the timing part (after writing the millis() part as a "dummy").
For an oven timer the accuracy of the Arduinos clock should be ok, since it doesn't really matter, if it is a few seconds off. And for testing and writing the first code version it is also sufficient.

If the IC you are referring  to is a RTC (Real Time Clock) module, the code for it should be pretty simple to write. There are libraries for the most common RTCs. You might want to try the Arduino Time library.

source: Stack Exchange

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

sort: votes


text:
How do nested for loops work?
In the following code from an Arduino sketch will it run the first "for" statement before enacting the second "for" statement. Also how does it know go run the first stamens again? Will it continue to run till both statements are true?
for(int r = 0; r < 8; r++){
    for(int c = 0; c < 8; c++){
        lc.setLed(0, r, c, HIGH);
    }
}

A for statement repeats everything between { and }, (or just the next line if there is no { and } a certain number of times.  It's not as simple as you might at first think, but it makes more sense if you write it out as a while loop explicitly.
For instance, for (a; b; c) { ... } could be re-written as:
a;
while (b) {
    c;
}

So if you had:
for (int i = 0; i < 100; i++) {
    Serial.println(i);
}

it could be re-written as:
int i = 0;
while (i < 100) {
    Serial.println(i);
    i++;
}

The two mean exactly the same thing.  A for has the three elements - initializer, comparison and iterator.  The initializer is run before the loop starts, the comparison is used to work out when the loop should finish, and the iterator is used to move through each iteration of the loop.
To re-write your specific example:
for(int r = 0; r < 8; r++){
    for(int c = 0; c < 8; c++){
        lc.setLed(0, r, c, HIGH);
    }
}

You would end up with:
int r = 0;
while (r < 8) {
    int c = 0;
    while (c < 8) {
        lc.setLed(0, r, c, HIGH);
        c++;
    }
    r++;
}

Now, if we were to do away with the loops altogether and write it all out longhand, what would it look like?  Well, let's start with the inner c loop.  That loops from 0 to 7 (while less than 8), so replacing that loop with 8 discrete calls to the function replacing c each time would end up with:
int r = 0;
while (r < 8) {
    lc.setLed(0, r, 0, HIGH);
    lc.setLed(0, r, 1, HIGH);
    lc.setLed(0, r, 2, HIGH);
    lc.setLed(0, r, 3, HIGH);
    lc.setLed(0, r, 4, HIGH);
    lc.setLed(0, r, 5, HIGH);
    lc.setLed(0, r, 6, HIGH);
    lc.setLed(0, r, 7, HIGH);
    r++;
}

We could take it a step further and unroll the outer r loop.  A subset of what you would end up with would be like this (note, I have skipped a lot of the middle ones):
lc.setLed(0, 0, 0, HIGH);
lc.setLed(0, 0, 1, HIGH);
lc.setLed(0, 0, 2, HIGH);
lc.setLed(0, 0, 3, HIGH);
lc.setLed(0, 0, 4, HIGH);
lc.setLed(0, 0, 5, HIGH);
lc.setLed(0, 0, 6, HIGH);
lc.setLed(0, 0, 7, HIGH);
lc.setLed(0, 1, 0, HIGH);
lc.setLed(0, 1, 1, HIGH);
... skipped a lot ...
lc.setLed(0, 6, 6, HIGH);
lc.setLed(0, 6, 7, HIGH);
lc.setLed(0, 7, 0, HIGH);
lc.setLed(0, 7, 1, HIGH);
lc.setLed(0, 7, 2, HIGH);
lc.setLed(0, 7, 3, HIGH);
lc.setLed(0, 7, 4, HIGH);
lc.setLed(0, 7, 5, HIGH);
lc.setLed(0, 7, 6, HIGH);
lc.setLed(0, 7, 7, HIGH);

There would, of course, be 8 × 8 = 64 entries in there.
for loops can be used in lots of other fun ways too.  It's not just a simple "run this X number of times".  For instance, you can loop through a C string until you reach the NULL character at the end of the string:
for (char *p = str; *p != 0; p++) {
    ... do something with *p
}

You can iterate through the entries in a linked list:
for (struct mylist *scan = myListHead; scan; scan = scan->next) {
    ... do something to scan->whatever ...
}

You can even embed functions in there:
for (char c = 0; c != '\n'; c = Serial.read()) {
    ... Do something with character `c` until `c` is a line feed ...
}

As you can see for is an incredibly powerful and flexible tool that is often overlooked in favour of the more explicit while.

This was incredibly useful. Expressing it in terms of while made it easier to understand. Thank you.

Mr. Majenko, I'm a teacher trying to teach junior high kids programming using Arduino. I can do the basic "if," "else," etc. The kids wanted to learn how to program a game, I'm using this code http://www.itopen.it/arduino-pong-with-8x8-led-matrix-and-max7219/ I've tried to figure out the code with great success but I still have a few questions. Where is good place to ask them? Your answer was very useful but I often feel intimidated asking questions in this "forum." Thank you for your time.

@GabeRuiz Don't be intimidated.  We're here to help. It's only when people ask "Tell me how to do this project" and things like that we get a bit shirty with them. Questions like yours, along the lines of "How does this work" or "I don't understand this bit, can you explain it" are bread and butter for this site.  Feel free to ask away.

The preferable approach is to make an attempt on your own, and if it doesn't quite do what you want, post your code, describe what happened, and compare it to what your expectations were. Or if it does work, you might ask if there is a better way of doing it.

What you have there is a nested loop. The first for statement runs 8 times, incrementing r from 0 to 7. For each of those 8 iterations the second for statement runs, incrementing c from 0 to 7. Thus the setLed statement is executed 64 times.

Will it continue to run till both statements are true?

Yes. Unless you have a break or return statement somewhere in the part of the code you haven't shown.
Strictly-speaking, a statement does not become true. They will run while the test inside the for remains true (both tests).
This is standard C++ or C programming. You may wish to consult a C tutorial if you find this sort of thing puzzling.

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


text:
how to set the pin 13 only HIGH for 1 minute if sensor at pin 8 give HIGH?
int PUMP = 13;
int sensor = 8;
int val;

void setup() {
  pinMode(13,OUTPUT);
  pinMode(8,INPUT);
}

void loop() {
  val = digitalRead(8);
  if(val == HIGH)
  {
    digitalWrite(13,HIGH);
  }
  else
  {
    digitalWrite(13,LOW);
  }

  delay(0);
}

the digital input (pin8) has four basic states that you can be used to trigger an event (pin13)  ..... the four are low, rising edge, high and falling edge  ..... assume that the low and high states can be indefinitely long .... you have to decide which state triggers the 1 minute timer and whether some state re-triggers the 1 minute timer before it times out

Just add delay after you turn on pin 13. So it would be:
int PUMP = 13;
int sensor = 8;
int val;

void setup() {
  pinMode(13, OUTPUT);
  pinMode(8, INPUT);
}

void loop() {

  val = digitalRead(8);

  if (val == HIGH)
  {
    digitalWrite(13, HIGH);
    delay(60000); //60000ms is 1 minute
  }
  else
  {
    digitalWrite(13, LOW);
  }
}

I want to add to the answer of Ian:

If you later want to do something within that minute, you should not use delay. Instead use millis, see Blink without delay and use the same principle. It is considered bad practice to use delays, since it prevents from doing anything else in the mean time. For your small example it is not a problem though.
Also check what you really mean with requirement 'set pin 13 high if pin 8 is high' :

What if pin 13 stays high for 2 minutes, should pin 8 stay high 1 minute from the start that pin 13 got high (thus will be low when pin 13 is still high)
Or should pin 8 stay high 1 minute after pin 13 gets to low again. In this case you need to check for flanks instead of only the current state.

That's a poor way to do it, the uC is then sitting there for a minute unable to do anything else.
A better way is to capture the time of the input pin, then keep checking the time until 1 minute has elapsed.
void loop(){
   if ((digitalRead(8) == HIGH) && (timerRunning == 0)){
      startTime = millis(); // all time variables are type unsigned long
      digitalWrite (13, HIGH);
      timerRunning = 1;
   }
   if (timerRunning == 1){
      timeNow = millis();
      if ((timeNow - startTime)>= 60000UL){
         timerRunning = 0;
         digitalWrite (13, LOW);
      } //end time pass check
   } // end timer running check
   // now you can do other stuff while waiting for time to pass
} // end loop

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


text:
Arduino cat feeder
My cat feeder works like that:

LCD shows real time clock
Press a push button
LCD shows you to put the feeding time
You put the feeding time through a matricial keyboard
When feeding time is reached, a servo motor open the food container

The problem with my project is when the feeding time is reached, the servo motor doesn't open the food container! I'll put my code below, can you guys help me!! It's a project for college!!
#include  DS3231.h>
#include  Servo.h>
Servo microservo9g;
#include  LiquidCrystal.h>
#include  Keypad.h>
#include  Wire.h>

const byte ROWS = 4; // Four rows
const byte COLS = 4; // Three columns

// Define the Keymap

char hexaKeys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.

byte rowPins[ROWS] = {2, 3, 4, 5};

// Connect keypad COL0, COL1 and COL2 to these Arduino pins.

byte colPins[COLS] = {6, 7, 8, 9};

//  Create the Keypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS );
DS3231  rtc(A4, A5);
LiquidCrystal lcd(A0, A1, A2, 11, 12, 13); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7)
Time t;

 //int angle = 0;
// int potentio = A0;      // initialize the A0analog pin for potentiometer
 int t1, t2, t3, t4, t5, t6;

boolean feed = true; // condition for alarm

 char key;
 int r[6];

 void setup()
 {
  microservo9g.attach(10);
  lcd.begin(16,2);
  microservo9g.write(0);
  Serial.begin(9600);
  rtc.begin();
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(A2, OUTPUT);
 }

 void loop()
 {
lcd.clear();
lcd.setCursor(0,0);
int buttonPress;
buttonPress = digitalRead(A3);

if (buttonPress==1)
 setFeedingTime();
 char customKey = customKeypad.getKey();

//Serial.println(buttonPress);

 lcd.print("Time:  ");
 String t = "";
 t = rtc.getTimeStr();
 t1 = t.charAt(0)-48;
 t2 = t.charAt(1)-48;
 t3 = t.charAt(3)-48;
 t4 = t.charAt(4)-48;
 t5 = t.charAt(6)-48;
 t6 = t.charAt(7)-48;

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

 if (t1==r[0] && t2==r[1] && t3==r[2] && t4==r[3]&& t5<1 && t6<3 && feed==true)
 {
  microservo9g.write(90);
 //command to rotate the servo to the specified angle

  delay(400);
  microservo9g.write(0);
  feed=false;
 }
 }

void setFeedingTime()
{
  feed = true;
   int i=0;

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Set feeding Time");
  lcd.clear();
  lcd.print("HH:MM");
  lcd.setCursor(0,1);

  while(1){

key = customKeypad.getKey();

  char j;

 if(key!=NO_KEY){

  lcd.setCursor(j,1);

  lcd.print(key);

   r[i] = key-48;
    i++;
    j++;

 if (j==2)
    {

  lcd.print(":"); j++;
    }

   delay(500);
  }

 if (key == '*')

 {key=0; break; }
  }
}

Align your code (select code, press ctrl-k)

Your code still looks messy with al the parenthesis not aligned (very hard to see which code belongs to an if/while statement). Did you try the servo motor in an example? Also it will help to add Serial.print statements to show exactly the values around the places where you want the motor to start (and all other relevant places), to rule out if it is a software problem or hardware problem. At least check all values for t1 to t6, r[0] to r[3] and feed.

This code would not compile: Look at the #include statements. Each of them is missing an  beginning  <.  And also your poor cat has only 400 milli sec to eat.  :-( .i.e Perhaps the door is closed before you can see it open.

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


text:
How many connections can Arduino I2C method create?
I was just learning about I2C between 2 Arduinos, one as sender and another as a receiver
So I have got curiosity to know how many Arduinos can be connected to I2C connection in serial?
I mean,
Arduino1 --> Arduino2
Then can I connect Arduino3 to
Arduino 2 then again Arduino 4 to Arduino 3? Till how many Arduinos can I continue this connection?

you can't connect Arduino 3 to Arduino 2 as slave to master, because the MCUs you tagged have only one I2C interface and Arduino2 is already a slave. but you can connect many slaves to Arduino1 because I2C is a bus.

@Juraj I2C allows for multiple masters. Though it's rarely used, and requires some extra work to prevent collisions.

@Gerben that would be really very useful

@Gerben, the question describes a chain where 1 and 3 are connected only over 2. I only tor OP to realize the difference

@Gerben hello? I have a question that can a slave send data to master?

Not really. The master has to request the data. Some I2C devices have an interrupt pin, so they can "notify" the master that there is new data.

The limiting factor is the bus capacitance. This is the limit of the total capacitance of the bus from all devices connected to it plus the capacitance of the wires used.
It is also affected by the value of the pullup resistors.
The limit, according to the specifications, is 400pF.  An Arduino has an input capacitance of 10pF.  So ignoring the wires that's an absolute limit of 40 Arduinos all connected together.
Reduce that a bit for the wires, so say 30 is a reasonable estimate. Then reduce that again if you're using the internal pullups which are about 10x bigger than they should be. That gives you a guestimate of 5-10 devices.
Use proper pullups instead of the internal ones (why oh why oh why did Arduino ever encourage and even make default such a stupid option?!?!?!) of say 1kΩ and keep wires very short and you'll probably be OK up to 20-25 devices.

OP doesn't understand I2C and wants to connect Arduino 3 to Arduino 2, not to Arduino 1.

@Juraj With only one I2C interface the only way is with a bus. Whether it's 1-2,1-3,1-4 or 1-2,2-3,3-4 it's still a bus. Just the arrangement of the wires differs. I understand him to mean wiring A4/5 on 1 to A4/5 on 2, then A4/5 on 2 to A4/5 to 3, etc. That's just a single bus.

with two interfaces the MCU could be a master and slave

@Juraj Indeed. But the Uno only has one, so that observation is irrelevant.

I have to connect master arduinos scl and sda using same wires for all other slaves scl and sda ?

@SubhaJeetSikdar You can connect it how you like. You could go SDA/SCL on 1 to A4/A5 on 2, then SDA/SCL on 2 to A4/A5 on 3, etc. A4/A5 and SDA/SCL are directly connected to each other inside the Arduino's PCB. It's the same as connecting all the A4s together and all the A5s together, or connecting one A4 to another A4 to another A4 etc.

And adding pull up resistance means that 2 1k resistors will be needed per scl sda connection?

You need exactly 2 resistors, one on the SCL and one on the SDA. There is only one SCL and one SDA no matter how you arrange the wires.

And final question, can I call Arduino 3 from master Arduino when the Arduino 2 is acting as a slave?

You will have one master Arduino and a number of slave Arduinos. Every slave can be contacted by the master at any time. Only the master can talk to a slave, but it can talk to any slave it chooses. Each slave must have a unique address.

Thanks, u have cleared all my doubts :)

Hello? @Majenko can the address be a string else than an integer?

No. It has to be a number. That's how i2c works. Learn the protocol before you use it

The number is as many as you want.  There are switches that allow you to select different busses and each buss supports its full complement. From my point you are trying to use a solution before you have defined the problem fully. I have a feeling they will not be within a few inches of each other so consider an alternative designed for this type of use. CAN, RS485 and other interfaces would work much better with a lot less effort on your part.


text:
Seems like I cant control 4 stepper motor at once
Im trying to control 4 stepper motors with the AccelStepper library.
Something like this:
AccelStepper FL(1,stepPin,dirPin);
AccelStepper FR(1,stepPin2,dirPin2);
AccelStepper BL(1,stepPin3,dirPin3);
//AccelStepper BR(1,stepPin4,dirPin4);

The problem is, It works just fine if I declare 3 instance of the AccelStepper, but once I uncomment the 4th one there's an error.
Error message: Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "ESP32 Dev Module, Disabled, Default, 240MHz (WiFi/BT), QIO, 80MHz, 4MB (32Mb), 921600, None"

In file included from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/esp32/xtensa/xtruntime.h:30:0,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/freertos/freertos/portmacro.h:80,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/freertos/freertos/portable.h:94,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/freertos/freertos/FreeRTOS.h:105,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/Arduino.h:32,

                 from sketch\Test_file.ino.cpp:1:

C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/esp32/xtensa/config/specreg.h:40:13: error: expected unqualified-id before numeric constant

 #define BR  4

             ^

C:\Users\Parit\Desktop\Test_file\Test_file.ino:31:14: note: in expansion of macro 'BR'

 AccelStepper BR(1,stepPin4,dirPin4);

              ^

Multiple libraries were found for "WiFi.h"

 Used: C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\libraries\WiFi

 Not used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\WiFi

exit status 1

Error compiling for board ESP32 Dev Module.

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

Im not sure if the problem is the ESP 32 or the code. I use the A4988 driver to connect with all 4 stepper motors.

Please show the complete error message

Not in the comments please. You can add this information to your question by editing it

ok sorry, i'll add it now

The variable name BR is already used somewhere else.
Use a different variable name
AccelStepper FL(1,stepPin,dirPin);
AccelStepper FR(1,stepPin2,dirPin2);
AccelStepper BL(1,stepPin3,dirPin3);
AccelStepper BackRight(1,stepPin4,dirPin4);

Thank you ! It's working now. But it's weird, I can confirm that I haven't used a variable with that name any where in my code/

It's explained in the error message. It says BR is defined as a constant with value 4 ( #define BR  4)

Alright, but still, I didn't write  "#define BR 4" In my code. Anyways, it's working now so it doesn't matter, Thanks.

The first definition necessarily in your code - it may be in one of the libraries your code included.

According to the error message it's inside the file specreg.h. Try reading the error messages you get. They contain a lot more information than you'd think. They can be a bit overwhelming at first, but after a few of them you'll get a feel for what's relevant, and what to look for.


text:
Safely enabling voltage divider on a 12V battery
I'm planning to monitor voltage of a 12V battery with an Arduino's ADC pin connected via a voltage divider. Since I don't want the circuit itself to drain the battery when not in use, I want to use a transistor to "enable" it via an Arduino DIO pin like:

Is this a safe circuit to use?
If I set EN low to disable the divider, will that risk putting 12V directly on the ADC pin and burn it out? I've found alternative designs, but they seem overly complicated.
Edit: The battery is a Lipo which is also powering the Arduino through a step-down DC converter.

No, that will not accomplish your goal.  The top resistor may be large enough that the Arduino MCU's protection diode may be able to handle the current sourced from the battery, however you will still be draining the battery, which is what you were trying to avoid. What is the capacity and chemistry of your battery?  I'd expect something like a car battery may have a self discharge rate that hides the load of your voltage divider.

The "Controllable Voltage Divider" on the page you linked seems more sensible to me. Plus I chuckled at the "NdN" transistor you were using. ;)

@ChrisStratton, How is it still draining the battery? Would it be different if I relocated the transistor to the high-side?

It is still draining the battery because there is a protection diode from the input to the ATMEGA's power supply, which clamps the input voltage at around .6v above the supply voltage, and that will be fed by the top resistor in your circuit.  Potentially (with a smaller resistance) this could even end up powering the ATMEGA from an input, though doing so is out of specification as the diodes are tiny and easily damaged.

@ChrisStratton, Right, so wouldn't moving the transistor to the high side should fix that? With EN pulled low, there won't be a circuit connecting 12V to the ADC input.

No, because on the high side you would need a PNP, and when connected to an MCU pin, you can't not pull its base low which would turn it on. So you use an NPN to turn on the PNP, and are basically in the territory of the multi-stage circuits already proposed.

I use a similar system on a product I recently worked on to monitor the battery voltage - and of course I didn't want it on all the time to drain the battery.
The trick, though, is to do the exact opposite of what you are doing.  Instead of isolating the ground (which leaves the battery then directly connected to the Arduino) you need to completely isolate the battery from the divider.
This can be accomplished by using a P-channel MOSFET which you can then drive with an N-channel MOSFET:

The theory is, when the Arduino DOUT is either LOW or not connected (pulled low by 10K resistor) the N channel MOSFET is turned off.  That means the gate of the P channel MOSFET is being pulled up to the battery voltage by the other 10K resistor, so the P channel MOSFET is off, which isolates the whole divider from the battery.
When DOUT goes HIGH it turns on the N channel MOSFET which then pulls the gate of the P channel MOSFET down to ground which then turns it on, thus connecting the divider to the battery.
When the P channel is OFF the only circuit connected to the ADC is the connection between the ADC input and ground through a 10K resistor, so everything is happy and safe.
You should not use resistors greater than around 10K in size on the input to the ADC because the ADC itself has a resistance (the impedance) which is placed in parallel to the lower resistor of the divider.  If the divider's resistors are too large that impedance will affect the accuracy of your readings because the total resistance of the lower resistor will be skewed slightly.  Yes, it's possible to compensate in software, but as long as you keep to a limit of 10K or so for the resistors you won't need to worry about doing such things.
Note that it is important to use a P-channel MOSFET for this, not a PNP transistor.  A P-channel MOSFET, when on, looks like a very small resistor.  A PNP transistor is seen as a fixed voltage drop skewing your results.  The N-channel MOSFET can be replaced by an NPN transistor if you wish, it makes no real difference. I nearly always use MOSFETS these days instead of BJTs though as a matter of course.
As an aside, the only other way of achieving this whilst maintaining the isolation of the ADC from the battery would be to replace the P channel MOSFET with a small relay (say a reed relay), but then you still have to build a relay driving circuit which is just about as complex as this one.

Interesting analysis. That's a good point about MOSFET vs BJT, however, I'm still not sure how the overall design fundamentally differs from my approach. If I relocated my transistor to the high side, and turned it off, wouldn't the ADC be similarly disconnected from the battery? Also, why can't you wire the DOUT directly to the P-MOSFET's gate? Will the P-MOSFET only activate with 12V?

The P mosfet's gate has to be pulled up to the source potential to turn it off - i.e., 12V.  Wiring it to 5V it will never turn off. You can't just move your transistor, you have to change the transistor's polarity (PNP instead of NPN or P channel instead of N channel) which then also means driving it properly with an N channel or NPN.

It appears you have the Drain and Source mixed up on the P-FET. I created your circuit in tinkercad and was having an issue until I switched them. Thanks for the circuit design - I'll try building it for real now. Here's the Tinkercad link if you're curious.

I'd use some very large resistors (e.g. 1 and 2 Mega Ohm), and add a small capacitor to the center, to stabilize the value during sampling. Using 1 and 2 MOhm would result in 10uA of current loss, which is probably negligible in your cases.

No, don't do that. Think about the input impedance of the ADC and what affect such large resistors would have...

@Majenko That's what the capacitor is for. Just make sure there is some time between measurements for the capacitor remain charged at the right voltage. But I might be wrong here!

Oh, and I wouldn't call 10µA negligible.  My last project idled at 50µA total - adding another 10µA on top of that would have been an increase of 20% current consumption.

10uA would take about 2 years to discharge a CR2032 coin cell. Since this is a 12V battery I assume it's more that 240mAh. Indeed 10uA isn't always negligible.

Keep in mind that an ADC of the type used here is typically not a steady-state load, but rather a pulsed one.  If you go with this route, it would be a good idea to evaluate the readings for various resistor and capacitor sizes.  I do expect you will see some distortion of reading, but I also expect it will be possible to get a decent reading with a circuit whose load is dwarfed by the self-discharge rate of a larger lead-acid battery if that is indeed what is being monitored.

@Majenko, How would such large resistors affect the ADC? What is the maximum resistance that should be used?

Depends on the sampling rate. The resistor should be small enough, so that the capacitor is being "fully charged" between reads.


text:
Practicality of recording speech
Is it practical to record speech with the Leonardo?
I want to record speech via a MEMS microphone and stream it over a serial connection to a Raspberry Pi for speech-to-text processing.
This article states that the typical bitrate for recording voice podcasts is 64 kbps. The Arduino's analogRead() function has a maximum sample rate of typically 8,600 times/sec for a maximum bitrate of 8,600 samples/sec * 10 bits/sample = 86 kbps, so theoretically, it should be fast enough to record decent voice audio.
However, will the serial connection be fast enough to stream this much data? Theoretically, the Leonardo's serial connection can go up to 115,200 bps, but I've never reliably gotten it to go faster than 57,600 bps, which would mean the serial connection would a bottleneck that would prevent it from sending a continuous stream of 64 kbps, and therefore it would be impractical to record speech with the Arduino.
Am I wrong? Has anyone had success with voice recording while streaming it over serial?

@Greenonline, sorry, I've fixed the link.

On my page about the ADC converter I attempted to record a 4 kHz sine wave on the ATmega328P with the following code:
const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

// ADC complete ISR
ISR (ADC_vect)
  {
  if (resultNumber >= MAX_RESULTS)
    ADCSRA = 0;  // turn off ADC
  else
    results [resultNumber++] = ADC;
  }  // end of ADC_vect

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);  // WTF?
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

  // wait for buffer to fill
  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
    Serial.println (results [i]);

  }  // end of setup

void loop () { }

The code (rather inefficiently) sends the results in ASCII, like this:
378
710
899
992
966
827
609
367
159
38
35
147
350
593
817
965
1001
917
733
494
259
88
21
76
239
471
711
905
1001
977
839
620
376
164
39

This gave reasonable results:

Now the Leonardo is, of course, a different processor. However it is similar. The ADC on it should be capable of similar performance.

I should point out that this code records first, then sends the data. This is so the recording can keep up. A normal ADC conversion (if you don't change the ADC prescaler) takes 104 µs. To send 10 bits via serial at 115200 baud rate would take 173.6 µs because it would require two bytes per sample (unless you somehow compress each reading). If you could put up with 8-bit resolution (per sample) then you halve that, and can probably just stream the data out fast enough.

Do you really need to enable the TIMER1_COMPB interrupt? The doc of the ADC says the conversion is triggered by the rising edge of the interrupt flag, and the interrupt flag does not need the interrupt enable bit to work. Did I miss something?

You could be right. Try it without the interrupt. However the EMPTY_INTERRUPT probably just generates an RTI instruction.

I tried it with the interrupt disabled: it doesn't work. Seems there is an error either in the silicon or in the datasheet: “Note that an Interrupt Flag will be set even if the specific interrupt is disabled or the Global Interrupt Enable bit in SREG is cleared. A conversion can thus be triggered without causing an interrupt.” You may have noticed the inconsistency if I understand the comment next to setting TIMSK1. The empty interrupt is indeed just a reti, but the whole interrupt processing (save context, load address of vector, execute vector (jmp), reti) takes 11 cycles.

There's no traditional meaning to baud rate on a Leonardo.  Transmitting extra data over USB, at least in binary, is probably faster than doing logarythmic encoding as traditionally used for 8-bit telephone links.

I did some extra tests: my previous comment is wrong. What I missed is the conversion being triggered by a rising edge of the interrupt flag used as a trigger source. In order to have more than one such edge, the flag has to be cleared after it is set. This can be done automatically by enabling the interrupt: “OCF1B is automatically cleared when the Output Compare Match B Interrupt Vector is executed.” The other option is to clear the flag manually, e.g. by doing TIFR1 = _BV(OCF1B); inside ISR(ADC_vect).

You don't actually have to initialize your connection to 115,200 bps or 57,600 bps. You can use a custom baud rate of 65,000 bps.
One thing to keep in mind that, you can use any custom baud rate you want, as long as it's supported by the hardware. The Arduino IDE however only supports standard baud rates.
One more thing, as you are streaming data (kind of), you might also want to look into Arduino serial buffer sizes.

There's actually no (traditional) meaning to the baud rate setting on a Leonardo.


text:
FSR wiring using internal pullup resistors?
What are the disadvantages to using Arduino's internal pullups with a force force sensitive resistor (FSR) sensor?
All the wiring examples I see for FSRs place the sensor on the high side and use a 10k pulldown resistor. Searching Google, I can find virtually no one who places the FSR on the low side and uses the internal pullup. Since this would reduce complexity by using one less wire and resistor, I have to assume there's some big downside I'm not seeing. Why shouldn't you use the internal pullup?
I've worked with conventional potentiometers in the 100k ohm range, and I've found that with values that high, the Arduino's ADC finds a lot of noise, resulting in a sensor value that jitters and drifts. I found that the only reliable way to get a stable ADC value is to use a potentiometer with a maximum value of 10k or less. Since the FSR's range is up to 1M ohms, I'm worried I won't be able to get a stable reading. Does wiring it via the high side or low side effect this? What can I do to minimize noise from the FSR, other than shielding the sensor cable or adding a capacitor between the signal a and ground wire?

There is probably no practical difference concerning high side vs low side (except the Arduino Uno only has a pullup, and no pulldown).
The issue would be the accuracy of the pullup (graphs in the datasheet show variations of 10% with temperature) vs the accuracy of the resistor (1% is now commonplace).
The pullup is usually a current source, not a specific resistor value. Even if the supply voltage is not known, the maths involved with solving a known resistor is series with an unknown resistor is quite straightforward.
Short answer, using the pullups would probably work, but you would have to confirm accuracy, calibration and even repeatability, while this is already well known for a resistor.
Datasheet, see graphs on p412:
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf


text:
weird output from keyboard program
I am trying to write a keyboard (Key-glove) program. There are 4 buttons, and inputs should type specific keys. when the keyboard is active, I get output, but not what I am expecting for output. I get "EnE" and "EC".
The Hardware is an adafruit Circuit Playground
Here is my source:
//keyboard control for TuxKart power Glove
#include <Adafruit_CircuitPlayground.h>
#include "Keyboard.h"

// set pin numbers for the five buttons:
const int Fire = 6;
const int Nitro = 9;
const int Eagle = 10;
const int _Esc = 12;

bool slideSwitch;

void setup() { // initialize the buttons' inputs:
  pinMode(Fire, INPUT);
  pinMode(Nitro, INPUT);
  pinMode(Eagle, INPUT);
  pinMode(_Esc, INPUT);

  Serial.begin(9600);
  // initialize mouse control:
  //Mouse.begin();
  Keyboard.begin();
}

void loop() {
  if (!CircuitPlayground.slideSwitch()) {
    return;
  }

  // use the pushbuttons to control the keyboard:
  if (digitalRead(Fire) == HIGH) {
    Keyboard.write('KEY_SPACE');
    Serial.println("A");
  }
  if (digitalRead(Nitro) == HIGH) {
    Keyboard.write('n');
    Serial.println("B");
  }
  if (digitalRead(Eagle) == HIGH) {
    Keyboard.write('KEY_BACKSPACE');
    Serial.println("Z");
  }
  if (digitalRead(_Esc) == HIGH) {
    Keyboard.write('KEY_ESC');
    Serial.println("Y");
  }
delay(700);
}

What does this have to do with Adafruit, and what board are you running it on?    What program on the PC or USB host is interpreting the keystrokes, and how exactly where you expecting it to respond to the escape key?  How exactly are your input switches or devices wired?  Does HIGH mean active or inactive?

Remove the single quotation marks for Keyboard.write. Use Keyboard.write(KEY_SPACE); and so on. Keep them for 'n', but not for the others.


text:
Storing Long numbers in arduino like phone numbers...How?
I am using 20 x 4 LCD And 3 x4 keypad I want to enter and store 3 inputs in different variables the code I am using can store 3 inputs and display it right in serial monitor example I type 5 digits using keypad it will store and display correctly in LCD and serial monitor the right value however if its more than five it has negative output and very far to what inputted. Thank you for help .The code is...
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
SoftwareSerial mySerial(6,5);
#include <Keypad.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};
byte rowPins[ROWS] = {19, 18, 17, 16}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {15, 14, 13}; //connect to the column pinouts of the keypad

int count=0;
Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

char entryStr[12];   // This can hold up to 4 digits
int i=0;

void setup()
{
    mySerial.begin(9600);
    Serial.begin(9600);
    lcd.begin(20, 4);
}

void loop(){
    long n1, n2 , n3;

    lcd.setCursor(0,0);
    lcd.print("Enter n1:   ");

    lcd.setCursor(0,1);
    n1 = GetNumber();
    Serial.println ("n1: ");
    Serial.println (n1);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Enter  n2:   ");

    lcd.setCursor(0,1);
    n2= GetNumber();
    Serial.println ("n2: ");
    Serial.println (n2);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Enter n3:   ");
    lcd.setCursor(0,1);
    n3 = GetNumber();
    Serial.println ("n3: ");
    Serial.println (n3);
}

int GetNumber()
{
    long num = 0;
    char key = kpd.getKey();
    while(key != '#')
    {
        switch (key)
        {
            case NO_KEY:
            break;

            case '0': case '1': case '2': case '3': case '4':
            case '5': case '6': case '7': case '8': case '9':
            lcd.print(key);
            num = num * 10 + (key -'0');
            break;

            case '*':
            num = 0;
            lcd.clear();
            break;
        }
        key = kpd.getKey();
    }
    return num;
}

Phone numbers should be handled as strings. Otherwise 1, 01 and 000000001 will be the same.

int GetNumber()

should be changed to
long GetNumber()

It is because the function type is the type of value that returning. In this case you are returning a long so you have to change it. An int can handle a number from -32 768 to 32 767. A long on the other side can handle a number from -2,147,483,648 to 2,147,483,647.

thank you I followed what you advised it displayed the right value however if i tried to typed 091234 i can only see 91234 thank you very much I a newbie I appreciate your help a lot thanks

can be risky but use a char instead. the arduino sees your number as a litteral mathematical number. it will simplify your number by removing the 0s like when you do a calculation in math. please dont tell me you do 0003 x 0009 = 0027. using a char is like sending a complete word like HELLO then you can decompose it into multiple small bits such as H, E, L, L, O,. It also works with numbers like if your password was 0192, you can decompose it to 0_1_9_2

Thank you I'll try what you advices thank you again I appreciated your help and sharing your time thank you .

its char* btw. char is different then char* dont forget the *


text:
Switching methods/functions with a button
I am trying to program a basic counter using 7segment display and a button.
What I am trying to achieve is the following:

Display 0 at the beginning.
When the button is pressed: Start Loop 0-9
Display 0 when the button is pressed the second time.

So basically the button should function as ON/OFF switch for the looping numbers function.
So far I have managed to change the mode from  displaying 0 to looping 0-9, but can't seem to get changing the mode back to displaying 0:
int buttonPin = 10; // Button connected to digital pin 10.
// variable for reading the pushbutton status
boolean buttonPressed = false;
int mode;

void setup() {
    // initialize the pushbutton pin as an input:
    pinMode(buttonPin, INPUT);

    pinMode(1, OUTPUT);
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);
    pinMode(13, OUTPUT);
}

void displayZero() {
    //while (buttonState == true){
    // Displays 0.
    digitalWrite(11,1);
    //button();
    delay(1000);
    //}
}

void displayCounter() {
    // Displays 0.
    digitalWrite(4,1);
    digitalWrite(11,1);
    delay(1000);

    //Displays 1.
    digitalWrite(2,1);
    digitalWrite(3,1);
    digitalWrite(4,1);
    digitalWrite(8,1);
    delay(1000);

    //Displays 2.
    digitalWrite(2,0);
    digitalWrite(8,0);
    digitalWrite(6,0);
    digitalWrite(4,0);
    digitalWrite(9,1);
    digitalWrite(3,1);
    digitalWrite(11,0);
    delay(1000);

    //Displays 3.
    digitalWrite(4,1);
    digitalWrite(9,0);
    digitalWrite(11,0);
    delay(1000);

    //Displays 4.
    digitalWrite(2,1);
    digitalWrite(8,1);
    digitalWrite(3,0);
    delay(1000);

    //Displays 5.
    digitalWrite(6,1);
    digitalWrite(2,0);
    digitalWrite(8,0);
    digitalWrite(11,0);
    delay(1000);

    //Displays 6.
    digitalWrite(4,0);
    delay(1000);

    //Displays 7.
    digitalWrite(3,1);
    digitalWrite(4,1);
    digitalWrite(6,0);
    digitalWrite(8,1);
    digitalWrite(11,1);
    delay(1000);

    //Displays 8.
    digitalWrite(3,0);
    digitalWrite(4,0);
    digitalWrite(8,0);
    digitalWrite(11,0);
    delay(1000);

    //Displays 9.
    digitalWrite(4,1);
    //button();
    delay(1000);
}

void loop() {
    // Check button status.
    int buttonStatus = digitalRead(buttonPin);

    if (buttonStatus == HIGH)
    {
        // Checks if button is pressed and changes buttonPressed from false to true.
        buttonPressed = true;

        // While button is pressed.
        while(buttonPressed == true) {
            // Calls displayCounter method 10 times.
            for (int i=0; i<10; i++) {
                displayCounter();
                delay(30);
                buttonPressed == false;
            }
        }
    }
    else if (buttonStatus == LOW)
        displayZero();
}

You try to set pin 10 in INPUT then OUTPUT mode, hence it will not receive any input from your button. Also, based on your circuit, you may need to use INPUT_PULLUP instead of mere INPUT, otherwise you may have a dangling input signal.

In your loop() function, the statement buttonPressed == false; doesn't do anything; it is simply an expression that evaluates to 0 or false (because buttonPressed is equal to true). Your while() loop will never end which is why you can't stop the counter by pressing the button again.
You probably meant buttonPressed = false;, which is an assignment statement setting the value of buttonPressed.  But doing that within the while loop makes the loop contents iterate once which it would do anyway, so there is no need for the surrounding while statement. The for() statement will still be executed once, without the while (the loop contents will be iterated 10 times in that one execution).
So you can reduce your loop() function to:
void loop() {

// Check button status.
   int buttonStatus = digitalRead(buttonPin);

   if (buttonStatus == HIGH)
   {
      // Calls displayCounter method 10 times.
      for (int i=0; i<10; i++){
         displayCounter();
         delay(30);
      }
   }
   else
      displayZero();
}

which will check the button state on each call to loop() and either run the counter or zero it, once, depending on the state.
You'll need another refinement, that of debouncing the button. Push buttons (and some other kinds of switches don't have a clean 0 -> 1 (or vice versa) transition but take some amount of time during which their state appears to bounce between 0 and 1 before finally settling to the new state. Read Nick Gammon's excellent article about contact bounce to see why and what to do about it.

Not sure but this should work
const int segment[7] = {2,3,4,5,6,7,8}; //pins for each segment

const int nums[10][7] = //declaring array
{
  {1,1,1,1,1,1,0}, //0
  {0,1,1,0,0,0,0}, //1
  {1,1,0,1,0,0,1}, //2
  {1,1,1,1,0,0,1}, //3
  {0,1,1,0,0,1,1}, //4
  {1,0,1,1,0,1,1}, //5
  {1,0,1,1,1,1,1}, //6
  {1,1,1,0,0,0,0}, //7
  {1,1,1,1,1,1,1}, //8
  {1,1,1,0,0,1,1}  //9
};

//=======================================================================

#define button 9 //defining button that is connected to pin 9

//=======================================================================

void setup() {
  for(int i=2; i<=8; i++) //shorcut for declaring a buch of pin modes
  {
    pinMode(i, OUTPUT);
  }

  pinMode(button, INPUT); //set button as an input
}

//=======================================================================

void loop() {
  while(digitalRead(button) == LOW) //wait until user click the button
  {
    number(0); //display 0 when waiting
  }

  bool state = false; // create a status varible

  for(int i=0; i<10 && state == false; i++) //run the numbers from 0-9
  {

    number(i); //display the number

    for(int j=0; j<100 && state == false; j++)
    {

      if(digitalRead(button) == HIGH) //if the button is clicked, then cancel the loop ans go back to displaying 0
      {
        state = true;
      }

      delay(10); //this delay while execute a 1000 times so there is actualy a 1sec delay

    }
  }
}

//=======================================================================

void number(int num) //num is the number to display
{
  for(int i=0; i<7; i++)
  {
    digitalWrite(segment[i], nums[num][i]);
  }
}

Good starting answer, however there are few problems - you are displaying the current number 1000 times. This is not needed and takes a lot of time too. The call to number(i) should be just before the 'j' loop. Also you don't need millisecond granularity so the 'j' loop could be 0 to 10 and the delay could be 100 ms (or slightly less to adjust for the execution time of the extra commands). The user will probably not notice the difference, but then the timing would be closer to 1 second.

done, still prefer to have the delay low for better input resolution. espacially if he clicks fast. 100 ms is a liitle too much. also tried to keep it simple and not use any ISRs

Only one more thing - since you are iterating 100 times the digitalRead will be called 100 times - this will introduce extra delay so the numbers are going to be displayed more than one second. This could probably be adjusted in real life by timing and decreasing the loop maximum from 100, or decreasing the delay(10) accordingly.

Thanks for the answer, howeverm I didn't get it to work with my breadboard coupling. The way I have set my wires and display is, instead of turning the LEDs ON, it turns all the other LEDs OFF to display a certain number.

Apart from apparent issues in the details, the approach of using a lookup table here is far more sound than what Daniel was trying to do.  However, it looks like Daniel has a common anode display (drive segment low to illuminate), while this assumes common cathode (drive segment high).  Therefore, Daniel either needs to swap the 1's and 0's in the table, or change the output line to use the opposite of the table contents, ie !nums[num][i]

Also the table really shouldn't be of type int as that is just wasteful (16 bits to store just 1 with meaning) when a char (8 bits) would suffice, and this is a target without a lot of memory.   Most real implementations would actually make it a bitmap, using 1 bit to per bit of meaning, but that is conceptually more complicated.


text:
Extra characters remain in Serial
I have spent the whole day trying to deal with this problem connecting Arduinos together using UART (Serial). But the problem is that it always behaves weirdly. For now the problem is that if previous number (I am sending numbers over serial) stays in the serial port.
Let me describe the problem. I want to send the following sequence of numbers 16 4 100. Numbers are sent with a terminator char after each number, but on the receiver side I get the following result 16 46 100.
As you can see if the previous number is longer (length, has more digits) than the current one, like 16 and 4, 132 and 34, the difference (number of digits) remains in the next result: for 16 and 4 it will be 16 and 46, for 132 and 34 it will be 132 and 342.
I have tried different ways to solve this problem, but unfortunately I cannot find the solution.
Here are my functions used for communication:
void sendCommandToSerial(int command) {
  Serial3.print(command);
  Serial3.print(TERMINATOR_CHAR);
  Serial3.flush();
}

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

int readRawBytes(char *inputBuffer,const int bufferSize) {
  return Serial3.readBytesUntil(TERMINATOR_CHAR, inputBuffer, bufferSize);
}
int readIntFromSerial() {
  if(readRawBytes(inputBuffer,DEFAULT_BUFFER_SIZE) > 0) {
    return atoi(inputBuffer);
  }
  return -1;
}
int readFloatFromSerial() {
  if(readRawBytes(inputBuffer,DEFAULT_BUFFER_SIZE) > 0) {
    return atof(inputBuffer);
  }
  return -1;
}

I have tried both software and hardware serials, still the same.
Please help to find and solve the problem.

The Stream member function readBytesUntil() does not null terminate the string. It returns the number of characters read. You must terminate the string with null(0) before calling atoi() and atof() or fill the string will null(0) before calling readBytesUntil().
For more details see Arduino Stream.cpp.
Cheers!


text:
Problem in RS485 Communication between Arduino and PC
I'm trying to sending and receiving data via RS485 communication. Interfacing Arduino and PC(laptop)
using SN75176 RS485. I wrote a program to send a string "Hello" from arduino via Tx pin. My intention is to receive
the "Hello" string in my PC's hyperterminal. After uploading the program im receiving junk data. The baud rate i've mentioned in
my program and i gave in hyperterminal are same. I've checked the wire connection, it is ok. Then, what is the problem?
Code:
#include <SoftwareSerial.h>
int Txpin = 1;
int ditpin = 5;  //for 1st rs485
int ditpin1 = 2; //for 2nd rs485
void setup()
  {
          // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(Txpin,OUTPUT);
    digitalWrite(ditpin, HIGH); //For transmit data from arduino
    digitalWrite(ditpin1, LOW); //For receive data to hyperterminal
  }

void loop()
  {
    Serial.println("Hello\r\n");
    delay(1000);
  }

Wire connection:

No ground on the PC side?

Thanks for the reply...No. I didnt connect. Will it be the problem?

Instead i short both rs485 GND.

The control pin, VCC and ground is not correctly wired on the PC side. Google how to connect RS485. Too many issues with this wiring. Please see this reference. http://www.gammon.com.au/forum/?id=11428

Hi @MikaelPatel. Thanks for the post. Actually i'm not connecting two arduinos, connecting one arduino to PC using RS232 converter. As you said i connected the rs232 converter's(5th pin) GND to RS485's GND, but i'm giving power supply 5v it from arduino board on PC side since my rs232 converter doesnt have power supply pins.

Please start by fixing the ground connection to the PC. There are other issues but start with that.

Hi @MikaelPatel. I did that ground connection correctly. Still can't receive the data.

Did you forget the 120 ohm resistors?

Is 120 ohm will be the problem? I read that "to use resistor for long distance". Is it should place? Thanks..

I think I understand what you are trying to do. You do know that the signal (R) is not RS232 levels? It is 5V. I think you are looking for a TTL to RS232 converter and not RS485. Something like http://pdfserv.maximintegrated.com/en/ds/MAX3222-MAX3241.pdf. Or http://www.ebay.com/itm/MAX3232-RS232-Serial-Port-To-TTL-Converter-Module-Male-DB9-COM-Serial-MAX232/221545502349?_trksid=p2047675.c100005.m1851&_trkparms=aid%3D222007%26algo%3DSIC.MBE%26ao%3D1%26asc%3D34875%26meid%3D8f4caa5def98499c9502dd70b3505a35%26pid%3D100005%26rk%3D1%26rkt%3D6%26sd%3D221022603873

Hi @MikaelPatel. what about using 5v to 3.3v voltage divider circuit? Will it work link

You cannot connect from Arduino serial input/output with RS485 circuit and then to the PC RS232 port. You need a TTL to RS232 adapter. For instance an adapter based on MAX3222.

Cheers!


text:
MPU9150 (JEFF LIB) + FIFO_OVERFLOW INTERRUPT + SERIAL PRINT
Overflow enthusiasts!
I am trying to log accelerometer and gyro data using Serial.print. I have enabled the FIFO_Overflow interrupt. Whenever I log data, the serial port freezes. I am suspecting an interrupt issue while I am using Serial.print. Is there any way to get continuous data for debugging purposes? I know that the Serial library can affect interrupts and wonder whether you guys could help me a little bit ?
#include "Wire.h"
#include "I2Cdev.h"
#include "MPU9150.h"
#include "helper_3dmath.h"

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for InvenSense evaluation board)
// AD0 high = 0x69
MPU9150 accelGyroMag;
#define LED_PIN 13
volatile boolean state_fifo_int = false;
uint16_t fifo_count;
uint8_t fifo_buffer[8];
int16_t acc_temp[3];
int16_t gyro_x;

void setup(){
    // join I2C bus (I2Cdev library doesn't do this automatically)
    Wire.begin();
    // initialize serial communication
    // (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
    // it's really up to you depending on your project)
    Serial.begin(115200);
    // initialize device
    Serial.println("Initializing I2C devices...");
    accelGyroMag.initialize();
    // verify connection
    Serial.println("Testing device connections...");
    Serial.println(accelGyroMag.testConnection() ? "MPU9150 connection successful" : "MPU9150 connection failed");
    // configure Arduino LED for
    pinMode(LED_PIN, OUTPUT);
    attachInterrupt(0,fifo_int,CHANGE);
}

void fifo_int() {
  state_fifo_int = true;
}

void loop(){
  while(!state_fifo_int) {
    accelGyroMag.setIntFIFOBufferOverflowEnabled(true);
    // enable fifo_interrupt
    accelGyroMag.setFIFOEnabled(true);
    accelGyroMag.setAccelFIFOEnabled(true);
    accelGyroMag.getXGyroFIFOEnabled();
    accelGyroMag.getAccelFIFOEnabled();
    fifo_count = accelGyroMag.getFIFOCount();
    accelGyroMag.getFIFOBytes(fifo_buffer,8); // fill in fifo bytes
    acc_temp[0] = (((int16_t)fifo_buffer[0]) << 8) | fifo_buffer[1];
    acc_temp[1] = (((int16_t)fifo_buffer[2]) << 8) | fifo_buffer[3];
    acc_temp[2] = (((int16_t)fifo_buffer[4]) << 8) | fifo_buffer[5];
    gyro_x = (((int16_t)fifo_buffer[6]) << 8) | fifo_buffer[7];
    Serial.print((float)acc_temp[0]/16384);
    Serial.print("  ");
    Serial.print((float)acc_temp[1]/16384);
    Serial.print(" ");
    Serial.print((float)acc_temp[2]/16384);
    Serial.print(" ");
    Serial.println(gyro_x);
   }
   accelGyroMag.setIntFIFOBufferOverflowEnabled(false);
   // disable fifo_interrupt
   accelGyroMag.resetFIFO();
   state_fifo_int = false;
}

The library for the MPU9150 is by Jeff Rowberg.

Do you guys think it will work without the Serial.print library ? I cant approve if i get the right values. Dont want my project to crash.

Whenever I log data, the serial port freezes - after how much data? A line? 100 lines?

Arbitrary 50-70 lines

After reading the datasheet on the PS manual, I found out that the INT1 pulse had a width of 50uS.
So what I simply did was to declare a global integer and check it at the end of the loop.
Whenever I checked the incremented variable at the end, it was 48!.I personally suspected that my loop speed was to slow. Additionally the timeout value 14 ms per loop arbitrary. Clearly a disparity exists in the interrupt routine for the sensor and the microcontroller.
So what I simply did was to reconfigure the sensor output to a latched signal which clearly solved the problem. I am now getting synchronized interrupt with convincing results.
Here is the code:
#include "Wire.h"
#include "I2Cdev.h"
#include "MPU9150.h"
#include "helper_3dmath.h"

#define LED_BUILTIN 13

MPU9150 accelGyroMag;

volatile boolean state_fifo_int = false;
int x = 0;

void blink(uint16_t offTime, uint16_t onTime){
digitalWrite(LED_BUILTIN,HIGH);
if(onTime) delay(onTime);
digitalWrite(LED_BUILTIN,LOW);
if(offTime) delay(offTime);
}

void resetSensor(){
  accelGyroMag.reset();
  delay(50);
  accelGyroMag.initialize();
  //Serial.println("Initialize if connection test failed");

  if(accelGyroMag.testConnection()){ //disable interrupts
     accelGyroMag.setIntFIFOBufferOverflowEnabled(false);
     // disable fifo_interrupt
     accelGyroMag.resetFIFO();
        // verify connection

     //Serial.println("Connection tested successfully, Disabling interrupts");
     }
if(!accelGyroMag.testConnection()){ // try to recover sensor
  accelGyroMag.initialize();
    //Serial.println("Initialize if connection test failed");
  }
if(accelGyroMag.testConnection()){  // reconfigure sensor for Fifo and interrupts

   accelGyroMag.setFIFOEnabled(true);
   accelGyroMag.setXGyroFIFOEnabled(true);
   accelGyroMag.setAccelFIFOEnabled(true);
   accelGyroMag.setInterruptMode(false);// Set interrupt logic level mode 0 = active-high
   accelGyroMag.setInterruptLatch(true); //set interrupt 1=latch-until-int-cleared ( latch after INT_STATUS READ)
   accelGyroMag.setIntFIFOBufferOverflowEnabled(true);

   }
else {
 // Serial.println("MPU9150 connection failed");
  //Serial.println("locking UP");
  while(true){
     for(uint8_t i=0;i<3;i++){blink(50,100);} // S
     delay(250);
     for(uint8_t i=0;i<3;i++){blink(50,300);} // O
     delay(250);
     for(uint8_t i=0;i<3;i++){blink(50,100);} // S
     delay(500);
    }
  }
}

void setup(){
  Wire.begin();
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT);
// other stuff
  attachInterrupt(0,fifo_int,RISING);
  resetSensor();
}

void fifo_int() {
  x++;
  state_fifo_int = true;

}

static unsigned long timeout = 0; // used to detect dead sensor/connection
uint16_t fifo_count;
uint8_t fifo_buffer[8];
int16_t acc_temp[3];
int16_t gyro_x;

void loop(){

  if(state_fifo_int){ // interrupt has triggered
    blink(0,1);  // really quick blink // really quick blink
    //Serial.println(x);
    state_fifo_int = false;
    accelGyroMag.resetFIFO();
    accelGyroMag.getFIFOBytes(fifo_buffer,8); // fill in fifo bytes
    accelGyroMag.getIntFIFOBufferOverflowStatus(); // read the INT_STATUS reg in order to clear the Latch.
    acc_temp[0] = (((int16_t)fifo_buffer[0]) << 8) | fifo_buffer[1];
    acc_temp[1] = (((int16_t)fifo_buffer[2]) << 8) | fifo_buffer[3];
    acc_temp[2] = (((int16_t)fifo_buffer[4]) << 8) | fifo_buffer[5];
    gyro_x = (((int16_t)fifo_buffer[7]) << 8) | fifo_buffer[8];

    timeout = millis();

  }

 if((millis()-timeout)>1000){ //last interrupt was over 1 second ago! better reset Sensor!
   blink(100,500);
   blink(100,500);

   resetSensor();
  }
}

When I've gotten into a bind with data being generated faster than I can dump it, or the process cannot tolerate the printing delays, I've made a memory buffer to store as much raw data as I can and print it after the test-run. If you're not using a debugger (which can print memory contents), you'll still need to have serial print code in your sketch but it can execute after the you run the code under test. Store the minimum size raw data (to maximize the amount you can store) and do the formatting on your PC.
If you need to be able see what happened prior to an unusual event your code can detect, use a ring buffer (FIFO) in memory and let it wrap around (don't even bother to detect wrap-around). As soon as your code detects the event, print the ring-buffer contents.
It's not continuous capture but often, it's enough.


text:
Stop Arduino Timer after some seconds
I'm building a basic program that when a button is pressed, a buzzer comes on.
I would like however to make it so that the buzzer stops after a short period of time (e.g. 5-7 seconds).
Here is the code I have so far which is pretty basic I know forgive me but I have no clue on how to go forward.
// Setting The Pin Numbers
const int touchsensor = 2;     // the number of the touchsensor pin
const int buzzer =  4;         // the number of the LED pin

// variables:
int touchsensorState = 0;      // variable for reading the touchsensor status

void setup() {
  // initialize the buzzer as an output:
  pinMode(buzzer, OUTPUT);
  // initialize the touchsensor as an input:
  pinMode(touchsensor, INPUT);
}

void loop() {
  // read state of the pushbutton value:
  touchsensorState = digitalRead(touchsensor);

  // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
  if (touchsensorState == HIGH) {
    // buzzer will emit sound:
    digitalWrite(buzzer, HIGH);
  } else {
    // buzzer will not sound:
    digitalWrite(buzzer, LOW);
  }
}

Easy way: After turning on the buzzer, delay for your wanted amount of milliseconds, then turn the buzzer off. Little bit harder but more efficient way: Blink without Delay technique (https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay)

You set a timestamp = millis() when the button is pushed and then you disable the buzzer only when millis() - timestamp > timeout
if (touchsensorState == HIGH) {
    // buzzer will emit sound:
    digitalWrite(buzzer, HIGH);
    timestamp = millis();
}
if(millis() - timestamp > timeout) {
    // buzzer will not sound:
    digitalWrite(buzzer, LOW);
}

Note: If you press the button during the time the buzzer is active, it will re-write the timestamp so that it is triggered in "now + timestamp", i.e. prolong the time when it's turned off. You may want to insert a "if button is already active, do not modify timestamp" logic if you need it.

You can time this with the millis() function. Refer to the BlinkWithoutDelay example from the Arduino IDE.
Then you set a timestamp, when the button is pressed:
if(touchsensorState == HIGH) timestamp = millis();

And then you are checking this timestamp against the current time:
if(millis() - timestamp > duration){
  digitalWrite(buzzer, HIGH);
} else {
  digitalWrite(buzzer, LOW);
}

duration is the timespan during which the buzzer should stay on after the button was released. If you want to turn it of, regardless of the button state, you can add a boolean flag to your if-statement, to set the timestamp only, when the button was pressed first:
if(!button_pressed && touchsensorState == HIGH){
  timestamp = millis();
  button_pressed = true;
}

In this case you have to reset the button_pressed variable to false, when you are turning of the buzzer in the millis()-else-statement

I keep getting timestamp was not declared in this scope?

because you have to declare it as a variable (of type unsigned long, since this is the return type of millis())


text:
Is there a way to increase the number of output pins in Arduino Uno?
I am an amateur. I know about Arduino, but I am still learning.
And I was making this Bluetooth rover with a camera, ultrasonic sensor, mecanum wheels, air-soft shooter, and sand sample collector. I am using two L298 motor drivers, because L23D requires soldering and is a bit less compatible with me. So, when creating this amazing robot I realised that I ran out of pinmode spaces for the air-cannon and some other features.
So, is there a way to increase the number of output pins in an Arduino Uno or can I connect the Rx and Tx pins of the Bluetooth module and the trig and echo pin and use them both as one for two more spaces?

There is I2C I/O expanders that can solve this issue.

As an extension to Dario.Casciato’s response, there are not only I²C I/O expanders, but also the simple 74HC595 IC, which can be cascaded and used via Arduino's shiftOut function. It needs three signal pins for 8 / 16 / 24 ...  outputs.
The link is not a purchase recommendation, but rather a technical hint.

thank you! I was able to use this and increase the number of features originally planned

It sounds like you are using some GPIOs ;) If you need more digital pins, you can use the analog pins as digital pins (if you didn't already).

If you already occupied these pins, then I would think about getting an I/O expander. It's a chip/IC that can be mostly controlled via I²C, offering you a way to scale your project's GPIO capabilities.

thank you for your comment, I wanted it to be a small robot for a competition but with your help I was able to add even more features than the air cannon!

@AnikSingh That's nice to hear! glad i could help!

What you probably want is called an ‘I/O Expander’. They come in many different varieties based both on exact means you use to communicate with them, how many I/O pins they give you, and what you can do with those pins.
The usual recommendation for use with an Arduino is an I²C based I/O expander, such a Microchip MCP23017 (available readily online from many sources and available in a DIP format so that you can use it with solderless breadboards), because this provides a reasonably fast interface that is very well supported on the Arduino and uses relatively few pins (only 2 pins are required, not counting Vcc and ground).
I’ve also personally used a Analog Devices DS2408 for this purpose before. It uses a 1-Wire interface, cutting the required pins down to only 1 not counting Vcc and ground, and also not actually requiring the use of a specific I/O pin like a proper I²C device would, but it’s also slower and not as nice to work with (you need a separate library to work with 1-Wire on most Arduino chips), and also only comes in SOIC packages (so requires some precise, but not necessarily difficult, soldering).
In theory you could also use an SPI I/O expander, but they are often a bit more of a pain to work with, and eat at last three pins (possibly four) other than Vcc and ground.

In theory, there are two other options in specific circumstances.
The first is a multiplexer chip, which is essentially a fancy solid-state switch with multiple outputs. These are only really practical if you just need to trigger external devices individually, though that may be viable for your use case (it could easily drive a simple level trigger for the airsoft gun and a simple edge trigger for the sand sample collector).
The second is to use a shift register. These are only viable if you have some way to latch outputs (for example, putting a gated D-latch on each output) or only need the outputs to be valid at specific points in time, because updating the outputs cycles each pin through the output values of each other pin. They’re great if you are doing something like implementing a parallel bus, but not as good if you need fast outputs that retain state.

Re “[shift registers] are only viable if you have some way to latch outputs”: the 74HC595, which is kind of a standard in Arduino land and has been mentioned in a previous answer, is double-buffered. A rising edge on RCLK latches the shift register proper into the storage register, which is the one you see on the outputs of the chip.

thank you so much I was able to complete the air cannon and even add more features!


text:
Why is communication between a Python program and Arduino not producing the expected result?
I have written some Arduino code (with help from the post Serial Input Basics). On serial I send some data and, based on certain values sent, certain LEDs will be lit. Here is the Arduino code:
const byte numChars = 32;
char receivedChars[numChars];
char tempChars[numChars];        // Temporary array for use when parsing

// Variables to hold the parsed data
//char messageFromPC[numChars] = {0};
int cmd = 0;
int pitch = 0;
int velocity = 0;
int integerFromPC = 0;
int int2FromPC = 0;
boolean newData = false;

void setup() {

    // Put your setup code here, to run once:
    Serial.begin(9600);//set baud rate

    //Configure pins 2:5 as OUTPUT
    pinMode(2,OUTPUT);
    pinMode(3,OUTPUT);
    pinMode(4,OUTPUT);
    pinMode(5,OUTPUT);
    pinMode(13,OUTPUT);
}

void loop() {
    recvWithStartEndMarkers();
    if (newData == true) {
        strcpy(tempChars, receivedChars);
        // This temporary copy is necessary to protect the original data
        // because strtok() used in parseData() replaces the commas with \0.

        parseData();
        showParsedData();
        if(cmd==144 && velocity!=0){
            switch(pitch){
                case 30:
                    digitalWrite(2, HIGH);
                    break;

                case 31:
                     digitalWrite(3, HIGH);
                     break;

                case 32:
                    digitalWrite(4, HIGH);
                    break;

                case 33:
                    digitalWrite(5, HIGH);
                    break;

                default:
                    break;
            }
        }
        if(cmd==144 && velocity==0){
            switch(pitch){

                case 30:
                    digitalWrite(2, LOW);
                    break;

                case 31:
                    digitalWrite(3, LOW);
                    break;

                case 32:
                    digitalWrite(4, LOW);
                    break;

                case 33:
                    digitalWrite(5, LOW);
                    break;

                default:
                    break;
            }
        }
        newData = false;
    }
}

void recvWithStartEndMarkers() {

    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // Terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    }
}

void parseData() {      // Split the data into its parts

    char * strtokIndx;  // This is used by strtok() as an index

    strtokIndx = strtok(tempChars, " "); // Get the first part - the string
    //strcpy(messageFromPC, strtokIndx); // Copy it to messageFromPC
    cmd = atoi(strtokIndx);

    strtokIndx = strtok(NULL, " ");      // This continues where the previous call left off
    //integerFromPC = atoi(strtokIndx);  // Convert this part to an integer
    pitch = atoi(strtokIndx);

    strtokIndx = strtok(NULL, " ");
    velocity = atoi(strtokIndx);         // Convert this part to a float
}

void showParsedData() {
    Serial.print("Comm ");
    Serial.println(cmd);
    Serial.print("Ptch ");
    Serial.println(pitch);
    Serial.print("Velo ");
    Serial.println(velocity);
    Serial.println("\n");
}

Now this works perfectly with sending data from the Arduino's serial monitor, so for example if I type the following on serial monitor:
<144 30 45>

Then the LED I expect to get lit does, and I can turn it off by:
<144 30 0>

Now, I want to send this data from a Python (2.7) program which I am reproducing here:
#!/usr/bin/env python
import time
import serial
ser = serial.Serial('/dev/cu.usbmodem1421', 9600)
noteOn = 144
veloMid = 75
veloSilent = 0
def sendData(cmd, pitch, velocity):
    global ser
    cmd = bytes(cmd)
    pitch = bytes(pitch)
    velocity = bytes(velocity)
    ser.write("<")
    ser.write(cmd)
    ser.write(pitch)
    ser.write(velocity)
    ser.write(">")

while 1:
    notes = range(30, 34)
    for note in notes:
        sendData(noteOn, note, veloMid)
        time.sleep(2)
        sendData(noteOn, note, veloSilent)

The idea was to do the same thing I was doing manually in serial monitor, except using a Python script. But this produces no result. I see the RX and TX pins on the Arduino toggling, so it looks like the program is indeed communicating with the Arduino. In the Python IDE I wrote a few lines as follows to read the data from Arduino:
import serial
ser = serial.Serial('/dev/cu.usbmodem1421', 9600, timeout=5)
while True:
    data_raw = ser.read()
    print data_raw

With above code I receive the following characters in the Python IDE:
C
o
m
m

P
t
c
h

V
e
l
o

I have a feeling there is some mismatch between the data types of the data I am sending between the Python script and the Arduino, but I am not sure exactly what this mismatch might be.

Why am I not seeing the values of cmd, pitch and veocity being printed out from the serial.read() although the other strings "Comm   Ptch   Velo" are printed?
What dataype is serial.write passing on that might than be causing mismatch with my Arduino code?

This is how you format code: Use the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you. It was hard work changing your tags (from I don't know where) into what works here.

In your test with the serial monitor you are putting spaces between each number. Using my logic analyzer I got this being sent from your Python code to the Arduino:

No spaces, right? So the Arduino is receiving:
<1443175>

And since you are using a space as a numeric delimiter your decoding isn't working.

Something like this is probably warranted:
    ser.write("<")
    ser.write(cmd)
    ser.write(" ")
    ser.write(pitch)
    ser.write(" ")
    ser.write(velocity)
    ser.write(">")

Nick....You are a genius!!! The spaces were exactly the problem. I completely forgot the spaces when I switched to the python code. After correctly formatting my output string things work as I want. Many thanks for your suggestion. I also apologize for the formatting issue. I will keep your suggested link handy next time I submit a question.


text:
3.3 V Pro Micro clones flashing LEDs after 1200 bit/s touch
I have several Pro Micro clones.
This morning I uploaded a sketch into one of them (that was previously unprogrammed, so it stayed in bootloader mode) and when I wanted to upload the sketch a second time, the problem began:
When I now run the reset procedure for Arduinos with integrated USB (open the COM port of the Pro Micro for example in PuTTY at 1200 bit/s and close it again), the LEDs start flashing rapidly and the Arduino disappears from the Windows Device Manager.
Hover for a (slightly annoying) image:

So then I grabbed a second, identical Pro Micro and uploaded the Blink sketch into it. It was also previously unprogrammed. The sketch executed, but when I now do the reset procedure, it exhibits the same behavior now (flashing LEDs).
I can still upload sketches just fine, by setting the COM port to a different (arbitrary) COM port to prevent the reset procedure from reaching the Pro Micro and resetting the Pro Micro manually after starting the upload procedure.
This only happens with the 3.3 V/8 MHz variant, not with the 5 V/16 MHz variant. I have selected the appropriate variant in the IDE.
How can I repair the automatic reset function?

It's not really clear what you're asking. If you open and close the CDC @1200 baud, it will reset to receive new firmware over USB. This is what the Arduino IDE uses to upload new sketches. Link 1 Link 2
What are you trying to do? Why do you need to open it at a baud rate of 1200 baud?

That's the point - it should reset and go to bootloader mode but instead it starts flashing and disappears completely from the device manager.

I was finally able to solve this by using one of the Pro Micros to re-burn the bootloader of the other one.
For reference, the process is like this:

Flash the example sketch "ArduinoISP" into the first Pro Micro
Connect the two Pro Micros like this:
Programmer (on USB)   Target
GND ----------------- GND
VCC ----------------- VCC
15 ------------------ 15
14 ------------------ 14
16 ------------------ 16
10 ------------------ RST

Choose "Arduino as ISP" as Programmer
Because both are Pro Micros, selecting a different board is not necessary.
Click "Burn Bootloader"

Striking out is not a good idea. An answer should only have the current best information. The historical information belongs in the revision history (do provide a comprehensive summary, though, as the intent is not always in the diff). If there should be information for earlier versions of the IDE then split it in two, e.g. "For Arduino IDE v. y.y.y and later: ABC" and "For Arduino IDE v. x.x.x and earlier: XYZ". Put the information that benefits more readers first (there is no requirement to have it in chronological ascending order) - that is probably for the newer versions of the IDE.

I removed the step, will (should) long be using a newer version anyway.

Arduino Pro micro will enter bootloader if you connect it with 1200 baudrate. See this pos Upload code on Arduino Leonardo using command line

I like your other post. Maybe you could expand this post a little, as it is a little short and terse.

And it doesn't answer the question. The question is about why it does not enter the bootloader. (The bootloader would be visible on the USB bus.)

@vanbwodonk, AndreKR will not receive a notification in his inbox and may see your reply, if you don't address your comment to him using an@ as I have just done to you. Repost your comment and add their name with the preceding @

@AndreKR Actually i not really understand what are you asking about. Led flashing indicate that's Arduino Pro Micro successfully jump into bootloader. Of course it will change COM port under windows (I assume you using windows).

@vanbwodonk Are you sure that it should flash when in bootloader mode? Because mine doesn't, so this might indicate something. Can you make a video of the flashing and the device manager/lsusb so I can see the timing?


text:
Same code in setup() and loop() give different results
As the answers to this question and this one state, setup() and loop() are identical in the way they execute code (apart from the obvious looping function of loop()).
However.
I get different results with following two pieces of code:
Code run once, in setup()
/*
 * light_ws2812 library test
 */

#include <WS2812.h>

WS2812 LED(1); // 1 LED

cRGB value;

void setup() {
    LED.setOutput(13); // Digital Pin 13

    value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Yellow?
    LED.set_crgb_at(0, value); // Set value at LED found at index 0
    LED.sync(); // Sends the value to the LED
}

void loop() {
}

Code run once, in loop()
/*
 * light_ws2812 library test
 */

#include <WS2812.h>

WS2812 LED(1); // 1 LED

cRGB value;

bool hasBeenSet = false;

void setup() {
    LED.setOutput(13); // Digital Pin 13
}

void loop() {
  if (hasBeenSet == false){
    value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Red
    LED.set_crgb_at(0, value); // Set value at LED found at index 0
    LED.sync(); // Sends the value to the LED
    hasBeenSet = true;
  }
}

The difference:
The code run in setup() makes the LED flash once with the desired color.
The code run in loop() makes the LED stay lit with the desired color.
With the data being transmitted on pin 13, I can tell (because of the LED on there) in both cases data is being sent only once. With the loop() version I can even disconnect the data line after the color has been set, and it will stay lit.
I can only conclude the same code is executed differently in both cases.
Is there some sort of (soft) power reset after setup()? That could be a potential cause, as the color is stored in volatile memory on the WS2812B (if I'm not mistaken).

Link to the library used: http://github.com/cpldcpu/light_ws2812

Let us continue this discussion in chat.

After some discussion it turned out to be a hardware problem. For the sake of completeness I'll outline the suggestions I made.

There was some initial confusion (see the edits) where the hasBeenSet flag was initialized the wrong way around.
I could not reproduce the problem on my Uno and my WS2812 chip, so the issue was: what was different between his setup and mine?
Possible wiring issue. Make sure +5V, Gnd and Din (data in) are wired correctly.
Possibly faulty WS2812 chip - try with another one.
Possibly faulty Arduino - try with another one.
Possibly Arduino running at the wrong clock speed which would throw the timings out.
Possible extra components (eg. capacitors) added to the circuit which were throwing timing out.
Possible bug in the library. We eliminated that by trying with my library for Neopixels.

In the end DaJF reported that the problem was solved by using another (or no) breadboard. It seems the breadboard was introducing issues, maybe noise or bad connections.
We never really worked out why doing it in loop rather than setup made such a difference. I can only conclude that the slight timing difference compensated for the bad connections (or capacitance) on the breadboard.
I'm going to stick my neck out a bit and suggest that the capacitance in the breadboard was affecting the "shape" of the signal (we are talking about timings of around 350 ns here). Possibly if you measured with an oscilloscope you would see the problem.

The hasBeenSet thing was a copy-pasting error. I was trying other stuff in the loop() and I didn't want the hasBeenSet thing to run, so I disabled it. I removed the irrelevant bits of code when I pasted it here, but forgot to make the hasBeenSet thing work again. So technically the cause of the difference wasn't a programming error on my part. I would like you to update that in your answer. If not, that's fine too, it'll make future readers consider their code too :) Otherwise, great answer!

Maybe you could add a link to your page about the NeoPixels/WS2812B as well? As in a "More info about that {here}." at the end of the last paragraph?

Well, the link is mentioned in the last bullet point. Did you want it mentioned again?

I reworded the part about it being a bug to "confusion".

I should've checked, but I figured the link was the GitHub repo. My bad.
I think it's perfect now, thanks!

As you can see in the source code there is really nothing going on between the setup call and the first loop iteration.
If I'm not mistaken, this type of LED needs a frequent "update" on which color to display, at a precisely timed interval (I suppose this gets more important the more LEDs you have, since they are "addressed" bases on this signal timing.)
I think you really should keep calling sync() in the loop even if you are not actually changing the desired color, to keep "refreshing" the LED. This is just based of a quick analysis of the library code and examples though.
Why you get different results in the samples below could simply be due to the LED randomly "settling" in two different states when no longer getting data. The chst conversation seems to indicate there may have been other reasons as well.

No, the LED doesn't need updating. Once the signal is latched you can disconnect the data pin. I have a page about NeoPixels which shows the timings. There are other useful pages about them elsewhere. The latching is done by a gap of about 9 µs with no data (no 1-bits). Once latched they stay latched until more 1-bits arrive.


text:
Multiple client server over wifi
Trying to setup a server on Arduino to support multiple clients,
I am able to support one but I don't want to flush that client to make another connection.
#include <ESP8266WiFi.h>
const char* ssid = "your-ssid";
const char* password = "your-password";
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  delay(10);

  // prepare GPIO2
  pinMode(2, OUTPUT);
  digitalWrite(2, 0);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();

  // Match the request
  int val;
  if (req.indexOf("/gpio/0") != -1)
    val = 0;
  else if (req.indexOf("/gpio/1") != -1)
    val = 1;
  else {
    Serial.println("invalid request");
    client.stop();
    return;
  }

  // Set GPIO2 according to the request
  digitalWrite(2, val);

  client.flush();

  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
  s += (val)?"high":"low";
  s += "</html>\n";

  // Send the response to the client
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");

  // The client will actually be disconnected
  // when the function returns and 'client' object is detroyed
}

Using this code, the server handles only one client at a time, but I need to connect multiple clents simultaneously.

Please post the code you're using (a minimal complete verifiable example http://stackoverflow.com/help/mcve) and perhaps someone will help you.

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

You need to keep track of multiple WiFiClients - declare an array of them, for example, and each time server.available() gives you a new one, store it in the array.
Then you need to make sure your code doesn't stick waiting for data from each item.  You could service each WifiClient in turn: if it has data waiting (client[i].available() is true), read the data (client[i].read()) and store it. When you get a \r from a client, you know you have a whole line, and you can process it.
Here's a nearly-complete (but untested) example so you can see what I'm talking about.  Naturally it's not the only way to do it.
#include <ESP8266WiFi.h>
const char* ssid = "your-ssid";
const char* password = "your-password";
#define MAX_CLIENTS 10
#define MAX_LINE_LENGTH 50
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);
WiFiClient *clients[MAX_CLIENTS] = { NULL };
char inputs[MAX_CLIENTS][MAX_LINE_LENGTH] = { 0 };

void setup() {
  Serial.begin(115200);
  delay(10);

  // prepare GPIO2
  pinMode(2, OUTPUT);
  digitalWrite(2, 0);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a new client has connected
  WiFiClient newClient = server.available();
  if (client) {
    Serial.println("new client");
    // Find the first unused space
    for (int i=0 ; i<MAX_CLIENTS ; ++i) {
        if (NULL == clients[i]) {
            clients[i] = new WiFiClient(newClient);
            break;
        }
     }
  }

  // Check whether each client has some data
  for (int i=0 ; i<MAX_CLIENTS ; ++i) {
    // If the client is in use, and has some data...
    if (NULL != clients[i] && clients[i]->available() ) {
      // Read the data
      char newChar = clients[i]->read();

      // If we have the end of a string
      // (Using the test your code uses)
      if ('\r' == newChar) {
        // Blah blah, do whatever you want with inputs[i]

        // Empty the string for next time
        inputs[i][0] = NULL;

        // The flush that you had in your code - I'm not sure
        // why you want this, but here it is
        clients[i]->flush();

        // If you want to disconnect the client here, then do this:
        clients[i]->stop();
        delete clients[i];
        clients[i] = NULL;

      } else {
        // Add it to the string
        strcat(inputs[i], newChar);
        // IMPORTANT: Nothing stops this from overrunning the string and
        //            trashing your memory. You SHOULD guard against this.
        //            But I'm not going to do all your work for you :-)
      }
    }
  }

}

Should i create multiple server ir multiple clients

No - you create one WiFiServer and it will give you a new WiFiClient for each client which connects.

I have created an array of clients, how to use server.available with that

Do you know how to put items into an array in general?

Create_client (){

int i=1;                                                               Create_client (){ WiFiClient client [i];  i++;}

Whenever there is new connection i use create_client function

How to check when there is a new connection and what is server.available for

OK, pretty much full code added. It's untested so I recommend you read it and try to understand what it's doing, then do it yourself, RATHER THAN trying to run it as-is and finding all my typos.  If this is helpful, please consider accepting and up-voting the answer. Thanks.

This should be accepted as the answer, and since the question comes up so often it probably should be added to the arduino IDE built-in examples for WiFi101 and other similar WiFi libraries.

I'm not sure storing IP adress is a good way of doing....
Internet is not a network with constant connection. So no way to be sure the computer using an IP at one time is the same computer one minute later, just because it has the same IP.

@Peter Should this comment be under the other answer?

Here , I have  used array of WiFiClient .
The reason is  array pointer will hold previous plus latest WiFiClients (emoteIP and remotePort ) and user will be able to choose which WIFiClient to be used for communication.
We can store  IPAddress , Port as well as whole WiFiClient object in an array
 //===========================================
       WebServer  Wserver(80);

       WiFiClient Wclient;

       WiFiClient *Wificlients[10] = { NULL };

       int  Clientindex=-1;

       Wclient = Wserver.client(); // or  server.avilable() if WiFiServer

       Wificlients[Clientindex++]=new WiFiClient(Wclient);

       int   cntloggedinclient=0;
       int kk=0;

       while(Wificlients[kk] != NULL)
           {
               cntloggedinclient++;  // Total clients count
               kk++;
           }

         // Multicasting bytes to all connected clients.
         int kkk =0;
         while(kkk<cntloggedinclient)
         {
           Wificlients[kkk]->write((unsigned char*) &newbuff,len);
           kkk++;
         }

You can't rely on all the data arriving together - your loop which does tree read() will be unreliable. You need to store the WiFiClient object if you want to have multiple connections at the same time.

I have a solution using RTOS Tasks, I think this is the best way to manage multiple clients at same time. I test this code in ESP32 dev module.
#if CONFIG_FREERTOS_UNICORE
#define ARDUINO_RUNNING_CORE 0
#else
#define ARDUINO_RUNNING_CORE 1
#endif
#include <WiFi.h>

const char* ssid = "[YOUR-NETWORK-SSID]";
const char* password = "[YOUR-SSID-PASSWORD]";

void TaskClientSocket( void *pvParameters );

WiFiServer wifiServer(80);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(1000);
  WiFi.begin(ssid,password);
  Serial.println("Connecting to Wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("Connected to WiFi network");
  Serial.println(WiFi.localIP());

  wifiServer.begin();
}

void loop() {
  WiFiClient client = wifiServer.available();
  if( client){
    Serial.println("New Client Connected...");
    xTaskCreatePinnedToCore(
    TaskClientSocket
    ,  "TaskClientSocket"
    ,  4098
    ,  &client
    ,  2
    ,  NULL
    ,  ARDUINO_RUNNING_CORE);
  }
}

void TaskClientSocket( void *pvParameters )
{
    WiFiClient clientHandle = *((WiFiClient*)pvParameters);
    for (;;)
    {
      while(clientHandle.connected()){
        while(clientHandle.available()>0){
          char c = clientHandle.read();
          clientHandle.write(c);
        }
        vTaskDelay(100);
      }
      clientHandle.stop();
      Serial.println("Client disconnected");
      vTaskDelete(NULL);
    }
}