text:
I have downloaded the library but not sure what went wrong
C:\Users\Dray98\AppData\Local\Temp\arduino_modified_sketch_819854\sketch_jun09a.ino:2:29: fatal error: Adafruit_Sensor.h: No such file or directory

 #include <Adafruit_Sensor.h>

                             ^

compilation terminated.

Multiple libraries were found for "DHT.h"
 Used: C:\Users\Dray98\Documents\Arduino\libraries\DHT_sensor_library
 Not used: C:\Users\Dray98\Documents\Arduino\libraries\DHT-sensor-library-master
Using library DHT_sensor_library at version 1.3.0 in folder: C:\Users\Dray98\Documents\Arduino\libraries\DHT_sensor_library
exit status 1
Error compiling for board Arduino/Genuino Uno.

Please edit your question and add an explanation of what you are working on.  Place this text before what appears to be the output of your Arduino compiler session.  Tell us how you tried to fix this problem.  Posters who have tired and fail get better responses then posters who try nothing at all.  If you do not do this soon people will likely vote to close your question and you will not get an answer.

When you encounter a No such file or directory error it usually means you need to install the library that contains the missing file (in this case Adafruit_Sensor.h).
Ideally the documentation for the code you are trying to compile will have instructions for installing dependencies.
Sometimes the author did not make the effort to write this documentation and you'll need to go searching for the missing library.
Many Arduino libraries are in the Library Manager index, which makes them quite easy to install:
Library Manager installation

(In the Arduino IDE) Sketch > Include Library > Manage Libraries.
Wait for the download to finish.
In the "Filter your search..." box, type your search query, in this case "adafruit unified sensor abstraction layer" would get you the one correct result but with a little searching through the results of a more general search like "adafruit sensor" will get you there also.
Scroll through the search results to find something that looks correct (in this case "Adafruit Unified Sensor by Adafruit"), then click on it.
Click "Install".
Wait for installation to finish.
Click "Close".

If you don't find the library you need in Library Manager you'll need to spend some time with your favorite search engine. Once you find the library and download it you'll need to install it.
.ZIP Installation

(In the Arduino IDE) Sketch > Include Library > Add .ZIP Library
Select the downloaded file (must be a .zip).
Click "Open".

The above installation instructions require the .zip file to have a specific folder structure. In some cases the library author has not been kind enough to provide the correct folder structure. If you get a "Zip doesn't contain a library" error message then you will need to do a manual installation of the library.
Manual Installation

Unzip the downloaded file
Browse through the unzipped folder until you find the library folder. This will either have a library.properties file and/or a .h file.
Copy the library folder to {Sketchbook folder}/libraries. You can find the sketchbook folder in the Arduino IDE at File > Properties > Sketchbook location.
You will need to restart the Arduino IDE before the examples sketches for manually installed libraries will appear under the File > Examples menu.

Your problem is, that you haven't installed the Adafruit_Sensor.h, which is a dependency of Adafruits DHT library. The README on Github for the DHT library also states this:

You must have the following Arduino libraries installed to use this
  class:
Adafruit Unified Sensor Library

You can find the Adafruit_Sensor.h here at Github. Install it in your libraries folder. You can refer to the answer from per1234 for instructions on installing libraries.
--
The second part in your error output is not really an error. As others stated before, the IDE only tells you, which version of the DHT library it uses. If you want to have multiple version in your libraries folder, you will have to make sure, that you always use the correct one. If they are identical, you can delete one of them, if you want to. The outcome would not be any different, except for that the IDE doesn't have to tell you, which library it uses.

Have you installed the Adafruit_Sensor library correctly? If not, at top of IDE, click  Include Library > and see if it's in the list and click it, if not, go to top of list and click Manage Libraries..., search for and click on it.


text:
Why this code for ESP8266 goes into STA+AP mode?
I'm using Arduino IDE 1.6 nightly with Generic ESP8266 Board.
Why this code runs in mesh mode instead of simply connecting to my wifi?
My goal is to test out MDNS, but so far I found this:

board connects to my wifi
but board also opens an ESP- access point
when connected to my wifi on my computer I cannot resolve http://esp8266-webupdate.local/update
when connected to the open ESP- wifi I can resolve http://esp8266-webupdate.local/update

To my understanding such code should just connect to my wifi and I would then be able to navigate to http://esp8266-webupdate.local/update, am I missing something?
output (note STA+AP)
Booting Sketch...
......
Connected, IP address: 192.168.1.20
Mode: STA+AP
PHY mode: N
Channel: 10
AP id: 0
Status: 5
Auto connect: 1

code
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>

const char* host = "esp8266-webupdate";
const char* ssid = "myhomeap";
const char* password = "blabla";

ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;

void setup(void){

  Serial.begin(115200);
  Serial.println();
  Serial.println("Booting Sketch...");
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);

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

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  WiFi.printDiag(Serial);
  MDNS.begin(host);

  httpUpdater.setup(&httpServer);
  httpServer.begin();

  MDNS.addService("http", "tcp", 80);
  Serial.printf("HTTPUpdateServer ready! Open http://%s.local/update in your browser\n", host);
}

void loop(void){
  httpServer.handleClient();
}

because of the WiFi.mode(WIFI_AP_STA); line?

the mdns propagation is not instant. wait some time

thanks, do you happen to know if is it necessary to go into this mode for mdns to work? this code was taken from examples

mdns works as expected in STA mode. only sometimes it takes time until the mdns name appears in IDE Port menu. (I use Eclipse and there I can type the address if it is still not found by mdns service)

yeah I mean, is this mode necessary (instead of going only pure station) for this example to work?

STA only yes. and it doesn't need mdns. you can use the IP address. for Upload from IDE use ArduinoOTA library

the code in question is example from the ESP8266HTTPUpdateServer library. it runs a web server and this web server enables to upload a new esp8266 code in binary form. after the code is uploaded the esp8266 restarts with the new code.

It goes into STA+AP mode because your code is telling it to do that.
If you want it to just go into STA mode then your line:

WiFi.mode(WIFI_AP_STA);

should be

WiFi.mode(WIFI_STA);

thanks, the code was taken from examples, do you know if going into AP mode is necessary for MDNS to work at all?

In theory MDNS should work in any mode, but of course would only be visible on networks that the ESP was actually connected to.
There are several issues filed on the MDNS code that show other people having trouble with STA+AP mode. There was a fix checked in but it's not clear that it really resolved the problem. So you're not the only one with problems with it; I wouldn't expect it to definitely work, unfortunately.

source: Stack Exchange

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

sort: votes


text:
Timer frequency calculation for UNO/Atmega328
I must be overwrought or something... I just can't get the calculation of the timer frequency right. I have a 16 MHz crystal on the Atmega328. I want 1 kHz timer interrupt rate. So I chose prescaler = 64 and counter top = 249, that is
fTimer = fCPU/prescaler/(top+1) = 16 MHz/64/250 = 1 kHz
But my oscilloscope shows 2 kHz... !? Why?
I have read Timer2 Compare Interrupt not working as expected but the accepted answer doesn't make it better. There the frequency is half as high whereas mine is twice as high as expected.
Code:
const int signalLED = 1; //14;

void setup()
{
  pinMode(signalLED, OUTPUT);
  digitalWrite(signalLED, LOW);

  TCCR2A = 0; // set TCCR2A register to 0
  TCCR2B = 0; // set TCCR2B register to 0
  TCNT2  = 0; // reset counter
  OCR2A = 249; // top value in CTC mode
  TCCR2A |= (1 << WGM21); // enable timer2 CTC mode
  TCCR2B |= (1 << CS21) | (1 << CS20); // 1:64 prescaling for timer 2
  TIMSK2 |= (1 << OCIE2A); // enable timer2 compare interrupt
  sei(); // allow interrupts
}

ISR(TIMER2_COMPA_vect)
{
  // generate peak
  digitalWrite(signalLED, HIGH);
  digitalWrite(signalLED, LOW);
}

void loop()
{
}

Your comment:
TCCR2B |= (1 << CS21) | (1 << CS20); // 1:64 prescaling for timer 2

doesn't match the actual setting (= 1/32)
Also there are some issues with setting Timer2 CTC mode, it's better to set mode, then OCR2A + TCNT2 + interrupts and then Prescaler to start the timer. It behaves as there is OCR2A=0, so the frequency is much higher than expected.

That was the problem. I just mixed up the prescaler setting specs of Timer1 with those of Timer2. For Timer1 CS11|CS10 is 64. I knew that standing up too early wouldn't be good for me... ;-)

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


text:
Motor unexpectedly moving at reset
I'm playing with the standard L298N motor board and Arduino MKR 1000. However something strange happens: when I upload a new firmware and when I turn on the Arduino power supply (every time Arduino resets) the motors unexpectedly move for 2 seconds.

From what I've seen in other questions, it should be enough to pull down the pwm signal (in fact it seems that the floating status of these pin in the reset procedure produces this problem). I used a 10k resistor as suggested, but with no effect.
I've tried also a 100 ohm resistor: in this case the motor makes some noise but it doesn't move. However, it won't move when it is supposed to in the loop section.
I've also tried to pull down all the three signals (enable, in1, in2) of the motor but with no difference. I've also tried to pull up to 5V, instead of pulling down: same issue at reset, but the motor spinning in the other direction.
I've also tried to put a relay controlling the motor external supply. However the reset procedure also turn 'on' the relay (no progress on the problem).
It isn't a software issue because it happens with an almost empty sketch. Same software+circuit on Arduino UNO doesn't cause the problem.
What should I do?

standard L298N motor board ... there is no such thing as standard board

https://arduino.stackexchange.com/questions/16438/when-the-arduino-is-in-reset-mode-are-the-digital-pins-high-impedance

@jsotola thanks for the link.. I've tried lots of different pins so I don't think it's something strictly related to a particular pin, but more of a general issue with high impedance state in MKR1000... so I can't understand how should I fix it..

put 1k resistors between the arduino output pin and ground .... if it works, increase the resistance until it fails again

@jsotola I tried 1k but with no result. When I put a 100 ohm resistor then it can't move at reset, but it also won't move when I want to!

i just noticed that you are using the Arduino MKR 1000 which uses the ATSAMW25H18-MR510PB microcontroller, therefore the link that I posted does not apply ....... do not use low value pulldown resistors

try posting at this website  .... https://community.atmel.com/forum/atsamw25h18-inconsistent-results

maybe something can be found here about the initial state of I/O pins ....   http://ww1.microchip.com/downloads/en/DeviceDoc/40001882A.pdf  ........ http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42436-SAMW25-MR210PA-HW-Design-Guidelines_UserGuide.pdf

something may be here .... https://github.com/arduino/ArduinoCore-samd/tree/master/bootloaders/zero

@jsotola I'm sorry but I don't have an in-depth knowledge in this field, so I still don't know what could I do..

Try to add an capacitor between reset and GND https://goo.gl/images/rFMyho

@Coder_fox I don't want to prevent reset when I open the COM port.. In fact the problem is related to microcontroller initialization and of course happens also when I plug in the power supply..

@Surferonthefall ok but than the board woun't reset at all


text:
What is corrrect the way to find roll, pitch, yaw?
I have an MPU9250. I have calculated accelerometer, gyroscope, magnetometer. But I want to know how to caclulate roll yaw pitch. I have searched on Google. I found many answer
roll  =  (atan2(-Accel_Y, Accel_Z)*180.0)/M_PI;
pitch =  (atan2(Accel_X sqrt(Accel_Y*Accel_Y + Accel_Y*Accel_Y))*180.0)/M_PI;

source: https://theccontinuum.com/2012/09/24/arduino-imu-pitch-roll-from-accelerometer/
   accelerationX = (signed int)(((signed int)rawData_X) * 3.9);
   accelerationY = (signed int)(((signed int)rawData_Y) * 3.9);
   accelerationZ = (signed int)(((signed int)rawData_Z) * 3.9);
   pitch = 180 * atan (accelerationX/sqrt(accelerationY*accelerationY + accelerationZ*accelerationZ))/M_PI;
   roll = 180 * atan (accelerationY/sqrt(accelerationX*accelerationX + accelerationZ*accelerationZ))/M_PI;
   yaw = 180 * atan (accelerationZ/sqrt(accelerationX*accelerationX + accelerationZ*accelerationZ))/M_PI;

source:  https://engineering.stackexchange.com/questions/3348/calculating-pitch-yaw-and-roll-from-mag-acc-and-gyro-data
  Accroll = atan2( accy / (accy^2 + accz^2) )
  Accpitch = atan2( accx / (accx^2 + accz^2) )

source: http://franciscoraulortega.com/pubs/Algo3DFusionsMems.pdf
 Accroll = atan2(accy, accz)
 Accpitch = atan2( -accx, sqrt(accy^2 + accz^2) )

source:https://www.nxp.com/docs/en/application-note/AN3461.pdf
What is the correct way to find roll yaw pitch?

The accelerometer is noisy and the gyro drifts and only the magnetometer knows the direction. The correct way is a filter that uses all sensors combined, sometimes called: sensor fusion. For example the ahrs filter. See the mpu-9250 and ahrs at sparkfun: https://learn.sparkfun.com/tutorials/mpu-9250-hookup-guide

Before everyone makes this problem complicated, the first thing to figure out is if the device is moving and/or changing orientation. If it is not, the problem is a lot simpler and many of the things being suggested are unnecessary.

For a stationary accelerometer sensing the acceleration of gravity, I see "dead zones" when the Pitch, Yaw or Roll axes are parallel or close to parallel to the gravity vector.
Likely this is why accelerometers are used in conjunction with gyroscopes.
Refer to this NXP (aka Motorola, Freescale & Qualcomm) document for an in depth discussion regarding the necessary math.  Note the section regarding "Regions of Instability".
Also, refer to this class and this class from rutgers.edu which work students through a project using an Arduino and an accelerometer in the 1st class then adds a gyroscope in the 2nd class to improve the response.
(Added Later)
The rutgers.edu links don't appear to work anymore and this link has been suggested as an alternative.

The links to the rutgers.edu class pdf file doesn't work anymore. Seems that https://aatishb.com/materials/srr/materials.html is the new homepage.

Thanks @MartinMeixger, I've added your new link.


text:
Long freezes at the beginning of sd card transfer
I am creating an accelerometer data logger that writes data to sd card. After some sort of "warm-up" everything works perfectly for at least ~15 minutes (which is what I have tested so far).
However, during the first few seconds there are some pretty long freezes of the File.write() function (180 ms instead of 50us for normal writes!) which I can identify on an oscilloscope (see picture below, signal low after starting high indicates File.write() phases) and which I can also see in the data if I include in them a milis() timestamp.
Since RAM on the Atmega328 is limited, there is also tight limits to the amount of sensor data I can buffer (I am using an interrupt for transfer from the sensor, where I can store the data to a buffer and thus bridge the shorter sd card delays).

I stripped down my code to the absolute bare bones, just writing nonsense data instead of those from the accelerometer. What could be the reason for these freezes? The data rate is the same during the whole run. Isn't the sd card electrically or logically initialized after SD.begin()? It doesn't seem to be a problem with erasing flash memory blocks because it only occurs in the beginning. Even if I restart the application a second time (after staying electrically on all the time) it already shows no freezes anymore. Whereas if I unplug/plug power, the freezes in the beginning reappear.
And most importantly: how can I solve it?
Of course I could write the dummy data before receiving the start button. But how many? Does it depend on sd card type? Does it depend on cpu or spi clock frequency? I want a robust solution that doesn't break when I use another type of sd.
Code:
#include <SPI.h>
#include <SD.h>

const int chipSelect = 10; // chip select of the sd card
const int pushButton = 9; // this is where the start button is (on a pulldown resistor)
const int debugPin = 1; // a line used for displaying a debug bit on the oscilloscope

const int bufferSize = 14;
byte buffer[bufferSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; // for the test just dummy values

String fileName = "accellog.raw";

void setup()
{
  pinMode(pushButton, INPUT);
  pinMode(debugPin, OUTPUT);

  if (!SD.begin(chipSelect))
  {
    // on error stop execution
    for(;;);
  }
}

void loop()
{
  // wait for the start button to be pressed
  while (digitalRead(pushButton) == HIGH);
  delay(100); // debounce delay
  while (digitalRead(pushButton) == LOW);

  // remove old file on sd card
  if (SD.exists(fileName)) SD.remove(fileName);

  File dataFile = SD.open(fileName, FILE_WRITE);

  if (dataFile)
  {
    // Debugging: indicate start of whole data transfer on an oscilloscope
    digitalWrite(debugPin, HIGH);

    int lastMillis = millis();

    for (long i=0; i<10000; i++)
    {
      // wait until millis changes in order to get SD writes at
      // whole millisecond boundaries (some cycles may get lost,
      // however, during lengthy SD writes)
      int tempMillis = millis();
      while (tempMillis == lastMillis)
      {
        tempMillis = millis();
      }
      lastMillis = tempMillis;

      // Debugging: indicate file access times by sending 0 to the DSO
      digitalWrite(debugPin, LOW);

      dataFile.write(buffer,bufferSize);

      // Debugging: indicate end of file access on DSO
      digitalWrite(debugPin, HIGH);
    }

    // Debugging: indicate end of whole data transfer
    digitalWrite(debugPin, LOW);

    dataFile.close();
  }
  else
  {
    // on error stop execution
    for (;;);
  }
}

try to open file and then close it without any writes

@jsotola: unfortunately that didn't change anything. But I will see how far I get with writing some nonsense data in advance (in a different file).

I can't really reproduce that. On my SD card I get an initial delay (between the first and second write) of about 30 ms, followed by a batch of writes, then a 20 ms delay, then another batch and so on. The pauses are between about 512 bytes being written out which would be the buffer (in the SD library) actually being written to the SD card. My suggestion is to try a different card and see what happens. Maybe one with a fast write class (eg. the sort you use for taking videos).

@NickGammon: yeah, maybe it's the card. I took the cheapest 16 GB cards I could get. :-) I have also been thinking about data loss on the SPI lines as a cause, but the lines on my board are a lot shorter than what you have in a breadboard setting. Anyways, I have a workaround now, at least. I will have to check what happens with cards that have been written full once...

I don't think data loss would really do it. The data either arrives or it doesn't. I took the cheapest 16 GB cards I could get - it looks like you got what you paid for. :)

As a temporary workaround I have come to the following procedure:
I inserted a function that writes a certain amount of bytes into a dummy file, closes it and finally deletes it, all during setup().
This does indeed seem to cure the freezes if (in my scenario) I write at least 6 blocks (512 bytes each, i.e. total 3072 Bytes). Remarkably there were always exactly 6 freezes visible in my oscilloscope plots. I don't even remotely know what the meaning of this magic number 6 could be...
Just to have some additional safety in case I choose a different type of sd card (and this workaround becomes permanently temporary...), I have decided to write 16 kB into the dummy file. This is ~5 times as much as the empirical minimum value (3 kB) and is still pretty fast so that I don't notice any significant startup delay after power-up.
This empiric approach is still unsatisfactory though, and certainly a piece of mediocre engineering. So I won't mark my answer as accepted, to leave the chance for someone else to give a more well-founded answer.
void writeAndEraseDummyFileToEliminateFreeze()
{
  if (SD.exists("dummy")) SD.remove("dummy");
  File dummyFile = SD.open("dummy", FILE_WRITE);
  int n = 16384/recordSize+1; // write 16kB in chunks of recordSize (just because we have that buffer already
  for (int i=0; i<n; i++)
  {
    // buffer values are uninitialized, but who cares, we'll dispose of them anyway
    dummyFile.write(buffer,recordSize);
  }
  dummyFile.close();
  SD.remove("dummy");
}

void setup()
{
  // ...other things I have been already doing...

  writeAndEraseDummyFileToEliminateFreeze();
}

You could measure the time needed to do the write, and repeat as often as necessary, aborting when the number or time exceeds a decent limit.


text:
DT-06 WIFI. How to program with Arduino Uno
I have a DT-06 wireless WiFi. I can connect using my phone but I cannot access 192.168.4.1/status.html or /wifi_set.html like in the tutorial
I put this module in wiring with Arduino Uno on 5v. I notice that the LED is low lighting until I put pin state in GND. Then I get full power red led. I put RX module to TX Arduino and TX module to RX Arduino but i can not access it using Arduino.
How can I program this module or how can I access? Any tutorial links are welcome.
Thanka. Sorry for my English.
L.E.
Module RX - Arduino TX
Module TX - Arduino RX
Module VCC - Arduino 5v
Module GND - Arduino GND
Module STATE - GND
My module has a red led on it. This led is low lighting until i put pin STATE in GND. After that the red led is full lighting.
After i put VCC and GND i can "see" my module using my phone wireless connection

I didn't really understand, what LED you mean exactly. Also provide a schematic or wiring diagram, so that we can see, how you connected the DT-06. It sounds, like as if you use a digital output pin to provide it with power. This would be absolutely wrong.

If you refere to a tutorial, please provide a URL to it.

Please check my edit in the question

Are you wiring it to Arduino pins 0 & 1? These are hard-wired to the other processor on the Arduino board that handles USB to/from your PC. There may be interference with the DT-06 unless you disconnect from your PC after upload. But then you'll need an alternate source of power to the Arduino.
You can pick another pair of pins and use the SoftwareSerial library (up to 9600 baud) to talk to the DT-06. Make sure Arduino and the DT-06 use the same baud-rate. You may have to experiment to find what baud-rate the device has now, in order to set it to 9600.
Update:

Do i have to use any resistence?

Two sites I looked at described the DT-06 voltage requirement as:
"Working voltage: 4.5V~6.0V, TTL working voltage: 3.3V (compatible with 5.0V);", so you should be OK without voltage divider resistors.

And what settings to make in arduino IDE before uploading code?

You won't need to change your IDE to upload code to the Uno.

Can you please make me a wiring scheme and also tell me the arduino code?

This discussion talks about using SoftwareSerial and setting the baud-rate. It was written about an ESP8266 module but most of it will apply to your module, too.

Do i have to use any resistence?

And what settings to make in arduino IDE before uploading code?


text:
How much low analog voltage can Arduino uno read?
Today I was playing around with arduino analog voltage ranges, the error in output
 with respect to a digital multimeter started to happen when the reading was around 0.0014volts. How much low an arduino can read?

What reference voltage do you use?

you could use an opamp to scale (amplify) low voltages like (0-0.05) to a 0-5v range.

There are other possibilities to make more precise readings: one can use Arduino with an external ADC with better voltage resolution (e.g. 16 bit), or average several readings to reduce measurement noise.

If you are measuring lower voltages, you can use the internal 1.1 band gap voltage as a reference voltage.

The Arduino Uno uses a processor containing a 10 bit ADC.  This means the ADC can resolve (if we do not consider noise) 2 to the 10th or 1024 voltage levels between zero and the voltage supplied to the Arduino Uno at the AREF pin.  There is a good explanation of the AREF pin in this stackexchange.com question / answer.  It is common practice to supply the AREF with voltages lower than the positive rail the processor is operating at to improve resolution of expected lower voltages.  For example, if you do not expect to measure voltages higher than 3.3 volts on a 5 volt Arduino, use the 3.3 volt supply as a reference.  Relative to using a 5 volt reference, using a 3.3 volt reference decreases your granularity from 0.00489 to 0.00322 volts per step.
Of course there is a lot of noise in most ADC circuits.  Finding the average of many ADC readings helps mitigate this problem.  Consider using exponential averaging.

You divide your reference voltage by 1024.  That tells you what the step size is.  The smallest you can measure is an ADC reading of 1.  So for say a 5V reference that works out to 0.00488V


text:
Arduino 3rd party cores
I am trying to use Arduino platform.txt to run some extra pre-processing on my Arduino codes.
As far as I can understand the best way to do that is to use prebuild hooks as mentioned below
https://github.com/arduino/arduino/wiki/arduino-ide-1.5-3rd-party-hardware-specification
I am using the hooks as follows
recipe.hooks.sketch.prebuild.1.pattern=echo {source_file} sketch pret;
recipe.hooks.sketch.prebuild.2.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"

This is the output I get for the hooks
echo "{source_file}" sketch pret;
{source_file} sketch pret;
"/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc" -c -g -Os -w -std=gnu11 -ffunction-sections -fdata-sections -MMD -flto -fno-fat-lto-objects -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10804 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   {includes} "{source_file}" -o "{object_file}"
avr-gcc: error: {includes}: No such file or directory
avr-gcc: error: {source_file}: No such file or directory
avr-gcc: fatal error: no input files
compilation terminated.

The {source_file} variable is used in a compilation reciep as follows
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"

and the recipe runs as follows
"/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10804 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino" "-I/Users/vinayakjoshi/Library/Arduino15/packages/boltiot/hardware/avr/1.0.0/variants/boltduino" "-I/Users/vinayakjoshi/Documents/Arduino/libraries/boltiot-arduino-helper-update-dev/src" "-I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/src" "/var/folders/kp/9gnp402j7_nfb1qpqpdkxgcr0000gn/T/arduino_build_658970/sketch/CommandHandler.ino.cpp" -o "/var/folders/kp/9gnp402j7_nfb1qpqpdkxgcr0000gn/T/arduino_build_658970/sketch/CommandHandler.ino.cpp.o"

As you can see, in a standard recipe, the variable {source_file} and other such definitions are correctly replaced. But in the hooks, this is not happening.
I want to know whether it is possible to get the value of the {source_file} variable to be used with the hooks, so that I can do some extra pre-processing with it. And if it is, how can I do it.
P.S. IDK what tag has to be used. I couldn't find platform.txt or 3rd party cores. I used the Arduino-IDE tag, as this question definitely asks how the IDE works.

It looks like those properties are only expanded in:

recipe.cpp.o.pattern
recipe.S.o.pattern
recipe.c.o.pattern
recipe.preproc.includes
recipe.preproc.macros

They are not expanded in any of the hook recipes.
This actually makes sense for {source_file} with the current build system because the hooks are not run before and after the compilation of each file but rather before and after the entire sketch compilation, so even if that property was expanded it could only give you an arbitrary filename, perhaps the first file to be compiled in the prebuild hook and the last in the postbuild hook, but that leaves all the other filenames inaccessible so it really wouldn't do much good. See related issue report.
If you're actually trying to use {source_file} to get the preprocessed sketch file, that's accessible from any recipe as {build.path}/sketch/{build.project_name}.cpp.
As for {includes}, it seems like an unnecessary restriction for that property to only expand in specific recipes. If you can present a good case for this behavior being changed, it might be worth opening a feature request to see what the Arduino developers will think.


text:
How to expand an Arduino when using a TFT display shield?
I am really new to this Arduino stuff. I can't figure out one of my problems on my own.
I am using this 2.4 TFT display shield on an Arduino Uno. It works fine so far: I have coded a little sketch for it that displays a start button and after tapping that it shows random colors.
Now I would like to connect a circuit with jumper cables that are used as sensors. When I touch one of the jumper cables the light connected will turn on.
The problem I have now is that this specific circuit is using an other Arduino because my first Arduino is already 'full' because the TFT shield is taking up all pins.
How can I resolve my problem? Is it possible to Stack Arduinos? Is it possible to connect those Arduinos somehow? Thanks in advance!

Have you tried googling "communication between two arduinos"?  what did you learn?

I suggest adding your circuit and program.

As I mentioned my problem is mainly that my arduino is fully used, I guess, by my tft shield.

As I can read your link, the shield is using D2-D8 and A0-A3, leaving some pins unused. So some Arduino pins are still free to use, just the shield is in the way to get connected there.
So there are some possible ways:

brutally solder some wires to the shield unused pins from front side and use that wires to connect where you want (sensors, breadboard, universal PCB, ...)
brutally solder some wires to arduino bottom on unused pins, then continue as mentioned
create intermediate shield (there are many, which allow you connect to arduinou on bottom and stack antother shield on top, draw your wires from there (and maybe even put some circuities on the middle shield, if you want
(something like this https://www.aliexpress.com/item/UNO-Prototype-DIY-shield-kit-for-Arduino-UNO-Universal-Extend-Board-UM-UNO/32555004112.html or any "arduino universal shield"

https://www.indiegogo.com/projects/ardushield-most-universal-shield-for-arduino-ever#/ works excelently across arduinos and other shields/breadboards ...
or anything along this lines ... http://shieldlist.org/sunhayato/universal

use pins D10-D13 as they are connected also to ISP header https://www.arduino.cc/en/Tutorial/ArduinoISP and could be connected from there. As they are part of SPI interface
https://www.arduino.cc/en/Reference/SPI that could be good coise too (if you manage ChipSelect somehow.

As for other part of question -
It is possible to connect more arduinos, there are so much different ways, that it is hard to write here all - choose one, that would suit you best. (anyway you would need some access to some pins anyway )

Ok, your problem seems to be that you have run out of pins. Currently you are using an Arduino Uno. I would go out and buy an Arduino Mega.
Alternatively you could use the analog inputs as digital inputs.
Arduino Uno
Digital I/O Pins    14 (of which 6 provide PWM output)
Flash Memory    32 KB (ATmega328P) of which 0.5 KB used by bootloader
Arduino Mega
Digital I/O Pins    54 (of which 15 provide PWM output)
Flash Memory    256 KB of which 8 KB used by bootloader

Alright. Is the arduino mega working the same way as the arduino uno except it has more power and pins?

Pretty much! - I'll add links to my answer.


text:
Reed Sensor matrix for chess board query
NOTE:
This is not a question that has been answered previously in similar questions.
I am using an arduino Mega
I have gone through Bergers Blog(schematic is in this link), but have been breaking my head on the logic of your sensor matrix, I have been breaking my head for the past few days on this one thing.

Initially he set all rows to HIGH then reset the 1st row to LOW to scan the reed sensors, let's assume that all the sensors in the 1st and 2nd row are closed.

My question is that since the 1st row is set to LOW won't it get shorted because the second row is initially set to HIGH?
Also, I used the same matrix as berger but instead I enabled the internal Pull up pins of all the 8 input pins, but yet again I faced the same problem of getting a short , since if a row 1 is set to LOW and row 2 is initially set to HIGH then One sensor in row 1 is closed and a reed sensor in row 2 below the sensor mentioned in row 1 is also closed. Then won't we get a short and random values show on the arduino.

Can you include the schematic in your question please? Things shouldn't get shorted because of the diodes.

@Nick Gammon,Aren't diodes used to solve the problem of ghost activation's.Also The  schematic is in the link.

The HIGH signal from the row can’t get anywhere because of the diode. Also, this matrix won’t work without the pull-up resistors.

@Gerben ohh ok..I understood but, won't the same happen to the LOW signal sent?

The LOW signal can get through the diode, and the de reed (if closed), to get to the column. It get then get through the reed of the other rows (if closed), but then can’t get any further because of the diode. Try printing out the schematic, and get some different colored markers, and try out the different scenarios, and see if you can get a short. Maybe that will help understanding it.

how do you know that you are getting a short between rows?

Almost all switch matrix keyboards use normally open / momentary contact switches. Consider this when discussing switch matrix behavior. Your initial (text) description is of a switch matrix only comprising of switches.  For such a matrix, only one switch may be closed at any given moment. This is to prevent aliasing.  A conditions where multiple simultaneous switch closures cause the incorrect key to be detected. And, in some cases, prevents harmful shorts.
Adding a forward biased diode to every switch in a matrix prevents harmful shorts.  For a design where one row is driven high and all other rows are driven low, closing two switches in a single column can directly connect the row driven high with a row driven low in a switch matrix only comprising of switches.  However, if a normally forward biased diode is placed in series with both of these closed switches, only the diode connected to the row driven high would be forward biased.  The diode connected to the row driven low would be reversed biased preventing the harmful short.
Using diodes on every switch is costly.  Most computer keyboard do not use this approach.  Instead they use clever circuitry and layouts to prevent shorts and improve their perceived performance.  In reality, almost all computer keyboard have an n-key-roll-over limit.  A point at which the keyboard fails to detect or distinguish a new pressed key while other keys are already pressed.
For a graphic example of the behavior of a forward and reversed biased diode consider this image from allaboutcircuits.com where the diode on the left is in forward biased and the diode on the right is in reversed bias:

Mega has 70 inputs, 86 if you use a '2560 in a full breakout board.
I offer a couple of form factors to access all pins at http://www.crossroadsfencing.com/BobuinoRev17
Chess board will always have multiple pieces in multiple rows and multiple columsns pressed until near the end of the game. I'd wire up each square individually, make life a lot easier.  Read ports 8 pins at a time, 8 reads to have all 64 squares read.


text:
DT-06 program using arduino uno
I'm working to program DT-06 wireless wifi module.
And right now when i'm trying to program i get the following error message :
espcomm_send_command: can't receive slip payload data
Module RX - Arduino RX
TX - TX
VCC - 5v
GND - GND
Right now i can upload black program to arduino and send serial AT commands to my module and alson getting response.
How can i program ?
Thx
Appendix:

Module:  https://www.banggood.com/Geekcreit-DT-06-Wireless-WiFi-Serial-Port-Transparent-Transmission-Module-TTL-To-WiFi-p-1141047.html

Oh sorry I think I misunderstood the question -- Do you want to Programm the DS-06 module or do you want to program an Arduino to talk to the DS-06 module? If it is the latter, what current code are you using?

i want to programm the DT-06

Just program it like you would program a normal ESP8266.
The documentation is here:

https://github.com/SmartArduino/SZDOITWiKi/wiki/ESP8266---TTLtoWiFi

The datasheet provides the schematic of the module

So SW2 is the reset button and "SW1" is the "FLASH" button. To enter the bootloader mode in which the ESP8266 can be programmed, you first have to hold down the "FLASH" button then press "RESET" once.
For programming you would ideally get a 5V USB-UART adapter make the connections

VCC to 5V (it has a regulator to generate the actually needed 3.3V)
GND to GND
EN to 5V (e.g. via a pullup)
TXD to RX of UART adapter
RXD to TX of UART adapter

After the ESP is in the bootloader mode as described above, you can just program it normally through the Arduino IDE. Follow the instructions at https://github.com/esp8266/Arduino to install the ESP8266-Arduino core in the board manager.
Refer to the similiar procedure:

https://www.hackster.io/harshmangukiya/program-esp8266-esp-12e-with-arduino-using-ftdi-cable-2310c9

Thank you very much sir!  i'm new to this things. Thank you very much !

Right now i can flash the module like you show me. The code is uploaded but nothing in the serial monitor. #include <ESP8266WiFi.h>
WiFiServer server(80);
void setup() {
WiFi.mode(WIFI_AP);
WiFi.softAP("Hello_IoT","12345678");
server.begin();
Serial.begin(115200);
IPAddress HTTPS_ServerIP= WiFi.softAPIP();
Serial.print("Server IP is: ");
Serial.println(HTTPS_ServerIP);
}

@user863873 Did you press the reset button (SW2) after flashing?

Yes. I get in serial the reset 2 and the rest of the info

More info : i haven 2 module. One i did flash it and the other one not. When i wire the second one (the one that i dont flash it) it responds in serial using arduinonto AT commandas. The second with the same wiring and code using same arduino does not. Maybe it helps

What is the output after reset on 38400 baud (bootloader messages?) Can you try to blink GPIO4? pinMode(4, OUTPUT); et cetera. @user863873

I don't know if i understand correctly. But i flash the following code : void setup() {
pinMode(4, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(4, LOW);
delay(1000);
digitalWrite(4, HIGH);
delay(1000);
} with no  blink led from my module. I did hit "reset"

What does the bootloader report? What USB/UART adapter are you using?

I'm using arduino to flash my module

i'm getting 100% when i flash my module

After i flash my module and "reset" i get : ets Jan  8 2013,rst cause:2, boot mode:(3,6)
load 0x4010f000, len 1384, room 16
tail 8
chksum 0xef
csum 0xef
csum err
ets_main.c

There is a checksum error because you probably selected the wrong module size. Try selecting a different board variant in the Arduino IDE with different flash sizes until one works. Could also be the flash mode (DIO/QIO) or you must mass-erase the flash once. See the https://www.letscontrolit.com/forum/viewtopic.php?t=3071

That was the fix. After i set to ESP8285 all was good. Also i notice that i must have blank code in my arduino to be able to flash my module. Thank you sir !


text:
Help - Atmega328p, converting a PWM servo code from pin9 to pin6
I found a working code that uses pin9 (PB1) on my Arduino for controlling a Servo, but in my project, an ultrasonic sensor is already using that pin/timer. I want to convert the code to use pin6 (PD6), changed the registers according to the atmega's datasheet, but it doesn't work. Need help :/
The code should allow me to turn a servo using a potentiometer.
#define F_CPU 16000000 //16MHz
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdlib.h>

#define PWM_PRESCALLER 64
#define ICR_MAX (long double)F_CPU/PWM_PRESCALLER/50
#define OCR_MIN (float)ICR_MAX/37.5 // /8.75
#define OCR_MAX (float)ICR_MAX/8.7 // 37.5

volatile unsigned long adc_val=0;
volatile unsigned long counter=0;
unsigned long curr_adc=0;

ISR (ADC_vect)
{
adc_val += ADC;
counter++;
}

int main(void)
{
    DDRD |= (1<<DDD6);
    ICR1 = ICR_MAX;
    OCR0A = OCR_MIN;
    TCCR0A = (1 << COM1A1) | (1<<WGM00) | (1<<WGM01);
    TCCR0B = (1<<WGM02) | (1<<CS01) | (1<<CS00);
    ADMUX = (1 << REFS0);
    ADCSRA = (1 << ADEN)|(1 << ADATE)|(1 << ADIE)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);

    sei();
    ADCSRA |= (1<<ADSC);

    while(1)
    {
        if(counter >= 1000)
        {
            cli();
            unsigned long round_val = round(adc_val / counter);
            adc_val=0;
            counter=0;
            if(abs(round_val - curr_adc) > 1)
            {
                curr_adc = round_val;
            }
            long double ocr = OCR_MIN + ((long double)curr_adc * (OCR_MAX - OCR_MIN)/1024);

            OCR0A = (int)round(ocr);
            sei();
        }
    }
}

Please edit your question and try pasting the code again. Somehow there are extra newlines and all indentation was removed, making the code pretty hard to read.

Wouldn't it be a lot simpler to just do an analogRead each time through your loop? And use the Servo library to control the servo?

PORTB bit 6 is controlled with TIMER0 while PORTB bit 1 is controlled with TIMER1.  Therefore you need to change the timer variables appropriately.  One mistake in your code is that you leave ICR1.  It should be OCRA if you want to use TIMER0.

I thought of ICR0, but according to the datasheet, there is no ICR0.

Checked that, you are right.  I think you can only use OCRA.  Not OCR0A?

No OCRA according to Atmel studio

Timer0 is already used for delay and millis. Use pin 3 or 11, as those use timer2 which isn't used.

My problem is now that I have to use ICR0 for my servo and ultrasonic sensor and then they get confused. Is there an alternative for this ICR0?

I think you will solve it by reading the data sheet.  Values for TCCR0A and TCCR0B are determined by the waveform generation mode, value of TOP and clock prescaler.  According to your code, WGM=0x7 i.e. fast PWM, OCR0A=TOP.  Read section 19.7.3 of Atmel-42735B-ATmega328/P_Datasheet_Complete-11/2016

I agree with Nick Gammon's comment that it is a lot easier using the Arduino Platform and use AnalogRead() function in conjunction with the servo library.
Having said that, you have chosen to write the program from scratch as many others prefer to do for one reason or another. I wanted to pass on the 2 web pages that I always go to when I am playing with the PWM frequencies and setup.

http://playground.arduino.cc/Main/TimerPWMCheatsheet
https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM


text:
Powering a water pump with nodemcu
I want to use a nodemcu to water my plants. I connected a pump with a 2N2222 transistor (I know i should add a diode and a pull down on the gate). The pump is DSL370 and when it is off i measure 4.4V on the Vin pin while using a 2A charger connected to the USB port. When the pump is active, the vin voltage drops to 4.1V and the LCD becomes hard to read. I measured the current the pump uses and it is 300mA. What is the reason for the voltage drop? I thought the charger should be able to handle it.

Is this the pump you are using? https://www.aliexpress.com/item/YIXINYOU-DC-12V-Diaphragm-Vacuum-Pump-Water-Pump-Oxygen-Pump-Air-Pump-DSL-2-12-020/32819735122.html

Your question does not seem to have anything to do with either Arduino Hardware or Arduino software, so it is unclear on what basis it would belong on this site.  Generally for a motor you want an NFET, not a bipolar transistor, and you must not route the power through the microcontroller board.

It is indeed the pump i am using.

Your charger may be able to handle 300mA, but you're pulling that power through your Arduino and that isn't good.  The pump should have a separate power supply, or at least be powered in parallel with the Arduino.  Don't pull power for a motor from the Vin pin unless you just want to destroy the Arduino.

But as shown here: http://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/
The Vin is connected to the USB port via a diode so the power does not go "through" the Arduino.

@zbut you just described the power for the pump doing through the MCU board and specifically its diode, which exactly what you were told was a bad idea.


text:
Connecting Arduino ethernet shield (ip address - 0.0.0.0)
I need some help to connect my arduino uno R3 and ethernet shield. I don't have a mac address with my shield so I'm using this one: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
The Ethernet controller on the Ethernet shield is W5100 and I don't use SD card.
I have receiver module wich receives data from transmitter and I want to save it in database, but there is issue related to the connection. When I print the Ethernet.localIP i observed only 0.0.0.0.
This is the IP address of my local network - char server[] = "192.168.0.106"
You can find my code below:
  #include <Wire.h> // use Wire library for protocol i2c (A4 = SDA & A5 = SCL)
  #include <VirtualWire.h> // use Virtual library for decode signal from Rx module
  #include <SPI.h>
  #include <Ethernet.h>

  EthernetClient client;
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  char server[] = "192.168.0.106";

  int humidity=0;
  int temp=0;
  int pressure=0;
  char MsgReceived[21];

  void setup()
  {
     Serial.begin(115200);
     Ethernet.begin(mac);

     Serial.println(Ethernet.localIP());

    // Bits per sec
    vw_setup(2000);
    // set pin for connect receiver module
    vw_set_rx_pin(3);
    // Start the receiver PLL running
    vw_rx_start();

  }
  void loop()
  {
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  //Taking the data from the control base
  if (vw_get_message(buf, &buflen))
  {
    int i;
    // Message with a good checksum received, dump it.
    for (i = 0; i < buflen; i++)
    {
      // Fill Msg Char array with corresponding
      // chars from buffer.
      MsgReceived[i] = char(buf[i]);
      //Serial.print(MsgReceived[i]);
    }

    sscanf(MsgReceived, "%d,%d,%d",&humidity, &temp,&pressure); // Converts a string to an array
    lcd_display();
    memset( MsgReceived, 0, sizeof(MsgReceived));// This line is for reset the StringReceived

    Serial.print("Temperature = ");
    Serial.print(temp);
    Serial.println(" *C");
    Serial.print("Pressure = ");
    Serial.print(pressure);
    Serial.println(" Pa");
    Serial.print("humidity = ");
    Serial.print(humidity);
    Serial.println(" %");

if (client.connect(server, 80)) {
   Serial.println("CONNECTED");
   client.print( "GET /diplomna/Arduino/add_data.php?");
   client.print("temperature=");;
   client.print( temp);
   client.print("&&");
   client.print("humidity=");
// change this to a print rather than println
   client.print( humidity );
// add a leading space in this println
   client.println( " HTTP/1.1");
// add a second cr/lf here to denote end of header
   client.println();
   client.println( "Connection: close\r\n" );

   while(client.connected()) {
      while(client.available()) {
        char ch = client.read();
        Serial.write(ch);
      }
    }
   client.stop();
   Serial.println("DISCONNECTED");
   }
 else {
   // you didn't get a connection to the server:
   Serial.println("-> connection failed/n");
 }
   delay(10000);
  }
  }

You can find the serial monitor output below:
0.0.0.0
Temperature = 26 *C
Pressure = 997 Pa
humidity = 57 %
-> connection failed/n
I also tried to execute the following example code (DhcpAddressPrinter)  and the results are the same - 0.0.0.0
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};

// 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;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    for (;;)
      ;
  }
  // print your local IP address:
  printIPAddress();
}

void loop() {

  switch (Ethernet.maintain())
  {
    case 1:
      //renewed fail
      Serial.println("Error: renewed fail");
      break;

    case 2:
      //renewed success
      Serial.println("Renewed success");

      //print your local IP address:
      printIPAddress();
      break;

    case 3:
      //rebind fail
      Serial.println("Error: rebind fail");
      break;

    case 4:
      //rebind success
      Serial.println("Rebind success");

      //print your local IP address:
      printIPAddress();
      break;

    default:
      //nothing happened
      break;

  }
}

void printIPAddress()
{
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }

  Serial.println();
}

Serial monitor output:
Failed to configure Ethernet using DHCP
I also tried to set the ip address of the shield to be 192.168.137.1 and made the following update:
  Ethernet.begin(mac);  ===>  Ethernet.begin(mac,ip);
The results are the same.
Could you please help me to debug this issue.
Thanks in advance!
Regards,
SK

If you're not using one of the peripherals in your program, you'll need to explicitly deselect it. To do this with the SD card, set pin 4 as an output and write a high to it. https://store.arduino.cc/arduino-ethernet-shield-2

what research have you done? .... did you try the example sketch?

How is your Ethernet shield wired to your network? What does your network consist of?

Hi Juraj,
thank you for the feedback. I will try this today.

Hi jstola,
Yes I made reasearch. I read many thames and reviwed a lot of videos regarding the issues related to the connections. Did you have a chance to read about my issue before to comment? There I explain that I have tried an example sketch, but the results are not as expected.

Hi Majenko,
I use straight connection cable to connect the ethernet shield to my laptop and I use wifi network. I also use xampp to create a virtual host with port 80.

Also asked at: http://forum.arduino.cc/index.php?topic=552471 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

Hi per, you are right. Thank you for the comment.

in my case was the SS pin, it was disconnected.

from comments:
  " I use straight connection cable to connect the ethernet shield to my
  laptop and I use wifi network. "

This is the problem. Connect to router.
The direct Ethernet connection may require the use of a cross-over cable and the PC probably doesn't have a DHCP server for the Ethernet interface, so you should set an IP address for the network interface and in the Arduino sketch.
see this SO question

Hi Juraj, you are right. I have connected the ethernet with the router and now the example scratch works.

The first thing you should do is disconnect or disable all devices from the Arduino except the network card then run your tests again, if they work (which I doubt) then the problem is a hardware resource clash, for which you will need to read the datasheets.
I suspect the problem you have is more fundamental, do you have a DHCP server on your network?
The first example doesn't specifically mention DHCP, but the second example makes the same call top Ethernet.begin() and seems to expect the call to have configured the NIC via DHCP.
So my advice would be to look at the API for the NIC and see what you need to do to statically configure you IPv4 settings.  Also you might need to bone up on IPv4 addresses and net masks, because the addresses you mentioned won't be able to communicate unless you have some special routing gear (it could be I read the question wrong).
Hope that helps.


text:
Arduno as bridge between two i2c masters
so I am gonna just jump right into the topic. Recently, I have been trying to build a project where I need to connect an ev3 to a raspberry pi. I have decided doing it by i2c after reading (and successfully replicating) an article about connecting an ev3 to arduino by i2c https://www.dexterindustries.com/howto/connecting-ev3-arduino/.  However, after setting it up with raspberry pi, I realized a huge problem that I am facing, both of these devices acted as masters and I could not get them to connect to each other. So I decided to use an arduino between those two which transports the data that it receives to the other device, which I couldn't get working. I have no idea how to get it working anyways, it was just a hopeless try. Now I am doubting myself If I can't do it. So my question is, is such a project possible or should I just give up. If I should, what type of communication do you suggest that I use.

Your question is confusing.  You successfully connected an Arduino to a device using I2C?  Then you added a Raspberry Pi putting 3 I2C devices on the same I2C bus and it does not work?  And instead of posting this to raspberrypi.stackexchange.com you are posting it here in arduino.stackexchange.com?  FYI, it is hard to imagine an I2C bus with more than one master.

An Arduino can be put into I2C slave mode, so I imagine a Raspberry Pi can be as well. I suggest asking on the Arduino Pi Stack Exchange how to do it. I can migrate this question there if you like.

https://raspberrypi.stackexchange.com/questions/5584/i2c-raspberri-pi-as-a-slave


text:
Write and read operation via synchronous serial port (Arduino Uno + ADNS2610)
1.Preliminaries
I have optical sensor ADNS2610 (see datasheet here) which I plug in to Arduino Uno R3 board.
It is possible either to read from either to write to the sensor. Here is what datasheet says (p. 12):

Write Operation
Write operations, where data is going from the microcontroller to the
  ADNS-2610, is always initiated by the microcontroller and consists of
  two bytes. The first byte contains the address (seven bits) and has a
  “1” as its MSB to indicate data direction. The second byte contains
  the data. The transfer is synchronized by SCK. The microcontroller
  changes SDIO on falling edges of SCK. The ADNS-2610 reads SDIO on rising edges of SCK.

Read Operation
A read operation, meaning data that is going from the ADNS-2610 to the
  microcontroller, is always initiated by the microcontroller and
  consists of two bytes. The first byte that contains the address is
  written by the microcontroller and has a “0” as its MSB to indicate
  data direction. The second byte contains the data and is driven by the
  ADNS-2610. The transfer synchronized by SCK. SDIO is changed
  on falling edges of SCK and read on every rising edge of SCK. The
  microcontroller must go to a High-Z state after the last address data
  bit. The ADNS-2610 will go to the High-Z state after the last data
  bit. Another thing to note during a read operation;
  SCK needs to be delayed after the last address data bit to ensure that the ADNS-2610 has at least 100 μs to prepare the requested data.
  This is shown in the timing diagrams below (See Figures to 23).

2 Arduino program
WriteRegister and ReadRegister functions are borrowed (though slightly modified) from OptiMouse project by zapmaker.
2.1 SetAddress function
This function writes the first byte: data direction (MSB) and address of a register (seven bits) which user intents to read from or to write to.
void ADNS2610::SetAddress( uint8_t address, DataDirection direction ) const
{
    pinMode( sdioPin, OUTPUT );

    /*Specify data direction:
     *MSB = 0   ===>   read operation
     *MSB = 1   ===>   write operation*/
    switch( direction )
    {
        case( toSensor ) :
            address |= 0b10000000 ;
            break;
        case( fromSensor ) :
            address &= ~0b10000000 ;
            break;
    }

    for( uint8_t mask = 0b10000000; mask; mask >>= 1 )
    {
        digitalWrite( sckPin, LOW );
        digitalWrite( sdioPin, address & mask );
        digitalWrite( sckPin, HIGH );
    }

    /*Wait for 100 microseconds between address write operation
    *and read data operation (see p.15 of the datasheet)*/
    delayMicroseconds( 100 );
}

2.2 ReadRegister function
uint8_t ADNS2610::ReadRegister( uint8_t address ) const
{
    SetAddress( address, fromSensor );

    uint8_t data = 0;

    /*Read data from a register*/
    pinMode( sdioPin, INPUT );
    for( int i = 7; i >= 0; i++ )
    {
        digitalWrite( sckPin, LOW );
        digitalWrite( sckPin, HIGH );

        data |= ( digitalRead( sdioPin ) << i );
    }

    /*Wait for 0.25 microseconds between read and either
     *read or write operations (see p.15 of the datasheet)*/
    delayMicroseconds( 1 );

    return data;
}

2.3 WriteRegister function
void ADNS2610::WriteRegister( uint8_t address, uint8_t data ) const
{
    SetAddress( address, toSensor );

    /*Write data to a register*/
    for( uint8_t mask = 0b10000000; mask; mask >>= 1 )
    {
        digitalWrite( sckPin, LOW );
        digitalWrite( sdioPin, data & mask );
        digitalWrite( sckPin, HIGH );
    }

    /*Wait for 100 microseconds between write and either
    *read or write operations (see p.15 of the datasheet)*/
    delayMicroseconds( 100 );
}

3.Discussion
3.1 Write operation
According to the datasheet

... The microcontroller changes SDIO on falling edges of SCK. The ADNS-2610 reads SDIO on rising edges of SCK.

And this is how I understand the code (see sec. 2.1):
digitalWrite( sckPin, LOW );//create a falling edge
digitalWrite( sdioPin, address & mask );//change SDIO on falling edge
digitalWrite( sckPin, HIGH );//create a rising edge (ADNS reads here)

Two questions here:

The first line in the above creates a falling edge only if the previous state of SCK was HIGH, doesn't it? So would it be better to have the following:
digitalWrite( sckPin, HIGH);
digitalWrite( sckPin, LOW );//create a falling edge
digitalWrite( sdioPin, address & mask );//change SDIO on falling edge
digitalWrite( sckPin, HIGH );//create a rising edge (ADNS reads here)

On figure 20 (see sec. 1, Write operation) you can see that it is required some minimal duration of the clock pulses (250 ns). Does the above code provide such a duration? I know that ATMega328p has frequency 16 MHz, so it seems that time between two operations could be less than 250 ns. Am I right?

3.2 Read operation
According to the datasheet

SDIO is changed on falling edges of SCK and read on every rising edge of SCK. The microcontroller must go to a High-Z state after the last address data bit. The ADNS-2610 will go to the High-Z state after the last data bit

And this is how I understand the code (see sec. 2.2):
digitalWrite( sckPin, LOW );//create a falling edge (SDIO changes here)
digitalWrite( sckPin, HIGH );//create a rising edge

data |= ( digitalRead( sdioPin ) << i );//read SDIO on rising edge

Three questions here:

The first line in the code above creates a falling edge only if the previous state of SCK was HIGH, doesn't it? Would it be better to have the following:
digitalWrite( sckPin, HIGH);
digitalWrite( sckPin, LOW );//create a falling edge (SDIO changes here)
digitalWrite( sckPin, HIGH );//create a rising edge

data |= ( digitalRead( sdioPin ) << i );//read SDIO on rising edge

On figure 23 (see sec. 1,Read operation) you can see that it is required some minimal duration of the clock pulses (250 ns). Does the above code provide such a duration?
How do I set the microcontroller into High-Z state after the last address data bit?

Question 1

The first line in the code above creates a falling edge only if the
  previous state of SCK was HIGH, doesn't it? Would it be better to have
  the following:
digitalWrite( sckPin, HIGH);
digitalWrite( sckPin, LOW );//create a falling edge (SDIO changes here)
digitalWrite( sckPin, HIGH );//create a rising edge

data |= ( digitalRead( sdioPin ) << i );//read SDIO on rising edge

If you start from Cycle one.. Yes. Looking at the read cycle waveform, SCLK should be high before initiating a read or write request and after completing the communication.
Question 2

On figure 23 (see sec. 1,Read operation) you can see that it is
  required some minimal duration of the clock pulses (250 ns). Does the
  above code provide such a duration?

Here is the code for digital write function
void digitalWrite(uint8_t pin, uint8_t val)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    volatile uint8_t *out;

    if (port == NOT_A_PIN)
        return;

    // If the pin that support PWM output, we need to turn it off
    // before doing a digital write.
    if (timer != NOT_ON_TIMER)
        turnOffPWM(timer);

    out = portOutputRegister(port);

    uint8_t oldSREG = SREG;
    cli();

    if (val == LOW) {
        *out &= ~bit;
    }
    else {
        *out |= bit;
    }

    SREG = oldSREG;
}

Please do not give any delay. the above DigtalWrite function will take 1000's of ns of delay already. it is sufficient.
Question 3:

How do I set the micro controller into High-Z state after the last
  address data bit?

I would do the following. Configure the pin which you want to set to high impedance as input pin. You can always change it to output mode before you want to use it again.


text:
Does delay() pause the counting of millis()?
If I add a delay for a few seconds, and then will the value given by millis () be equal just before and after delay?
Or to put it in other words, does the internal clock of Arduino stop during delay?

No, I cannot check it (no Arduino at hand), but afaik the clock always keeps counting, so if you perform a delay of 1 second, and diff millis() just before and after, it will be (slightly over) 1,000 (ms).
Note however, that the use of delay is discouraged and it is better to check millis() to perform the next state/command instead of a delay which prevents doing other tasks meanwhile. But the (internal) timer always keeps running.
Only during some deep sleep mode it might stop, but than a delay will not work neither. And when interrupts are disbled (see remark of Chris Stratton below).

You are missing the more common exception: time also stops incrementing when interrupts are disabled.

@ChrisStratton Thanks ... I added it in my answer. Also, I didn't know this although is seems very logical.

Delay uses millis. It just waits examining millis until a certain time has passed.
Millis is driven by an interrupt. The only thing that stops it working is another interrupt (you can only have one interrupt executing at once), which is why you can't use delay in an interrupt.

(delay actually uses micros not millis (source). But both millis and micros do indeed use the timer interrupt for counting time.)

Delay, millis, micros, etc, it's all one and the same.

That's not quite right either - disabling interrupts outside of an ISR will also stop it.

Ok, Mr pedant. We all know you value your opinion.

It's not a question of opinion, but of the misleadingly false use of the word "only" for something that is not in fact the only possibility.  Normally an answer doesn't have to mention everything, but if it is going to use exclusive language, it does, otherwise readers can be mislead.  For that matter, "borrowing" the utilized timer for some other custom purpose would break it, too.

You create a lot of useless nose on here you know. The users here don't need to know such levels of detail most of the time. Tailor the answer to the audience.


text:
Detect if Serial1 and Serial2 are defined, at compile time
I have my library that uses Serial, Serial1 and Serial2 to establish various logging scenarios. Library user would define the config at class constructor, using simple byte constants like 0, 1 and 2.
Problem is, Serial1 and Serial2 are not available in all board types. So when I compile my code (that compiles fine on Mega) on Uno, I get error
'Serial1' was not declared in this scope.
So I figure I need to adjust my code with preprocessor directive like #if defined, in order to include some code only if Serial1 is defined. But it wouldn't work, because Serial1 is defined later, at compile-time. So what is the accepted way to do this?

Not sure if the SDK has particular hardware defines setup for things like a serial port.  Most look at the SDK's processor defines and use conditional compilation directives such as "#ifdef ARDUINO_AVR_UNO".

Also, I'm looking at the ArduinoBoardManager at github source code and do not see where they define hardware like serial port on a per processor bases.  Maybe you could add that and re-use this code.  But I still think the easiest way about this is pick what serial port code you want to compile based on the processor type.  Look at the source code in this github project to see how they did this.

Why not make the constructor take an object reference of type Serial (or HardwareSerial or even Print)?

HardwareSerial.h in Arduino AVR boards core defines HAVE_HWSERIALX
example
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif

Consider the approach used here in the ArduinoBoardManager project at github.  The file ArduinoBoardManager.h uses conditional compiling to determine the correct code to compile based on processor type.  A similar approach can be used to asses if certain hardware peripherals such as serial ports were available based on processor type.
#if defined(__AVR_ATmega328P__) // uno, fi
  // Code compatible with an Arduino Uno
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  // Code compatible with an Arduino Mega
#endif

why do it, if HardwareSerial.h does it for you. and for example Uno Wifi has additional hw Serial1 (to connect onboard esp8266) even it is a 328p

Oh, I agree - I didn't know about the alternatives until posted here.  I just knew how the ArduinoBoardManager project was handling it.


text:
PWM fans causing temp sensor erroneus values (interference?)
I am learning Arduino programming and my current project for real use is to connect 10-17 PC chassis PWM fans to be temperature controlled by the arduino.
So, I have connected the fans exactly as in the picture.
Taken from https://www.racedepartment.com/threads/easy-diy-wind-simulator-for-assetto-corsa.133999/

The temperature sensor is a TMP36 (included in the official Arduino beginner's kit). It is connected to +5V and GND on the Arduino Uno R3. Middle pin is the output and is connected to A0 on the Uno.
Temperature readings seem to work well up until the point the fans start spinning. When they do, the output pin on the TMP36 sensor outputs junk values. Such as 0V or 700mV and it fluctuates up and down if I try probing it with a multimeter. When fans some to a stop however, the output once again stabilizes to a fairly correct value.
I am no expert in electronics interference, but electric motors I suppose cause some electrical noise? I had hoped that PC Chassis fans would already have electric components inside the hub to prevent such though...
Currently I am trying to run 2 fans at the same time but I wish to use 10-17 later once this works.
The fans I am using are Arctic 92mm PWM Rev 02.
I have checked the datasheet (https://www.arduino.cc/en/uploads/Main/TemperatureSensor.pdf) for TMP36 (TO-92 package type) and tried adding a ceramic 0.1µF capacitor between +5V and GND and also add resistor of varying values to the output pin. I believe I got some stabilization out of it but not  enough. Especially when the fans start spinnig faster than 20% duty cycle on pwm it starts to flip out.
I have tried to disconnect power to fans to check if PWM signal may cause it too, but this is not the case as the TMP36 remain stable with PWM on but fans disconnected.
Can someone please help me with explaining what is probably going on and how I can mitigate the problem in a preferably easy way? Do I need to add diodes, capacitors, resistors? Where? Or should I change to a different temperature sensor (which)?
Thankful for help!

Quick thought:   It may be that trying to do both is causing problems.  That is, you may be using the same processor resource(s) for both features.  Like a timer or a serial port.  Just because an Arduino program compiles doesn't mean that the libraries you include will work with one another.

BTW, you are using a second power supply to power the Arduino, right?  I say this as I realize 2 things.  1) I assume you have copied a working project exactly.  So there is precedence that the included libraries work together.  -and- 2) There is no second power supply in the diagram.  I think the original author just assumed there would be one.

@st2000 Hmmm, I only use PWM (analogWrite) and AnalogRead to read the temperature value. It feels like a very "simple case" for it to collide? That would cause lots of problems in projects of all kinds then. I tried to use an LDR instead of a TMP36 and fetch analog values and that worked like a charm.
The Arduino is powered via USB (PC connection). The fans are powered via external wall adapter as in the picture. So power for fans is drawn from the power adapter.

The LDR would have needed a pull up or pull down resistor.  (Did you use one?) Where as, I assume, the TMP36 would not.  I didn't look at the TMP36 spec, my bad, I didn't realize it developed an analog output.  I thought it was one of the common temperature probes which communicated over an I2C bus. Double check that you have connected to the correct pins of the TMP36.  Note the TO92 case is a bottom view whereas the other case views are from the top.

@st2000 You are correct, yes I had a resistor in series with the LDR (10kOhm) while the TMP36 did not need one (although in the datasheet I then found a section towards the end regarding high inductive loads showing a capacitor of 01µF and a resistor of 750 Ohm). Maybe is stailized things a tiny bit but as soon as fans spin up above 20% or so the TMP36 starts acting up. The connections to the TMP36 should be correct because it works fine when fans are not spinning. I feel that there's something missing, like some capacitor or diode or something for the fans maybe?

This is turning into guess work.  The series resistance and cap are likely to mitigate noise by matching the impedance of a long cable between the ADC and the TMP36.  Just keep it short for now. A foot / decimeter would be fine.  I suspect the current draw of the fans at speed is dripping the voltage of the fan power supply and dragging the laptop's USB power source with it resulting in unexpected readings.  Check to see if the power supply your are using is double the sum of the expected fan currents.  Also, try connecting only 1 fan to see if it will run as expected.

I suspect you will point out that the LDR / resistor divider had no problems controlling the fans to the desired fast speed.  If this truly is the case, I might guess that the impedance of the LDR / resistor divider is lower than that of the TMP36.  That in such a case, a little noise can manifest its self as larger voltage swings and more erratic ADC samples.   If true, that is, if the noise is random and the average reading accurate enough for this project, consider solving this problem in software.  Take the average of the readings and use that to control the fans.

@st2000 It is correct that the voltage values I got from reading the LDR were consistent, so I could set a PWM duty cycle based on lighting conditions in a consistent manner. I can't really take an average of the TMP36 though because when the fans are spinning and it gets affected by some interference, the output pin gives 0V or anything inbetween that and say 700mV and with a multimeter I can see that the output pin voltage jumps around all the time. Until I stop the fans, that is. Can I use a resistive temperature sensor instead (like the LDR for Light)? in so, which one has linear response?

Did you check the fan power supply is 2 x the sum of the peak current demand of the fans?  (Fans rated at 0.8A so both are 1.6A so 2 x means should use a power supply that can supply 3.2A.)  Or experiment w/only 1 fan - but use a power supply that can supply 1.6A.

Currently I use a power bank which can supply 12V. But the fans are rated 0.16A (not 1.6A  that would be raally powerful fans :) ). So with both fans at max speed I get 0.32A @ 12V. But I get sensor problems for anything above 20% speed when the two fans only draw very little current. I don't think that the power supply is too weak but I will try with another PSU.
If I had an oscilloscope I would be able to see if I have some distortion of voltage on the input to the sensor

In case anyone has the same problem, I solved it. Turns out is was a bad PSU. Buying a new, higher quality one made everything work. So the issue was high ripple I suspect, or at least high enough when applying some load (which is why I noticed that things got worse after the fans started spinning at greater than 20% duty cycle) for the temperature sensor to flip out.


text:
How to determine hardware/software compatibility?
Currently, I'm using Greiman's SdFat Library with Adafruit's Data logging Shield.
I'm thinking about switching to the Adafruit micro SD Card Breakout. I imagine that it will work as both products are made by Adafruit, and the board schematics look similar. However, I don't know what to look at to be sure they are the same.
Is it enough that they both use the HC4050M chip, or is there something else that I need to be aware of?
Short of buying one and testing it. What do I need to look at to verify that these two boards will work with the library?

A difficult question.  Any list would only be good if it were maintained, perhaps, monthly at the slowest.  Unfortunately, the obvious solution is likely the most difficult.  That is, to analyze the chip specifications used on each board and compare that with the source code in the intended to be used libraries.  That, or the hardware is usually cheap enough that trying to see if it works is also an option.  I should add that the schematic of the board and any non-volatile configuration data (like the address of an I2C chip) should also be considered.

look at example code if it is available

Will it work in principle? I'd say it is safe to assume it will. Will it work with your code? The easiest way to answer that is to test.

The HC4050M is just used for logic level translation (SD cards are 3.3V devices). It is "enough" that you are talking to an SD card using an SD card library. The SD card is really all the hardware there is - everything else is just interfacing fluff - completely transparent to the software.


text:
Arduino Nano off 9V : is there any change to output?
I'm building a test circuit on an Arduino Nano that consists of a simple 220 Ohm resistor and an LED on pin D2 which is routed back to GND (ground).
It's as simple as this:

It's running a very simple program to blink the LED on and off.  It all works while connected to the USB port.  I know the USB port provides 5V.
Now I want to run it my Nano and circuit from a 9V battery.  The datasheet says that you can run the Nano on 6V -12V by connecting it to pin 30 (VIN).  Of course, I know I'll have to add a line from GND back to the (common) battery ground also.
When I do that, the voltage on the OUTPUT pin (D2) will never be higher than 5V though, right?
I should not expect any change in output voltage even though I'm changing voltage that is powering the Nano, correct?

It looks like VIN connects to a LM2940, 5 volt regulator, so the voltage on the OUTPUT pin (D2) will never be higher than 5V.

Side note: The actually used voltage regulator differs from board to board (with chinese clones etc) so you always need to look at the datasheet. For the LM2940x in the 5V version, the output is between 4.85 to 5.15V (given about 10V input voltage at 25°C). Other regulators (AMS1117,..) might differ. [http://www.ti.com/lit/ds/symlink/lm2940c.pdf]

That's a great, definitive explanation because you've also shown me how to discover this information on my own. Thanks very much and for the note about the clones.


text:
Controlling two-pole contactor using Arduino
I am working with Packard C230C contactor to develop own EVSE. For a simple start i just want to toggle contactor using Arduino. OpenEVSE is already doing it. Just want to know how do they do it and some circuit explanation.
Reference : OpenEVSE Setup

the gray wires control the relay .... research how to control a relay with an Arduino .... also research how relays work  ..... btw: the link that you posted is bogus

I get grey wire controls contactor. But the voltage at that wire is around 120v while toggling a contactor state. generally relay is also +5v so question is how do you control 120~220v relay from arduino

@SurajJorwekar using a second relay that is controllable by 5V, that one doesn't need to switch a lot of power so can be a cheap one.

I use this module, controlled by 3.3 V pin of esp8266, powered with 5V to switch 10A AC http://wiki.seeedstudio.com/Grove-SPDT_Relay_30A/

Get solid state relays that have a operating voltage of 5V and can switch Mains AC


text:
Is there any version of arduino that can do something like serial interruption?
I am using an Arduino to control servo MX18A by serial, and trying to use computer to communicate with the Arduino by another serial to send commands to Arduino and change the servo control mode. Once the computer send a message to Aruduino, I hope it could response in time because may be there is something emergency like the servo being out of control ,under which circumstance I have to change the control strategy in time.
However, it seems like Arduinos like UNO, MEGA does not have serial interruption, so once the message from computer comes, it could not response in time.
I know that judging serial.available() in every loop is one solution, but in my different servo control strategy there are many time delays, for loops and while loops, which means that I have to put serial.available() in every time delay or for loops, making the code hard to write and maintain.

“there are many time delays”. This is your problem. Learning to program without delays is the solution.

@EdgarBonet What about for and  while loops? They are common in code design, and both of them will takes some time and have the same effect as  explicit delay.

Then you will need a finite state machine. In a nutshell: if you have to be responsive, program in a non-blocking fashion.

While all boards support serial interrupts on their serial port, beware that `328 based boards like the Uno only have one serial port.  "Software Serial" implementations can be partially interrupt based, but tend to need a lot of the processor's attention during reception so may not fit well into an interrupt-dependent program design.

@ChrisStratton I use UNO in my platform, which has four serial ports.

@bigxiao that makes no sense at all.  An Uno only has one serial port.  If you have an application that needs four, it is not the right choice for you as even a single software serial instance adds a lot of complication.  If you need four serial ports and Arduino may not be the solution for you at all, perhaps you should re-think your overall architecture.

The Mega does have 4 hardware serial ports.

It is not a case of "An Arduino" that can do serial interupts. All Arduino boards have serial interrupts, but they are already used to receive the data and store it in a buffer for you to consume when you have the time.
The Arduino API does not define any serial interrupt handling routines. That kind of thing is designed to be handled internally by the API code, not by the user. That's the whole point of the Arduino API - to abstract away such technicalities from the user.
If you want to use the serial interrupt yourself you will have to write your own serial handling code.
Or write your code in such a way that serial interrupts aren't needed.

How to write user-defined serial handling code and replace the original default code? Is there any interface for user to do that?

@bigxiao: Locate the file named "HardwareSerial.cpp" in the Arduino installation, copy it into your sketch's directory and tweak it to your needs.

Why not use a timer to check if any data is in the serial buffer every say 2 seconds.
The DUE has interrupts available on ALL pins so that could be a viable alternative solution.
You shouldn't use blocking code anyway, e.g. whiles and delays.

Arduino DUE has serial interruption, which is open for users?

It states that ALL digital pins on DUE work with interrupts so if you set an interrupt on a serial RX line it would trigger when data was received.


text:
TLC5917 Electrical Characteristics
I am using an Arduino Uno to communicate over SPI to 3 cascaded TLC5917 chips corresponding to the Red, Green and Blue rows of an RGB LED Matrix.
I am using direct output IO from the Arduino to power the columns.
Now I intend to use multiplexing to avoid drawing too much current at once, although it could still potentially be quite alot (3 x 8 x 20ma).
I have managed to display a full white screen using multiplexing with quite a high brightness, however this should not be possible to my knowledge.
Looking at the data sheet I found that at both at 3V and 5V the Output Voltage is rated at Vdd - 0.4 for Voh (Voltage High Level Output).
This means that at 5V the minimum output voltage should be 4.6V and at 3V it should be 2.6V.
Disabling multiplexing and simply writing to the registers and columns, and then measuring the voltage shows 2.5V, 2.8V and 1.8V for different colors.
This contradicts the data sheet.
The circuit contains no resistors except from GND to REXT using a 680Ohm Resistor.
The Arduino is powered over USB.
(http://www.ti.com/lit/ds/symlink/tlc5917.pdf)
Why is the Voltage so low, should it not be higher given the data sheet?
Am i reading the correct attribute?
How can my Arduino manage to drive so many LEDs (albeit through LED Drivers)?
What can I do to make this circuit more electronically safe and stable?

You are confusing logic signals with constant current sinks.

The concepts of HIGH and LOW, and thus the voltages associated with those concepts, apply only to logic signals.
LED drivers are not logic signals - they are constant current sinks. The voltages you are measuring are the forward voltages of the LEDs.


text:
Need help in connecting 64x32 LED Matrix
I recently got a 64x32 LED Matrix. However, I'm not sure how to connect it to an arduino uno. I tried following the docs here: https://cdn-learn.adafruit.com/downloads/pdf/32x16-32x32-rgb-led-matrix.pdf, but I can't get my OLED matrix to display the example.
This is my current connection so far:

(I have the R0 at the top left variant. I tried connecting it to the ESP8266 before and it works well, just that I do not know how to translate the connections to the Arduino UNO) I have a feeling that my connection is wrong since I copied the PI to PO connections from here:

and I only changed the PI to ESP8266 connections to the adafruit docs connections.
The code I am running is the example testshapes_32x64 from the RGB matrix panel library: https://github.com/adafruit/RGB-matrix-Panel/blob/master/examples/testshapes_32x64/testshapes_32x64.ino
EDIT: Since my connection for the CLK pin is connected to pin 8, I made changes in the code but it is still not working.
x-post from: https://www.reddit.com/r/arduino/comments/8qgm9x/need_help_in_connecting_a_64x32_oled_matrix_to_an/ and https://forum.arduino.cc/index.php?topic=552832.0

Why do you use connections shown on twitter? Have you tried doing all connections like described in Adafruits documentation, that you linked to? And using the same example code from there?

@chrisl that connection worked when I connected it to an ESP8266. I tried the connections and the code, but it didn't work.

@chrisl I even tried the connections from here: https://learn.sparkfun.com/tutorials/rgb-panel-hookup-guide but it isn't working

Jumping in, just wanted to make sure you @Dominic understand - just because different boards are all called Arduino does not mean the code nor electrical connections are compatible.  If you are going to use an Arduino Uno, you should start over with instructions and software specifically for an Arduino Uno.  Unless you completely understand the processor's hardware, the board's hardware and the software including the libraries.

If your matrix is the same as mine (32x64) I don't think you can drive it with a UNO. You should use a MEGA. Then follow the wiring supplied by SparkFun and make sure you connect CLK to Pin 11, NOT Pin 8.

There is NO demand for using an Arduino MEGA! If you read the documentation an Arduino UNO or eq. is sufficient.


text:
Is the ATMega328P powerful enough to deal with a lot of SPI data while reading a rotary encoder?
I need to:

Output data to a 128x64 screen with ug8lib (via SPI)
Keep track of the position of a high-precision rotary encoder (1024p/r)
Send about 2 bytes of data up to 120 times per second via an nrf24l01+ board (via SPI)
List item

Would the 3V Pro Trinket board, running an ATMega328P at 12Mhz, be powerful enough for this?
I was originally going to use a way more powerful STM32-based board for this project, but I'm having trouble making it work with my OLED screen, so am considering reusing an old Pro Trinket I've got lying around.

Presumably you'll handle the encoder with interrupts so consider pin choice carefully.  You've not stated the required update rate for the display or the allowed timing jitter for that or the radio.  240 bytes exceeds the nRF packet buffer so it will require a lot of interaction - do you require 240 bytes transferred or only 240 bytes attempted to be sent?  You may also end up tight on RAM.

Sorry, I wasn't very clear. I don't need to send 240bytes every second, but 2 bytes at a maximum of 120x per second. The display doesn't need to be updated too fast, but still about 20-40fps, and it doesn't need to be very precise. The radio however can't have much timing jitter at all.

You may need to just try it and see what difficulties you run into.  If you don't make your code to Arduino-ish you can likely re-use some of it for a different target.  Or try to get the STM32 working.  It's unclear if you've yet put much thought into the unreliability of the radio link.

does the screen have an integrated buffer? if not, then maybe use a second trinket to handle the screen display

You may be hitting a wall with SPI.  I have a 16x4 SPI board driven by an ATMege328P and it is quite slow updating.  However, I just purchased a TFT touchscreen 240x320 (https://amzn.to/2t27B5B) and I'm driving via ATMega328P and it is amazingly fast.  However, it has 8 separate data lines (parallel).  Check out the video I added to my amazon review and you'll see it can keep up with redraws.  Good luck.

The fastest SPI data transfer that I have done is 128,000 bytes in 1 second with an Arduino UNO at 16 MHz. That was transferring data points from an LTC1864 ADC to a SRAM chip for storage, with a simple data acquisition loop timed by hardware.  I think you can make your application work on a 328p if your code does not have too much time overhead.

If you are finding the SPI library too slow, you can also use AVR registers directly, i.e. SPDR, SPCR, SPSR


text:
WiFi problem on Mega + WiFi R3 ATmega2560 + ESP8266
I've got 2 "Mega + WiFi R3 ATmega2560 + ESP8266" (link) and both have same issue when trying to use the ESP chip.
Hope someone can point me toward something else to try in order to get them working properly.
Context
I'm able to flash the ESP chip using Arduino IDE or PlatformIO.
Dip switch need to be : 5, 6 and 7 ON to flash, and only 5 and 6 to debug through serial.
I've tried using different boards (Generic ESP8266 module, Wemos D1 R2 & mini, Node MCU) as well as different flash mode (DIO, QIO), crystal frequency (26 Mhz, 40 Mhz), CPU frequency (80 Mhz, 160 Mhz)
They all flash correctly without any error and I can get my serial output.
It's written ESP8266EX on the ESP chip. And I've tried with or without an antenna plugged on the board.
Problem
The problem I got on both of them is huge instability when using wifi. I cannot connect to them when they are in AP mode, they drop immediately.. And I cannot connect to or see my own wifi network from the Mega's ESP.
The same script and flashing config used on other ESPs devices work as expected (see [output other ESP board] below). I've tried on WeMos and NodeMCU devices.
But with the mega+wifi, it only see between 0 and 2 access point that are at a greater distance and weaker signal than my own wifi ([output mega+wifi] below).
Question
I don't have any clue on what can cause such a different result on device from same family (ESP/espressif). As if there was some sort of setting that need to be changed on those ESPs.
Any help or insight would be truly appreciated.
[code]
#include "ESP8266WiFi.h"

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

  // Set WiFi to station mode and disconnect from an AP if it was previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}

[output other ESP board]
scandone
scan done
8 networks found
1: 412 Precondition Failed (-67)*
2: VIDEOTRON1547 (-90)*
3: BELL275 (-94)*
4: BELL558 (-72)*
5: C-PC_Network (-88)*
6: BELL387 (-90)*
7: EBOX-4229 (-94)*
8: VIDEOTRON6825 (-80)*

scan start
scandone
scan done
11 networks found
1: 412 Precondition Failed (-63)*
2: VIDEOTRON1547 (-88)*
3: BELL681 (-90)*
4: BELL275 (-90)*
5: VIDEOTRON0442 (-90)*
6: BELL558 (-71)*
7: BELL602 (-90)*
8: IKA COIFFURE (-90)*
9: C-PC_Network (-87)*
10: EBOX-4229 (-87)*
11: BELL387 (-90)*

scan start
scandone
scan done
7 networks found
1: 412 Precondition Failed (-65)*
2: BELL681 (-88)*
3: VIDEOTRON1547 (-88)*
4: EBOX-4229 (-88)*
5: BELL387 (-87)*
6: BELL558 (-71)*
7: dlink-Ares (-75)*

[output mega+wifi]
SDK:2.2.1(cfd48f3)/Core:2.4.1/lwIP:2.0.3(STABLE-2_0_3_RELEASE/glue:arduino-2.4.1)
bcn 0
del if1
usl
mode : sta(2c:3a:e8:26:36:13)
add if0
wifi evt: 8
Setup done
scan start
scandone
scan done
1 networks found
1: BELL558 (-69)*

scan start
scandone
scan done
1 networks found
1: BELL387 (-88)*

scan start
scandone
scan done
no networks found

scan start
scandone
scan done
1 networks found
1: BELL387 (-87)*

[erasing flash]
PS \tool-esptoolpy> python .\esptool.py -p COM10 erase_flash
esptool.py v2.3.1
Connecting....
Detecting chip type... ESP8266
Chip is ESP8266EX
Features: WiFi
Uploading stub...
Running stub...
Stub running...
Erasing flash (this may take a while)...
Chip erase completed successfully in 14.2s
Hard resetting via RTS pin...

try to erase the flash of the esp8266 with esptool and then upload a sketch from IDE. choose Generic esp8266 as a board

I did it using python .\esptool.py -p COM10 erase_flash and that didn't changed anything. Output added to the question.

I had this problem. On Robotdyn D1 mini the esp8266 flash erase did help. On Robotdyn D1 R2 only the flashing of the AT firmware with Espressif Flash Download Tool restored the esp8266. After then the sketches from IDE had working WiFi.
There are some settings of the Espressif basic esp8266 libraries (SDK) saved on flash and there is some incompatibility between SDK versions. The Flash Download Tool creates right esp settings binary and flashes it to right address on flash.

ESP8266_AT_Bin_V1.6.2 ? and then at or at_sdio ? and how do I know the right addresses to use?

"at". addresses depend on the size of the flash and are listed in the readme file

Thanks. Just flashed it and even with direct AT command, on only sees very few wifi network
AT+CWMODE?
+CWMODE:2

OK
AT+CWMODE=3

OK
AT+CWMODE?
+CWMODE:3

OK
AT+CWLAP
+CWLAP:(2,"CHANTAL-PC-Network",-77,"00:26:5a:d1:c9:96",11,162,0,5,3,7,1)

AT+GMR
AT version:1.6.2.0(Apr 13 2018 11:10:59)
SDK version:2.2.1(6ab97e9)
compile time:Jun  7 2018 19:34:26
Bin version(Wroom 02):1.6.2

and can you connect to your network (CWJAP) ?

No..
AT+CWMODE=3
OK
AT+CWJAP_DEF="412 Precondition Failed","my pass"
+CWJAP:3
FAIL

and CWJAP:3 means "cannot find the target AP"

I also changed the country to US as it was to "CN" in case that could help but that changed nothing even after a reset

ideas: is the WiFi AP you try to connect 2,4 GHz? is it listed in scan? try to start AP with AT commands and connect to it.

Yes, it is 2,4 Ghz and no, it does not appear in scan on those devices. But it is visible (and connectable) from any other ESP board I have + computer + phone.

Let us continue this discussion in chat.

You state you "cannot connect to them when they are in AP mode" but I do not see AP configured in your code.
// ESP AP Server
// password can be blank
// must be min 8 chars or will not work
const char *APName = "MYESP8266";
const char *APPass = "MYPASS123";
// start the access point server
WiFi.softAP(APName, APPass);
// define web link functions
webServer.on("/", doRoot);
// start server
webServer.begin();

// In LOOP
// keep checking to see if someone connects to device
webServer.handleClient();

Regarding the mega-wifi-r3-atmega2560-esp8266
I am unsure how these work, is the code being flashed to the ESP chip or to the Arduino chip and ESP is in AT mode?

For the AP mode, I tried with the example provided here : http://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/soft-access-point-examples.html
I simply cannot connect to the AP (when I'm able to see it) even if I'm only 1 foot away from the board.

Do you get an error after typing in the password?

Try making the password all caps

No, from computer is says "can't connect to network" and from my phone the AP simply disappear. The same code work perfectly on other boards. Seems more like core firmware issue.

If it goes off then most likely the code is crashing and ESP rebooting

Strangely it's not.. nothing in the serial debug even if debug level include almost everything

If you've come upon this page because the ESP8266 on your (WeMos) Mega wifi won't connect to your router (etc), check the age/security of your router:
Wifi stopped connecting (Wemos D1 Mini)
This line of code that allowed connecting with my old router:
  WiFi.enableInsecureWEP();
which also highlights that I should upgrade it...