text:
Pull EN pin of regulator to ground
I have an Adafruit Huzzah Feather with ESP8266 board, but I think my question will apply to most all boards (as most all have an onboard regulator). Most regulators have an Enable pin (EN) as does my Adafruit board. Apparently, I can shut down the regulator by pulling this pin low. I have a specific application where an external device will provide a high signal to me when I want the device to turn on, otherwise, I want it off at all times. So, what I have is a 1k resistor pulling the EN pin low, to ground. I tried other values 10-20k but they did not pull enough low to shut down the regulator. For example, 20k pulled me down from 3.3V to 2.6V but the regulator stayed on. On the other hand, 1k pulls me down to .3V on the EN pin and this shuts it down.
Then, when the external device gives me the high signal, which I have also tied to the EN pin, this will pull it back up and turn on the regulator.
This seems to be working just fine, but I wanted to ask if this sounds reasonable (I know this is a general question but I want to know if there is a better way). A specific, related question would be am I wasting too much power by using a 1k resistor when powered up or pulled high since some of the supply current will be dumped via the 1k resistor to ground.
UPDATE: In looking at the schematic on the Adafruit site, it appears that they have pulled EN to the input via a 10k resistor. So, I am fighting that which is probably why values over 10k do not pull it down enough to turn off. If I was doing the board design, I would have reversed this and pulled EN low by default but this is not the case when using the off the shelf board. So, I guess any value below 10k should work, like 4.7k? I guess I could also remove their pull up if I wanted to get really crazy. Thoughts on all of this?
Thanks!

A better solution would be to use a PNP transistor to control the EN pin. A PNP is ON when the input to it is LOW (or lower than the collector minus 0.7V, that is).
Take this circuit, for instance:

simulate this circuit – Schematic created using CircuitLab
When the GPIO is HIGH the transistor Q1 is turned off (GPIO >= VCC-0.7). Also if the GPIO pin is disconnected it is turned off because R3 pulls it up to VCC.
Set the GPIO LOW and Q1 turns on since the base is now lower than VCC-0.7V. With Q1 turned on it connects the EN pin to ground, so it becomes LOW.
If you replace the PNP with an NPN (there's more chance you have one in your bits box) you can basically invert the logic:

simulate this circuit
Now when the GPIO is LOW or pulled down by R3 Q1 is off and EN is pulled HIGH. Set the GPIO HIGH and Q1 turns on and connects EN to ground setting it LOW.
In both these scenarios the EN pin defaults to HIGH. If you want it to default to LOW until you activate the GPIO pin (i.e., during bootloader operation when the GPIO is in INPUT mode) you can reverse R3 so it becomes a pull-down (for the PNP) or a pull-up (for the NPN).


text:
Issue with length of string value
I have been getting some weird issues with a sketch I put together(apart from memory low warnings, it was working fine)
When im about to post data to my php server - it seems not all the information is available
eg the output will be
42399.92
&HAAlt=-18.24

Is there a limit to string length?
Im crudely constructing a string to send to a post request
#include <SPI.h>
#include <Ethernet.h>
#include "DHT.h"
#include <math.h>
#include <Wire.h>
#include "MutichannelGasSensor.h"
#include "HP20x_dev.h"
#include "KalmanFilter.h"

unsigned char ret = 0;

/* Instance */
KalmanFilter t_filter;    //temperature filter
KalmanFilter p_filter;    //pressure filter
KalmanFilter a_filter;    //altitude filter

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
IPAddress server(192, 168, 0, 30); // numeric IP for Google (no DNS)
//char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 40);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

#define Vc 4.95
//the number of R0 you detected just now
#define R0 35.54
#define DHTPIN A1     // what pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

DHT dht(DHTPIN, DHTTYPE);

int pin = 8;
unsigned long duration;
unsigned long starttime;
unsigned long sampletime_ms = 2000;//sampe 30s ;
unsigned long lowpulseoccupancy = 0;
float ratio = 0;
float concentration = 0;
String data;
String data2;

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

  delay(150);
  HP20x.begin();
  delay(100);

  /* Determine HP20x_dev is available or not */
  ret = HP20x.isAvailable();
  if (OK_HP20X_DEV == ret)
  {
    Serial.println("HP20x_dev is available.\n");
  }
  else
  {
    Serial.println("HP20x_dev isn't available.\n");
  }

  pinMode(8, INPUT);
  starttime = millis();//get the current time;
  Serial.println("power on!");

  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);

  //if (Ethernet.begin(mac) == 0) {
  //  Serial.println("Failed to configure Ethernet using DHCP");
  // try to congifure using IP address instead of DHCP:
  Ethernet.begin(mac, ip);

  // give the Ethernet shield a second to initialize:
  delay(10000);
  Serial.println("connecting...");
  //}
  // give the Ethernet shield a second to initialize:
  //delay(1000);
  //Serial.println("connecting...");

  // Serial.println(Ethernet.localIP());

  gas.begin(0x04);//the default I2C address of the slave is 0x04
  gas.powerOn();
  //Serial.print("Firmware Version = ");
  //Serial.println(gas.getVersion());
  //Serial.println("Particles\tRS\tHCHO (PPM)\tNH3 (PPM)\tCO (PPM)\tNO2 (PPM)\tC3H8 (PPM)\tC4H10 (PPM)\tCH4 (PPM)\tH2 (PPM)\tC2H5OH (PPM)");
  dht.begin();
  delay(10000);

  data = "";
  data2 = "";
}

void loop() {

  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  float HATemp2;
  float HAPres2;
  float HAAlt2;

  if (OK_HP20X_DEV == ret)
  {
    long HATemp = HP20x.ReadTemperature();
    float p = HATemp / 100.0;
    HATemp2 = t_filter.Filter(p);

    long HAPres = HP20x.ReadPressure();
    p = HAPres / 100.0;
    HAPres2 = p_filter.Filter(p);

    long HAAlt = HP20x.ReadAltitude();
    p = HAAlt / 100.0;
    HAAlt2 = a_filter.Filter(p);

  }

  duration = pulseIn(pin, LOW);
  lowpulseoccupancy = lowpulseoccupancy + duration;

  float d;

  if ((millis() - starttime) >= sampletime_ms) //if the sampel time = = 30s
  {
    ratio = lowpulseoccupancy / (sampletime_ms * 10.0); // Integer percentage 0=>100

    d = 1.1 * pow(ratio, 3) - 3.8 * pow(ratio, 2) + 520 * ratio + 0.62; // using spec sheet curve
    //Serial.print("concentration = ");

    lowpulseoccupancy = 0;
    starttime = millis();
  }
  //Serial.print("\t");
  //HCHO

  int sensorValue = analogRead(A0);
  double Rs = (1023.0 / sensorValue) - 1;

  double ppm = pow(10.0, ((log10(Rs / R0) - 0.0827) / (-0.4807)));
  //Serial.print("HCHO ppm = ");

  //MultiChannel Gas
  float NH3 = gas.measure_NH3();
  float CO = gas.measure_CO();
  float NO2 = gas.measure_NO2();
  float C3H8 = gas.measure_C3H8();
  float C4H10 = gas.measure_C4H10();
  float CH4 = gas.measure_CH4();
  float H2 = gas.measure_H2();
  float C2H5OH = gas.measure_C2H5OH();

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  data = String("dust=") + d + "&rs=" + Rs + "&hcho=" + ppm + "&nh3=" + NH3 + "&co=" + CO + "&no2=" + NO2 + "&c3h8=" + C3H8 + "&c4h10=" + C4H10 + "&ch4=" + CH4;
  data2 = String("&h2=") + H2 + "&c2h5oh=" + C2H5OH + "&temp=" + t + "&hum=" + h + "&HATemp=" + HATemp2 + "&HAPres=" + HAPres2 + "&HAAlt=" + HAAlt2;

  Serial.println(data);
  Serial.println(data2);

  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("POST /air_add.php HTTP/1.1");
    client.println("Host:  192.168.0.30");
    client.println("User-Agent: Arduino/1.0");
    client.println("Connection: close");
    client.println("Content-Type: application/x-www-form-urlencoded;");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.println(data);
  }
  else
  {
    Serial.println("could not connect");
  }

  if (client.connected()) {
    client.stop();
  }

  Serial.println("done.");

  delay(30000);
}

There isn't a real limit on the length of a String that you are running into.  But when you are running low on RAM (the low memory warnings you mentioned) then there is a limit on how much memory you have to put that String before you cause memory corruption and either crash the program or at best get some weird output.
The String class is particularly wasteful of memory and it has some issues when using the + operator to concatenate Strings that will leave the heap memory full of holes and reduce the amount of memory you have even further.  On memory constrained systems like microcontrollers, the String class crutch is a thing to be avoided.  Learn to use char arrays and real c-style strings and you'll be better off.
One place you could immediately save some memory would be by putting all the constant strings in your code into PROGMEM instead of leaving them out in RAM.  So this:
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded;");

becomes
client.println(F("Connection: close"));
client.println(F("Content-Type: application/x-www-form-urlencoded;"));

It was memory!! thank you - I did as suggested and it had a huge impact on usage

output is now dust=0.62&rs=12.29&hcho=13.54&nh3=2.71&co=13.67&no2=0.78&c3h8=4579.24&c4h10=2334.79&ch4=42399.92&h2=4.14&c2h5oh=7.25&temp=23.20&hum=65.90&HATemp=11.52&HAPres=507.68&HAAlt=-8.82
:)

Is that good or bad?

It’s good. That’s the full list of sensor data

There is no limit for String other than the available memory. No String can be longer that ~2KB.
In these statments
data = String("dust=") + d + "&rs=" + Rs + "&hcho=" + ppm + "&nh3=" + NH3 + "&co=" + CO + "&no2=" + NO2 + "&c3h8=" + C3H8 + "&c4h10=" + C4H10 + "&ch4=" + CH4;
data2 = String("&h2=") + H2 + "&c2h5oh=" + C2H5OH + "&temp=" + t + "&hum=" + h + "&HATemp=" + HATemp2 + "&HAPres=" + HAPres2 + "&HAAlt=" + HAAlt2;

you are creating and deleting a lot of temporary Strings. How much memory will you need to hold all those temp Strings togheter? You don't know. Hard to say, because it's implementation dependent.
In Arduino you have to learn to use char arrays (and pointers) to works with strings. With a low level C method you know exactly how much space you will need. If you don't have enough memory, you still can reorganize your sketch to work around limitations.
Arduino is a low level world.

+1  - I will investigate optimisation via char arrays

source: Stack Exchange

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

sort: votes


text:
Connection of serial pin on ATMEGA328P to connector B type(female) D+ and D-
Now I am using ATMEGA328P and want to communicate with computer in serial using B connector female (also want to provide power from computer to ATMEGA328P using B connector).
So here is my question. How can I connect D+ and D- to ATMEGA328P's pin No. 2 (PD0/RX) and pin No. 3 (PD1/TX)? In other words which pin should I connect to D+ and D- ? Also is it possible to connect them directly?
Thank you in advance.

Have you examined the schematic of an Arduino device that uses the '328P?

I have seen the schematic of Arduino but  they connect D- and D+ to ATMEGA1602. But this time I want to use ATMEGA328P only.

Did you ever stop to wonder why they do that?

I'm not quite sure, maybe due to converting. But now I am asking is it possible doing that with ATMEGA328P only?

Pull up the datasheets for both devices; you don't need the complete datasheets, just the summary datasheets will do. Examine and compare the front pages.

I did. But really don't get what to see. If possible could please explain weather it is possible to use ATMEGA328P only.

Are you asking how to connect a USB "B" connector to pins 2 and 3 of the Atmega328P?

Yes. Exactly.  I want to realize serial communication with computer.

The Arduino Uno (and similar boards) have a chip on them that does serial communication via a dedicated USB chip (the ATmega16U2 chip). You can't just connect pins 2 and 3 to D+ and D- and turn that into USB.
You can conceivably do it using V-USB which does USB in software in conjunction with a few extra components.
You can also buy external serial to USB adapters which do the conversion externally. If you Google serial to usb adapter you will find quite a few for around $3.

The Adafruit Trinket Pro https://www.adafruit.com/product/2000 uses this, so does the usbasp (not Arduino code) http://www.fischl.de/usbasp/ @zalt, if you have to ask, don't do this. I has special requirements for the hardware and software, and it is something for advanced engineers. Stay away from it.

ok I did with HID-class USB Serial Communication for AVRs using V-USB. I  could monitor the incoming data to PC  by HID Serial Monitor.
However, I need to monitor the incoming data by Serial monitor such as tera-term or Arduino's serial monitor.
Is there anyway to do that with HID-class ?
I tried trinket-fake-usb-serial, but did not work at all.
Please I need help.

This sounds like a different question to me. First you ask if certain ports can be connected to a USB device, now you are asking about monitoring serial data with a HID-class USB. I suggest you make a new question. Offhand, using a HID (Human Interface Device) when there isn't a human there clicking away seems like a misuse of the hardware.

All I want to do is just getting the serial data from MCU(ATMEGAA328P)
to PC  without using serial to usb adapter.

The Atmega328P doesn't have a USB interface so what you want isn't really practical. There is no "simple wiring" that will achieve that.

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


text:
ATtiny85 MIDI IN using SoftwareSerial - Is it possible?
I'm trying to read MIDI notes using an ATtiny85 via SoftwareSerial; so far, I've got no success at all.

The ATtiny is using the internal clock, 8Mhz, 5V.
The MIDI keyboard sends clean note on/off messages (tested with a MIDI monitor).
I've tried several test programs, particularly Nick Gammon's, as described here.
I've followed Nick's schematics to build the connector, and I can confirm his program works with an Arduino, but not with the ATtiny.
I calibrated the Tiny with OSCCAL - still no luck.
As far as I can tell, midiSerial.available() is always 0, in every program I've tried.
SoftwareSerial works fine for the purpose of MIDI out.

That's as far as I've got. I'd appreciate any pointers, especially if anyone else could try Nick's code and see if it works.
EDIT
There was an issue with my local version of SoftwareSerial. I had commented out code so that I could use pin change interrupts in my MIDI out program, but those interrupts are essential for MIDI input. Once I uncommented the code, all the programs I tested worked, so it is indeed possible to receive MIDI using an ATtiny.
That said, I've tried four keyboards as inputs and only one has worked so far, a Korg 01/W proX. The same happens when I load the MIDI code directly in the Arduino, so based on the answers below I will try a different optocoupler, and post my results here for the sake of improving on the answer.
Here's the schematics I was talking about:

The schematic is wrong: pin 2 at the receiver must not be connected to ground, and the optocoupler is not reliable at MIDI speeds. See 4N35 opto-isolator for MIDI input does not work?

You posted a link to a page that have a link to another page that contains the info your talking about.

true- I've just added the schematic above. The code is relevant because the author claims it's been tested, but it's one of several I've tried with identical results, so I don't think it is as central to the question.

Your link now points to a better schematic …

@LookAlterno there's no double jump - scroll down to "Example code for ATtiny85"

You might try NeoSWSerial.  It has a configuration option to avoid the PCI vector problem, and it now supports the MIDI baud rate.  It is MUCH more efficient than SoftwareSerial.

I'd also say it's the opto isolator. I am getting good results with a 6N138. I also had good results with a 6N137 but based on reports from other people it seems that it can fail with certain devices.

@CL fixed up the earth pin on the schematic.

I have done tests with a normal Arduino with software serial and missed quite a bit of messages, so I would advice to use hardware serial's instead.
For MIDI Out probably it works, but for MIDI In I have bad experiences. Especially when it comes to many messages, like aftertouch/pitch bend etc.
Also, I tried some optocouplers which didn't work well (like 6N137). I now use H11L1 optocouplers (they are white compared to most black ICs) and work perfectly.
You already checked the clean note on/note off ... are you sure it doesn't send active messages?
Below the schematic as I use it.. It does not matter if an STM32 or Arduino is used. Actually I haven't checked if H11L1 are 3.3V or 5V but they seem to work on both.

simulate this circuit – Schematic created using CircuitLab

Yes, no other messages at all.

From yours and CLs comment it looks like I can't rely on the 435, so I'll try the H11L1.

It might be that different resistor values should be used, if you want I can check when I'm home this evening.

I'd be very grateful if you could :)

I added my circuit (hopefully without mistakes)

That looks great, I'll order the parts and report back asap!

Good luck .. btw I tried it earlier with an Arduino Uno/Mega (5V) and today with a STM32 (3.3V). ... both work. Btw, there is no difference between H11L1 and H11L1M except the manufacturer (some are white, some are black).

The pin numbers and several connections are wrong.

@CL I checked it and the only mistake I could find was the connection with the wire left of R2. I'm really interested what pin numbers/connections are wrong, because it is according to the circuit I built (on a breadboard).

DIN connector number the pins differently. R4 must be a pullup on the output signal. (And this schematic would be much more readable if you didn't try to connect all VCC and GND signals together; see, e.g., this page.)

@CL Thank you for the comments ... true, I numbered the DIN pins myself (I will follow the original numbering, but get always confused about the side to look at). And a good tip about the VCC/GND ... I really used the pullup the way in the schematics and works, but I will check the official one and change mycircuit accordingly.

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


text:
How to filter data of ultrasonic sensor using arduino
I am working on a project that uses ultrasonic HC-SR04 sensor to measure distance. I've connected the sensor to the Arduino Uno board, I am also using Arduino IDE to program the Arduino. The problem is that I am not getting stable readings, there is the presence of some noise in the readings. How should I filter out this noise.
Circuit connections are as follows:
Ultrasonic sensor | Arduino
VCC                 5V
GND                 GND
Trigger             12 (digital)
Echo                11 (digital)

I am using new ping to measure distance.

Having noise in the sensor data is common and normal, especially on low end sensor.
As you can imagine there is a "data science" to clean up the values, mostly based on statistic.
One of the easiest trick is to remove all values that have a difference > Xt from previous value; as you can imagine the tolerance Xt is calculated by a factor X, let's say a bit more the maximum speed you think the system will operate in time multiplies by the time since the last valid measure.
For example you expect a max distance chance of 10m in one second, so we use as tolerance 15m/s. If we don't read valid value, after 6 seconds our tolerance is 15m/s * 6s = 90m
Of course after much time maybe you just want to accept the first reading that seems valid, so you analyze 10, 100, 1000 value and see if they seems correct.
Then for a quick and dirty smoothing and cleaning if the remaining data, you can run a average on the value, there are different forms, and more value you use more stable are your output, but also less fast to follow changes.
A kallmann filter is the most common but also complex way to clean the data, but I guess in most hobbyist application is just overkill.

First off, Start a time counter. You can get the current time instant by using:
unsigned long StartTime = millis();

After that, keep counting time by using the following block:
 unsigned long elapsedTime = currentTime - StartTime;

With this you can know how much time (in ms) has passed since StartTime. In this time loop, keep reading data from the Ultrasonic sensor. As the sensor may need some time to get each reading, take a conservative delay (e.g. 100 ms). You can again increment the timer by using a goto statement. Note that you must also maintain a counter for later. In this time loop, keep adding the readings from the sensor to itself. Finally when the stipulated time is over, you can take the average by dividing the final sum of the sensor values with the counter maintained earlier.


text:
Hall effect sensor
I've taken velocity readings of a wheel using a hall effect sensor. Is it possible to take the acceleration readings corresponding to those velocities as well? Do I just have to divide the velocity by the time taken?

Yes, you can divide speed by time and get acceleration, obviously that will give you the mean acceleration between speed reading.

Cheers Lesto!!!


text:
Advice for lower power clock type project
Arduino newbie here! I'm a programmer but my hardware knowledge is ... slim.
I'd like to build a clock type wake up timer for my daughter, using an Arduino type board. Probably overkill, but it's practice for me, not just the end result! The idea is that is sleeps all night, then around say 4, gradually fade on a red LED. At 6, which is when she's allowed to come in, the red LED switches to a green, or some colourful sequence that tells her it's time. At a later time, maybe 7/8, it goes back to sleep to conserve power.
I have an Arduino Uno, but looks like I'll also need an RTC, and I've read that the sleep power consumption is ~40mA, which on batteries is what? A day or two max?
So I'm thinking I can't do this with a Uno.
So, my question is, are there any very low power Arduino compatible boards with built in RTCs that I can use for this project that will get me up and running as quickly as if I was using the Uno?

Is plugging it into a wall not an option?

An Arduino Micro Pro could be used (after removing the power LED and voltage regulator). It is possible to reduce to less than 10 uA.

@ratchetfreak It's sadly a suboptimal option as the room has extremely limited power sockets, however thinking about it actually might be the perfect option to make a proof of concept at least.

A extension cord with multiple outlets should help with that.

Try one of supported RTC's boards. The most popular (and simple) are: DS1302, DS1307, PCF8563, and - very nice, precise DS3231 (my fav). Hook any of them up to your Arduino, add some (readily available) libraries, tweak a little and voila. Most (if not all) of mentioned RTC have 'alarm' function: you can set up your system to wake up your Arduino from sleep (sleep state to save battery) and gradually light up the LED.

i would use an esp8266 to "drive" the LEDs and send color commands over wifi from a computer that knows the time. i use such a setup for several LED matrix clocks, and it works well w/low effort (little c++ coding, no soldering, no RTC or external modules besides the matrix).

I will make my comment an answer:
Try one of Arduino supported RTC's boards. The most popular (and simple) are: DS1302, DS1307, PCF8563, and - very nice, precise DS3231 (my fav). Hook any of them up to your Arduino, add some (readily available) libraries, tweak a little and voila. The RTC will work from coin battery (or high capacity capacitor called supercapacitor, like this one)
Most (if not all) of mentioned RTC have 'alarm' function: you can set up your system to wake up your Arduino from sleep (sleep state to save battery) and gradually light up the LED.
To limit current of Arduino try removing LED, or - better - try to use Arduino Pro Mini. To modify it for better power saving see here
EDIT:
There are some other low-power boards:
Moteino
Rocket Scream Mini Ultra
JeeLink
Also, (as mentioned in one of comments) you can try one of ESP8266 and push it to one of many sleep modes. Try this link.


text:
My Arduino isn't showing up on my computer. What should I do?
You have your spangly new Arduino board, you've installed the software, and you plug it in. Nothing happens. Diagnosing problems may be a little tricky for the beginner, so what hoops should you go through to try and work out where the problem is and why you can't get your board working?

Note: this is an FAQ. Do not use it to ask about your specific problem. Comments will be deleted. Either ask a new question detailing all the steps you have taken, or, better, discuss your problem in chat.

Linux
Getting Arduino and Arduino-like boards working properly under Linux can be a troublesome task if you are not familiar with how Linux works.
So I am going to introduce you to some of the basic tools you will need to work out why your board isn’t working as you’d like it to work.
The majority of problems a new user is faced with boil down to one simple thing: permissions. A normal user doesn’t, by default, have permission to talk to much in the way of hardware. That include serial ports and USB serial emulation ports (FTDI, etc). Fortunately granting permission to your user to access the serial ports is a simple matter, and one that you should always do by default to make life much simpler for you. This is done through a Linux permission facility called groups. A group is a name given to a collection of users, files, devices etc., that go together. Permissions can be granted on files to the group that it belongs to, and users that are in that group can access those files. On Linux most devices are just files.
The serial ports are all in the default group dialout, but your normal user isn’t. So you need to add your user to that group. Only root has the permission to do that, so use sudo to execute the commands as root. If you don’t have access to root through sudo or some other means then you will have to seek the assistance of an administrator who does have permission.
First add your user (you’re called fred, right?) to the dialout group:
$ sudo usermod -a -G dialout fred

The “-a” is of vital importance. That says “Add the user to these groups”. Without it you have “Set the user’s groups to be this list”. If you omit the “-a” by accident you will remove your user from any other groups before setting them to be in the dialout group. That means you will never be able to run sudo again. So be sure not to miss that one out, eh?
Now that has only changed the configuration files (/etc/groups in this case) and the change hasn’t actually had any effect yet. The groups are only set when you log in to the computer, so you will either need to log out and back in again or (a more definite solution, especially if you have auto-login turned on) reboot the computer.
Now you should be in the dialout group:
(before)
$ id
uid=1000(fred) gid=1000(fred) groups=1000(fred),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)

(after)
$ id
uid=1000(fred) gid=1000(fred) groups=1000(fred),4(adm),20(dialout),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)

Now try it, see if that has got you working.
Next step, if that doesn’t fix your problems, is to see if the computer knows about the Arduino. First look to see if there is a device file for the Arduino and if it has the right permissions:
$ ls -l /dev/ttyACM* /dev/ttyUSB*
ls: cannot access '/dev/ttyUSB*': No such file or directory
crw-rw---- 1 root dialout 166, 0 Aug 24 11:05 /dev/ttyACM0

Don’t worry about the “cannot access…” message unless you get two of them. There are two sets of device names that the Arduino could be under depending on which type it is. Genuine UNO and similar boards (the ones with the ATMega16U2 chip as the USB interface) are /dev/ttyACM*. Clones using the CH340G, and FT232 based boards appear as /dev/ttyUSB*. We just asked for both there, so it complained when it couldn’t find any entries for one of the types. Which is fair enough. If you get:
$ ls -l /dev/ttyACM* /dev/ttyUSB*
ls: cannot access '/dev/ttyACM*': No such file or directory
ls: cannot access '/dev/ttyUSB*': No such file or directory

however, then worry. That can’t find anything at all. The computer doesn’t know the Arduino exists.
One thing to check is the permissions on the files that have been listed above. You see the word “dialout” in the list? That’s the group that the device belongs to, and it should match the group you added yourself to earlier. There are times when it may say “tty” instead. This is because some other program has grabbed the device and is using it to allow remote access to the computer through that serial port. For that you need to make sure that there are no agetty processes using that port. How you do that is very much down to your version of Linux. Modern Debian based systems (such as Debian Jessie and Ubuntu) use systemd to manage it. You can examine what is running on your system using
$ systemctl status

That returns a tree of all the services that your system is running. Look through that list to see if there are any “serial-getty” services running. If there are you should remove them:
$ sudo systemctl stop serial-getty@ttyACM0
$ sudo systemctl disable serial-getty@ttyACM0

While you’re there look through the list for another troublesome member: ModemManager. This is a program used to dial out to the internet through old-fashioned modems (you know, the kind that go beep beep beep squark squeek squark ) or USB DSL modems (that no one uses any more, we’re all wireless now. Remember the old green “frog” modem from way back when…?). That has a habit of grabbing a serial port as soon as it appears and trying to configure a modem attached to it. While that’s happening nothing else can access the serial port. It’s especially a problem with boards like the Arduino Leonardno or chipKIT Lenny which create a new serial port when they enter programming mode. So unless you really need the functionality that ModemManager provides you should just remove it:
$ sudo apt-get remove modemmanager
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED
modemmanager
0 to upgrade, 0 to newly install, 1 to remove and 138 not to upgrade.
After this operation, 2,826 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 180827 files and directories currently installed.)
Removing modemmanager (1.4.12-1ubuntu1) ...
Created symlink from /run/systemd/system/ModemManager.service to /dev/null.
Removed symlink /run/systemd/system/ModemManager.service.
Processing triggers for man-db (2.7.5-1) ...
Processing triggers for hicolor-icon-theme (0.15-0ubuntu1) ...
Processing triggers for dbus (1.10.6-1ubuntu3) ...

Another useful tool is lsusb. This lists the USB devices that are connected to your computer. You should find your Arduino listed there. This is especially useful for boards that don’t present a serial port for programming, but we’ll cover those in more depth a little later on.
$ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 002: ID 80ee:0021 VirtualBox USB Tablet
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

Nothing much on this computer. Well, actually I am using a virtual machine for this, as you can see by the VirtualBox USB Tablet entry. But let’s connect my Arduino UNO:
$ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 004: ID 2341:0001 Arduino SA Uno (CDC ACM)
Bus 002 Device 002: ID 80ee:0021 VirtualBox USB Tablet
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

So we know that the operating system has identified it. You can find out lots more information about it if you so desire, with:
$ lsusb -v -d 2341:0001

That gives you all the device descriptors for the device. Tells you all you could ever want to know about the information the board sends to the computer when it is connected.
Another useful tool is dmesg. This is the system message log viewer and can be used to find out exactly what is going on with your computer.  It has a useful “keep running” mode specified by the flag -w. I like to run dmesg and then press return a few times to create a breakpoint in the listing, then plug in the board I am diagnosing to see just what the messages are that pertain to that board:
$ dmesg -w
[ 0.000000] Initializing cgroup subsys cpuset
[ 0.000000] Initializing cgroup subsys cpu
[ 0.000000] Initializing cgroup subsys cpuacct
[ 0.000000] Linux version 4.4.0-24-generic (buildd@lgw01-12) (gcc version 5.3
... lots of stuff spools past ...
[ 19.425870] NFS: Registering the id_resolver key type
[ 19.425883] Key type id_resolver registered
[ 19.425885] Key type id_legacy registered
<press return a few times>

<connect Arduino>
[ 131.232511] usb 2-2: new full-speed USB device number 3 using ohci-pci
[ 131.519307] usb 2-2: New USB device found, idVendor=2341, idProduct=0001
[ 131.519312] usb 2-2: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[ 131.519315] usb 2-2: Product: Arduino Uno
[ 131.519317] usb 2-2: Manufacturer: Arduino (www.arduino.cc)
[ 131.519319] usb 2-2: SerialNumber: 64934333235351B002E0
[ 131.605485] cdc_acm 2-2:1.0: ttyACM0: USB ACM device
[ 131.613792] usbcore: registered new interface driver cdc_acm
[ 131.613796] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

Press CTRL+C to terminate the listing.
If nothing appears when you connect the Arduino then there is something fatally wrong. My money is either on a faulty cable (some cheap cables on eBay only have power wires and no data wires) or the Arduino itself is completely dead.
More likely though you get error messages. I can’t replicate them right now (I don’t have a faulty Arduino) but they usually pertain to things like “device not accepting address” and “Error -71”. This is usually caused by bad USB communication. It may, again, be a faulty cable, or it may be that the USB interface chip is not working right. Maybe the crystal has drifted and it’s not running at precisely the right frequency. Maybe it’s a cheap CH340 chip that has failed. Maybe the firmware on the ATMega16U2 has become corrupted.
If all that checks out fine so far and you still can’t upload a sketch there may be something even more fundamentally wrong with your Ardunio board. Maybe it’s time to look to see if there is actually any communication happening. I find the program minicom invaluable, although you could use the ghastly Serial Monitor in the Arduino IDE.
First you need to disable the main chip on your Arduino. You can do this simply by connecting the RESET pin to GND with a piece of wire. Or you can hold the RESET button down, but that means you’re then typing one-handed. That stops the main chip from interfering in any way with the serial communications while you’re testing it. It can also prevent any damage to the chip while testing.
The second step is to connect the TX and RX pins together (pins 0 and 1 usually) with another piece of wire. You are now in what is known as a loopback mode. Any serial data you send to the board should be sent straight back to where it came from. So now fire up minicom and try it out (you will need to install it first of course with sudo apt-get install minicom).
$ minicom -D /dev/ttyACM0 -b 115200

Of course replace the /dev/ttyACM0 with the real device name for your board. The -b 115200 is the baud rate, though that is pretty much irrelevant since we’re not actively communicating with an external device.
Now you should be able to type some gibberish and get some gibberish back. If you do then communication is working fine, and the problem most likely lies within the target MCU – maybe the bootloader has become corrupted and needs re-flashing, or the chip has died.
CTRL+A, X gets you back out of minicom again.
If you didn’t get your gibberish back, or you got back different gibberish than you sent, then there is definitely something up with the serial communications. The main culprit is, again, the USB interface chip.
All this, of course, has been focusing on the traditional Arduino style interface with a USB serial port of some form. Not all boards give you that though. Some, such as the Launchpad boards, use a hardware programmer on the board, and that doesn’t always give a serial port – certainly the programming isn’t done through the serial port. To gain access to those (again by default you don’t have permission to access the low-level devices) you have to get deeper into the operating system.
For these you need to make modifications to the configuration of a system called udev. This is a management system for the devices on your computer and is used to control what happens to them when they are plugged in. One of the things you can do is set the permissions on that device so people can actually access it.
The system is configured by a set of rules in “rules files”. These are stored in /etc/udev/rules.d and there should already be a few in there for other purposes. You will need to, as root, create a new file to put your rules in.
$ sudo nano /etc/udev/rules.d/50-boards.rules

The most important thing to know is the VID and PID (Vendor ID and Product ID) of your board. You can get that from lsusb as above (it’s the vvvv:pppp bit – v = VID, p = PID). You can then feed that into a simple rule, such as:
ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="0033", MODE="0660", GROUP="plugdev"

There we are matching a vendor (04d8 = Microchip) and product (0033 = PICkit2) and assigning it to the group plugdev (make sure you are in that group – default users should be already) and allowing the group members read and write access to it (MODE="0660"). Save that file and restart udev for the changes to take effect (or reboot your computer if you like):
$ sudo /etc/init.d/udev restart

Now plug the device in and you should have permission to access it.

Windows
Ok, the first thing you need to do is identify the kind of board you have. I don't mean is it an Uno, a Mega, or one of Intel's brief forays into the Arduino world - I mean what kind of USB interface the board has.
Boards can be loosely grouped into two categories - CDC/ACM and Custom USB Profile.
Current versions of the official Arduino Uno and Mega are both CDC/ACM devices (CDC/ACM, by the way, stands for Communication Device Class / Abstract Control Model). This means that between the main microcontroller (ATMega328P, ATMega2560, etc) there is another microcontroller - usually an ATMega16U2. This takes the serial data from the main microcontroller and sends it to the PC over USB using the USB CDC/ACM protocol.
You can identify these boards by the chip that is nearest the USB connector.

That small black chip with the Atmel logo on it is the USB interface chip.
Boards of this style have the USB drivers included in the Arduino IDE. If you have installed the IDE properly the drivers should have been installed for you automatically. Also Windows 10 (finally) contains "class compliant" drivers for CDC/ACM, so no drivers actually need to be installed for these boards anyway (installing the Arduino ones doesn't hurt, though, and helps it to show the right board name in the device manager).
The other category of board, "Custom USB Profile", use different chips. And there's lots of different chips it can be using.
Early Arduinos and some other makes of board (such as chipKIT boards from Digilent) use the Future Technologies RT232R chip. This sometimes looks at first glance like the Atmel chip above, but is very very different. You have to check the number on it to be sure. Other times a different package is used and it's obvious it's different.
Then there are the cheap clone boards you get on eBay and Amazon. These, more often than not, use yet another chip - the CH340G. This is a fraction of the cost than the FT232R or ATMega16U2 chips, which is why cheap boards tend to use them. They're also less reliable and harder to get working in some operating systems (most notably OS X).
For these kind of chips you need to install the right driver for the specific chip you have. For the FT232R chips that's not too hard - Future Tech have the drivers on their website.
The CH340G driver is harder to find from a reliable source.(someone with more knowledge please fill this in)
Ok, so your board is a CDC/ACM based one, or you are sure you have installed the right drivers. The next thing to check is if the board is even being seen by the operating system.
When you plug it in for the first time it should pop up a bubble saying it found new hardware:

Or something similar to that. It should also make a noise.
If neither of those happen then it's likely the computer isn't seeing the device at all. This sounds more like a hardware problem than a Windows problem.
The first thing to try is to plug the Arduino into a different port. Even better is, if you have access to one, plug the Arduino into an entirely different computer.  What you are trying to diagnose here is if the problem is related to the Arduino/USB cable or to the computer/USB port.
If it works in a different computer but not your computer then there is something wrong with your USB ports. It may be that you are using a computer that is locked down (such as in a school or an office) where the "group policy" has been configured to not allow any USB devices to be used (chiefly to prevent people bringing in memory sticks with viruses on them). If this is the case you will have to consult with the powers that be in your organisation to get your device authorised.  If not, then you may have more luck plugging your Arduino into a powered USB hub instead of directly into your computer (it may be that the computer can't provide enough current for the Arduino to run properly).
If it's failing equally as badly on another computer / port then you should start looking at the USB cable and the Arduino.
It is quite common for small battery powered devices that are charged through USB to be shipped with cheap cables. These are cables that only have the +5V and GND wires in them - no D+ and D- wires. For obvious reasons these can't be used with an Arduino: with no data wires how can the computer see it? However it's generally impossible to tell these cables apart from a full USB cable.
If you happen to be using one of these cables without knowing it you'll get a power light on the Arduino and not much else. So you need to swap the USB cable for another one - preferably one you know works properly.  If it suddenly springs into life then you know you have a bad cable. Throw the old one away - it's almost useless - or stick a label on it saying "power only" so you know what it is.
Another thing to mention in passing: I have known some of the early Arduino boards to have lower quality USB connectors on them (Uno R2). These sometimes have trouble connecting properly with some cables (not all), so maybe a better quality cable may fix the problem, or tweaking the contacts within the USB connector with a needle may help.
Right - the other direction to go in is if it does identify that you plugged a board in, but can't install the drivers. Maybe it's saying the device failed, or it can't find the drivers.
Step one is to go into the device manager and look for an "Unknown Device":

That is most likely the Arduino.  You should be able to inspect all the data for it to find the USB Vendor ID (VID) and Product ID (PID).  If those are showing up as corrupted, not available, or FFFF, then your Arduino has a serious problem and Windows cannot work out what it is. In this case it may be that the USB interface chip has failed (there have been unsubstantiated rumours that shorting 5V to GND on an Uno R3 can kill the ATMega16U2 chip). There's not much you can do when that has happened.
If you can find reasonable data in the device manager, as in the image below, then it's going to be a case of trying to fix (or find the correct) driver, since you may not have the right one installed. Also note that some other board manufacturers use the same VID and PID as the Arduino and having their drivers installed could cause the Arduino to not function properly - you should uninstall their drivers first, or manually set the Arduino to use the proper Arduino driver.

MAC OS X
Getting an Arduino to work with OS X can be as simple as "plug and play" to almost impossible. It depends on which version of OS X you are using, and more importantly, what "kind" of Arduino you have. "Kind" means, is your Arduino a genuine Arduino, a "counterfeit" claiming to be the real thing or a cheap "knock off" using the CH340 USB interface.
Your first step is to identify exactly what you've got. If you have a CH340 chip on your Arduino like the one on this cheap "knock off" of an Arduino UNO, then you'll need to install a driver so that OS X can communicate with it.

Download a CH340 driver for the exact version number of OS X you are using and install it as per the manufacturer's instructions. If you download a driver for the latest version of OS X and install it on an older version of OS X, it may install just fine. When you plug in your Arduino device, OS X reads the .kext file and sees it's for a newer version of the OS so it doesn't load it, and never will (unless you upgrade to that exact version someday).
Here is a picture of a "counterfeit" Arduino UNO. It uses the ATMEL MEGA 16U2 chip as a USB interface which is "suppose to work" with OS X's existing drivers. If you have one of these and it's "not working", don't bother installing the FTDI drivers because that won't solve your problem.

Unfortunately, what works on one version of OS X doesn't always work on another version. Solutions are usually specific to OS X versions, but there are some common troubleshooting steps to follow once you know what Arduino USB Interface you have and you've installed the correct driver (if required).
Verify that OS X is recognizing your device.

Click on the Apple icon in the top left corner of the menu bar.
Click on "About This Mac".
Click on the "More Info…" button (OS X 10.6) or "System Report…" button under the "Overview" section (OS X 10.7 and higher).
Expand the "Hardware" menu item and click on USB.

You should see something like this:

If you plugged in your Arduino and is not listed somewhere on the USB Device Tree, I can guarantee it will not show up in the Arduino IDE Serial Port Menu. It won't show up in the /dev list using terminal either. Please keep in mind that System Profiler does not refresh automatically. If you un-plug your Arduino and plug it back in again, you have to MANUALLY re-fresh System Profiler to see the current data

If you still can't get your Arduino working, try swapping the USB cable or using a different computer / OS to see if it works.

But what is the question? Unless you have a Chinese device with a CH340 it just works.

And therein lies the information that needs putting in. Also it "just works" in Linux (more so - no need for CH340G drivers) yet things do go wrong - and people need to know how to perform the troubleshooting to identify the problem. Do not assume it "just works" for everyone - the OS may be fine but the Arduino may not be. How do you work that out in OS X? If you know, please fill out this answer with the steps you'd take and the methods you'd use.

Obviously an exercise in futility when contributions are deleted by people who don't even realise OSX is obsolete!


text:
Arduino Mega 2560 + BL-TB6560+ Stepper
I am working on an Arduino Mega 2560 and BL-TB6560-V2.0 driver for running a stepper motor. Initially I was able to run the stepper in both direction with code given and a schematic as per this image.
.
int dirpin = 7;
int dirH = 12;
int steppin = 9;

void setup() {
  pinMode(dirpin, OUTPUT);
  pinMode(steppin, OUTPUT);
  pinMode(dirH, OUTPUT);
}

void loop() {
  digitalWrite(dirpin, LOW); // Set the direction.
  digitalWrite(dirH, LOW);
  delay(1000);
  for (int i = 0; i<32767; i++) {
    // Iterate for 4000 microsteps.(32767)
    digitalWrite(steppin, LOW); // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(50);
  }
  delay(1000);
  digitalWrite(dirpin, LOW); // Set the direction.
  digitalWrite(dirH, HIGH);
  for (int j = 0; j<32767; j++) {
    // Iterate for 4000 microsteps.
    digitalWrite(steppin, LOW); // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(50);
  }
}

But now when I am trying it, the same stepper is not rotating. What could be the reason? I have checked the driver voltage, it's ok, and the code and schematic is the same.

http://idownvotedbecau.se/imageofcode

Schematic photo is not bad by itself. It's the bad drawing, the photo angle, the bad lighting and the poor contrast.

There is no ground connection to the arduino on the schematic, hope there is one in the real world.

Why do you inverse the polarity on the 24V site ? Is this a mistake in the drawing ?

I just removed the ENE(+) pin of the driver, which was connected to the +5V. Now it's working and the stepper is rotating.
I just got a hint from this video.


text:
Store 3-dimensional char array in program memory with PROGMEM
I'm running a sketch whith a quite big, constant three dimensional char array (or simply, a table of strings). As this takes lots of RAM I'd like to store it in programm memory in order to keep the RAM free. This is the Sketch I'd like to run (my first idea):
const char *rules [16][5] PROGMEM ={
 {"1Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr", "sed di7am nonumy 8eirmod tempor invidunt"},
 {"2Lorem ipsum dolor sit amet, consetetur sadipscing2 elitr", "sed diam nonumy 9eirmod tempo5r invidunt"},
 {"3Lorem ipsum dolor sit amet, consetetur sadipscing 4elitr", "sed0 diam nonumy 1eirmod tempor invidunt"},
 {"4Lorem ipsum dolor sit amet, consetetur sadips3cing elitr", "sed diam nonumy 2eirmod tempor in5vidunt"},
 {"5Lorem ipsum dolor sit amet, consetetur 3sadipscing elitr", "sed 7diam nonumy 3eirmod tempor invidunt"},
 {"6Lorem ipsum dolor sit amet, conset9etur sadipscing elitr", "sed diam n8onumy 4eirmod tempor invidunt"},
 {"7Lorem ipsum dolor sit amet, consetetur sadipsc3ing elitr", "sed diam nonumy 5eirmod tempor inv4idunt"},
};

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(115200);
  for(int i = 0; i < 16; i++){
    for(int j = 0; j < 5; j++){
     Serial.println(rules[i][j]);
    }
  }
}

void loop() {
}

But this fails with the following error:
variable 'rules' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

According to Arduino's FAQ this can be solved by changing the array's declaration to
const char * const rules [16][5] PROGMEM ={

The sketch compiles now without errors, but the global variables (here only the array) still need lots of RAM:
Sketch uses 2484 bytes (7%) of program storage space. Maximum is 32256 bytes.
Global variables use 880 bytes (42%) of dynamic memory, leaving 1168 bytes for local variables. Maximum is 2048 bytes.

I'm not sure what causes this, but is it possible that only the pointers to the strings are stored in program memory, while the strings theirselves are still copied to RAM?
How do I put the whole arary in programm memory?
There has already been a question like this on StackOverflow, but the answer recommends using prog_chars, which are according to the AVR documentation deprecated.

See http://www.nongnu.org/avr-libc/user-manual/pgmspace.html and also use the special program memory access functions to get the string pointers.

Can you use fixed length data ? That would make it very easy. In that case, don't use a pointer, declare the array with data completely in PROGMEM with "const char rules[16][5][50] PROGMEM = {". The Arduino can not run code from ram and can not read data from program memory. As @MikaelPatel wrote, you need special functions. Read this https://www.arduino.cc/en/Reference/PROGMEM and this http://www.gammon.com.au/progmem Don't rush through those pages, read them. They explain how to use data and a table with pointers in PROGMEM to optimize memory usage.

Fixed data length would be wasting space as the data I really want to store has different lengths. What causes this issue? Is what I described in the question (pointers in PROGMEM, strings in RAM) correct?

Yes, you describe in the question pointers in PROGMEM and strings in RAM. Actually the strings are loaded from PROGMEM to RAM by the program startup code (init).

Maybe wasting a few hundred bytes is acceptable.

Here you have:
const char * const rules [16][5] PROGMEM ={

One const refers to the char* part. It means the pointer value doesn't change.
The other const refers to what it is pointed by. It means the thing this pointer points doesn't change (but the pointer itself can change).
In your sketch the thing that get put into PROGMEM is the pointer array; the texts themselves are still in RAM. Have a look at PROGMEM page and  study this example:
const char string_0[] PROGMEM = "String 0";   // "String 0" etc are strings to store - change to suit.
const char string_1[] PROGMEM = "String 1";
const char string_2[] PROGMEM = "String 2";
const char string_3[] PROGMEM = "String 3";
const char string_4[] PROGMEM = "String 4";
const char string_5[] PROGMEM = "String 5";

// Then set up a table to refer to your strings.

const char* const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5};

You need to declare each string by itself, and later put them in an array.
As you can see, pointer are inescapable.
Edit: The F() Macro
Here is a proof of concept of how to manage an array of string (lowercase "s") and strings constants in PROGMEM:
const char uno[] PROGMEM = "1Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";
const char dos[] PROGMEM = "2Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";
const char tre[] PROGMEM = "3Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";
const char cua[] PROGMEM = "4Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";
const char cin[] PROGMEM = "5Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";

const char * const rules [3][2] = {
 {uno, dos},
 {tre, cua},
 {cua, cin}
};

void setup() {
  Serial.begin(115200);
  Serial.println(F("PROGMEM string test"));
  Serial.println(F("-------------------"));
  for(int i = 0; i < 3; i++){
    for(int j = 0; j < 2; j++){
      Serial.print(i); Serial.print(" "); Serial.print(j); Serial.print(" ");
     Serial.println((const __FlashStringHelper *) rules[i][j]);
    }
  }
}

void loop() {
}

Use the F() macro to put constant strings in PROGMEM. Otherwise, the strings will live in RAM. Are running short of RAM? Put the F() macro around those pesky strings and send them out of your RAM.

So if I want a three dimensional array, I would change the last line like this?: const char* const string_table[2][2] PROGMEM = { {string_0, string_1}, {string_2, string_3}};` Would that be correct?

Yes; that's the correct syntax. BTW, yours is a two-dimensional array.

Yes, it's a two-dimensional array containing (pointers to) one-dimensional arrays, right?

@LookAlterno Might need to update the answer with how to print the strings. This is tricky as a special form (helper class) is used for the F() macro.

How do I declare the strings? Should I use const char string_0[] PROGMEM = "String 0"; (as in the exapmle on the Arduino page) or const char* const uno PROGMEM = "1Lorem.."; as in your second example? I'm not sure where the difference is. The first one creates an array while the second one creates a pointer, right? Why is it possible to store multiple chars in one char pointer?

Your proof of concept does not work: you have a PROGMEM array full of pointers to strings in RAM. You need to declare character arrays instead (const char uno[] PROGMEM). But then, as Mikael Patel puts it, the printing gets trickier.

@LookAlterno When I run your second example, printing to Serial works fine. But when I run this code (which is merged from my original code and your second example) I only get rubbish on the Serial. Why does this happen? Am I trying to print the pointer itself instead of the string it points to? If yes, how do I fix this?

@EdgarBonet is right, running you code needs 492 bytes for global variables which shows that the strings aren't stored in program memory. Would it be recommendable to open a new question how to print those strings from program memory?

You can fix the printing with Serial.println((const __FlashStringHelper *) rules[i][j]);.

Duh! I accepted the edit by @tr01.


text:
Which of the clock sources are actually internal to the ATmega328P?
I am trying to determine exactly what all of the fuse settings correspond to on the ATmega328P. The options for the CKSEL bits are:

1111-1000: Low Power Crystal Oscillator
0111-0110: Full Swing Crystal Oscillator
0101-0100: Low Frequency Crystal Oscillator
0011: Internal 128kHz RC Oscillator
0010: Calibrated Internal RC Oscillator
0000: External Clock

Clearly, the clocks labeled "internal" are part of the "guts" of the microcontroller. No external components are required to use those clock sources. The external clock is clearly an external source.
My question is this: are the low power, full swing, and low frequency sources built in to the microcontroller itself, or do they require an external crystal oscillator to be purchased and connected to the clock pins? This is not 100% clear from reading the data sheet. (Although I am under the impression that they are not internal to the device.)

If it requires a crystal, as the ones in question clearly state, then obviously you need to connect a crystal (and load capacitors).  Or use a ceramic resonator.
Only those labelled as internal are internal. Everything else is external.

Thanks. That's what I thought, but the fact that it said "external" for one, and not the others, confused me.

An external clock is a specific physical thing - as is a crystal.


text:
Cannot get any readings from DHT22 Sensor connected to Arduino M0 Pro
I have directly connected a DHT22 to my Arduino M0 Pro. I have put a 10k Resistor across the Data & V+ of the sensor pinout. The data is connected to pin 5 and I have it connected to 3.3V output of Arduino.
I am just trying to see some readings from the sensor via the SerialUSB console. I have downloaded and unpacked the DHT libraries that I got on the Adafruit website/GitHub. As far as I know I have these libraries in the right directory - C:\Program Files (x86)\Arduino\libraries\DHT...
I also have installed the Adafruit Unified Sensor library on the IDE.
I am trying to use the Tester program that is provided, this compiles ok but the SerialUSB printout prints:
Failed to read from DHT sensor!
Failed to read from DHT sensor!
Failed to read from DHT sensor!

And so on...
I have tried another DHT22 sensor to no avail.
The only part of the code I have changed is the pin number and changed from Serial to SerialUSB.
Not sure if I have to change anything else? Or am I doing something really silly!

Here is the code:
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN 5     // what digital pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  SerialUSB.begin(9600);
  SerialUSB.println("DHTxx test!");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    SerialUSB.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  SerialUSB.print("Humidity: ");
  SerialUSB.print(h);
  SerialUSB.print(" %\t");
  SerialUSB.print("Temperature: ");
  SerialUSB.print(t);
  SerialUSB.print(" *C ");
  SerialUSB.print(f);
  SerialUSB.print(" *F\t");
  SerialUSB.print("Heat index: ");
  SerialUSB.print(hic);
  SerialUSB.print(" *C ");
  SerialUSB.print(hif);
  SerialUSB.println(" *F");
}

Unrelated to your problem, but FYI C:\Program Files (x86)\Arduino\libraries\DHT is not the correct place to install libraries. It does work but the problem is any time you update to a new version of the Arduino IDE everything you install to C:\Program Files (x86)\Arduino will be lost. This is why you should always install libraries to the libraries subfolder of your sketchbook folder. See https://www.arduino.cc/en/Guide/Libraries.

Thanks, yeah I had to figure that one out the hard way, thanks again though.

Found what the fault was, it was a solder short between pins on a custom PCB that was sitting on top of the Arduino board. My bad! At least I have it working now!


text:
PROGMEM on Arduino Due (ARM Cortex M3)
I've been working with the PROGMEM function on my Arduino Uno and I'm thinking about changing to the bigger Arduino Due which is based on a ARM Cortex M3 processor instead of the AVR processor on the Uno.
The Arduino Reference now says:

PROGMEM is part of the pgmspace.h library that is available in the AVR architecture only.

My question now is: Is it possible to store constants in program memory instead of flash on the Due?
If found this post on the Arduino forums, suggesting that this is done automatically. Does anyone know something about that?
EDIT: Arduino IDE doesn't give stats about RAM usage after compiling, so I can't just try.

I guess you have already looked at the source code for the Arduno-SAM core. There is a port of the AVR program memory functions (pgmspace.h); https://github.com/arduino/ArduinoCore-sam/blob/master/cores/arduino/avr/pgmspace.h. The actual answer is that const data is stored in the program flash and loaded to RAM by the program startup code.

Thank you @MikaelPatel. But doesn't that dissent from what Majenko wrote in his answer?

@MikaelPatel That's not a port of them - that's creating aliases for them for backwards compatibility. It just removes all _P suffixes and ignores all PROGMEM, etc.

@Majenko "port" ;)

There is no PROGMEM required on ARM. There is no memory bus separation between Flash and RAM, so it doesn't copy constants from flash to RAM which PROGMEM is used to prevent.


text:
Confused between SPI and I2C for SSD1306 OLED
I recently got myself an SSD1306 OLED display:
I haven't been able to successfully wire it to an Arduino (Mega 2560) however. I have been reading up on I2C and SPI and checked some libraries from Adafruit and U8G2.
However, I'm confused, since most of the Internet is talking about a similar OLED display with GND - VDD - SCL - SDA labelled pins, where mine has SCK instead of SCL.
Now, the number of pins make me believe I need to interface with I2C, but the SCK label points to SPI, right?
One person seemed to have the same problem as me, but the solution he got (pull-up resistors) didn't do the trick for me, I'm afraid.
So, my question remains: how to wire this OLED display to the Mega 2560?
Much appreciated if someone could point me to the right direction.
Thanks!

manufactures are terrible about printing the right labels on those interface pins. i've seen SPI MOSI labeled: MOSI / SPI / DO / SDI / SDA / AD / A0 and DC; some of those aren't even close! there's only 2 wires, so that's a I2C. try flipping the pins if it doesn't work; ive seen them labeled backwards too.

SCK and SCL are the same thing.

Serial ClocK
Serial CLock

They seem to be interchangeable. The fact you have SDA (Serial DAta) as opposed to separate SDI / SDO or MOSI / MISO pins means it's I2C.
Wire it like you would any other I2C device.

It is i2c, but these display are known for disturbing the i2c bus. They might be 3.3V i2c, or missing an acknowledge. Adafruit adds a i2c level shifter to similar oled displays. The U8g2 has an option for software i2c without acknowledge.

thanks a lot, that works (also, for reference: the I2C address for this display is 0x3C)

U8g2 in software I2C mode works well on the GM009605 v4. I can pretty much use any pin. Looks stable too.

I have what appears to be the same display (GM009605 v4) and while both SCL and SCK both stand for Serial Clock many development boards have different SCK and SCL pins that you'd need to interface. On a Wemos d1 mini for example I have this display plugged into SDA => D2 & SCK => D5 where as if it was SCL it would to to D1.
FWIW I use the Wire.h and SSD1306.h libraries (https://github.com/ThingPulse/esp8266-oled-ssd1306) to interface with the display using the Wemos D1 mini.

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


text:
Wake up arduino mini with a external signal from a rf wake up receiver
I am working in an arduino which sleeps after 1.2 seconds of running time and wake up when receiving a signal in the pin 2, but this last part is not working. I tried with the four modes of the interrupt ( LOW, CHANGE, RISING, FALLING) and also tring to connect it to vcc and disconect it myself, depending on the mode.
The sleeping part works as wanted
#include <avr/sleep.h>

// ### pin paging ### \\

#define RLEDPIN 13       //pin for red led
#define GLEDPIN 12       //pin for green led
#define BLEDPIN 11       //pin for blue led
#define wakePin 2        // pin used for waking up

// ### measure variables ### \\
unsigned long times;

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

void setup()
{
  Serial.begin(115200);
  pinMode(RLEDPIN, OUTPUT);
  pinMode(GLEDPIN, OUTPUT);
  pinMode(BLEDPIN, OUTPUT);
  pinMode(wakePin, INPUT);

  attachInterrupt(0, wakeUpNow, CHANGE);
}

void sleepNow()         // here we put the arduino to sleep
{

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    sleep_enable();          // enables the sleep bit in the mcucr register
                             // so sleep is possible. just a safety pin

    attachInterrupt(0,wakeUpNow, CHANGE); // use interrupt 0 (pin 2) and run function
                                       // wakeUpNow when pin 2 gets LOW

    sleep_mode();            // here the device is actually put to sleep!!
                             // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

    sleep_disable();         // first thing after waking from sleep:
                             // disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the
                             // wakeUpNow code will not be executed
                             // during normal running time.

}

void loop()
{

    digitalWrite(GLEDPIN, HIGH); //set green led high

  times = millis();

  if(times>=1200)
  {

    digitalWrite(GLEDPIN, LOW); //Reset the LED's
    digitalWrite(BLEDPIN, LOW);
    digitalWrite(RLEDPIN, LOW);
    sleepNow();
  }
}

Only a LOW interrupt will wake the chip from PWR_DOWN mode. Does your device set the pin LOW when it's activated?

@Majenko I tried that and also having the pin 2 conected to vcc and when the arduino is sleeping putting it to ground and nothing happend, in case it was a failure of my device

By the way: sleep_mode() does all of sleep_enable() and sleep_disable() for you - you don't need to call them.

@Majenko  I had the code from the arduino web: code for sleep


text:
The most efficient way to test whether a byte is "empty" (B0000000) or not?
I have completed a small project I did to challenge myself to learn more about my arduinos programming. In this project, inside a for loop I have to check whether a MyVar byte fetched from an array of bytes, is "empty" (or 0, or B0000000 what applies best). Rough description of the program in note 1.
I did a lot of trial and error, and quickly realized that just asking
byte MyVar = B0001111
if {MyVar = 0 ; DoSomethingSpecial() } else {ProceedLoop()}

did not produce anything near the desired state. I deduced that testing bytes probably need to happen bitwise, or something clever (=beyond my understanding) is going on in how the compiler interprets the conversion.
So I created a dummy variable byte
byte EmptyValue = B0000000

and then did a logical AND between the MyVar and the EmptyValue
if (MyVar&EmptyValue) {DoSomethingSpecial(); } else {ProceedLoop(); }

which seemed to do the trick - it was getting late and my ability to find useful Serial.print() to capture the different values was getting low, but the results running the program were at the time indistinguishable to me from the expected way.
My question, firstly - is this a reasonable way to check if a byte is zero? Does it actually do that? I have been reading up on these bitwise calculations and I am truly confused to how it compares a final TRUE or FALSE from comparing.
Secondly, what would be a more processing-time-optimal way of doing this comparison? Is there a null-test of sorts? Should I have cast it into integer and tested against integer 0?

  const int interval=400;
  const byte ByteArrayMakeSound[11]={
    B0001111,                                       //H - length 4
    B0001111,                                       //E - length 4
    B0001111,                                       //L - length 4
    B0001111,                                       //L - length 4
    B0000111,                                       //O - length 3
    B0000000,                                       //
    B0000111,                                       //W - length 3
    B0000111,                                       //O - length 3
    B0000111,                                       //R - length 3
    B0001111,                                       //L - length 4
    B0000111                                        //D - length 3
    };
  const byte ByteArrayLongShort[11] =   {
    B0001111,                                       //H = --- --- --- ---
    B0000001,                                       //E = o o o ---
    B0001011,                                       //L = --- o --- ---
    B0001011,                                       //L = --- o --- ---
    B0000000,                                       //O = o o o
    B0000000,                                       // (pause 7 intervals)
    B0000100,                                       //W = --- o o
    B0000000,                                       //O = o o o
    B0000101,                                       //R = --- o ---
    B0001011,                                       //L = --- o --- ---
    B0000011                                        //D = o --- ---
  };

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

void loop()
{
  for (byte x = 0; x < 10; ++x) {
   byte sound = ByteArrayMakeSound[x];
   byte longshort = ByteArrayLongShort[x];
   byte emptyvalue {B0000000};
    if (sound&emptyvalue) {
      delay(7 * interval);
    }    else    {
      for (byte y = 0; y < 7; ++y)  {
        if (sound & (1<<y)){
          if (longshort & (1<<y))     {
            MakeSound(3);
            delay(interval);
          }   else    {
            MakeSound(1);
            delay(interval);
          }
        }   else      {}
      }
    }
      delay(3 * interval);
  }
}

void MakeSound(int del) {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(interval * del);
  digitalWrite(LED_BUILTIN, LOW);
}

Note 1: Program purpose

The program started as a hello world program with me trying to write
  "hello world" in morse code with the builtin led. The two byte arrays
  store the "letter length" of the morse and the "daa" / "dit"
  assignment. I use empty bytes to separate words, which means a delay
  of 3 intervals (= length of "daa") should happen. Then including the
  entire letter-table of morse and a string to byte table conversion (to
  create the byte arrays). It is not very quick... But I am tinkering
  with moving the byte arrays into the flash memory. Just for Hello
  World it is fast enough, but the "daas" and the "dits" are slightly
  uneven so programming time is impacting performance.

"=" is an assignment; "==" is a equality comparison. You are missing the semi-colons. Logical AND is "&&", not "@". That's not C, nor any know programming language.

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets. Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem. Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant. Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem

"&" is the bit-wise AND operator. "&&" is the logical AND operator. "A&B" is not the same that "A&&B".

Get a copy of "The C Language 2° Edition" by K&R. It's a short book. Read it from cover to cover. I think you are smart enough, but lacking formal training. You also need some introductory text to computers (in general). Cheers!

@LookAlterno Thanks for the tip, let's hope Amazon delivers as quickly as stackexchange =)

The fast way is:
byte x;
...
if (x) {
// not zero.
} else {
// zero
}

You are barking at the wrong tree.

So an empty byte itself is interpreted as false? Thats efficient.

There is no such thing as an empty byte (int, long, float, ...). Every byte (int, long, float, ...) has a value inside. Value can be zero, but that's is not empty. Zero is a legal value, just like any other.

Yes, a zero valued byte, not empty. Gotcha. It was just not obvious to me that simply asking if directly on a byte variable type returns false if the byte happens to have only zeroes. Like for strings, even if a string value will be interpreted as zero, it often doesn't compute inside an if. Thank you for clearing this up. I'll keep the question open for another 24h as per the rules.

@StianYttervik. Be aware that strings and Strings in C/C++ doesn't work exactly like strings in JavaScript, PHP or any other language. There are some differences that will bite you hard.

Try Serial.println(true); and Serial.println(false); to get a better understanding of why this works. ;)


text:
Arduino only supports 140 LEDs
I've a problem with an Arduino Uno board. It only supports 140 LEDs using the FastLED library. Any LED which is higher than that number can't be turned on or off using FastLED.
Is this related to the board, the library or any other  circumstances? And help or advice would be appreciated.

Did you read this https://github.com/FastLED/FastLED/issues/288

Maybe your code or inadequate power supply? We need more info.

Depending on how fast you need to go, the apa102-arduino library by Pololu doesn't seem to have a hard limit on their LED capacity.  They say the refresh rate goes down after 60 LEDs, but don't say anything about the maximum amount of LEDs you can have.
https://github.com/pololu/apa102-arduino
The max I'm doing at a time is only a string of 48, so I haven't checked how many it can update at once.  I am, however, running a total of 180 LEDs with this library, over 5 separate "channels".
To make it even a tiny bit harder, I'm doing it with a Nano.
This library has a "slow" and "fast" way to update the LEDs.  So far, the "slow" way is faster than the BlueTooth connection I'm sending data over to update the LEDs.
They state that the "fast" method is something like 20x faster than the "slow" way, but takes a little more in-depth programming.  Since the "slow" way works for me, so far, I haven't bothered trying the "fast" way.
Other option:
Talking with a friend at my local maker space, he said that it could be due to the speed of your board vs the timing of your LEDs. If your board isn't running fast enough, it can prevent the LEDs from being updated correctly after a certain amount of LEDs.
He was also saying that if you don't have enough available memory, it can affect how many LEDs you can update.
Seeing as you have an Arduino Uno, you shouldn't have a problem with speed or memory. Without knowing what else you are running on your Arduino (code, sensors, GPS, other shields, etc.), it's hard to say what could be holding you back.
My friend's son uses the FastLED library, so I'm going off other-than-first hand knowledge here.


text:
Is there any arduino microphone that can record heart sound?
I'm currently undergoing a project where I record heart sound (mechanical response) and send it over bluetooth to an app.
However I'm finding it really hard to find an arduino microphone or just general microphone that can listen to heart sound.
Any guide would be highly appreciated.
Thanks

Sounds like you need three things: a microphone, and amplifier, and an A2DP sender. No need for anything Arduino there.

How is it possible to connect your microphone to A2DP sender? @Majenko

With an amplifier and wires.

it would be better to use an adruino heart beat module, about $2 on ebay...

First, there is no such thing as an Arduino microphone. There are boards specifically for Arduino which have a microphone, but also these are just generic 'electronic sound sensors'.
In principle any microphone would be a valid choice, but you have to test what are the requirements (distance to heart, environment noice). You also could use piezo sensors for vibration checking possibly.

Apologies for pointing such non existing device. What I'm looking for is a simple micrphone that can just detect heart sound and send over bluetooth. The environment: lets assume a classroom. And generally speaking the microphone should be attached close to your heart (as in your chest).

https://www.gearbest.com/development-boards/pp_75530.html?currency=GBP&vip=760250&gclid=CjwKCAjwhOvPBRBxEiwAx2nhLlhykouF1qt4QXcvS-roOTPu6pJfeAN4x3KBNUvmFtm34ohKPtwyEhoCQzQQAvD_BwE

Have a look at this link. Would you think this would be suitable?

I don't know if it is suitable ... I would say for 2 dollars, buy it and check. If not buy a better one. It could work, since the heart will be close. Btw, for bluetooth sending you need another device, completely unrelated to microphones. Do one step at a time. Hopefully you don't mean 'in your body' ... in that case many more requirements should be met.

Also for detecting heartbeats there might be a simpler device possible: same as what sport watches use: a 'special ?'  led on a wrist watch on the inside checking the wrist blood-vain.

As part of this research, I'm opting out from any consumer complete products. ANd yes your right I should take one step at a time. Currently Im so baffled by how we can send microphone data over bluetooth.

Sending microphone data over bluetooth or any other data does not make much difference. Unless you want to send a lot (like the 'waveform raw data'  of the microphone. But I don't have experience with bluetooth

Just a thought, depending on your requirements, you might want to consider the use of a small microphone inserted in the tube of a modified stethoscope, or some such.  Prior to their invention, doctors would use a short tube, with one end over the heart, and the other at the ear, thus making the sound readily audible.  I think that detecting the heart beat is the easy part.  Your problem will be sending data by bluetooth, how to then receive and then analyse to produce useful information.


text:
Help with multi function momentary buttons
I'm using the PunchThrough Bean and trying to build a two button project that has multiple functions. The idea is the user can press button 1 or button 2 for either short or long presses, or they can press both buttons simultaneously for a short or long press. This would give the user up to 6 different functions. Below is my code. I can get button 1 or button 2 press to work, but can't get pressing both to work. Also, I can't figure out how to have a function depending on how long a button sequence was pushed. Any help would be greatly appreciated.
const int btn0 = 2;
const int btn1 = 3;

void setup() {
  Bean.enableWakeOnConnect(true);
  Bean.enablePairingPin(true);
  BeanHid.enable();
  pinMode(btn0, INPUT_PULLUP);
  pinMode(btn1, INPUT_PULLUP);
}

void loop() {
  bool connected = Bean.getConnectionState();
  pinMode(btn0, INPUT_PULLUP);
  pinMode(btn1, INPUT_PULLUP);

  if (connected) {
    int btn0State = digitalRead(btn0);
    int btn1State = digitalRead(btn1);

    if ((btn0State == LOW) && (btn1State == HIGH)) {
      Bean.setLed(255, 0, 0);
      Serial.print("up");
      BeanHid.sendKey(KEY_UP_ARROW);
      Bean.sleep(500);
      Bean.setLed(0, 0, 0);
    }

    if ((btn1State == LOW) && (btn0State == HIGH)) {
      Bean.setLed(0, 255, 0);
      Serial.print("down");
      BeanHid.sendKey(KEY_DOWN_ARROW);
      Bean.sleep(500);
      Bean.setLed(0, 0, 0);
    }

    if ((btn1State == LOW) && (btn0State == LOW)) {
      Bean.setLed(0, 0, 255);
      Serial.print("right");
      BeanHid.sendKey(KEY_RIGHT_ARROW);
      Bean.sleep(500);
      Bean.setLed(0, 0, 0);
    }

  }
}

We need a FAQ for buttons, multi-buttons, debouncing, menu navigation ..

Don't act immediately when a button gets pressed, instead when a button is pushed all you do is set the timestamp on that button and set a flag.
Then when it is released or the time elapsed is large enough do the appropriate thing.
void loop(){
    int btn1State = digitalRead(btn1);
    static bool button1 = false;
    static unsigned long time1 = 0;

    if (btn0State == LOW && !button1) {
        button1 = true;
        time1 = millis();
    }

    if (btn0State == LOW && button1) {
        if(millis() - time1  > SHORT){
            //do long action
            time1 = millis(); //reset timer
        }
    }

    if (btn0State == HIGH && button1) {
        button1 = false;
        //do short action
    }

}

That would cause bad user experience. When a button has both a “short press” and a “long press” action, user expectation is that the “long press” action happens as soon as the press reaches the required duration, not when the button is released. Otherwise it would be, for the user, hard to know how long is long enough.

@EdgarBonet fixed the answer


text:
Interrupts not firing sometimes
I am a little new to the arduino space, so forgive me if this question is a bit noobish.
Below I have linked the code. I am using an Arduino Mega and using photosensors, specifically this one EE-SPY415 Reflective Photomicrosensor with a detectable sensing distance of 3- to 19-mm
I am using this with a skeeball type arcade and the Arduino is using usb to communicate with a Pi. I am not sure if this is the best way, so if someone has a better way please let me know. There are 6 sensors now and 2 more that need to be hooked up. I will be using a library that allows for more than 6 interrupts to be used, but wanted to rule out the library as being at fault.
My issue in question is when the game is started, the serial.write isn't always firing when a ball goes through the hole. I am not sure yet if the interrupt fires and not the serial write, so any help there would be good too.
https://pastebin.com/zbVuqec2
Here is the ino file in question.
#include <Wire.h>

String inputString = "";         // a string to hold incoming data
boolean startGame = false;
boolean stopGame = false;
boolean readSensors = false;

boolean sensor_1_tripped = false;
boolean sensor_2_tripped = false;
boolean sensor_3_tripped = false;
boolean sensor_4_tripped = false;
boolean sensor_5_tripped = false;
boolean sensor_6_tripped = false;

#define SENSOR_1 2
#define SENSOR_2 3
#define SENSOR_3 21
#define SENSOR_4 20
#define SENSOR_5 19
#define SENSOR_6 18

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  pinMode(SENSOR_1, INPUT_PULLUP);
  pinMode(SENSOR_2, INPUT_PULLUP);
  pinMode(SENSOR_3, INPUT_PULLUP);
  pinMode(SENSOR_4, INPUT_PULLUP);
  pinMode(SENSOR_5, INPUT_PULLUP);
  pinMode(SENSOR_6, INPUT_PULLUP);

  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}

void loop() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inputString == "start") {
      startGame = true;
      stopGame = false;
      readSensors = true;
      Serial.write("STARTED");
      inputString = "";
      return;
    }
    if (inputString == "stop") {
      stopGame = true;
      startGame = false;
      readSensors = false;
      return;
    }
  }

  while (startGame) {
    while(readSensors) {

      attachInterrupt(digitalPinToInterrupt(SENSOR_1), sensor_1_callback, FALLING);
      attachInterrupt(digitalPinToInterrupt(SENSOR_2), sensor_2_callback, FALLING);
      attachInterrupt(digitalPinToInterrupt(SENSOR_3), sensor_3_callback, FALLING);
      attachInterrupt(digitalPinToInterrupt(SENSOR_4), sensor_4_callback, FALLING);
      attachInterrupt(digitalPinToInterrupt(SENSOR_5), sensor_5_callback, FALLING);
      attachInterrupt(digitalPinToInterrupt(SENSOR_6), sensor_6_callback, FALLING);

      if(Serial.available()) {
        char inChar = (char)Serial.read();
        inputString += inChar;
        if (inputString == "stop") {
          stopGame = true;
          startGame = false;
          readSensors = false;
          inputString = "";
          Serial.write("STOPPED");
          break;
        }
      }

      if(sensor_1_tripped == true) {
        sensor_1_tripped = false;
        Serial.write("1");
      }
      if(sensor_2_tripped == true) {
        sensor_2_tripped = false;
        Serial.write("2");
      }
      if(sensor_3_tripped == true) {
        sensor_3_tripped = false;
        Serial.write("3");
      }
      if(sensor_4_tripped == true) {
        sensor_4_tripped = false;
        Serial.write("4");
      }
      if(sensor_5_tripped == true) {
        sensor_5_tripped = false;
        Serial.write("5");
      }
      if(sensor_6_tripped == true) {
        sensor_6_tripped = false;
        Serial.write("6");
      }
    }
  }
}

void sensor_1_callback() {
  sensor_1_tripped = true;
}
void sensor_2_callback() {
  sensor_2_tripped = true;
}
void sensor_3_callback() {
  sensor_3_tripped = true;
}
void sensor_4_callback() {
  sensor_4_tripped = true;
}
void sensor_5_callback() {
  sensor_5_tripped = true;
}
void sensor_6_callback() {
  sensor_6_tripped = true;
}

Why do you use attachInterrupt() every time sensors are read? Is not it enough to do it only at the beginning of the game?

Those booleans that are used in the ISR and are also read from loop need to be volatile.

I added volitile but it didn't help (I did read about how that needed to be done though). As for the attachInterrupt I have it now in the setup() but if its already attached it ignores it. Either way the interrupts still arent working as expected.

Could you try to test with a simpler code without any Serial.read() and also correct your code in the question (volatile and only attach in setup). It is easier to help if the problem is narrowed down as much as possible.

I ended up using Android Things GPIO library and built a custom board that plugs into the Pi via the UART

The best solution I found for communicating interrupts to the Pi3 from Arduino is by using the GPIO. Android Things has a library for this and it all works without any lag!


text:
What's the point of a USB to Serial converter in Arduino Uno?
I am trying to understand how an Arduino Uno communicates with a PC and why it does so.
As far as I understand, an Arduino can be programmed to communicate with a PC only via a COM interface. At the same time, an Arduino Uno uses a physical USB interface to connect to a PC and it has a USB-serial converter onboard. So data sent from the board is converted from COM to USB to be transferred to the PC where USB data is converted to COM by a device driver to be read by a COM-port listener.
Why does this COM-related stuff is needed if the Arduino already uses the USB stack for connection? And is the Arduino able to emulate a keyboard and mouse if it has to use interrupts for this, so it has to act like USB device without using COM?

You seem to have multiple Arduino products jumbled up together in your mind.

@IgnacioVazquez-Abrams can you please provide detailed answer and point me where i am wrong?

The problem with your understanding is with what "COM" is.
"COMx" is not a physical serial port - it is merely a concept. It is a "serial device" in Windows.
That Serial Device is implemented as a CDC/ACM protocol on USB. It's not "converted" - "COMx" is just the visible interface to the PC's end of the CDC/ACM connection.
The ATMega328P chip (and the ATMega2560) can't talk USB directly. They talk UART. So UART data is sent to another chip that can talk both USB and UART to bridge the two technologies.
So from the PC perspective the chain is:
CDC/ACM Driver ("COMx") => USB => ATMega16U2 => UART => ATMega328P

Boards with an ATMega32U4 chip on them, like the Leonardo, can talk USB directly - so the sequence is much shorter:
CDC/ACM Driver ("COMx") => USB -> ATMega32U4

Again there is no conversion from "COMx" to "USB" since "COM" is just the name given to the exposed end of the CDC/ACM driver.
It can be said that CDC/ACM emulates a serial port over USB. It forms a channel between the CDC/ACM driver ("COMx") and a pair of bulk endpoints in the chip at the other end of the connection.

Is using ATMega16U2 a real need or just workaround for ATMega328P talking USB? I wonder why Uno has more complex and costly (in my opinion) two chips solution instead of 1 chip like Leonardo.

Because it does. That is what the designers designed it to be. If you don't want to use it then don't use it. There is this little thing called "choice". The great thing with the Uno is you can remove the MCU from the board and embed it in your own circuit and still communicate with it (UART is simple, USB is complex). You can't do that with a Leonardo.

Of course you can make your own board with the Leonardo's ATmege32u4 or any of the many other USB-enabled MCUs.  But they're generally only available in 20-year old surface mount packages, not 40-year old DIPs, so you have to be willing to use moderately modern fabrication methods.


text:
Transmitting signal from a Photon Redboard to an Arduino Uno
I am doing a basic electronics course revolving around the Internet of Things*, and we have to make a final project to present what we have learnt.
* Hear me out - I don't think this belongs on IoT SE, since the question is electronics-based
My project involves lighting up an LED matrix with predefined input from the web.
There are three factors causing a problem for me:

The LED matrix only seems to work on an Arduino (even though the programming language and setup are very similar), and we only have Arduino Unos available to us.
We are required to use a Photon Redboard to receive/send data through the internet.
The code running the LED matrix interferes with the TX/RX terminals on the Arduino since it uses the SPI bus, so after turning on the LED board I cannot receive any data from the Photon Redboard through the TX/RX pins (0 and 1).

Main question (to avoid the XY problem):
How could I receive digital data on the Arduino Uno from the Photon Redboard without using the serial ports?

What I have done to try to fix the problem:

Google-fu didn't turn up anything.
Changing the location of serial use in the programming - it works before the SPI bus is initialised but not after, which is useless for me since changing the board in response to an input from the Photon Redboard is the point of my project, and I can't change the board if it's not on.
Connecting a digital port programmed for output on the Photon Redboard to a digital port programmed for input on the Arduino Uno — this gives a value on the Arduino Uno that seems to switch between HIGH and LOW every few seconds, regardless of how the Photon Redboard is programmed to send values.

Subquestion(s):
If I am connecting the boards as described above, do I need to ground/insert current into the connection, and if so, is there a particular board this needs to be done on?
(Out of curiosity, also, what is causing the value to flip like this?)

Checking the components individually - the LED matrix works fine by itself, serial over TX and RX works fine by itself, the digital pins work fine by themselves (NB: tests were carried out with an LED or a button to provide visual feedback).

Here are pictures of both the Photon Redboard and the Arduino Uno for reference (click on images for better resolution, Arduino just shows circuitry without chips etc.):

Sources: Sparkfun and Arduino main websites

The code that seems to interfere with the Serial is below (directly copied from online here):
//----------SPI BUS SETUP----------
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR1);  //Enable SPI HW, Master Mode, divide clock by 16

//Set the pin modes for the RGB matrix
pinMode(DATAOUT, OUTPUT);
pinMode(DATAIN, INPUT);
pinMode(SPICLOCK,OUTPUT);
pinMode(SLAVESELECT,OUTPUT);

//Make sure the RGB matrix is deactivated
digitalWrite(SLAVESELECT,HIGH);
//----------END SPI BUS SETUP----------

The four lines of pinMode(PIN,I/O) refer to pins 10-13 (in standard SPI order, but I can't remember what order that is and I don't have access to the code).

A quick google search says the photon board has an spi port.  So, send the LED commands directly from the photon board to the LED controller and leave out the Arduino.

@JRE I tried that, but the code I acquired for the board used Arduino-specific variables that I couldn't work out how to transfer to the Photon board. Though they both have SPI capabilities, they are handled differently.

Then start from the datasheet of the LED module and write your own code for the photon board.

The code running the LED matrix interferes with the TX/RX terminals on the Arduino since it uses the SPI bus - the TX/RX pins are not used for SPI.

@NickGammon I know, but presumably some internal variables are shared between Serial and SPI

Why would you presume that? What internal variables?

@NickGammon I assumed that since when moving lines of code around I observed that serial worked before SPI bus setup and serial did not work after SPI bus setup. I cannot think of another reason that that could happen - everything else works fine. (As an aside, maybe we should move this conversation to chat?)

I don't see any lines of code in your question.

@NickGammon I've edited it in.

Hmmm. I'm reminded of the web page Snippets R Us. Without knowing what the constants DATAOUT etc. have as values, your snippet tells us nothing.


text:
How to send message from one embedded system to another embedded system like in cars, from one car to another?
I want to send message from one embedded system to another embedded system, like from one car to another without using phone number. just turn on the wifi.. connect and send message. There are ways to to send text to phone but not this kind of texting? Iam short of time. I only need to know what will be required to do this ? PLease help

If you want to communicate over WiFi, you need WiFi modules. And then you can use HTTP, TCP or UDP.

You can use ESP8266 modules( like Wemos d1) for wifi connections. The good thing about those are that they are also programmable and you can use arduino IDE to program. You can get two of those and make first one a server/host and second on a client for connection. There is more options of course: Bluetooth, RF link etc. Google "short distance connection arduino"

ESP8266 WiFi Module is a WiFi serial transceiver module, based on ESP8266 SoC. This chip implements a full TCP/IP protocol stack and the very interesting feature is that it has also a great computational power onboard. You can easily program it using Arduino IDE. You can buy this development boards in town market and its very low cost also.
Bluetooth/BLE4.0 Bluetooth is a type of wireless communication used to transmit voice and data at high speeds using radio waves. It is a standard protocol for short-range radio communications between many different types of embedded devices. Devices need to be within approximately 10 meters of each other, and the typical data transfer rate is around 2 megabits per second (Mbps).

These two are the most preferable for shorter distance communication.