text:
Why is this IIR Filter unstable on the Arduino Due?
I am using an Accelerometer (on the MPU6050) and connected it to the Arduino Due. In order to filter the signal I am using an IIR Filter with the following transfer function:
H(z) = Y(z)/X(z) = B/A
B = 0.00000376 + 0.00001127*z^(-1) + 0.00001127*z^(-2) + 0.00000376*z^(-3)
A = 1 - 2.9372*z^(-1) + 2.8763*z^(-2) - 0.9391*z^(-3)
which is an IIR 3th Order Butterworth, Cutoff Freq: 0.5Hz, Samling Freq: 100Hz. These numbers can be calculated by any IIR calculator.
Thus, then discrete equation is:
y[n] = 0.00000376*x[n] + 0.00001127*x[n-1] + 0.00001127*x[n-2] + 0.00000376*x[n-3] + 2.9372*y[n-1] - 2.8763*y[n-2] + 0.9391*y[n-3]
I first tried it on the Arduino UNO. Then I found out that decimal point precision (float & double) on the UNO is only 6-7 digits. But the therm "B" in the transfer function has for example (0.00000376) 9 digits. I thought this is the porblem, so I switched to Arduino Due and now I am using double (instead of float) which should have enough precision.
It is still unstable. It is not oscillating but getting bigger. I also tried an IIR 4th Order Butterworth, Cutoff Freq: 1Hz, Samling Freq: 100Hz. This one is oscillating.
However, the only IIR that seems to be stable is an IIR 3th Order Butterworth, Cutoff Freq: 1Hz, Samling Freq: 100Hz.
I have no idea so far what the problem is. Could anyone help please?

Please, post your sketch to begin to work with your question, a set of data to test and the correct results your are expecting.

The precision of a float is about 7 significant digits. The
constant term of B in your transfer function (0.00000376) has only 3
significant digits.
Your transfer function has a pole at z = 1. It is thus not really
stable, but only marginally stable. Any parasite DC component in
the input will make the output drift without bounds.

It seems to me that your problem is not related to the implementation of
the filter on the Arduino, but rather to the filter design. Where did
you get that transfer function from?
Edit: I looked at the filter you are trying to make. It turns out it
is very sensitive to the precision of the coefficients of A(z). If you
try to add these coefficients, they almost cancel out: their sum is
about 3e-5. At zero frequency, both A and B are 3e-5, and the transfer
function, which is their ratio, is 1. By rounding the coefficients to
four decimal places, you made the cancellation exact, and the transfer
function infinite.
Just write the transfer function with more decimal places in the
coefficients and it should work:
H(z) = 3.75592×10−6 (1 + 3 z−1 + 3 z−2 + z−3)
         ÷ (1 − 2.9371759 z−1 + 2.8763097 z−2 − 0.9391038 z−3)

I used:
https://ch.mathworks.com/help/signal/ref/butter.html
for the filter. You can use their "in Browser Matlab" for free.
Then you can also use:
https://ch.mathworks.com/help/matlab/ref/roots.html
in order to see that the absolute values of the complex poles are insed the unit circle. Ok so, what am I getting wrong here? :-/

@user3554669: I don't have a MathWorks account. But you can easily derive the transfer function yourself: Wikipedia provides the continuous-time transfer functions on the page Butterworth filter. And also a description of the bilinear transform, which you can use to derive a discrete-time transfer function.

That's what I am saying. It should be stable. Poles are inside unit circle.

@user3554669: No, it is not expected to be stable. For real stability, poles should be in the interior of the unit disc. A pole in the exterior would cause exponential instability. With a pole at z = 1, unbounded linear drift is expected. Note that rounding errors, even at double precision, could put your pole on the exterior.


text:
How to connect an Arduino and a WAMP server's MySQL database?
I'm trying to connect an Arduino Mega to my WAMP server's database using MySQL connector for attendance logging. But it shows "Connection failed".
What is my WAMP server's IP address?
I connect my laptop and Arduino with a router so:

My laptop is 192.168.1.2
My Arduino is 192.168.1.3

I think this is correct.
/*
  MySQL Connector/Arduino Example: basic insert
  This example demonstrates how to issue an INSERT query to store data in a
  table. For this, we will create a special database and table for testing.
  The following are the SQL commands you will need to run in order to setup
  your database for running this sketch.

  CREATE DATABASE test_arduino;
  CREATE TABLE test_arduino.hello_arduino (
    num integer primary key auto_increment,
    message char(40),
    recorded timestamp
  );

  Here we see one database and a table with three fields; a primary key that
  is an auto_increment, a string, and a timestamp. This will demonstrate how
  to save a date and time of when the row was inserted, which can help you
  determine when data was recorded or updated.

  INSTRUCTIONS FOR USE

  1) Create the database and table as shown above.
  2) Change the address of the server to the IP address of the MySQL server
  3) Change the user and password to a valid MySQL user and password
  4) Connect a USB cable to your Arduino
  5) Select the correct board and port
  6) Compile and upload the sketch to your Arduino
  7) Once uploaded, open Serial Monitor (use 115200 speed) and observe
  8) After the sketch has run for some time, open a mysql client and issue
     the command: "SELECT * FROM test_arduino.hello_arduino" to see the data
     recorded. Note the field values and how the database handles both the
     auto_increment and timestamp fields for us. You can clear the data with
     "DELETE FROM test_arduino.hello_arduino".

  Note: The MAC address can be anything so long as it is unique on your network.

  Created by: Dr. Charles A. Bell
*/

#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(192, 168, 1, 3); // IP of the MySQL *server* here
char user[] = "root"; // MySQL user login username
char password[] = ""; // MySQL user login password

// Sample query
char INSERT_SQL[] = "INSERT INTO test_arduino.hello_arduino (message) VALUES ('Hello, Arduino!')";

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    Serial.println("Connected Successfully...");
    delay(1000);
  } else
    Serial.println("Connection failed.");
}

void loop() {
  delay(2000);
  Serial.println("Recording data.");
  // Initiate the query class instance
  MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
  // Execute the query
  cur_mem->execute(INSERT_SQL);
  // Note: since there are no results, we do not need to read any data
  // Deleting the cursor also frees up memory used
  delete cur_mem;
}

The IP address of the laptop (with your MySQL server) is 192.168.1.2, but you are trying to connect to 192.168.1.3.

As gre_gor pointed out, it looks like your connecting to the wrong ip.
Change:
IPAddress server_addr(192, 168, 1, 3); // IP of the MySQL *server* here

To:
IPAddress server_addr(192, 168, 1, 2); // IP of the MySQL *server* here

source: Stack Exchange

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

sort: votes


text:
Physical safety: Prevent linear actuator from crushing my fingers
Our project consists of an old wooden barrel, whose top lid is opened/closed with a simple linear actuator. I am a bit afraid that it might crush somebody's fingers while closing.
How could I detect trapped objects effectively?
Elevators often have light barriers, but the problem here is that the opening has a 360° border.
Force sensitive resistors seem to be an option too. However, since the border is a circle, I guess applying them would not work too well (folding issues) and look bad on a vintage barrel.
I'm very sorry if I maybe created a duplicate here and I would like to encourage me to provide links to similar questions. I simply couldn't come up with useful search words for my problem.

Surely detecting objects that might become trapped would be a better idea?

Preventing would be the best option, but detecting it while it is happening is good enough too. E.g. force sensors cannot foresee it, but they enable us to stop and go backwards before things are getting crushed.

Have a look a this table saw with finger detection emergency brake. https://www.youtube.com/watch?v=FbndZtkfcqs

Some work was done, IIRC, with leaky fibre optics on the top of electric car windows. Pressure makes the light leak out and the window stops moving.

I think the saw emergency brake works with conductivity. It goes in the same direction as force sensitive resistor strips

sounds like a good use case for those new cheap microwave radar motion sensors, partially shielded to cover just opening.

The easiest way to prevent things becoming trapped is to take reasonable steps to prevent things getting near the "danger zone", so a barrier 2 metres around the barrel would be a good start.  Probably it would be an impractical idea, but...
A physical barrier of some sort would be the best idea, because that is less likely to suffer a failure than an electronic system (well assuming it has been designed right).  If you are using an electronic system then it needs to "fail-safe", when it suffers a failure it must adopt its safe state (barrel open).
You could surround the lid with IR lights and receivers in the lip.  They would need to be spaced at a distance where an arm/finger couldn't get between the lid and lip without breaking a beam.  This solution would only work over the last few inches, because of the angle of the beams.  If all receivers had a signal the it would be safe to close.  The problem is the receivers would need to be close together to prevent transgression.
Monitoring the current drawn by the actuator and the position of the actuator might be another.  I am assuming that there is an increase in current draw when the lid actually closes, and a similar increase in draw when something is trapped.  If the lid isn't fully closed when the current increases then something is trapped.
The final way I can think of is probably the most effective.  As the barrel closes don't close it the last few inches, allow it to 'fall' as the actuator descends.  This means if there is an object in there the actuator isn't pulling the lid down and the object will hold the lid against gravity.  This would be done by having a channel in the mounting block for the actuator 'pin'/ connection point to slide up and down.

OK Its not an electrical solution.

I really like the last idea. I have to check what type of actuator I have, because I was under the impression that it holds the position when unpowered which would make "sliding down" impossible.

I don't think I phrased that very well.  When the actuator first pull the lid it will be at the bottom of the 'channel'.  Once gravity takes over the lid will 'jerk' downwards as the channel moves and the actuator pin slides to the top of the channel (you might want to damp that with a spring to make it look slicker).  Then the actuator's downward movement will slow the effect of gravity and it will effectively be controlling the fall.  If you stick you arm in the lid will stop on your arm, and your arm will prevent gravity closing the lid.  [Continued....]

The actuator's pull will now move the pin down the channel until it reaches the end of its normal movement effectively doing nothing.  The channel height needs to be at least the same size as the largest object that a person is going to stick in the way.    Obviously you can't cater for every object and if someone sticks their head in, well a little chlorine in the gene pool every now and then is a good idea. :)

Thinking about it, if little Joey does stick his head in your barrel you might want to have a cut off if the actuator starts drawing to much current as well as a backup.  I suspect the change in current draw will not be enough to prevent saw fingers, but it will just give him a sore head to remind him not to be so stupid in future.

Hmm did I understand the channel concept correctly: It is about the bottom mounting of the actuator (bottom of the barrel) to have vertical leeway, so that if something blocks the lid, the actuator would pull it's lower end up instead of the lid down?

That wasn't what I meant, but I think your idea is a much better idea.  It hides the ugliness much better.

Ah now that I think about it, that would actually enable me to watch for the lower end of the actuator raising, e.g. with a physical switch or a plug which the actuator would tear off! And I could implement it inside the barrel, well hidden!

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


text:
What is Clock pin and Data pin, Orientation in Grove LED bar
I'm trying to use Grove LED Bar with Arduino

Grove – LED Bar is comprised of a 10 segment LED gauge bar and an
  MY9221 LED controlling chip. It can be used as an indicator for
  remaining battery life, voltage, water level, music volume or other
  values that require a gradient display. There are 10 LED bars in the
  LED bar graph: one red, one yellow, one light green, and seven green
  bars. Demo code is available to get you up and running quickly. It
  lights up the LEDs sequentially from red to green, so the entire bar
  graph is lit up in the end.

In the github example there are Clock pin, Data pin and Orientation.
// Arduino Clock pin, Data pin, Orientation
// Grove_LED_Bar bar(7, 6, 0);

https://github.com/Seeed-Studio/Grove_LED_Bar/blob/master/LP%20examples/BasicControl/BasicControl.ino
But I have no idea what are they. Where can I find the documentation for them?

Did you try Google it? It take only a few minutes ...

It took me over an hour and with your answer I still can't get it. I asked what is "Clock pin". And your answer doesn't have the word. Probably it's because of lack of my basic knowledge, though.

Grove modules are like Lego for electronics. You can connect your Grove module directly to Arduino, as Ratchet suggest, and it will works.. What the Grove shield gives to you is error-free, secure and clean connections instead of a rat nest breadboard.

on the LED circuit board there are a few connections, notably DI and DCKI.
The DI pin is the data pint and DCKI is the clock pin.
According to the header orientation is about which way the pins are oriented red-to-green or green-to-red. It affects at which end led 1 is.

Thanks I get it now! So I had to guess that DCKI represents clock pin, right? Or maybe there is a rule for abbreviation?

How to connect Grove to your board
You need a Grove Expansion Board which to attach the Grove modules. The Grove Expansion Board provides the processing power, and the modules offer the input sensors and output actuators of your system. There are many Grove Expansion Board for different platform already, they include Arduino UNO, Particle Phone, BeagleBone board etc.

Features
There are intotal 16 grove connectors on the Base Shield, here we use a table to show the details.
Specification

Apart from the rich grove connectors, on the board you can also see an RST button, a green LED to indicating power status, ICSP pin, a toggle switch and four row of pinouts. There is no need to explain the RST button and LED, but you really need to know below two features that is very important for your usage.
1.Power Compatible:
Every Grove connector has four wires, one of which is the VCC. However, not every micro-controller main board needs a supply voltage of 5V, some need 3.3V. That's why we add a power toggle switch to Base Shield v2 so that you can select the suitable voltage of the micro-controller main board you are using via this switch.
For example, if you are using Arduino UNO with Base Shield v2, please turn the switch to 5v position; while using Seeeduino Arch with Base Shield v2, please turn the switch to 3.3v.
2.Board Compatible:
The pinout of Base Shield V2 is the same as Arduino Uno R3, however Arduino Uno is not the board one that the Base Shield V2 is compatible with, here we listed the boards that we have confirmed that can be used with Base Shield V2.
Arduino Uno

Seeeduino V4.2

Arduino Mega / Seeeduino Mega

Seeduino LoraWan

Arduino Leonardo / Seeeduino Lite

Arduino 101

Arduino Due

Intel Edison

Linkit One


text:
This is a flood sensor. Moisture sensor and servo working together but it shows different errors
Sometimes the servo moves unnecessarily without moisture sensor giving out any readings.
Another problem is that the servo moves very slowly. Is there a way to counter this problem?
const int VAL_PROBE = 0; // Analog pin 0
const int MOISTURE_LEVEL = 250; // the value after the LED goes ON
#include <Servo.h>
Servo myservo;

void setup() {
  myservo.attach(9);
  Serial.begin(9600);
}

void Servo(int state) {
  digitalWrite(13, state);
}

void loop() {
  int moisture = analogRead(VAL_PROBE);

  Serial.println(moisture);

  if(moisture > MOISTURE_LEVEL) {
    myservo.write(90);
  } else {
    myservo.write(0);
  }
  delay(1);
}

Try giving external power supply to Servo( not from Arduino )

Your sketch is missing pinMode for the pins your are using.

@LookAlterno please elaborate

The only pin that could possibly need a pinMode is in a function that is never called.

What do you mean by that

One complete year and no answer??


text:
Visual Studio for Arduino - Deep Search Issue
Finally got some time to play with my Arduino. I downloaded the Arduino editor and wrote a quick sketch which worked fine.
I then downloaded the Visual Studio extension from  VisuaMicro. I configured it to point towards my Arduino directory, which in my case is : C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt
I created a new Arduino project and copied the same sketch it. When I try to build it I get errors as below:
Compiling debug version of 'Sketch1' for 'Arduino/Genuino Uno'
Build Folder:
file:///C:/Users/bbbsb/AppData/Local/Temp/VMBuilds/Sketch1/uno/Debug
Additional Defines: VM_DEBUG;VM_DEBUG_ENABLE
1;VM_DEBUG_BANDWIDTH_THROTTLE_MS 50;VM_DEBUGGER_TYPE_HARDWARESERIAL
0;VM_DEBUGGER_TYPE_SOFTWARESERIAL 1;VM_DEBUGGER_TYPE_FASTSERIAL
2;VM_DEBUGGER_TYPE_USB 3;VM_DEBUGGER_TYPE_TEENSY 4;VM_DEBUGGER_TYPE_UART
5;VM_DEBUGGER_TYPE_USART 6;VM_DEBUGGER_TYPE_USBSERIAL
7;VM_DEBUGGER_TYPE_TTYUART 8;VM_DEBUGGER_TYPE_NET_CONSOLE
9;VM_DEBUGGER_TYPE_Uart 10;VM_DEBUGGER_TYPE_COSA
11;VM_DEBUGGER_TYPE_CDCSerialClass 12;VM_DEBUGGER_TYPE_HARDWARESERIAL1
13;VM_DEBUGGER_TYPE_HARDWARESERIAL2 14;VM_DEBUGGER_TYPE_HARDWARESERIAL3
15;VM_DEBUGGER_TYPE_NET_UDP 16;VM_DEBUGGER_TYPE_USBAPI
17;VM_DEBUGGER_TYPE_SERIALUSB 18;VM_DEBUGGER_TYPE
VM_DEBUGGER_TYPE_HARDWARESERIAL;VM_DEBUG_BREAKPAUSE;
Architecture Tools:
file:///C:/Program%20Files/WindowsApps/
ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/
Api: 1.1706.25-9.061
Sketch Book: file:///C:/Users/bbbsb/Documents/Arduino
Sketch Include Paths
Core Include Paths
Include Path     file:///C:/Program%20Files/WindowsApps/ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/arduino/avr/cores/arduino
Include Path     file:///C:/Program%20Files/WindowsApps/ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/arduino/avr/variants/standard
Searching for libraries ...
"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DVM_DEBUG_BREAKPAUSE -
DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -
DVM_DEBUGGER_TYPE_SERIALUSB=18 -DVM_DEBUGGER_TYPE_USBAPI=17 -
DVM_DEBUGGER_TYPE_NET_UDP=16 -DVM_DEBUGGER_TYPE_HARDWARESERIAL3=15 -
DVM_DEBUGGER_TYPE_HARDWARESERIAL2=14 -DVM_DEBUGGER_TYPE_HARDWARESERIAL1=13 -
DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE_COSA=11  -
DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -
DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -
DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_UART=5 -
DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_USB=3 -
DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -
DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -
DVM_DEBUG_ENABLE=1 -DVM_DEBUG   -DF_CPU=16000000L -DARDUINO=10805  -
DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino" -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\variants\standard" "C:\Users\bbbsb\AppData\Local\Temp\VMBuilds\Sketch1\uno\Debug\Sketch1.cpp" -o "nul"
Access is denied
Preprocess: "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DVM_DEBUG_BREAKPAUSE -
DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -
DVM_DEBUGGER_TYPE_SERIALUSB=18 -DVM_DEBUGGER_TYPE_USBAPI=17 -
DVM_DEBUGGER_TYPE_NET_UDP=16 -DVM_DEBUGGER_TYPE_HARDWARESERIAL3=15 -
DVM_DEBUGGER_TYPE_HARDWARESERIAL2=14 -DVM_DEBUGGER_TYPE_HARDWARESERIAL1=13 -
DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE_COSA=11 -
DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -
DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -
DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_UART=5 -
DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_USB=3 -
DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -
DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -
DVM_DEBUG_ENABLE=1 -DVM_DEBUG   -DF_CPU=16000000L -DARDUINO=10805 -
DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I"C:\ProgramFiles\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino" -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\variants\standard" "C:\Users\bbbsb\AppData\Local\Temp\VMBuilds\Sketch1\uno\Debug\Sketch1.cpp" -o "nul"
Object reference not set to an instance of an object

An error was encountered during the 'Deep Search' library discovery process.

Debug build failed for project 'Sketch1'
I've obviously not setup something correctly but cnnot work out what?
Any ideas?

I suspect that the problem is that you're using the Windows App Store version of the Arduino IDE. Windows puts some strange restrictions on the C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt folder that the Windows Store version of the Arduino IDE is installed to. Please try uninstalling this App thing and instead use the standard IDE downloaded from https://www.arduino.cc/en/Main/Software.

If I remember well, you have to "import" the libraries for your project from within Visual Micro.

I had the same problem and just tried it as per1234 suggested: installed the full windows version (not the windows app version), configured the VS extension accordingly and now it builds (same code).

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


text:
Wiring light sensor OPB704WZ to Arduino Due
I would like to create a tachometer with the light sensor OPB704WZ.
I followed this schema https://tonyrobotdt081.wordpress.com/2014/04/10/report-on-the-light-sensor-opb704wz/ on a bread board (for now), and tried to measure the voltage difference on the signal pin (green on the schema).

Problem is, I don't see a clear difference between a white surface and a black one; It does change if I put the sensor closer or further away, but that's about all I can see.
Is there something else I need to add to my wiring to make the difference between high and low depending on the luminosity more obvious? I know others have been able to use this sensor for the same purpose.

Are you sure that the LED is on? You can check it using a camera.

As with most links Arduino users "find" that one displays a complete lack of basic electronic understanding.

Regardless of the colour of the reflector you are most likely driving the transistor into saturation. You'll never see any difference in the reflectivity with it like that.

If you read the datasheet you see no mention is made of colour - only how diffuse the surface is. Even a black card can still be highly reflective to infra-red - you just can't see it.  A sheet of polished black metal is more reflective that a piece of white paper. You can't see your face in the paper (unless you're a criminal) but you can see it in the polished black metal.

@Majenko None of your comments are helping in any way.

You expect that the white surface to reflect the infrared light and the black surface does not.
Your theory is correct; white surfaces should reflect pretty much all light and the black surface should absorb all light.
The problem is that the black surface is reflecting enough light to turn the photo-transistor on.
The theory is correct but in the real world this is not perfect. For example a white surface is not completely white. Likewise no black surface is completely black.
We also know that a mirror is much better at reflecting light than a white surface. The black surface could be shiny. I am looking at my shiny black monitor stand, and even though it is black I can still see the reflection of the window.
I suggest trying with a number of black surfaces (such as paint, card, cloth) and finding the one that works best. I would imagine that chalk board paint would work well at absorbing and diffusing the infrared light. Also experiment with the distance away from the surface. You may have to move it further away from the surface.
If I am imagining your tachometer right, your sensor will see a reflective surface and then it will see empty space (and then repeat). This should work fine. Give it a try.

You want some Vantablack 2.0 ;)

Vantablack is a substance made of vertically aligned carbon nanotube arrays and is one of the darkest artificial substances known, absorbing up to 99.965% of radiation in the visible spectrum. -Wikipedia

Vantablack 2.0 is even blacker.

I see and understand your point. I need to measure (and change) the number of rpm on a tool. It has a stainless steel surface, and I intend to grind a stripe about  a 1/4" wide, and paint with mat black. I do believe this will work, as there should be a maximum contrast between the shiny steel and mat black
BUT, before getting there, I would like to test, just moving by hand this sensor. I will try your suggestion.

@BernardG, I look forward to your results.

@sa_leinad, tested a bit further today, and yes, it does works as expected! Thanks. Now I can start working on the actual thing.... :-)


text:
Multitasking for music light sculpture
First of all, I'm new so please don't think this is dumb. I am creating a light culture with RGB LEDs that should play to programmed music. I have uploaded the following code to a spark fun redbird for now, but will later put it on a arduino mega. My circuit is working fine mostly except for the fact that the lights and music play separately and not next to each other. Note: this is just trial code, I will put my own music and light sequencing in later.
const int buzzerPin = 6;    // connect the buzzer to pin 6
const int RED_PIN = 11;
const int GREEN_PIN = 12;
const int BLUE_PIN = 13;
const int RED_PIN2 = 8;
const int GREEN_PIN2 = 9;
const int BLUE_PIN2 = 10;
const int songLength = 18;  // sets the number of notes of the song

const int DISPLAY_TIME = 100;
// Notes is an array of text characters corresponding to the notes
// in your song. A space represents a rest (no tone)

char notes[songLength] = {
  'c', 'd', 'f', 'd', 'a', ' ', 'a', 'g', ' ', 'c', 'd', 'f', 'd', 'g', ' ', 'g', 'f', ' '};

// beats[] is an array of values for each note. A "1" represents a quarter-note,
// "2" a half-note, and "4" a quarter-note.
// Don't forget that the rests (spaces) need a length as well.

int beats[songLength] = {
  1, 1, 1, 1, 1, 1, 4, 4, 2, 1, 1, 1, 1, 1, 1, 4, 4, 2};

int tempo = 113;  // The tempo is how fast to play the song (beats per second).

void setup()
{
  pinMode(buzzerPin, OUTPUT);  // sets the  buzzer pin as an OUTPUT
   pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);
   pinMode(RED_PIN2, OUTPUT);
  pinMode(GREEN_PIN2, OUTPUT);
  pinMode(BLUE_PIN2, OUTPUT);
}

void loop()
{
  mainColors();        // Red, Green, Blue, Yellow, Cyan, Purple, White
  int i, duration; //

  for (i = 0; i < songLength; i++) // for loop is used to index through the arrays
  {
    duration = beats[i] * tempo;  // length of note/rest in ms

    if (notes[i] == ' ')          // is this a rest?
      delay(duration);            // then pause for a moment
    else                          // otherwise, play the note
    {
      tone(buzzerPin, frequency(notes[i]), duration);
      delay(duration);            // wait for tone to finish
    }
    delay(tempo/10);              // brief pause between notes
  }

  // We only want to play the song once, so we pause forever
  }
  // If you'd like your song to play over and over, remove the while(true)
  // statement above

int frequency(char note)
{
  int i;
  const int numNotes = 8;  // number of notes we're storing
  char names[numNotes] = {
    'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C'    };
  int frequencies[numNotes] = {
    262, 294, 330, 349, 392, 440, 494, 523    };

  // Now we'll search through the letters in the array, and if
  // we find it, we'll return the frequency for that note.

  for (i = 0; i < numNotes; i++)  // Step through the notes
  {
    if (names[i] == note)         // Is this the one?
    {
      return(frequencies[i]);     // Yes! Return the frequency and exit function.
    }
  }
  return(0);  // We looked through everything and didn't find it,
  // but we still need to return a value, so return 0.
}

void mainColors()
{
  // Red
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, LOW);
  digitalWrite(BLUE_PIN, LOW);
   digitalWrite(RED_PIN2, HIGH);
  digitalWrite(GREEN_PIN2, HIGH);
  digitalWrite(BLUE_PIN2, HIGH);
  delay(DISPLAY_TIME);

  // Green
  digitalWrite(RED_PIN, LOW);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, LOW);
    digitalWrite(RED_PIN2, HIGH);
  digitalWrite(GREEN_PIN2, LOW);
  digitalWrite(BLUE_PIN2, HIGH);
  delay(DISPLAY_TIME);

  // Blue
  digitalWrite(RED_PIN, LOW);
  digitalWrite(GREEN_PIN, LOW);
  digitalWrite(BLUE_PIN, HIGH);
   digitalWrite(RED_PIN2, LOW);
  digitalWrite(GREEN_PIN2, HIGH);
  digitalWrite(BLUE_PIN2, HIGH);
  delay(DISPLAY_TIME);

  // Yellow (Red and Green)
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, LOW);
    digitalWrite(RED_PIN2, HIGH);
  digitalWrite(GREEN_PIN2, HIGH);
  digitalWrite(BLUE_PIN2, LOW);
  delay(DISPLAY_TIME);

  // Cyan (Green and Blue)
  digitalWrite(RED_PIN, LOW);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, HIGH);
    digitalWrite(RED_PIN2, LOW);
  digitalWrite(GREEN_PIN2, LOW);
  digitalWrite(BLUE_PIN2, HIGH);
  delay(DISPLAY_TIME);

  // Purple (Red and Blue)
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, LOW);
  digitalWrite(BLUE_PIN, HIGH);
    digitalWrite(RED_PIN2, LOW);
  digitalWrite(GREEN_PIN2, HIGH);
  digitalWrite(BLUE_PIN2, LOW);
  delay(DISPLAY_TIME);

  // White (turn all the LEDs on)
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, HIGH);
    digitalWrite(RED_PIN2, HIGH);
  digitalWrite(GREEN_PIN2, LOW);
  digitalWrite(BLUE_PIN2, LOW);
  delay(DISPLAY_TIME);
}

I strongly propose to delete delay from Arduino code base. Using delay is the root problem in 50% of questions posted here ... Just kidding ... no, not kidding. Really. Delete it.

You need a state machine. It goes like this:
You divide your actions in states. Each state is a collection of actions that must performed in group (sequentially). In your case, you have one state for each note and for each ligth color and a duration.
Now, your score (music + light) is made of a sequence of states:
> state 1: Play Fa, Light up RED - Duration 500ms.
> state 2: Play Re, Light down RED - Duration 200ms. ...
>
> state n: Play Fa, Light up BLUE - Duration 250 ms.

You have many states; put them in an array and then loop across the array.
The code looks like this:
typedef struct {
    int note;  // Musical note
    int color; // Led color
    int length; // Duration in ms
} STATE;

STATE score[] = {
    {0, 0, 0},
    {FA, BLUE, 500},
    [RE, RED, 400},
    ...
   {FA, GREEN, 400}
   };

int state = 0;

void loop()
{
    static unsigned long stateStart = 0;

    if(state == sizeof(score) / sizeof(STATE)) {
        //  reset and start again
        state = 0;
        stateStart = 0;
    }

    if(millis() - stateStart >= score[state].time) {
        // Advance state and play next thing
        state++;
        playNote(score[state].note, duration);
        playColor(score[state].color);
        stateStart = millis();
    }

}

void playNote(int note, duration)
{
    // Play a note.
}

void playColor(int color)
{
    // Light up a color.
}

Note: this is just the general idea. You must adapt and adjust things, like how you code note and colors. You better Google "Arduino state machine".
My code probably contains errors, but I gave you a starting point.
You have to implement playNote and playColor.


text:
I need help setting up my Arduino Uno with the port
I'm using a Windows computer, and if I recall correctly I installed the IDE using the installer, so I probably don't need to manually install the drivers. However, I can't figure out how to set up the serial port with the Arduino. For me under Tools, there's no "Serial Port" option but instead "Serial Monitor" and "Serial Plotter."
When I tried to upload my file, it failed. When I clicked Serial Plotter, it gave this error message:
Arduino: 1.8.4 (Windows 8.1), Board: "Arduino/Genuino Uno"

Sketch uses 940 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for
local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\\.\COM1":
The system cannot find the file specified.

Problem uploading to board.
See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
Board at COM1 is not available

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

How am I supposed to resolve this?

Check the Hardware manager in Control panel that recognizes your arduino board connected.

Is it a genuine Arduino or a cheap clone from eBay or Amazon?

"under Tools, there's no "Serial Port" option". It's Tools > Port. Is that menu item disabled?

Yes, it's the only option under Tools that's grayed out and disabled for me.

I'm not sure if this is related but my computer doesn't seem to see my Arduino although it's plugged in. If I go to the Device Manager it's not even there.

Before we can help you, you must answer my question.

Yes, I bought it from Adafruit and I am 100% it is completely legit.

If you don't believe me: https://imgur.com/a/fZjc5

You need to see it in the device manager. I don't have Windows 8 to test it on, but I think the Windows versions of the IDE ship with a device driver for it.

It's not a question of believing you - the cheap clones use a different USB chip and the solution to your problem would be completely different depending on if it's a genuine Arduino (CDC/ACM interface) or a cheap clone (CH340G interface). The latter requires special drivers not bundled with the IDE.  Since it is a CDC/ACM interface based one we can assume it's not the drivers if you installed the IDE properly. So it may be your USB cable (note: some cheap charger cables don't have data wires) - try a different USB cable, try a different USB port, and at a pinch, try a different computer.

I figured it out by following the tutorial by Adafruit. I had to install it manually in order for it to work.

The idea behind answering your own question is that it could be helpful to others who are having the same problem. This answer does not provide enough details to be helpful. Please edit to improve it. What tutorial are you talking about? Add a link to it. But don't only rely on the link for your answer because if the link goes dead the information is lost. Add a description of what you mean by "install it manually".


text:
Arduino Due custom platform for school and library installation
I have made a custom-development hardware for our school, where you can plug in an Arduino Due. It is mainly for driving all kind of motors and reading sensor signals. Therefore I added a custom SAM board into board.h based on a copy of the Arduino Due. Furthermore I need a global PWM frequency on all PWM Channels of 20 kHz. So I also changed the variants.h file.
(I have not found a solution that is setting all the underling Timer/Counters for PWM on the Due Pins 2, 3, 4, 5, 6, 7, 8, 13 to 20 kHz by user code, I think this is only possible with the variants.h file - because some timers can not be reset after they where set within the Arduino IDE once)
The Question now:
Today all students have to find and modify their variants.h file, which can be located almost anywhere! (Sometimes it is located in the support packages of Matlab...).
Is there an easy solution to give the students one .zip containing the Arduino IDE already with the custom Board included?
There is the Arduino IDE working without installation for download on the Arduino website. But how can I add my custom SAM board to it?

"I have made a custom arduino board". Please edit your question to explain exactly what you mean by that. Did you just add a new board definition to the Arduino SAM Boards boards.txt file or did you create a complete hardware package? "give them one Zip with everything included". Please edit your question to explain what you mean by "everything". Does that mean the Arduino IDE and the custom Due hardware definition or the custom hardware definition only?

thanks for the hints. Is the question more clear now?

The part about what you mean by the .zip file is clear but you forgot to answer my first question.

I think I did it :)

It's still not very clear. I'm going to assume that you mean you added a new entry to the Arduino SAM Boards boards.txt file rather than creating a complete hardware package and my answer reflects this assumption. If this is not the case then I will need to modify my answer somewhat.

Exit the Arduino IDE.
Create a folder in the Arduino IDE installation folder named portable. This will cause the Arduino IDE to run in portable mode.
Start the Arduino IDE.
Tools > Board > Boards Manager
Wait for the download to finish.
Click on "Arduino SAM Boards".
Click "Install".
Wait for installation to finish.
Make your modifications to the Arduino SAM Boards hardware package installed at {Arduino IDE installation folder}/portable/packages/arduino/hardware/sam.
If necessary, configure File > Preferences to your liking.
Exit the Arduino IDE.
Zip the Arduino IDE installation folder.

When you run the Arduino IDE in portable mode it causes hardware packages installed via Boards Manager to be installed to the portable folder, rather than a folder outside the Arduino IDE installation folder. It also stores preferences.txt in the portable folder. This means you can supply a .zip file that contains a copy of the Arduino IDE with the customized Arduino SAM Boards package already installed.
By default it will also set the sketchbook folder to be there but that can be changed via File > Preferences > Sketchbook location if you like.

this is exactly what I was looking for! Thanks a lot!


text:
floor( 1.0f ) bugged?
I just displayed the value for floor( 1.0f ) and surprisingly, it's 0.
Anyone knows about that? Is there a fix in libc expected any time soon?
I've been looking at libc::floor.s but it's a bit dodgy and 1) I don't want to break my other existing code and 2) don't have time for that so I'll add an epsilon at the moment (but that defeats the purpose of floor)...
Thanks for posting any fix or idea on how to bypass the issue.

Post your complete, working sketch that show your problem.

I'm voting to close this question as off-topic because it's a generic computer problem (aka, internal floating point representation), not related to any platform in particular.

@Patapom Please expand on your question. Please also your code so far. Only then will people consider to re-open the question.

It's not a generic computer problem : this is the way floating-point values are handled by the libc and it can be fixed directly in libc.
As far as I know, arduino boards don't have FPUs so it's a software problem and on my board floor( 1.0 ) returns 0.0...

I ran this sketch:
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println(floor(1.0f));
}

It outputs "1.0"

What can I say more? I'm using Arduino v1.6.19 and the libc attached to that version, I wrote the exact same code as you did and it displays 0.0...

The first thing is to update to the last Arduino IDE 1.8.5. Second ... post your sketch!!! It can be the most trivial thing, but no sketch, no help.

Okay okay thanks! I'm new there... :D
(anyway, my sketch is the same as yours) (I'll update my version)


text:
How does the microcontroller know which clock to use?
I had seen some tutorials on how to assemble an Arduino on a breadboard. They all just place the external crystal oscillator according to the circuit and then, just burn the bootloader and it starts working. According to my little knowledge the fuse bits have to be set before using the external clock.
My question is - How does the microcontroller know which clock to use internal or external? Is there any setting already in the bootloader that tells the microcontroller to use the external clock?

Burning the bootloader via the Arduino IDE also sets the fuse bits according to its configuration files.

So, if I have to use the internal clock, I need to change the configuration file?

Yes, or you could find and use a core meant to be used with bare chips. I know of at least one that has the correct configuration.

So your keeping it a secret? Which core(s)?


text:
Can't upload arduino code on the board due to some programmer issues
As I connected my arduino-uno board and made sure of the "Board" selected, and the "Port" selected as well. There is a problem while uploading, I tried updating the arduino IDE, reinstalling all the arduino drivers, I tried to borrow a new arduino board from a friend and I am 100% sure it is working.
The message I get from the IDE:
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1d

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Thanks in advance!

First of all thank you for replying,
I double checked the chip and it is atmega328 and I am selecting the board.
But I want to try to change the baud rate to 9600 (Overriding Baud Rate) but I do not know how, do you have any clue?

I faced the same problem while uploading.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
To solve that I changed my port to another USB port and I selected the particular port, Its uploaded successfully. But it's in MacBook not in Windows.
Try this once, by changing the port.

Try changing baud rate to 9600.
Another thing to check is the chip your Uno has. My Uno has the atmega328. Make sure you select that board.

All Unos will have the Atmega328P.

The ide does not allow you to upload sketches? If it does not allow you to upload to your oard or your friends board i would assume the issue is witb the software. Maybe try reinstalling the ide. I had the same error problem with a avrdude and the buad rate was wrong. That might not be the case with yours.


text:
How to reset an arduino while being able to know which button has been pressed?
Context
I keep the board in sleep mode and want to wake it with different buttons. I need to know which button has been pushed on boot.
In the following schematic, SW-R is actually used to reset the board.
If I hold SW-D5 or SW-D6 while pushing SW-R, the code can detect which button I pushed.
Problem
I don't want to have to push 2 buttons at the same time and, being new to electronic, I don't know how to wires things up so it reset and set a pin to HIGH simultaneously.
Question
How can I reset the board and trigger a HIGH on an IO corresponding to a button while it boot?
Considering the HIGH only need to be hold for less than a second, can it be simply achieved with capacitors and/or transistors? If so, how? Or any other suggestion?

simulate this circuit – Schematic created using CircuitLab
The actual code example only contain 1 button but I'll have many.
#include <Spi.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>

int buttonPin = D5;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(BUILTIN_LED, OUTPUT);

  int buttonValueAtBoot = digitalRead(buttonPin);
  Serial.begin(115200);
  Serial.println();

  if (buttonValueAtBoot == HIGH) {
    // I want to trigger this code pushing only 1 button
    // should also work with many buttons
    Serial.println("button was pressed");
  }

  digitalWrite(BUILTIN_LED, HIGH);
}

void loop() {
  delay(5000);
  ESP.deepSleep(0);
}

Things would be simpler if your used a "shallower" sleep mode permitting wake on a pin change interrupt.  If you want to actually reset the processor, you may need to find a way to activate the reset and the input pin from the same button, apparently in a way that supports multiple buttons, and perhaps also locks out generating additional resets once the chip is awake..

Please, post your solution as an answer and then accept it to close the question. That way it will be clear to others what was the problem and what is the solution. Or delete your question if you thing your case is too particular.

just use a pin that's high during reset, then you don't need to switch anything.

@dandavis can you please be more explicit? Use it in which way?

feed a pin that's high during reset (0,2,3,16) to the input that needs to be high during reset .

@dandavis oh got it! you suggest to use/route a pin that is HIGH at boot time as a source to my button pin. Seems like a good idea, but how to wire that up in a way that is temporary and that will be compatible with multiple buttons? Each button needs to trigger the reset and keep it's pin high at least for the boot delay.

Just found that I can change pins behavior. Inverting things a little bit, I can get my pins to work as LOW instead of as HIGH.
That way, I only need 1 button to trigger a reset and change pin status. Plus, grounding the reset is done temporarily because of the capacitor, which is what I need.
Here is the new schema

simulate this circuit – Schematic created using CircuitLab
New code
#include <Spi.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>

int buttonPin = D5;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(BUILTIN_LED, OUTPUT);

  int buttonValueAtBoot = digitalRead(buttonPin);
  Serial.begin(115200);
  Serial.println();

  if (buttonValueAtBoot == LOW) {
    Serial.println("button was pressed");
    digitalWrite(BUILTIN_LED, HIGH);
  }

  // Avoid problem when the button is hold
  while (digitalRead(buttonPin) == LOW) {
    // wait before going to deepsleep
    // or the capacitor will be drained
    delay(1);
  }

  Serial.println("going to sleep");
  ESP.deepSleep(0);
}

void loop() {
}


text:
What is a faster alternative to parseInt()?
I'm making an LED spectrum analyzer with an Arduino Due and my PC. The audio processing is done on the PC, and then sent to the Arduino. The exact data sent is a 'coordinate', or more specifically, a number representing a particular band, and another number representing the maximum amplitude of that band. There are 11 bands. Each coordinate has a x and a y value, separated by a comma, and then sent on a new line.
This is my code as of now:
void loop() {
  if (Serial.available()) {
    xCoord = Serial.parseInt();
    yCoord = Serial.parseInt();
    if (xCoord != 0) {
      int r, g, b;
      for (int i = 0; i < 8; i++) {
        int fromCoordToIndex = ((xCoord - 1) * 8) + i;
        //
        //do some calculations for the color
        //
        strip.setPixelColor(fromCoordToIndex, strip.Color(r, g, b));
        strip.show();
      }
    }
  }
}

The problem is parseInt seems to be very very slow (it's not the timeout issue, it's set to 1). From what I can see, it seems to be skipping some data, so every now and then a band gets missed out. The only way I can fix this is to insert a delay between each coordinate being sent. I found that 40 ms works ok, but remember there are 11 bands, so that means about half a second to refresh the whole board, which feels like a slide show...
I've tried inputting individual characters and then using toInt, I've tried parseInt obviously, I've tried native USB (it's a Due), and I've tried fiddling with baud rates. None seems to have had any effect.

You can made a faster parseInt if your data has a rigid format (for example, always 3 digits long, padded with zeros or spaces. Tell us if that is the case (and what format are you using).

Do you send some form of separator character between your numbers?

@LookAlterno it's not rigid but would take 2 seconds to make it rigid, the format is x,y (including the comma as a separator, and it's sent as a line)

Post the details of your format to nail the question.

I don't understand what you mean

A much faster alternative is to not require parsing at all. Send binary data instead.

For example, all values are positive 3 digits (padded with zero), and they come in pairs, comma separated, like 003,456 ... 450,001 ...

But doesn’t that come out as a string, I’ll still have to parse it to use it won’t I?

And I have some other calculations to do removed from above, will I still be able to do that if they are binary?

MatthewInglis you have to specify the format. That is where to start. Which number can be a byte which numbers are larger, can they be negative, and so on. Once you have specified that, turn it into a fixed/ridig format as @LookAlterno is trying to tell you. After that, you could add a checksum, or STX and ETX (starting and ending markers). Or specify that there is always a LineFeed or CarriageReturn at the end. But first specify the format, edit you question and add that to it.

It's more likely that those calculations you do after you get the data is the slow part. Floating point operations are pretty slow on arduino due to lack of floating point hardware instead prefer fixed point calculations using integral types only.

@ratchetfreak yes, of course, and a timeout of 1ms will make the parseInt abort (depending on baudrate, which we don't know). But we first have to determine the protocol of the serial data.

First hint is to read all the data before processing and displaying. Also avoid sending additional data before the previous is completed. The second is to check the Due hardware serial implementation that it actually is interrupt driven and buffers.

⇒ It is okay to ask this question somewhere else, but don't try to hide that from us. You should have given a link to http://forum.arduino.cc/index.php?topic=508343.0

move strip.show(); out of the loop for a bigger speedup than type conversion overhead

@dandavis good point, thanks, I should have seen that...

The annoying thing about parseInt() is not its speed, it's the fact
that it relies on a timeout. If the timeout is too long, it slows you
down. If it's too short, it may induce errors.
A safer way to parse the sort of messages you are using is to buffer all
the incoming characters until you find a carriage return, then parse the
whole line. For example:
// Just echo the messages with a different separator.
void parse(char *buffer)
{
    char *s = strtok(buffer, ",");
    int x = atoi(s);
    s = strtok(NULL, ",");
    int y = atoi(s);
    Serial.print(x);
    Serial.print(':');
    Serial.println(y);
}

void loop()
{
    static char buffer[BUFFER_SZ];
    static size_t lg = 0;
    while (Serial.available()) {
        char c = Serial.read();
        if (c == '\r') {        // carriage return
            buffer[lg] = '\0';  // terminate the string
            parse(buffer);
            lg = 0;             // get ready for next message
        }
        else if (lg < BUFFER_SZ - 1) {
            buffer[lg++] = c;
        }
    }
}

Note that you should add some error checking when you call strtok().

#include <SoftwareSerial>
SoftwareSerial s1(5,6);

void setup {
s1.begin(9600);
s1.setTimeout(50); //sets the timeout of parseint() to 50ms

}

Please note that lowering the timeout too much can cause errors, i would not go below 10.

Premature optimization is the root of all evil (or at least most of
  it) in programming. Donald Knuth.

I don't know how fast/slow parseInt() is. Neither do you. You have to time it first.
OK. Maybe it's really slow, but is it the slowest part of your code? Slow compared to what?
Is parseInt what you need? parseInt doesn't convert negative values and it can time-out (but still return zero ... Duh!).
If you read the whole line as a String and then parse the values, you avoid the time-out problem and you can also verify that the data is correct.
This sketch show how to process your data:
void setup() {
  Serial.begin(9600);
  while(!Serial);

  String lines[] = {
    "1,1",
    "10,20",
    "11,1000",
  };
  int channel;
  int value;

  for (int i=0; i < 3; i++) {
    sscanf(lines[i].c_str(), "%d,%d", &channel, &value);
    Serial.print("channel="); Serial.print(channel);
    Serial.print(" value="); Serial.println(value);
  }
}

void loop() {
}

Well, I'm using sscanf, that's slower than parseInt for sure, but it get the job done. I doubt you (or me) can do it better, and there more useful thing to do with our time.
Edit:
I profiled
sscanf("0001,0001", "%d,%d", &channel, &value);

with an Arduino UNO and it took 147us to convert a single par of values.

Instead of using parseint, send the data for the 11 bands in a very specific form to the Arduino so the Arduino can 'parse' it very easily.
Maybe instead of sending text, send 33 bytes for RGB (3) times 11 bands are the levels (0-255) of the consecutive channels. Than there is no conversion needed (except for reading the bytes).

Well I don't need to send the color, I just need to know how high each band should be. So sending extra values would just be pointless.

In that case 11 bytes would be enough, one value for each band.

Excuse my ignorance, but what exactly do you mean by byte? If each band has a number between (and including) 0 and 13 how do I represent that as a byte?

A byte is 8 bits (8 zero's or ones). WIth a byte (8 bits) you can store a number between 0 and 255 (or 256 different values). You could even send 2 values from 0-13 in one byte by putting by calculating value1 * 13 + value2 (which will always be less than 256). Or more according bits: value1 << 4 + value2... The << operator shifts the bits four to the left, which is equally as multiplying by 16. Value1 will be in the left (MSB) four bits, and Value2 in the right (LSB) four bits. So if your system changes to 16 channels you don't have to change anything (compared to the 11 channels using this).

Ok, so if I send "025" to the arduino with serial, could I use serial.readBytes()? And if I do that, would converting it to an integer be slow like from a string?

Well you can better not send "025"  because that is 3 characters (bytes). You can send for example the first two by 0 * 16 + 2 = 2... so send a byte with value 2 (that's not character 2).

Your data has 11 channels and a single value for each channel. The values will be presented in graphic format, so it fits in the range 0-255 without degrading the presentation. You always can scale your readings to your display's resolution.
You then send these 11 values in binary form. One byte per channel plus one byte to separate one data set from another. You don't need to send the channel number, just the values.
At the Arduino end you read 12 bytes and then loop thru it converting the bytes to ints.
#define CHANNELS 11

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

  while(!Serial);
}

void loop()
{
  char packet[CHANNELS + 1];
  int values[CHANNELS];

  // Read 12 bytes (11 bytes of data + 1 byte delimiter)
  int nBytes = Serial.readBytes(packet, sizeof(CHANNELS + 1));

  if(nBytes == CHANNELS + 1) {
    // Convert bytes to ints;
    for(int i=0; i<CHANNELS; i++) {
      values[i] = packet[i];
    }
  } else {
     // Error.
     }

  // Here you display your graph.
}

This code doesn't have any error-detection. For that you can add an extra byte with the checksum of the whole dataset.

Interesting issue with this one, nBytes never will be 11+1, when I tested it, it would always be 4, then 4, and then 4, rather than 12 in one go. Any ideas?

You are doing almost right. When dealing with comms (Serial, tcp/ip) never assume that you will get all your bytes in one reading. You have to be prepared to read data in pieces. You have the basic idea; now is up to you to fill the remaining details. Another problem in front of you is syncing both computers: you have to reserve a special value (255, for example) to signal the start (or end) of dataset. Right now, the first bytes sent are probably lost. After you add all your error-checking, recovery and buffering your code will be 5x bigger. That's is how it works.

I seem to have fixed it by lowering the baud rate from 115200 to 9600. This answer inspired the change. Apparently, the higher the baud the faster the information is sent, but the higher the likelihood of an error, and the lower the baud rate, the slower it is sent, but the more reliable it is.


text:
Space needed for local String variable
I tried to run this code on my Arduino Uno clone (which has no function so far and is a shortend version of my programm):
String rules [16][5] ={
   {"B0 B5", "", "", "cs S0", "", },
   [...]
};

void setup() {
  Serial.begin(9600);
  String foo = "bar";
  Serial.println(foo);
}

void loop() {
}

I left the rules array out, but it is quite big. It isn't used yet, but it contains rules how to react on certain situations (which should be used later).
As the Arduino IDE gives the following after complilig:
Sketch uses 4316 bytes (13%) of program storage space. Maximum is 32256 bytes.
Global variables use 1174 bytes (57%) of dynamic memory, leaving 874 bytes for local variables. Maximum is 2048 bytes.

When I run this sketch there is nothing on the serial monitor. If it works, there should appear bar, but it does not. The Arduino sends only a linebreak over the serial, but no text.
When I remove some characters from that array so that there are about 900 bytes the script works and prints bar to the serial monitor.
So, aren't 874 bytes not enough to store a three-character string? Why does it need 900 bytes to store such a short string?

Because String instances are more than just their characters.

The very first Serial.print is usually lost (or garbage). Usual idiom to put a while (!Serial); in setup, before printing anything. Pay attention to the semi-colon.

Please, post your real, working, complete sketch. You posted one incomplete sketch and the stats for another sketch unkown to us. Info is inconsistent.

You are requesting 80 String objects.
Each String object allocates memory to store its data. When you provide a string constant that string constant data's length is used for the allocated data size (including the NULL character at the end), and the string constant data copied in.
On top of that you have a bunch of other data that is needed for the String class to do its work. The total size of a String object is 6 bytes.
So the memory you need for your array of Strings can be calculated as:

Let C be the total number of characters in all the string constants
Let N be the number of String objects in the array
Let T be the total number of bytes.
T = N * 6 + C + N

With no string constant data that would be:
T = 80 * 6 + 80

That's 560 bytes already, before you even start thinking about putting in the string constant data.
Also you may like to add to that the fact that the compiler may (though I am not certain on this) be also copying the string constants into RAM first because they aren't forced into PROGMEM with the F() macro.
So since you only have 2KiB of RAM to begin with, and a quarter of that is instantly gobbled up with your array, you can see how things might not be too happy.
Oh, and the String's internal storage is allocated at run time, not compile time, so the compiler can't know that it'll overflow - only when you run the program will it overflow and things go horribly wrong.
So you need to ask yourself "Why do I even want an array of String objects?" and the answer is most certainly: "Under no circumstances do you ever want an array of String objects". In fact I am a strong advocate of never using String objects ever, for any reason whatsoever.
If your data is constant there is absolutely no reason to store it as String objects. It's constant. It should remain constant. Copying it into a String object means it's no longer constant and wastes many many resources.

fwiw, i find the String interface to result in much more semantic and readable code ex: response.endsWith(token) compared to gibberish-ladden alternatives. my $0.02 as a JS dev.

Thank you. One Mord question: Would it be possible to use char arrays instead of String objects (as I don't really need their functionality). Would that (if possible) save space?

Absolutely. If they are constants then you need to learn about PROGMEM, the F() macro, PSTR, etc.

Would declaring the array with char[][16][5] also work?

That would probably end up wasting as much memory. First decide what you want this array to do. Then relate that to what different types of array can do. Then code using that kind of array.


text:
Arduino Mega 2560 LED is dim when powered from digital output
My circuit is a simple one, I am using an arduino atmega 2560.
One 5mm red LED connected in series with a 150 ohm resistor.
If I didn't make some kind of goof, a red LED has a voltage drop of 2 volts and operates at 20 ma.
So my calculations were, 5-2=3volts.
3V/150=20 mA. So I put a 150 ohm resistor.
My code to control it is the following:
int red = 48;

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

void loop() {
digitalWrite(red,HIGH);
}

When I run the code the red LED is dimly lit, when connected to the 5V on the board it lights brightly.
When I measured the voltage between pin48 and ground I got 1.7 volts.
When connected directly to the 5V and GND the voltage between them is 4.95V.
Measuring a pin with nothing connected set at HIGH results in a 4.99V reading.
Is my board malfunctioning or have I missed something?

It's pinMode(red, OUTPUT)

The pinMode() arguments are backwards. As it is the LED is powered through the input pullup resistor, which is about 20-50kohm.

You sir deserve a pizza, thank you so much!
I noticed it now, what a dumb mistake :D
Well I fixed it now and it works.
Cheers again for the help.


text:
Arduino pro mini not compiling after changing fuse to 128khz
I used Arduino UNO as ISP to change the fuse setting of Arduino Pro Mini. Using avrdude cmd, I successfully changed it to 8MHz setting. Due to curiosity, I decided to try changing it to 128kHz. But that ends up me being unable to further program it. The Pro Mini still works but just cant change fuse through avrdude cmd, burn bootloader and upload. Does 128kHz really leave atmega328p like that?
On one computer, the below error appears.
avrdude: stk500_recv(): programmer is not responding

On another computer, the below error appears
avrdude: Expected signature for ATmega328P is 1E 95 0F
Double check chip, or use -F to override this check
Wrong microcontroller found. Did you select the right board from the Tools > Board menu?

There are actually more errors because I trial and error different ways to solve it, i.e Nick Rammon's Atmega_Board_Programmer, cmd command with varying parameters (baud rate, programmer), inserting capacitor on UNO. But I dont remember every one of them because the not in sync:resp=0x.. differs from time to time
There is one method which I have not try, high voltage programming mode. I would try it out if it was detachable but atmega328p on Pro Mini is SMD. Is it possible to high voltage program on Pro Mini? Ultimately I am stuck.
Ignoring what I have done, I would once again like to try out every method you guys recommend. Hopefully everything can be step by step and the thing I want to know most is the setting of 'Board', 'Processor' and 'Programmer' in Tools.
I would give my best response possible to you guys who is willing to help me out. Thank you

Thanks to Ignacio, I found an answer. If anyone ever burn the fuse to 128kHz, got stuck there and wish to revert back to normal speed, download this sketch. Note that I am using Arduino UNO as ISP and Arduino Pro Mini as the target board
If you read the comment in the sketch carefully, you will see How to proceed:. The below is what I did.

Remove any pin connection on Arduino UNO
Plug Arduino UNO to PC
Open the downloaded sketch and uncomment #define LOW_SPEED
On Arduino IDE Tools menu, make sure settings are: Board: Arduino/Genuino UNO, Programmer: AVRISP mkII and upload the code
After uploading, unplug Arduino UNO from PC
Connect Pro Mini to UNO, making sure there is capacitor between reset and ground pin on UNO
Plug Arduino UNO to PC
Open CMD and type avrdude -P com5 -b 19200 -c avrisp -p m328p -U lfuse:w:0xFF:m -U hfuse:w:0xDA:m -U efuse:w:0x05:m. Change com5 to your UNO com port. The fuse are default Pro Mini setting.
You should see avrdude: safemode: Fuses OK <E:05, H:DA, L:FF>. Unplug UNO from PC
Remove pin connection on Arduino UNO
Plug Arduino UNO to PC
Now comment #define LOW_SPEED and upload the code.
After uploading, unplug Arduino UNO from PC
Connect Pro Mini to UNO like before and plug to PC
On Arduino IDE Tools menu, make sure settings are: Board: Arduino Pro or Pro Mini, Atmega328 (5V, 16MHz),Programmer: Arduino as ISP
Burn Bootloader and it is complete

Apologies for lengthy and repetitive steps. Many solutions skip many steps which leaves me in doubt. So I do not want that to happen to other people. Though I won't go into the details of setting up avrdude CMD in step 8.

Accept your own answer to close this question.

At that clock rate each programming clock cycle must be at least 3 system clock cycles, which means that the programmer either must use a much slower SPI rate, 42kHz or less, or it must provide an external pulse train to clock the device manually. Modify the ArduinoISP sketch to either use a slower clock or to provide an external clock to the target.

ArduinoISP sketch to slower clock: changing #define BAUDRATE 19200 to #define BAUDRATE 1200?
Is it possible to provide external clock to Arduino Pro Mini? If so, how should I connect it?

No clue. But that sounds like the speed it communicates with the host, not the target.

I have just used this code and upload to UNO with setting: Arduino/Genuino UNO,AVRISP mkII. Then I unplugged UNO from laptop, connected Pro Mini to UNO with capacitor connected, plugged to laptop and change setting to: Arduino Pro or Pro Mini,ATmega328 (5V, 16MHz),Arduino as ISP. Then I press Burn bootloader.
This error occur: avrdude: Device signature = 0x000000 avrdude: Yikes!  Invalid device signature.          Double check connections and try again, or use -F to override          this check.

i love you. from your tip, i found the code that slows down communication with target which i thought baudrate was the one.


text:
How to keep a pin LOW for a small amount of time after pushing a button and while device is booting?
Context
I keep the board in deepsleep mode and want to wake it with different buttons. I need to know which button has been pushed on boot. The board is immediately put back in deepsleep mode afterward.
I've been able to reset the board and pull a pin LOW at the same time. (see circuit below). The reset pin is momentarily pulled low so it reset the board effectively.
I'm not an electronic engineer, just a hobbyist, so any other method to do something are always welcome.
Problem
With the actual code/circuit, I need to hold the button until the device boot up so it can detect button was pushed but I would like to be able to just push the button quickly instead of having to hold it.
Question
How to add some sort of delay that will "hold" the SW-D5 button until the board boot?
Or anything that keep my D5 pin LOW for a short amount of time after the button has been pushed?
I think something in the range of 500 to 1000 milliseconds would be enough.
My actual circuit

simulate this circuit – Schematic created using CircuitLab
My code
#include <Spi.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>

int buttonPin = D5;

void setup() {
  // Read pin value as soon as possible after boot
  pinMode(buttonPin, INPUT_PULLUP);
  int buttonValueAtBoot = digitalRead(buttonPin);

  pinMode(BUILTIN_LED, OUTPUT);
  Serial.begin(115200);
  Serial.println();

  if (buttonValueAtBoot == LOW) {
    Serial.println("D5 was pressed");

    // Do something useful here like making an HTTP request.
    digitalWrite(BUILTIN_LED, LOW);
  }

  // Avoid problem when the button is being hold
  while (digitalRead(buttonPin) == LOW) {
    // wait before going to deepsleep
    // or the capacitor will be drained
    delay(1);
  }

  Serial.println("going to sleep");
  ESP.deepSleep(0);
}

void loop() {
}

write a pin to hold it down; pinMode() in setup() kicks in in about  200ms

@dandavis the problem is that the pin already changed its state back to normal once in setup().Push SW-D5 -> trigger reboot -> release SW-D5 -> few hundreds of milliseconds later -> setup()

A simple RC network should do the job.

simulate this circuit – Schematic created using CircuitLab
Ok. A quick explanation of what we have here.  C1 and R1 are the same as you have at the moment for your reset circuit. R1 is the existing pullup resistor in the Wemos. R3 recharges the C1 when the button is released. It's effectively the pullup for the button.
D2 is to separate the two parts of the circuit. It prevents R3 from charging the capacitor C2.
The magic happens with C2 and R2. Pressing SW1 discharges C2, and the GPIO goes low.  When you release SW1 C2 charges up again through R2.  When the voltage across C2 rises to the VIH of the GPIO the GPIO will go high.
D1 is to protect the GPIO from the negative pulse you can get from C2 as it discharges.
Here's a simulation. Top line is the GPIO, bottom is RESET.

VIH for the ESP8266 is 0.75VIO, so 75% of 3.3V, or 2.475V.
The charge time of the capacitor C2 is calculated as T=RC, where T is the time taken to charge up to 63% of the supply voltage (2.08V)
With the shown values the time taken to rise to 63% of 3.3V will be 10,000 x 0.0001 seconds, or 1 second.  So to get to 75% it will take a little longer than 1 second.  75% is about 1.4T, so if T is 1 as in the above equation then it will take 1.4 seconds (1 * 1.4) to rise enough for the GPIO to register as HIGH.
Note these times are all from the moment you release the button. Reset has already happened before that time.
Also the internal pullup of the GPIO should be disabled otherwise it will also charge the capacitor and the charge time will be reduced. Since you don't know that resistor value it then becomes impossible to calculate what the charge time will be. Simplest to just disable it and only use the external resistor R2.

If the button is pressed twice, C1 will still be charged after the first press. Reset does not work. When and how can C1 be discharged?

Good point. It wants a pullup - and maybe a diode to isolate the two signals. I'll tweak it.

Not so long ago, circuits for me were hieroglyphs. Now I can look at them and appreciate their beauty, how they work, the reason of everything. The joy of learning.

@majenko thanks for the time you took for all those very appreciated explanations. Will it work if I use diode instead of Schottky diode? I will try your suggested circuit as soon as I receive bigger capacitor this week

Yes it should work with a silicon diode.

The use of a schottky for D2 is to keep the LOW voltage as low as possible. As long as it's below the VIL of the ESP8266 then it doesn't matter what the diode is. D1 is to try and match the ESD diode in the chip itself. If it's forward voltage is above the ESD diode's forward voltage the ESD diode will conduct instead of D1 - both making D1 pointless and possibly (though highly unlikely) endangering the ESD diode in the chip.

@Majenko I've disabled the pullup of the GPIO and everything start working as expected using the circuit you designed except that it reset as soon as I push the button, not when I release it. But it's not a big deal tho.. I've even been able to add a second button duplicating the circuit before D2 and adding diodes between the buttons and R3, C1 junction. Your help and explanations were really appreciated! Now I'll investigate to find why it's not working properly when battery powered. Thanks again

@Majenko how did you generate your simulation image?

@Remi Yes, reset as you press the button is normal. It's a low-going pulse. I use Falstad to do my simple simulations. http://www.falstad.com/circuit/

This is amazing. I've been trying to figure this out for a week, trying everything from latch to 555 timers to get this to work and you've done it with a simple capacitor. Thanks!!

@Majenko How would you modify this if you want multiple buttons to reset the same device but track them on different gpios?

You should be able to pretty much duplicate the entire circuit and connect multiple copies to the RESET pin.

You may want to separate the circuits out with a Wired AND connection (a diode for each circuit).


text:
Limit to number of sensors attached to Arduino
Is there any limitation on how many sensors can be attached to one Arduino board? I am making elderly smart ban and I want to use GPS, GSM, gyroscope, pulse sensor, temperature sensor and I2C OLED. Right now I have only gyroscope, pulse sensor and GPS connected to Arduino Uno but I would like to add more stuff and also I am considering using Arduino Nano or only ATmega328P chip for finished product. My main concern is power.

Power is a concern, but the number of available pins is the more-limiting factor.  Even so, these units (I use Nano a lot) can easily handle several sensors simultaneously.  Mine output to Raspberry Pi via Serial cable so it can collect data for later processing.

There is no answer that can be given to you that is "correct". However, there are things for you to consider in your design process:

Can you fit all the code in flash, and the required variables in RAM?
Does the chip have all the IO you need, and can you use the required internal / interfacing peripherals in the right combinations to satisfy your requirements
Do the devices fit within your power budget (battery capacity, required run-time, power regulation efficiency).

The Arduino is just a component. It belongs in a circuit, and that circuit is what determines everything else. The ATMega328P has certain power requirements, as do all the other components in your circuit. It is up to you to design the right power system to provide that power with the right efficiency and power saving options (switching off circuit segments when not needed to save power), etc.
For prototyping and experimenting the Arduino provides a rudimentary power supply which is wildly inefficient. Not recommended for any battery powered scenario or any high current usage.

Thank you for advice. For code it is ok, it fits. But i am worried for power. Idea for now is to add more batteries

Calculate how much current you need for your sensors first. No one can help you until you do that.


text:
Error declaring two-dimensional array: 'x' was not declared in this scope
I'm trying to declare a 2-D array where each letter in the alphabet is keyed to a corresponding LED in my LED strip. But when I try to declare the array, Arduino flags the values and gives me a "not declared in this scope" error. I have no idea why. Am I missing a library or is it incorrect syntax?
Some of the places I've looked say to make sure it's declared globally. I've declared the array before void setup but it still doesn't work. Here's what I've got before void setup:
#include <Adafruit_NeoPixel.h>

#ifdef __AVR__
  #include <avr/power.h>
#endif

#define PIN 6

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(50, PIN, NEO_GRB + NEO_KHZ800);

//Create a 2-D array to store each letter and
//its corresponding LED number
char charKey[26][2]={
  {a, 0},
  {b, 2},
  {c, 4},
  {d, 6},
  {e, 8},
  {f, 20},
  {g, 18},
  {h, 16},
  {i, 14},
  {j, 12},
  {k, 10},
  {l, 22},
  {m, 24},
  {n, 26},
  {o, 28},
  {p, 30},
  {q, 40},
  {r, 38},
  {s, 36},
  {t, 34},
  {u, 32},
  {v, 42},
  {w, 44},
  {x, 46},
  {y, 48},
  {z, 50}
};

Without quotes, a, b, c etc. are just names. You didn't declare any of them, so the compiler complains.
Put single quotes around the letters to let the compiler know that they are char literals.


text:
Arduino industrial 101 digital pins
I don't see anything that has been clear about which digital pins map to which physical ones. If someone could point me in the right direction it would be a big help.
For exampleThrough trial and error, i've found that if i set digital pin 3 in the Arduino IDE, it is mapped to D0 on J6, but surely this is documented somewhere?

I just Google "Arduino  Industrial 101", tab Images and found what you are looking for. Pinout for other Arduinos can be a good starting point, I guess

We must have different search results, because that was the second thing i did and didn't see what i was looking for, but thanks for looking.

I found what i was looking for on the arduino github repository.
Arduino/hardware/arduino/avr/variants/


text:
Can I control a cellphone's lcd (+touch screen)?
I had an Xperia txt pro just laying around and tried to revive it. I burned it like an idiot using 5v in the battery pins by accident :/
So I decided to read it apart and got to the lcd, can I use my Arduino Mega to control it? Bc I have no idea how to use it.
These are the pins

No. For two reasons:

You will struggle to find the pinout of the TFT (or even identify the model). It will have most likely been custom made for the phone.
The Arduino doesn't have a GPU to drive it. Arduinos need a TFT with built in GPU since they lack the resources to drive one directly.


text:
Can the Mouse library scroll horizontally?
I'm using the Mouse library with an ATmega32U4 connected to Linux via USB.
I would like to issue horizontal scroll commands, but the Mouse.move() function only seems to accept X movement, Y movement and vertical scroll parameters.
How can I send horizontal scroll commands from the Arduino to the computer?

You need to rewrite the core to provide buttons 6 and 7.

You could combine it with Keyboard to use the Ctrl and Shift keys for other scroll options.

As suggested in the comments, I edited the core libraries to achieve this.
I'm using PlatformIO, so the library files I needed to edit were here:
~/.platformio/packages/framework-arduinoavr/libraries/Mouse/src/

And the required changes (to change a wheel parameter for horizontal (h) and vertical (v) scroll parameters were as follows:
Mouse.h
Change the declaration of move():
...
void move(signed char x, signed char y, signed char h = 0, signed char v = 0);
...

Mouse.cpp
Add the following to the report descriptor after the last INPUT message:
...
0x05, 0x0c,        //       USAGE PAGE (Consumer Devices)
0x0a, 0x38, 0x02,  //       USAGE (AC Pan)
0x15, 0x81,        //       LOGICAL_MINIMUM (-127)
0x25, 0x7f,        //       LOGICAL_MAXIMUM (127)
0x75, 0x08,        //       REPORT_SIZE (8)
0x95, 0x01,        //       REPORT_COUNT (1)
0x81, 0x06,        //       INPUT (Data, Var, Rel)
...

Change the definition of move():
void Mouse_::move(signed char x, signed char y, signed char h, signed char v)
{
    uint8_t m[5];
    m[0] = _buttons;
    m[1] = x;
    m[2] = y;
    m[3] = v;
    m[4] = h;
    HID().SendReport(1, m, 5);
}

The following terminal commands were also useful in testing these changes:
# List input devices
xinput --list

# List device capabilities
xinput --list <device-id>

# Watch for data sent from the device
watch -n 0.1 xinput query-state <device-id>

The NicoHood/HID library https://github.com/NicoHood/HID has a lot for keyboards (media keys and so on), but not everything for mice. I don't know if horizontal scrolling is somewhere in there.

Horizontal Scroll is achieved by holding shift when scrolling vertically.
Do this instead:
Keyboard.press(KEY_LEFT_SHIFT);
    Mouse.move(0, 0, 1);
    Keyboard.releaseAll();


text:
Problems connecting Adafruit Feather M0 to network
I'm trying to connect my Adafruit Feather M0 board to an existing WiFi network. Whenever I use the "ConnectWithWPA" example sketch, I receive "Attempting to connect to WPA SSID: "MyNetwork" " in the serial window, where "MyNetwork" is the SSID for the WiFi I wish to connect to. The network never gets connected. The WiFi I want to connect is WPA, password protected. When I connect the feather to an open network (one without a password) it does in fact get connected. The problem only occurs when I try to connect to a network with SSID and password.
Does anyone know what the problem may be?
#include <SPI.h>
#include <WiFi101.h>

#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the WiFi radio's status

void setup() {
  //Configure pins for Adafruit ATWINC1500 Feather
  WiFi.setPins(8,7,4,2);
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  // attempt to connect to WiFi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid, pass);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid); //, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.print("You're connected to the network");

 }

void loop() {
  // check the network connection once every 10 seconds:
  delay(10000);
  }

I was able to get the Feather board communicating with my WiFi network after I updated my Arduino IDE and firmware. Hope this helps anyone else facing this problem.


text:
How to determine which pins_arduino.h file is used?
For some applications I need access to the registers that control the output/input and high/low state of pins.  For example pin 10 on a adalogger is PORTB with a mask of _BV(6).  This information can be found in pins_arduino.h.  For some boards many variants get installed.  I turned on verbose compiling and looked through the output there as well as looking through boards.txt and platform.txt.  In that output I see an include to a directory with a pins_arduino.h file but there is nothing in that file but a definition for BUILTIN_LED.
When I run a function like digitalWrite(13,HIGH); how does it know which registers to use for pin 13?  Since my board has this pin, and digitalWrite(13, HIGH); makes an LED light up ... it's working.

In the boards.txt file for the core in question you have a line for each board:
xxxx.build.variant=yyyy

where yyyy is the name of the folder in variants for the board.
For instance, the Uno, has:
uno.build.variant=standard

which relates to:
variants/standard

with the pins_arduino.h file in it for that board.

Thanks, I found that line and it agrees with the output from the compiler.  The problem is that particular file is basically empty.  Does that mean there is a default somewhere that it's using as well?

It's far from empty on my installation. What version are you running? And what board / core is it?

I have hundreds of pins_arduino.h files throughout the system.  My problem is with the adafruit huzzah ESP8266.  The pins_arduino.h file is basically empty.

Well, that is down to the core. The core most likely has defaults that don't need overriding. Most ESP8266 boards just map the GPIOs 1:1 and don't need anything else. Remember: an ESP8266 is not an AVR Arduino and does not follow the same rules.


text:
How to use IRremote library with atmega8a
A few days ago I tested  a circuit on a  breadboard based on a ATmega8a with 1 MHz internal oscilator. It sould turn on and off a relay based on a IR code that is received and if it matches the programmed in the EEPROM it shoud enable or disable the relay. Now I developed a PCB and soldered everything together but now it isn't working. On an Arduino Nano it is working ok.
#include <IRremote.h>
#include <EEPROM.h>

int RECV_PIN = 11;
int RELAY_PIN = 4;
int setpin = 3;
unsigned long work_at;
unsigned long adres;
unsigned long irbuffer;
IRrecv irrecv(RECV_PIN);
decode_results results;

void dump(decode_results *results) {

    if(digitalRead(setpin) == 0){
      work_at = results->value;
      Serial.println(work_at, HEX);
    }
    irbuffer = results->value;

}

void eeprom_writer(){
  if (irrecv.decode(&results)) {
    if(digitalRead(setpin) == 0 && work_at != 0){
      EEPROM.put(0, work_at); //put walue
      Serial.println(work_at, HEX);
      adres = work_at;
      Serial.println(adres, HEX);
      delay(1000); //wait
   }
  }
}
void setup()
{
  EEPROM.get(0, adres);
  pinMode(setpin, INPUT_PULLUP);
  pinMode(RELAY_PIN, OUTPUT);
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

int on = 0;
unsigned long last = millis();

void loop() {
  if (irrecv.decode(&results)) {
    // If it's been at least 1/4 second since the last
    // IR received, toggle the relay
  //  if(&results == adres){
      dump(&results);
      if (millis() - last > 250) {
        on = !on;
        if(on == true && adres == irbuffer){
          delay(5000);
          digitalWrite(RELAY_PIN, on ? HIGH : LOW);
          dump(&results);
        }else if(on != true  && adres == irbuffer){
          digitalWrite(RELAY_PIN, on ? HIGH : LOW);
          dump(&results);
          delay(5000);
        }
      }
    //}
//    Serial.println(dump(&results));
//    Serial.println(count, DEC);

    eeprom_writer();
    last = millis();
    irrecv.resume(); // Receive the next value
  }
}

Did you solder the ATMega on the PCB? How do you connect everything?

@LookAlterno I soldered it ti the pcb and used dip connectors to conect the iscp uart relay and the ir module.

Maybe I should use a pin that supports PWM

Changing the internal oscillator to 8MHz helped.


text:
Unable to compare two integer values in Arduino Mega
I wrote Arduino code (code is given at the end) to compare two integer values. The steps I took was:

Give input to DC motor to rotate it using serial port. Input was: G254
Then I store it in XX string and using XX.remove(0,1); I removed G from G254. XX now become 254
Then I used Serial1.println("P"); to get position of motor after rotation. I stored this value in ZZ string using String  ZZ = Serial1.readString();. ZZ will be P254.
And using XX.remove(0,1); I removed P from P254. ZZ now become 254.
Now, I convert both XX and ZZ into integer from string using  XX.toInt(); ZZ.toInt(); .
After that, I compare both values using:

if (XX == ZZ)
{
    Serial.println("BOTH ARE EQUAL");
}
else
{
    Serial.println("BOTH ARE NOT EQUAL");
}

But it shows BOTH ARE NOT EQUAL which is not true. I want to know where I'm making a mistake?
Code I used:
void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    Serial1.begin(9600);

    pinMode(13, OUTPUT);
}

void loop() {
    // put your main code here, to run repeatedly:
    if (Serial.available() > 0)
    {
        Serial1.println(Serial.readString());

        String  XX = Serial1.readString();
        XX.remove(0,1);

        Serial1.println("P");

        String  ZZ = Serial1.readString();
        ZZ.remove(0,1);

        XX.toInt();
        ZZ.toInt();
        Serial.println(ZZ);
        Serial.println(XX);
        Serial.println(typeof(XX));

        if (XX == ZZ)
        {
            Serial.println("BOTH ARE EQUAL");
        }
        else
        {
             Serial.println("BOTH ARE NOT EQUAL");
        }
    }
}

Thanks.

A question will get downvotes if question shows no effort. Fine. But I tried hard and do above coding by myself. I need to add int x (Thanks @Michel) in my code which I don't know and that's why I put my question here. I think this question should not be downvoted  on the basis of efforts because I try to find out a solution from other sources but cann't and at last, I put my query here. I loose my points unnecessarily.

You should use
 int x = XX.toInt()

Without the int x = part, the string is converted and the result (the integer) is not used.
Also comparing strings should be done with the strcmp function. The problem is that if you compare two strings, you compare the pointers to those strings and two strings can have equal texts but (probably) not equal addresses.

Might need to add that XX.toInt() returns the value of the string after converting to a number. It does not convert the string (internally) to a number. The string is still a string. Also it is possible to compare the strings directly to be equal.

@MikaelPatel. String comparison is alphabetic, not numeric.

@LookAlterno True but equal is equal even for strings - isn't it :) https://www.arduino.cc/en/Tutorial/StringComparisonOperators

@MikaelPatel There are people that learn JavaScript or PHP as a first language; unaware of the differences.

Thanks for all comments, I updated the answer accordingly.

There are several issues with your code.
First, never assume that Serial.readString() will returns you a complete String; it can time out and return nothing, or return just an incomplete value.
Serial.available() > 0 doesn't imply that the reading is complete ...
Second, Serial.readString() returns everything, include the possible \r\n at the end of the string.
Here is a little sketch that shows a toInt implementation fit for you case. Run this sketch to see how it works.
void setup() {
  Serial.begin(9600);
  while(!Serial);
}

void loop() {
  String x = Serial.readString();
  Serial.print(x); Serial.print("=");
  Serial.println(myToInt(x));
}

int myToInt(String x) {
  char* p = x.c_str();
  int val = 0;

  while(*p != 0 && !isdigit(*p)) {
    p++;
  }

  while (*p != 0 && isdigit(*p)) {
    val = val * 10 + (*p - '0');
    p++;
  }
  return val;
}


text:
Arduino GY273 HMC5883L Constant Value
I have a GY-273 which has HMC5883L chip (I guess). I am trying to get data. I find a few codes and library (I don't have enough information about HMC5883L) but always all serial port screen there are only one value.
Here is my sketch:

#include <Wire.h>
#include "compass.h"

#define Task_t 10          // Task Time in milli seconds

int dt=0;
unsigned long t;
// Main code -----------------------------------------------------------------
void setup(){
  Serial.begin(9600);
  // Serial.print("Setting up I2C ........\n");
  Wire.begin();
  compass_x_offset = -48.23;  //122.17;
  compass_y_offset = 284.69;  //230.08;
  compass_z_offset = 59.87;  //389.85;
  compass_x_gainError = 1.07;  //1.12;
  compass_y_gainError = 1.09;  //1.13;
  compass_z_gainError = 1.01;  //1.03;

  compass_init(2);
  //compass_debug = 1;
  //compass_offset_calibration(3);

}

void loop(){

  t = millis();

  float load;

  compass_scalled_reading();

  Serial.print("x = ");
  Serial.println(compass_x_scalled);
  Serial.print("y = ");
  Serial.println(compass_y_scalled);
  Serial.print("z = ");
  Serial.println(compass_z_scalled);

  compass_heading();
  Serial.print ("Heading angle = ");
  Serial.print (bearing);
  Serial.println(" Degree");

  dt = millis()-t;
  load = (float)dt/(Task_t/100);
  Serial.print ("Load on processor = ");
  Serial.print(load);
  Serial.println("%");

  delay(100);
}

And Serial port screen is:
Gain updated to  = 1.22 mG/bit
x = -48.23
y = 284.69
z = 59.87
Heading angle = 99.62 Degree
Load on processor = inf%
x = -48.23
y = 284.69
z = 59.87
Heading angle = 99.62 Degree
Load on processor = inf%
x = -48.23
y = 284.69
z = 59.87
Heading angle = 99.62 Degree
Load on processor = inf%
x = -48.23
y = 284.69
z = 59.87

simulate this circuit – Schematic created using CircuitLab

What is your question?

@LookAlterno This value is always the same. No change.

Are you asking for someone to debug your code?

@LookAlterno Actually I didn't understand what is the problem. It is my first test. I'm not sure problem is code or module (or as I have just learned, continuous mode etc.). I'm asking what the problem is.

Those values are written in the setup function to the variables. You never get anything from the sensor. Run the i2c scanner to find the i2c address https://playground.arduino.cc/Main/I2cScanner . There are also clone sensors (QMC5883). What is "compass.h" ? Is that a library ? Did you write "compass.h" yourself ? The Arduino Nano runs at 5V, but the HMC5883L is a 3.3V sensor. It can get damaged when you connect sda and scl to the Arduino Nano without i2c level shifter.

@Jot Yes, compass.h is a library which is I find on the net. I have tried i2cscanner. It said I2C device found at address 0x0D. GY-271 3.3V but GY-273 3.3-5V as I saw on the net. compass.h is here

I think there are 4k7 pullup resistors on the module from sda to 3.3V and from scl to 3.3V. Therefor you can connect the module to an Arduino Uno without i2c level shifter. The address 0x0D is the QMC5883 (fake HMC5883L). There is a library for it: https://github.com/mechasolution/Mecha_QMC5883L but please don't use it. Get a real HMC5883L. Perhaps if you change the library (the compass_address to 0x0D in compass.cpp) and perhaps some of the fake sensor will work, although I read that the QMC5883 is not compatible with the HMC5883L.

@Jot I supposed it's HMC5883l. It works with the library which you gived thank you. I have changed the address but it didn't work.

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