text:
Using chipKIT WiFi Shield with an Arduino
I'm beginning with Arduino and I have to make two of them communicate via WiFi. I'm going to implement the examples for a WiFi Client and WiFi Server in their tutorials page.
The problem is I only have one Arduino WiFi Shield which is working fine. But I also have a chipKIT WiFi Shield.
My question is: Can I use this other shield to do what I want with one of my Arduinos (I have Uno, Mega and Due) and how? Because I've plugged the shield and I've uploaded the code but it didn't seem to work.

No, you can't. The only libraries available for the chipKIT WiFi Shield are written specifically for the chipKIT boards.
Also, how have you plugged the board into an Arduino? The chipKIT WiFi Shield has Digilent's own header layout with a double row of headers where the Arduino only has a single row. Half the pins won't be plugged into anything.

Thanks. I don't know much about chipKIT products. Only that I could use Arduino IDE also. And since I could plug it into a Uno I thought they could be compatible. The picture: https://www.dropbox.com/s/32pv2t0e0s1ptrh/2017-06-15%2007.19.04.jpg?dl=0

Look from the end - you'll see half the pins dangling in mid air.

You want something like an Uno32, uC32 or MAX32 to work with the WiFi Shield.

You're right, Majenko. But I thought that this was "normal". For some reason I thought the pins were like that so I could plug into different board sizes. My mistake. First time using shields.


text:
Wi-Fi module 5 GHz
What is a Wi-Fi module for an Arduino that works on 5 GHz? The ESP8266 - doesn't support 5 GHz according to:

Re: 802.11AC 5GHz
Why can't ESP8266 operate in 5 GHz since 802.11N is supported
my own experiments.

You may need to drop "Arduino" from your search term and simply look for something supporting a UART or SPI interface and having an on-board protocol engine (since running a TCP stack on an Arduino is often problematic).  Unfortunately on-board TCP stacks, while initially seeming convenient, can turn out in the long run to have severe, unfixable problems frustrating serious use.

I asked Microchip a while back if they planned to release a 5GHz WiFi module at any point in the near future. The answer was basically "No, there would be no benefit to it." For embedded systems there is no point in 5GHz since 2.4GHz is more than adequate and there are better long range solutions than WiFi (LoRa for instance).

I need to connect an Arduino to a 5Ghz Wifi hotspot. I will accept the first applicable workaround as an answer.

You may find an external module with SPI or UART interface. Arduino support for it may be lacking though. We can't do your shopping for you though.

source: Stack Exchange

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

sort: votes


text:
Sending Analog Input Data from Serial Port to Google Sheets
So I'm trying to make use of my Arduino Uno while I purchase the components for my next project.
I've made use of the Digital Hourglass project from the Starter Kit to make sure I get up and move around every 20 minutes while I'm at home. A temperature sensor was included in the Starter Kit as well, so I figured I might as well make use of it since I have extra I/O pins.
I wrote the code for in the Arduino IDE to display the temperature and the current time. I'm using: #include (Time.h) to also show the current time. I have two questions.
End Goal:
A Google spreadsheet (Cloud) that I can access anywhere that can show me the temperature of my apartment throughout the day. I can track how the trend changes over time through the day, week, or month.

What is the best way to output the current time; as seconds since 1970 (Unix time) or date and time format? I guess it's a preference.
How do I output the data from the Arduino serial port directly to Google Sheets? That may be difficult, so the other option is to energize the Arduino in the morning and remove power at the end of the day, output the Serial port to a .txt file, and then import into Google sheets. How do I do this?

Use Google's time stamp format: MM-dd-yyyy hh:mm:ss, see Google Sheets API v4 - Date and Number Formats.
There are a few ways. For example:

A PC connected to the Internet with software on it that listens for data form the Arduino. It would get the Arduino data over serial then send that via the Internet to Google.
A Wi-Fi, or network, shield connected to the Internet. You could then use Google's API to send the data directly from the Arduino, see Google Sheets API v4 - Writing.
Or - as you mentioned - physically get the SD card and manually upload.

The first one is the idea. I'm leaving the Arduino connected to my laptop throughout the day while I'm gone. It shouldn't be that hard to edit the script to at least send that data from being transmitted from the Arduino to a .txt document. Maybe I haven't done enough digging into the Arduino Playground. This should be able to work with any analog sensor.

I'd use an ESP8266 and IFTTT.
https://ifttt.com/maker_webhooks
https://ifttt.com/google_drive
You could write something on your PC that took the serial output from the Aurdino and posts a REST message to IFTTT.

Yes, I recently ordered the Sparkfun Photon kit for a lot of IoT training. This project that I posted about in particular is not meant to be an IoT project. It's meant to learn how to simply document data for later processing using the serial connection. Thank you though!

Wouldn't it be great if the data from Arduino obtained via serial port could be inserted directly at a local google spreadsheet url, without using any api nor post requests?
As far as I know, Google Spreadsheets can be updated (by a human) in the local machine even without internet.
What would be the benefit?
If eventually internet goes offline for several hours, no arduino data would be lost.
In the good working solutions provided, internet is always mandatory, if I see correct. No internet? Lost data. It seems to me.
But I really don't know if a script can get serial data from Arduino and then update an existing google spreadsheet url, as a human would do (typing a new row).
An autoit or autohotkey script would do on Windows machines by simulating mouse clicks and typing, but it must exist more beautiful solutions.
A solution like this would accumulate data with or without internet and, as soon as internet returns, all data would be updated to the cloud. If I see correct. (I am sorry if I made any mistake).

I guess I have a not so bad solution: save all data to a txt file. Then, periodically, try to update all data to a google spreadsheet using Sheets API or any internet-dependent way (Web App, etc).
In this case, if there's no internet, data still accumulates at a txt file. When internet returns, no data would had been lost.

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

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


text:
What's wrong with my code
I use a mega as a master and a nano as a slave.
Both should convey texts. However, I get the master always only the answer that I send.
The text from the slave does not arrive.
Master:
#include <SPI.h>
volatile boolean senden;
volatile char Paket_vom_Slave;
volatile char Paket_zum_Slave;
char buf [100];
volatile byte pos;
String Paket = "";
char x;

void setup (void)

{
  Serial.begin(9600);
  pinMode(53, OUTPUT);
  pinMode(SS, OUTPUT);
  digitalWrite(SS, HIGH);  //SS Pin auf HIGH setzten
  SPI.begin ();  //Verbindung starten
  SPI.setClockDivider(SPI_CLOCK_DIV8);  //Geschwindigkeit verlangsamen
}

void loop (void)
{
  //Text_erstellen();

  digitalWrite(SS, LOW);    //starten der Kommunikation mit Slave

  for (const char * p = "TxT v Master\n" ; Paket_zum_Slave = *p; p++)
  {
    //Text_erstellen();
    Paket_vom_Slave = SPI.transfer(Paket_zum_Slave); //senden von Text
    Text_erstellen();
    delayMicroseconds (500);
    Serial.print("sent: ");
    Serial.print(Paket_zum_Slave);
    Serial.print("\t empfangen: ");
    //Serial.println(Paket_vom_Slave);
    Serial.println(Paket);
    delay(200);
  }
  digitalWrite(SS, HIGH);  //beenden der Kommunikation
  delay (1000);  //kurze pause

}

void Text_erstellen()
{
  char c = Paket_vom_Slave;  //kopieren der Daten von SPI Buffer
  if (pos < sizeof buf)
  {
    buf [pos++] = c;  //hinzufuegen des naechsten Zeichens
    if (c == '\n')
      senden = true;
  }
  if (senden)
  {
    buf[pos] = 0;
    Paket = (buf);
    x = buf;
    Paket.trim();
    Serial.println (("empfangen :--->") + (Paket));
    Serial.println (("empfangen :--->") + (Paket));
    Serial.println (("empfangen :--->") + (Paket));
    pos = 0;
    senden = false;

  }
}

Slave:
#include <SPI.h>
volatile boolean senden;
volatile boolean versandbereit;
//volatile byte Paket_Master,Sendung_Slave;
volatile char Paket_Master;
volatile char Sendung_Slave;
String Paket = "";
String Sendung = "";
int i = -1;
char buf[20];
char buf1[20];
volatile byte pos;
volatile byte pos1;

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

 pinMode(12, OUTPUT);
  pinMode(MISO, OUTPUT);
 SPCR |= _BV(SPE);         // turn on SPI in slave mode

  //SPCR |= bit (SPE);
  senden = false;
  SPCR |= _BV(SPIE);   // turn on interrupts
  SPI.attachInterrupt();
}

void loop(void)
{

  if ((versandbereit) == false);
  {
    Paket_Text();
  }

  if (senden)
  {
    i = i + 1;

    buf[pos] = 0;
    Paket = (buf);
    buf1[pos] = 0;
    Sendung = (buf1);

    if (i == 12)
    {
      SPDR = "\n";
    }
    else
    {
      SPDR = (buf1[i]);
    }
    Paket.trim();
    Sendung.trim();
    Serial.println (("empfangen :--->") + (Paket));
    Serial.println (buf1[i]);
    Serial.println (i);
    Serial.println (("gesendet  :--->") + (Sendung));

    pos = 0;
    senden = false;
  }

  if (i == 12) i = -1;
}

ISR(SPI_STC_vect)
{

  byte c = SPDR;  //kopieren der Daten von SPI Buffer
  if (pos < sizeof buf)
  {
    buf[pos++] = c;  //hinzufuegen des naechsten Zeichens
    if (c == '\n')
      senden = true;
  }
}

void Paket_Text()
{
  if (pos1 < sizeof buf1)
    for (const char * p = "Paket--Slave\n" ; char c = *p; p++)
    {
      buf1[pos1++] = c;
                            Serial.println (buf1);
      if (c == '\n')
        versandbereit = true;
    }
}

I've updated the code above.
The slave now sends bitwise the same text length as it should, but another text like the master sent.
Unfortunately, the master always receives what he sends, not what comes from the slave.

I'm getting on slowly :-)
But I currently have a problem with the data transfer.
I hand over at startup: char package_to_master [50] = "Start from the slave.";
and change SPI interrupt routine content with "new text"
but is sent "starting from the slave."
How should I change that?
// Slave
char Paket_zum_Master[50] = "Starten vom Slave.";
volatile int pos;
volatile bool active;
String Send_Paket;
ISR (SPI_STC_vect)    // SPI interrupt routine
{
  Send_Paket = "neuer Text";
  char Sendung = ((Send_Paket + "\n").c_str());
  Paket_zum_Master[50] = Sendung;
  byte c = SPDR;
  if (c == 1)  // starting new sequence?
  {
    active = true;
    pos = 0;
    SPDR = Paket_zum_Master[pos++];   // sendet erste byte
    return;
  }
  if (!active)
  {
    SPDR = 0;
    return;
  }
  SPDR = Paket_zum_Master[pos];
  if (Paket_zum_Master[pos] == 0 || ++pos >= sizeof(Paket_zum_Master))
    //wenn pos=0 oder größer 1
    active = false;
}  // end

Pin 10 at the nano and the master pin 53 but the hardware exchange is ok, I've already checked

http://www.gammon.com.au/forum/?id=10892&reply=1#reply1

Unrelated, but a more-descriptive title might be a good idea.

You do not have pinMode(SS, OUTPUT); in setup() of the master.

digitalWrite(SS, HIGH);

I think with the command it happened:

I tried it once but the problem persists :-(

to use digitalWrite  pinMode must be set

do not set it to output on slave. on slave the SS pin is handled by hardware

Yes Mega Master Pin52 Nano =pin10

did you add pinMode(SS, OUTPUT); to setup() on master?

pinMode(SS, OUTPUT);  digitalWrite(SS, HIGH);   SPI.begin ();  SPI.setClockDivider(SPI_CLOCK_DIV8); is registered but it is not yet

if it worked for a moment, check the wiring. ground is connected between boards?

I try to explain the mistake again, maybe someone has an idea for me.
I send to Master "TxT v Master \ n" at the character "\ n" the slave gives me the message correctly.
The slave sends back ____ "package - slave \ n", but the master only shows me the text he sends himself.
When I send something without a "\ n" character from the slave, the master does not put any text together
void text_create () no cancel. But since the slave sends the same character length, the transmission seems obvious.
When composing, however the master only puts together what he sends. Do I have the worm somewhere

Paket_vom_Sklave; is clearly the valid return and with "\ n" the slave comes with the demolition.
In case of an invalid return but not.
I hope my explanation is understandable Mfg Dieter

If I have to change the pin mod how do I do that where I am still a stupid. Maybe someone can tell me where exactly I have to enter.

try the examples by Nick Gammon in the link I added in a comment to the question. the code is very similar to yours, but not same

If I have to change the pin mod how do I do that where I am still a stupid. Maybe someone can tell me where exactly I have to enter.

Nick Gammon seine Beispiele sind gut die hab ich aber schon hin und her gelesen und probiert leider ist es mir nicht gelungen da ein Nutzen raus zu bekommen. Mir fehlt noch einiges an Erfahrung.

Nick Gammon his examples are good but I have already read back and forth and tried unfortunately I did not succeed in getting a benefit out. I still lack a lot of experience. oh sorry was not englisch bevor

I've tried it on with Arduino Pro Micro as a master and Arduino Uno as a slave. It is working.

In the 'Note about Slave Select (SS) pin on AVR based boards' https://www.arduino.cc/en/Reference/SPI, it is notified that the SS pin should be set always as OUTPUT, even though you use another one to select the device.
The answer contains the text inside the SPI data register, you have to change it inside isr https://www.avrfreaks.net/forum/how-fast-can-spi-slave-reply, else it is the same text as that received
const char *p = "Reponse Uno\n" ;
ISR(SPI_STC_vect)
{
  byte c = SPDR;  //kopieren der Daten von SPI Buffer
  buf[pos++] = c;  //hinzufuegen des naechsten Zeichens

  if (pos < 13)
    SPDR = p[pos-1];
  else
    SPDR = 0;

  if (c=='\n') {
    for (int i=0;i<pos;i++)
        bufi[i]=buf[i];
    posi = pos;
    pos = 0;
    senden = true;
  }
}

The result is

By the way, it is another issue to make it work with Arduino Pro Micro as a slave ...

the problem is he doesn't set the SS as output even he uses it to select the slave

Yes it works for me so far but in the master with you, the slave sends the same synonymous yes the same back what he sends. The master should actually receive another text.

Added the way the master can get another text to the answer.

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


text:
Circuit diagram for ACS712 and ZMPT101B with ESP8266 using ADS1115
This is probably a cry for help for a circuit diagram which involves connecting ESP8266 with ADS1115 with ACS712 and ZMPT101B(voltage sensor). Since both of them uses analog pins, and using a diode separator is not a proper idea in real-life. Therefore I ended up using the ADS1115 for more analog pins, which should be working fine. I am not a electrical engineer so I am having real trouble as to how to fix all Four of them together. Can any one help me with a circuit diagram for this? Any links or research papers links, etc. Thanks

I hope you have modules not bare chips. Add links. The ADS1115 use I2C a.k.a. Wire to communicate with MCU. Default Wire pins on esp8266 are io 5 SCL and io4 SCA. I recommend to use this pins. Of course te module needs 3.3 V and ground.

If you can make your comment as an answer then I will mark it.

The ADS1115 use I2C a.k.a. Wire to communicate with MCU. Default Wire pins on esp8266 are io 5 SCL and io4 SCA. I recommend to use this pins. Of course the module needs 3.3 V and ground.

Step one is to get the ADC working.  Once that is done everything else will fall pretty much into place.
The ADC you have chosen is an I2C device.  The ESP8266 doesn't have I2C as such, but it does provide a software-emulated I2C implementation.  This can be used on any pair of pins, but the default ones are GPIO4 for the data (SDA) and GPIO5 for the clock (SCL) (this corresponds to the Arduino Uno using pins A4 and A5 for I2C, so it should be easy to remember).
Once you have that working the wiring for the rest is the same as for any other system. The only thing that differs is that your analogue inputs are on the ADC chip, not the main module.
Here's a block diagram to get you started:

simulate this circuit – Schematic created using CircuitLab
This is assuming:

Single voltage output from each of your sensor modules
I2C pullup resistors provided by either ESP8266 or ADS1115 (add your own if not)
All modules providing the required support components for the chip

ok, sorry i was inactive on this post, I did reply a comment to Juraj, dont know who deleted that.. Thank you so much for the circuit, I have been able to follow Juraj's instruction and come up with a circuit of my own. But your schematics help a lot as I am now confirmed that my circuit is correct. Although I am having another problem.But I will ask later, Thank you so much for the Help.

Majenko, can you share your code please

@LêHùng What makes you think I went to the effort to write any code? This is just a block diagram to show how it works.


text:
Random characters generated by LCD during serial.read()
I am using the following codes to print characters on LCD display....
#include <LiquidCrystal.h>

const int rs = 8, en = 9, d0 = 4, d1 = 5, d2 = 6, d3 = 7;
LiquidCrystal lcd(rs, en, d0, d1, d2, d3);

void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);
}

void loop() {
  if (Serial.available()) {
    delay(100);
    lcd.clear();
    while (Serial.available() > 0) {
      lcd.write(Serial.read());
    }
  }
}

but in the end it is generating an unwanted character also..

kindly help me with the problem

I guess, it is the newline character. What line end is Serial Monitor set to send?

Does 'lcd.write("Hello");' work? You should check if the problem is on the serial or on the LCD.

yes it works perfectly

@Gyan_mishra in that case, it doesn't appear to be a problem on the display's side. Is the same character generated when you do: "lcd.write("\r\n");"? Or choose "No line ending" in the Arduino serial monitor.

thanks for help @Paul .... the problem was exactly the same...

The character to the right of the 'A' on your LCD display does not correspond to any of the built-in character bitmap definitions (either on a EU or Chinese display).  This random pattern is likely one of the 8 programmable character bitmaps supported by the LCD that has not been defined yet (ASCII codes 0 to 7).
So, you're likely sending the LCD a character with a value between 0 and 7.  It's probably a good idea to filter out invalid characters before attempting to display them on your LCD.
Filtering Example:
char c = Serial.read();
if ((c >= 32) && (c <= 128))
  lcd.write(c);

could you tell me, how to filter out invalid characters before attempting to display

I've updated the answer to illustrate a simple filtering example.  Take a look at an ASCII table to understand why the numbers I chose are significant.

thank you @jeff, for providing me such an excellent example of filtering.. it worked


text:
Using Arduino's hardware serial to control SIM900
I have a SIM900 board which has a serial interface. I'm trying to control it using Arduino Uno. I've tried using SoftwareSerial on pins 10 (RX) and 11 (TX) to talk to my board. It works OK with different baud rates (SIM900 has auto-bauding). I'm connecting pin 10 directly to my board, but pin 11 is connected through a voltage divider in order to lower voltage from 5 V to 2.8 V (SIM900 uses 2.8 V CMOS logic levels).
But now I want to use Arduino's hardware UART to talk to SIM900. I'm using pins 0 and 1 with similar design as above (also using voltage divider). I just can't get it to work. No matter what I do I can't see any communication. I've tried different baud rates, but it just doesn't work. Here is my code:
void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);

  delay(10000);
  Serial.write("AT\r");
  delay(1000);
  if (Serial.available())
  {
    digitalWrite(13, HIGH);
  }
}

void loop()
{
}

So I should see a LED light up but nothing happens (SIM900 responds with "\r\nOK\r\n" to "AT\r"). What am I doing wrong?

2.8V is not high enough to register as a high on an AVR input. You will need to use a level converter to raise the TX line of the SIM900 from 2.8V to 5V.

So why it does work with software serial without any problems?

It is very marginal. The additional loading from the USB communication chip destroys this margin.

I see. Thank you for help. I'll use a level shifter as you suggested.

One would think that an idle USB serial chip would actually be pulling the line up thought its series resistor, rather than loading it down.

Arduino with sim900 module is disabled after a day or course sim900 module is completely safe and always receives sms but the Arduino module led after one or more days is no longer able to enable or disable.
#include <SoftwareSerial.h>
SoftwareSerial SIM900 (7, 8);
char incoming_char = 0; // Will hold the incoming character from the Serial Port.
int led_status = 0;
int led1 = 10;
int led2 = 13;
void setup () {
 pinMode (led1, OUTPUT);
 pinMode (led2, OUTPUT);
 SIM900power ();
  Serial.begin (19200); // Set the baud rate
 SIM900.begin (19200); // For GSM shield
 delay (20000); // Give time to log on to network.

 SIM900.print ( "AT + CMGF = 1 \ r"); // Set SMS mode to text
 delay (100);
 SIM900.println ( "AT + CNMI = 2,2,0,0,0 \ r");
 //SIM900.print("AT+CLIP=1\r "); // Turn on caller ID notification

 digitalWrite (led1, LOW); // Set led to LOW
 digitalWrite (led2, LOW);
// Serial.println ( "AT + CMGD = 1,4"); // Delete all SMS in box
}

void sendSMS (char led_status) {// SEND SMS

 SIM900.print ( "AT + CMGF = 1 \ r"); // AT command to send SMS message
 delay (1000);
 SIM900.println ( "AT + CMGS = \" + 9xxxxxxxx \ "\ r"); // Recipient's mobile number, in international format
 delay (1000);
 if (led_status == 0)
    {
      SIM900.println ( "ALARM ON");
      }
else

    {
      SIM900.println ( "ALARM OFF");
    }
  delay (1000);
 SIM900.println ();
 delay (5000); // Give module time to send SMS
}
void SIM900power ()
// Software equivalent of pressing the GSM shield "power" button
{
  digitalWrite (9, HIGH);
  delay (1000);
  digitalWrite (9, LOW);
  delay (7000);

}

void loop () {
// # A1s on & # a0s off
if (SIM900.available ()> 0)
{
incoming_char = SIM900.read ();
if (incoming_char == '#')
  {
  delay (10);
  incoming_char = SIM900.read ();
  if (incoming_char == 'a')
    {
  delay (10);
  incoming_char = SIM900.read ();
  if (incoming_char == '0')
  {
  digitalWrite (led1, LOW);
  digitalWrite (led2, LOW);
  }
else if (incoming_char == '1')
  {
  digitalWrite (led1, HIGH);
 digitalWrite (led2, HIGH);
  }
else if (incoming_char == 'S')
  {
  digitalRead (led1);
  led_status = digitalRead (led1);
  led_status = digitalRead (led2);
  Serial.print (led_status); // Prints status on serial terminal
  sendSMS (led_status);
  }
delay (10);
     }
                        // End AT command with a ^ Z, ASCII code 26

  delay (5000);

  led_status = digitalRead (led1);
  led_status = digitalRead (led2);
  Serial.print (led_status); // Prints status on serial terminal
  sendSMS (led_status);
  SIM900.println ((char) 26);
          }
   }
}

authors: Сергей Ерошкин


text:
Explain what is meant by "Arduino core"
What is an "Arduino core"?
Are there many different "Arduino cores"? such as a core that applies to LCD
displays, another core that applies to servos, etc.?

The Core is the software API for a specific group of chips.
For instance, the AVR core supports the AVR chips found on most Arduino boards. The SAM3X core supports the Arduino Due. Etc.
It is the code that provides things like digitalRead(), analogWrite(), millis() etc.
Since each family of chips works differently that abstraction layer between your sketch and the physical hardware of the chip needs to be different.
In your default IDE installation the Arduino AVR core can be found within the hardware/arduino/avr/cores/arduino folder.
Cores are usually installed as part of a "boards" bundle in the boards manager. This includes definitions for the boards ("variants"), the core and, equally importantly, the compiler and firmware uploading software for the chip on the board.

The "core" provides the low-level APIs (Application Programmer Interfaces) which are documented in the Arduino Reference page. For example, digitalRead, digitalWrite, delay and so on.
The core files usually contain the "include" files from Atmel which provide documented names for the various registers in the chip (eg. DDRB for data direction register B).
Since each chip type will have different addresses for the registers you will need a different core for each processor chip. Also in some cases people have assembled the chip onto different boards, and the cores will reflect how the board is wired. For example "edge pin 8" on one board may connect to a different pin on the processor chip compared to another board. Thus if you buy a board from a third-party they may also supply their own core files.

Are there many different Arduino cores such as a core that applies to LCD displays, another core that applies to servos?

These are usually implemented in libraries which you can optionally include into your code. The libraries extend the core. Often the same library will work with different cores as the core code handles the differences between chips, so that the library doesn't have to.

Selecting a core
As Majenko mentions in his answer, selecting a board in the IDE (Integrated Development Environment) usually tells the IDE to select the appropriate core for that board/chip combination.
More recent versions of the IDE allow you to install more cores by providing a link to where the core files are to be found, and then allowing you to choose one or more cores from that site.

As far as I know the cores are the different products which can be found at Products. In this list the Arduino cores can be selected in the IDE: Cores
LCD display (driver) etc. are mostly referred as shields or modules. A shield is a small 'board' you can stack on top of the Arduino (Core) and a module is normally to be used on a breadboard.

The collection of MCU's that are part of the Arduino family have differences from one to another in features like the address in memory-space of the basic processor registers, the I/O pin assignments to the I/O registers, nature and operation of timers, A/Ds, etc. The kinds of things we do with calls like pinMode(), digitalWrite(), or attachInterrupt().
These are considered the basic or "core" functions to be presented to the programmer by using libraries to present a common interface and hide those differences. The core libraries are managed by the Arduino IDE and the proper one(s) are selected when you select a board-type from the Tools | Board menu.
This is different from the user-contributed and other non-core dependent libraries you keep in your workspace 'libraries' folder. Both kinds are code libraries, but the so-called "core-libraries" are specific to the kind of processor you are compiling your sketch to run on.


text:
How to execute three functions at the same time?
How to implement three functions, which can execute in the same time (function of input random variables)?

You can't. An Arduino only does one thing at a time. The trick is to write your program so it interleaves your functions together.

See my post about How to do multiple things at once

No single processor can do more than one thing at a time. The best you can hope for is that each function runs for a short time only and gives the processor to the next one, giving the illusion that there is more than one thing happening at once. This is called multi-tasking or multi-threading.
There are some libraries that will do this for the Arduino (search "RTOS Arduino" or "Arduino multitasking"), or you can write each functions using the principles of Finite State Machine programming to achieve the same effect.

You can implement three functions but you can't able to execute them same time.

How to implement three functions, which can execute in the same time (function of input random variables)?

Micro-controllers such as the AVR used on Arduino boards have only one processing core but there are many hardware modules (ADC, UART, SPI, TWI, Timers, etc). Using these it is possible to achieve several "functions" at the same time, i.e. pure concurrency.
Some examples, while waiting for ...

ADC (analogRead) there are over 100 cycles
SPI (spi.transfer) there are 16 cycles
UART (Serial) is actually already concurrent with buffering and ISR's.
The same goes for I2C (twi).

These cycles can be used to interleave different functions or improve performance (e.g. pre-fetching, pipe-lining).
Another example; using direct port read it is possible to read the state of several pins at the same time.
With simple collaborative multi-tasking it is possible to context switch between several functions (tasks) on delay or yield. This can be done with a scheduler.

How to implement three functions, which can execute in the same time (function of input random variables)?

have three executors / arduinos, one for each function.

If the result of each function can be expressed as a single byte (i.e. an integer between 0 and 255) then you could:

Connect 3 shift registers (e.g. 74595 ic) to 3 pins on your Arduino
Assign one pin to each function
Use the shiftOut function to output the result of each function one bit at a time on its relevant pin
Use a 4th pin connected to all 3 shift registers as a common latch - when this pin is set HIGH the outputs from the 3 shift registers will all change at the same time.

Or put the three SR's in series, using 2 pins less


text:
Trying to send serial data to computer over network from Arduino Yún
Using Console.write() to send data to my computer over network, which works when I use the serial monitor. However, I'm using PLX-DAQ to receive Serial communication and input it into an Excel document. The problem with that is that PLX-DAQ only has the option to listen over physical ports.
Is there a workaround to this?
If it helps, the computer is a Windows machine.

Do you have the data in the ATmega32U4 (Arduino Leonardo alike part) or in the OpenWrt linux part ? If you have the data in the ATmaga32U4, then connect it to a computer via a usb cable en use the Serial functions. There are usb cables of 10 meters long and they allow even that a few are concatenated. I don't know if a Windows serial driver exists that accepts  data transmitted by Console.write(). I doubt if the Arduino Yun is reliable enough for that. You could have two Arduino boards, one connected to the computer, and communication between them with RF or UDP.

I can send the data through a USB cable, but the whole point is to send the data over a network. Also, I'd prefer not to buy any extra hardware. Thank you though.

Perhaps some kind of "serial over IP" with a virtual serial port on the computer. But I have never used something like that.


text:
Arduino Uno power input - is 5 V at 1 A enough?
I have a Arduino Uno board and phone power bank
Power bank details

Capacity - 8000 mWh
Input  - DC 5 V and 1 A
Output - DC 5 V and 1 A

Can I give the power to Arduino Uno using this power bank, through the Arduino Uno USB?

Already answered https://arduino.stackexchange.com/questions/39041/powering-an-arduino-with-more-than-5-v/39043#39043

I dont see why not - YES you can!
I regularly use usb powerbanks to power projects for testing. so long as you dont ask for too much current (unlikely but project specific) you will be fine!

Short answer:  Yes.
It depends on how you are feeding the power into the Uno and what you are trying to do with it.
My Unos use right at 0.35 amps, as measured by my USB volt/amp meter, until I begin adding things like DHT-22 temperature sensors and maybe a DS3231 RTC, then it will go up a bit.  I can generally just run from USB power.
Feeding power via USB is not a long-term solution in general, since most other USB sources are current-limited to 500 mA.  You could end up building a circuit that works fine on your power supply but not when running on just computer power.
Through testing using metered laboratory power supplies feeding into the barrel connector I am confident that 5V/1A is OK for light work.
And if you are POSITIVE that it is EXACTLY 5V then you can run it directly  into the 5V pin and avoid the regulator, which drops the voltage some.
(Of course, without the regulator you put the board at risk.)
Note that If you are trying to run an anemometer you need 9-12V for power for it.
Also, if you want to run a 432 MHz serial radio you will likely need more than 1A to make them work since they need a couple of hundred milliwatts just for the radio.  1A might work, but USB power certainly will not - (they won't even try to work with just USB power).
In any case, it sounds like you are set up nicely to fire the thing up and start programming.
Have fun!

Rendeverance , SDsolar    Thanks a lot for your information

By the way, the Uno has a really cool way of telling you if it needs more power - it quits working.  Ha!  But it won't hurt it to try.  1A should be good.


text:
Making an H-bridge with transistors
I am trying to make an H-bridge with two NPN and two PNP transistors to drive a motor which works fine on the 5 V Arduino. I have a schematic in the picture. When I use a simple code to have pin 9 HIGH and pin 8 LOW, the motor doesn't do anything. The transistor which I circled green is getting very hot. Is there something wrong with the schematic or code? Or is it my wiring?
I know people use diodes as well, but in my case the motor doesn't work, so the diodes aren't the problem.

This is my code:
     void setup()
    {

    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);

    digitalWrite(9, HIGH);
    digitalWrite(8, LOW);
    }

Could you give the transistors a number please? Do you use the Arduino 5v pin to power a motor? I hope not! You could use 4 pins and carefully write the code to avoid a shortcut. You could add two extra transistors to invert the signal. To turn on the motor you need to turn on the upper-left and the lower-right transistor. Or the upper-right and the lower-left.

I used the 5V to power the circuit. I tried to turn on the motor by connecting the upper-right and lower-left transistor to the same pin on the arduino, it didn't work. I used 4 different pins now and it also didn't work.

Unlike an NPN, a PNP turn on when you pull it's base LOW.

Thanks Edgar, I just found that out 10 minutes ago. So the bottum left en upper-left have to be connected to the same pins. Same for the right transistors.

I was wrong, the 4 pins are not needed and inverting the signal is not needed because you use 5v to power it. @smajli gave the right answer. Connect both on the left to a pin and connect both on the right to a pin, as his first picture shows. The arduino 5v pin can not supply a lot of current, you might run into troubles with that.

I exactly have this problem now. I am making an H bridge to control the steering wheel motor of an RC car which I want to make an obstacle avoiding car using the arduino. When I connect the motor directly to the 5V and GND of the arduino, the motor has enough power to turn the wheels. But with the H bridge it hasn't. What can I do now? I already tried to decrease the resistors at the base, but no succes. I also tried to replace the arduino power pins with a 9V battery and this didn't work as well.

There is a few possible scenarios to create a H-bridge:

with NPN transistors only or PNP
mix of PNP and NPN

You have to be careful to not mix the types and inputs. See pictures below:

Note that, while the Arduino boots, all its I/O pins but TX are configured as inputs, i.e. high impedance. In this situation, with the first schematic, all transistor will be on.


text:
Query related to Serial communication
I have a Raspberry Pi and an Arduino. On my Arduino I wrote a program, if you see the last two functions i.e. getMove() and SendMove() you will see that I am sending a move serially and the RPi will read the string only after it reads start. It is sending it to the RPi through serial communication using a USB (Note: As you can see the Arduino will send the string only one time and not again and again since once it sends the string the control will go into getMove() which waits for "Rstart").
Once I uploaded the code in the Arduino, I opened the serial monitor to check the output that I should be expecting in my RPi. Then I removed the USB from my laptop and connected the Arduino to the RPi and ran the Python code to read the string sent from the Arduino serially and got the string sent. I ran the code again on the RPi and got the string sent.
Now my question is, the first time when I opened the serial monitor on the laptop there was serial communication between the Arduino and my laptop, so I expected the string I sent to have gone to the laptop. So, when I connected the Arduino to the RPi, I didn't expect a string to be received on the RPi since the string was already sent to the laptop. Then again I ran the code on the RPi but still got the string sent.
Can someone explain how Serial communication works? Once I send something from the Arduino serially, will it always be in the serial buffer?
EDIT:
I have understood that unless the DTR pin of the serial connector is disabled the Arduino will keep resetting itself when connected to something new.
Now my question is, why does Arduino reset itself when I run the Python code (to read the serial buffer) again and again?
ARDUINO CODE
#include "LiquidCrystal.h"

const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; // 4 bit mode
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
int SensorValStore_Prev[8][8] = { {0,0,0,0,0,0,0,0}, \
                                  {0,0,0,0,0,0,0,0}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {0,0,0,0,0,0,0,0}, \
                                  {0,0,0,0,0,0,0,0} };

int SensorValStore_Curr[8][8]={ {0,0,0,0,0,0,0,0}, \
                                {0,0,0,0,0,0,0,0}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,0,1,1,1,1,1}, \
                                {0,0,0,0,0,0,0,0}, \
                                {0,1,0,0,0,0,0,0} };
//int SensorValStore_Curr[8][8];
int sum1[8],sum2[8],temp[8][8],k,l,i,j,rank,nextRow;
String file,moveSan,Temp,bestMove;
char Buffer[20];
void doAction();
void ReadSensor();
void Difference();
void binToIntCalc();
void check();
void getMovePlayed();
void SendMove();
void getmove();

void setup()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  pinMode(22,INPUT_PULLUP); // Reed switch - Row1
  pinMode(24,INPUT_PULLUP); // Reed switch - Row2
  pinMode(26,INPUT_PULLUP); // Reed switch - Row3
  pinMode(28,INPUT_PULLUP); // Reed switch - Row4
  pinMode(30,INPUT_PULLUP); // Reed switch - Row5
  pinMode(32,INPUT_PULLUP); // Reed switch - Row6
  pinMode(34,INPUT_PULLUP); // Reed switch - Row7
  pinMode(36,INPUT_PULLUP); // Reed switch - Row8
  pinMode(2,INPUT_PULLUP);// Push Button
  pinMode(38,OUTPUT);
  pinMode(40,OUTPUT);
  pinMode(42,OUTPUT);
  pinMode(44,OUTPUT);
  pinMode(46,OUTPUT);
  pinMode(48,OUTPUT);
  pinMode(50,OUTPUT);
  pinMode(52,OUTPUT);
  pinMode(3,OUTPUT);
  digitalWrite(38,HIGH);
  digitalWrite(40,HIGH);
  digitalWrite(42,HIGH);
  digitalWrite(44,HIGH);
  digitalWrite(46,HIGH);
  digitalWrite(48,HIGH);
  digitalWrite(50,HIGH);
  digitalWrite(52,HIGH);
  digitalWrite(3,LOW);
}

void loop()
{
  //if( digitalRead(10) == 0 )
  //{
  Serial.print("--------------------Initial Matrix-----------------------------\n");
  Print(SensorValStore_Prev);
  // doAction();
  delay(40);
  Serial.print("--------------------Final Matrix------------------------------\n");
  Print(SensorValStore_Curr);
  delay(40);
  Difference();
  delay(40);
  binToIntCalc();
  delay(40);
  check();
  delay(40);
  getMovePlayed();
  delay(40);
  getMove();
  delay(40);
  //}
}

void Print(int matrix[8][8])
{
  for(i=0;i<8;i++)
  {
    for(j=0;j<8;j++)
    {
      Serial.print(matrix[i][j]);
      Serial.print(" ");
    }
    Serial.println();
  }
}

void doAction()
{
  nextRow = 0;
  for(i=0;i<8;i++)
  {
    digitalWrite(38 + nextRow,LOW);
    delay(40);
    ReadSensor(i);
    digitalWrite(38 + nextRow,HIGH);
    delay(40);
    nextRow +=2;
  }
}

void ReadSensor(int iter)
{
  delay(10);
  for(j=0;j<8;j++)
    SensorValStore_Curr[iter][j] = digitalRead(j+2);
  Serial.print("----------------------------------------------");
  Serial.println("Value of sensory board after move is played");
}

void Difference()
{
  for(i=0;i<8;i++)
    for(j=0;j<8;j++)
      temp[i][j] = abs(SensorValStore_Curr[i][j] - SensorValStore_Prev[i[j]);
  Serial.print("-----------------------Difference---------------------------\n");
  Print(temp);
}

void binToIntCalc()
{
  for(i=0;i<8;i++)
    for(j=0;j<8;j++)
    {
      sum1[i] += pow(2,j)*SensorValStore_Prev[i][j];
      sum2[i] += pow(2,j)*SensorValStore_Curr[i][j];
    }
  Serial.print("---------------------sum1 and sum --------------------------\n");
  for(i=0;i<8;i++)
  {
    Serial.print(sum1[i]);
    Serial.print(" ");
  }
  Serial.println();

  for(i=0;i<8;i++)
  {
    Serial.print(sum2[i]);
    Serial.print(" ");
  }
  Serial.println();
}

void check()
{
  k=0;
  l=0;
  for(i=0;i<8;i++)
  {
    if(sum2[i]>sum1[i])
      k = i;
    if(sum2[i]<sum1[i])
      l = i;
    delay(40);
  }
}

void getMovePlayed()
{
  for(j=0;j<8;j++)
  {
    if(temp[k][j] == 1)
    {
      rank =k+1;
      file = String(char(97+j));
      delay(40);
      moveSan = file + rank;
      Temp = moveSan;
    }
  }
  for(j=0;j<8;j++)
  {
    if( temp[l][j] == 1)
    {
      rank =l+1;
      file = String(char(97+j));
      delay(40);
      moveSan = file + rank;
      Temp.concat(moveSan);
    }
  }
}

void SendMove(String movePlayed)
{
  Serial.println("start");
  Serial.print(movePlayed);
  Serial.println();
}

void getMove()
{
  while(1)
  {
    if(Serial.available()>0)
    {
      if(Serial.readString() == "Rstart")
      {
        bestMove = Serial.readString();
        lcd.setCursor(0,0);
        lcd.print(bestMove);
        delay(5000);
        lcd.clear();
        Serial.println(bestMove);
        exit(0);
      }
    }
  }
}

PYTHON CODE
import serial
from stockfish import Stockfish
s1 = serial.Serial('/dev/ttyACM0', 9600)
stockfish = Stockfish('/usr/games/stockfish')
while 1 :
    if str(s1.readline(),'UTF-8').strip('\n\r') == 'start' :
                move_played = str(s1.readline(),'UTF-8').strip('\n\r')
                print(move_played)
                // stockfish.set_position(move_played)
                // print("Rstart")
                // print(stockfish.get_best_move().encoded())
                break

the Arduino resets on new usb connection. and of course at power-up setup() runs

new usb connection is serial.Serial('/dev/ttyACM0', 9600)

It would help to see your code but bear in mind when you connect the serial monitor to your arduino it resets so any code will re-run

true, but the connection from PI resets it too

The arduino doesn't know what's connecting to it, opening the serial port from anything will reset it unless asserting the DTR pin on the serial connector is disabled by whatever is connecting. A quick google seems to indicate python on the pi can't reliably disable DTR but a hardware solution could be implemented

@Ba1n,@juraj I understand that the arduino re-runs, when conected to the rpi or serial monitor. But why does it re-run if I run the code on the rpi again. Shouln't it give back an error that it can't read anything from serial?


text:
How can I power a servo and Arduino from the same power supply?
I have an ESP8266 NodeMCU which I'm using for an automatic blinds project. The NodeMCU struggles to power the servo on its own, so at the moment I am using a 5 V supply for the servo and a USB cable for the NodeMCU (with a common ground).
The servo is an inexpensive MG996R which is rated up to 7.2 V I've read that NodeMCU can take 5-10 V on the VIN pin.
After I'm done prototyping, I want to only use one power supply. What could I use? Ideally it would be something with just a wall adapter and then I can cut the other and connect that to servo and MCU.

Wire the +5 and Ground from the supply to both the ESP's Vin & Ground and the servo's Vin & Ground. The only thing you have to avoid is trying to power the servo through the ESP.

You might be better off using an external supply with a voltage regulator like an LM7805. It would also be wise to add a protection diode to your servo motor if it does not already have one so that the microcontroller does not get damaged by any flyback voltages. The key thing to remember when running a supply from an Arduino is that it's on board supply current capabilities are very limited, especially in the case of a motor or servo. Good luck, I hope this helps, I recently replaced the blinds in my home and was thinking to build something similar myself!


text:
Sensor TSL2591 with Arduino Mega
I have three light sensors  TSL2591, of signal I2C, that I need to connect (together) to an Arduino Mega. However, I'm not very sure of how share the SDA and SCL pins of the three sensors and I don't know how to change their address for the Arduino to read and show the data of each sensor.
I have already read sensor's datasheet but there is not much information about this.

 there is not much information ... what information is there? ... also, please add a link to the data sheet to your question (do not put the link into comments)

Looking at the datasheet, the TSL2591 does not appear to have a comfigurable address mechanism, therefore you are most likely obliged to use an I2C Multiplexer.
One example of such a device is the TCA9545A, Low Voltage 4-channel I2C and SMbus Switch With Interrupt Logic and Reset Functions, that can split one I2C line into 4 buses.

They are very easy to use and the pinout (and datasheet) are self explanatory.
Don't forget that you will need 3k3 Ω resistors on the INT, RESET, SDA and SCL lines from the Arduino and on each of the INTx, SDx, and SCx lines from the TCA9545A:

Adafruit has a module with the TCA9548A. The advantage is that these multiplexer chips will also do level shifting for sda and scl. That is needed because the arduino mega is a 5v board and the sensor is a 3.3v sensor. An arduino mega has 10k pullup resistors. Pullup resistors for all the sensors should still be added if they are not on the tsl2591 module.


text:
ATmega328P SPI Slave
I was scrolling through the ATmega328P datasheet when I came across a rather fascinating statement about the way in which the data part of the SPI interface is buffered. I can't seem to understand why the double input buffer is necessary. The following statement can be found on page 161 (Datasheet):

The system is single buffered in the transmit direction and double buffered in the receive direction. This
  means that bytes to be transmitted cannot be written to the SPI Data Register before the entire shift cycle
  is completed. When receiving data, however, a received character must be read from the SPI Data
  Register before the next character has been completely shifted in. Otherwise, the first byte is lost.

Can someone please briefly explain to me why the double input buffer is necessary?

You have control over when you place a byte in the TX buffer and control over when you read a byte from the RX buffer. You don't have control over when the master sends data to you, though, so somewhere is needed to store that incoming data until you read it. Since the master can start sending another byte before you have read the last one it's critical that the receiving shift register is separate from the register you read the shifted in data from.  Only when the complete byte has been shifted in does it get copied to the receive buffer, so that another shifting in can begin.
When transmitting you don't need to worry about that since what you write into the TX buffer is what is about to be shifted out. You don't write anything else until it's time to send the next byte, at which point the TX register is empty anyway.

Aaah thanks! I guess this due to the fact that the SPIF flag is only set upon receival of a complete byte? Therefore (if enabled by the SPIE bit in SPCR) the corresponding ISR is only executed after the last bit in that byte.

That is correct.


text:
Tiny RTC module doesn't work properly when connected to an Arduino Uno together with 16x2 LCD
I am trying to make a digital clock using a tiny RTC, 16x2 LCD, and Arduino Uno. The RTC module works fine if 16x2 LCD is not connected to the Arduino. Both RTC and LCD are I2C modules and hence are using the same A4 and A5 pins of the Arduino. I have been informed that the I2C devices if connected in parallel should work. But, in this case, the clock doesn't show the time properly.

Have you checked that the i2c addresses are different? A schematic and minimal program that demonstrates the error would be useful.

Yes, I did and found that the addresses are different (LCD: 0x3F and RTC: 0x50 and 0x68). The addresses for RTC is reasonable since it has an EEPROM memory builtin.

Without more information we won't be able to help you.  Add a schematic and a minimal program that demonstrates the problem.

Thank you for your quick response. It was my fault that I pulled out the battery from the RTC module for a short time that ultimately reset the module.

An I2C scanner sketch can help to identify the actual addresses in use. I would use a sketch like on this page https://playground.arduino.cc/Main/I2cScanner or on this page http://gammon.com.au/forum/?id=10896&reply=6#reply6 . Or google 'arduino i2c scanner'.
Hook up the RTC by itself and run the scanner, then hook up the LCD by itself and run the scanner. The output will be on the serial monitor. If the devices have the same address, then that is your problem.
If one of the devices does not show up at all, then perhaps it is defective.

Thank you for the valuable information. I scanned the i2c device and found that they have different addresses.

I am incredibly sorry for my messy work. It all started when I pulled out the battery from the RTC. I was so frusted that I forgot to test the RTC module alone again. When I tried a different RTC, then that worked perfectly even with LCD. I found that the time can be adjusted as RTC.adjust(DateTime(F(__DATE__), F(__TIME__))); but, that also resets the time when the Arduino's reset button is pressed.

I find so often that I learn something unrelated to what I'm actually trying to do.


text:
How to produce multiple DC voltages for a single project
So the title pretty much says it all, but for an example, I have an arduino board, 5-12 V, an LED bank 18 V, and an ultrasonic mister 24 V.
I know some brute force methods to power them from one outlet, but I was wondering if there is a more elegant way to get the voltage for each device with only one transformer instead of three. The solutions I've come up with are less than elegant, and only moderately compact.
I was just wondering what solutions you guys have employed and hoped I could find something helpful.

First you want to take a regulated 24V supply. To that you want to add a switch-mode ("Buck") regulator to drop you down to 5V.  You don't want to try using an LDO for this unless you are happy to have a heat sink the size of a small car. A good cheap choice is a "UBEC" that can take 24V in and give 5V out (I use these).
That 5V can then be fed direct into the Arduino.
Depending on what the "LED bank" is you may get away with an 18V (or adjustable) LDO, or an adjustable buck regulator. Or a simple (though high wattage) resistor may be all that is needed. You will have to provide more detail on this to get more help.

Typically you'll only have a single transformer in this sort of design, to get you down to your highest DC voltage. Then you'll create lower voltage rails from that. You can use any number of approaches depending on your needs, e.g. capacitive dropper (on the 24Vac output of the transformer), resistor divider (on your rectified 24Vdc).
But, most typically for hobbyist projects you'll want to be using a regulator IC, either a linear regular/LDO (low noise but poor efficiency) or a separate onboard SMPS IC (good efficiency but typically noisy).


text:
How to calculate air velocity from wire resistance?
I want to construct a constant current hot wire anemometer. For this, resistance is the input of the Arduino. There is a relationship between wire resistance and air velocity.
How can I calculate velocity from wire resistance?

This is a very interesting question, but I am not sure how Arduino related this is, apart for you are using an Arduino. I think that you would get a better  response by asking a separate, non-Arduino related question on SE Physics first, to get an equation to use. Once you have that, then, maybe, come back here to ask how to put that equation/formula into an Arduino sketch.

Do you already have an equation? If so, edit your question to include it. What research have you done so far? What code do you already have? What is not working, exactly?

OK You have a theory, test it.  Its not going to take much to hook a wire up to an analog port and measure the changes in resistance.  You are probably only going to get minute changes so you will need to alter the other parameters to cater for it, and its possible that they might be outside the limits of what an Arduino can handle.

I think that, for this to work, you also need to measure the ambient temperature. You also need the temperature to resistance curve of the wire you are using.

Its very simple really, all you need to do is code the equations on this page and then supply some heat and you will be able to do it.  Just remember integer division rounds down :)
http://www-g.eng.cam.ac.uk/whittle/current-research/hph/hot-wire/hot-wire.html


text:
Access serial monitor on linux cli? Using arduino-cli?
I have an Arduino Uno connected via USB to a Raspberry Pi. The Raspberry Pi is accessible via SSH only.
Just started a bit with arduino-cli. I upload a sketch which reads my analog pins. How can I access the serial monitor to get the data?

I'm trying to upload a program for serial communication with 9600 Br with 1sec delay.
but this error is avrdude: stk500_recv(): programmer is not responding what should I do?

@user137442, Welcome! Placing a question in the comments section under an existing one, will probably not get your question answered. Please consider asking a separate question once you've made sure your question has not been answered elsewhere on Arduino Stack Exchange.

Programs such as screen, minicom or (my favorite)
picocom are useful if you want bidirectional communication
between the Arduino and the host computer. If you only want to read
what the Arduino sends, that can be done with cat:
stty -F /dev/ttyACM0 raw 115200
cat /dev/ttyACM0

I use minicom.
$ sudo apt-get install minicom
... blah blah blah ...
$ minicom -D /dev/ttyACM0 -b 115200

Minicom can take a bit of getting used to. Use CTRL-A to initiate a command sequence. CTRL-A X is exit. CTRL-A O is configuration ("Options") where you can configure flow control and such.
Many people also use screen to do the same job, but I like the interface that minicom gives - it's more terminal-like.

thx! Forgot about that, I knew it and also screen. Obviously did a bad job at web search on the topic :P

And how do you send "Hi Arduino" to the Arduino board?

@user171780 With minicom? Just type it when connected. With screen? Just type it when connected. From the command line? echo "Hi Arduino" > /dev/ttyACM0

If I type and hit enter, nothing happens. I only see whatever Arduino sent (after reset) but he is not listening to me (so no answer either).

@user171780 Unless you have programmed your Arduino to echo back what it receives you won't see anything. Without knowing what your code is I cannot help you.

I also had the problem that arduino-cli includes no serial monitor. I tried out screen, minicom and other but they are a bit difficult to get used with them. So I created a small python script which works as an serial monitor in the command line:
https://github.com/PBahner/Serial-Monitor

You can easily access the monitor with Arduino CLI:
arduino-cli monitor [flags]

For example, you can use this command for Arudino UNO:
arduino-cli monitor -p /dev/ttyACM0 -b arduino:avr:uno

Using this, you can get the values you read from the analog pins on the Arduino UNO via the serial monitor. You can view the Arduino CLI documentation about using the monitor here.

Note that this tool is very poorly documented. You can get out of it with Ctrl-C.

I absolutely agree that the documentation is very poor, I think there is not enough explanation in the documentation. But it's still useful, isn't it?


text:
There is no PWM output
I recently made a project where output is coming from the differential between data reading and reference value. It works on my Proteus simulation but there is no PWM output on my real world device.
Here is my code listing
for (z = 0; z <= output2; z++)
  if (output2 >= 30) {
   toggle == HIGH;
   en = !en;
  }
if (en == true) {
  OCR1A = map(z, 0, 255, 0, ICR1); ;
  OCR1B = 0;
} else {
  OCR1A=0;
  OCR1B = map(z, 0, 255, 0, ICR1);
}
if (output2 < 30) {
  en = !en;
  analogWrite(9, 0);
  analogWrite(10, 0);
}

What do you want to achieve by calling map()? Do you know what OCR1A/B are and how the analogWrite() function works?

i saw from other program that is for setting up the carrier frequency, so if icr1=1600, 0-255 = 0-10khz, cmiiw,

I’m not sure what you’re trying to accomplish, but you’re writing a constant 0 to the analog output.

if (output2 < 30) {
  en = !en;
  analogWrite(9, 0);
  analogWrite(10, 0);
}

To quote the analogWrite() doc

Syntax
analogWrite(pin, value)
Parameters
pin: the pin to write to. Allowed data types: int.
value: the duty cycle: between 0 (always off) and 255 (always on). Allowed data types: int

If you want to see an output, you have to write a value between 0 and 255.

yes it is purposely gives 0 cycle when the output is less than 30


text:
Using Arduino microcontrollers without board
I am new into Arduino. So if I program the microcontroller using the Arduino board and once it is doing what I want can I just take the microcontroller out of the board and use the microcontroller itself? If so could you please guide me to some tutorials on how to use it?

You prise the chip out of the board? What part are you wondering about?

@NickGammon Yes I meant taking the chip out and use it as you explained on your answer. Thank you very much!

@per1234 please stop making trivial, unnecessary edits to old questions.  It adds nothing, but uselessly bumps them to the top of the main page, stealing attention from topics that legitimately deserve attention.

I have a post about a breadboard Arduino - in that I demonstrate the minimal amount of parts you need to use the controller (which is not much).
Example of wiring it up:

If you want to use an external crystal or resonator you can add that to the board like this:

8 MHz crystal shown, but you could use 16 MHz. Or change the fuses and use the internal oscillator.

Schematic showing how you could (if you wanted) add an ICSP header and an FTDI header:

One quibble regarding that first picture being minimal ... what's your rationale for having a 10KΩ pullup on Reset instead of depending on the internal pullup? (30K-60KΩ, per Electrical Characteristics specs table 30.2, DC Characteristics)

There were reports of unreliability with only the internal pull-up, but certainly you could try omitting it. I notice you didn't ask me about the diode. ;)

I agree though, for minimal you may as well omit the 10k resistor.

I assume the diode keeps charge on C3 from pushing reset up to about 10V as RTS goes from low to high and also allows C3 to discharge so RTS can pull Reset low for automatic reset in programming

That's roughly it. In certain cases /Reset was being pushed high enough for the chip to enter High Voltage Programming mode, and thus was unresponsive to attempts to program it via the bootloader.


text:
Arduino Mega failure after first use of Mega Shield power connector
I have an XDRduino Mega clone with ATmega2560 and ATmega16U2 USB support chip.  I also have a Sensor Shield (same vendor), which provides screw terminals to Vin and Ground.
I connected the board with USB, loaded "Blink", and then changed the time interval.  Next I connected a 20x4 LCD using the Sensor Shield and a breadboard and loaded LCD "Hello world".  All seemed fine with the new board.
Each time I powered on or reset the Mega, the TX and RX LEDs flashed a couple of times and then my sketch started running.
Then I disconnected it from the PC (no USB for power anymore) and connected a (working from another project) S-60-12 power supply, DC Output 12V 5A to the shield screw terminals.  I verified polarity -V to GND, +V to VCC.
OK, I swear I hooked it up correctly.  But if you tell me that hooking it up backwards would explain all the symptoms below, then yes I'll believe you that I screwed up {sob}.
(And yes, you're right, there is no diode protection on Vin, just on the dc power jack.  Dummy me.  Double dummy me, as there was a screw type power plug laying unused on the bench {groan}.)
About 4 seconds later, I heard a snap and immediately pulled the plug on the power supply.  Yes, something probably smoked, but let's refine at bit, please.
I moved the Mega to my PC, (disconnecting the external power supply so to use only USB for power).  It is no longer recognized as a USB device, and the Arduino IDE (1.6.5) no longer finds the USB serial port.
Voltages at 3.3V pin and 5V pin are correct.  I've also probed the regulator and comparator and all looks well for the power circuitry. F1 is not blown (or there would be no power as USB is the only source).
Item: The TX and RX leads are on solid.  I expected them to flash then turn off.  (Power LED is on solid, which is normal.)
Item: The reset pin for the Mega reads 1.41 V.  It's connected through a 10K pullup to +5 V (reads 4.63 at USB pin, 4.53 at the 5V pin).  This seems way too low.
Item: The reset pin for the 16U2 reads V+ (4.35) and is has a 10K pull-up.
Item: AREF is 50 mV.  I believe it should be 1.1 V or 2.56 V.
Question: Is it reasonable to think the 2560 may be dead, and the LEDs are on because the 16U2 can't talk to it?  Any way to test this theory?
(If the 16U2 were bad, it would still be possible to program the 2560 via the ICSP header, thus salvaging something...)
Question: The 16U2 won't do the USB connection dance with the PC because the 2560 is dead?  Should the 16U2 to try to connect no matter what the state of the 2560?.
Question:  If the 16U2 is dead, should TX and RX LEDs be lit?
Question:  If I had reversed the hookup, should not the regulator (P1117 chip) have saved me?
Question:  Has anyone else had a failing component (other than the 2560 & 16U2) with these symptoms?

Are you sure the shield takes 12V? You didn't supply a  link to its circuit diagram. I suspect it is intended for 5V.

The shield is just a giant break-out box.
It contains no active and only two passive components (LEDs and their current resistors) replicating those on the Arduino itself (because installing the shield hides them).
All the rest is header pins and edge connectors and PCB traces.  For example, the power terminals I used to connect the supply just feed back to Vin and Gnd.

@jippie
I lied.  There is also a push button switch replicating the reset button on the base Audrino because the shield covers the base.
BTW, the shield was "clean".  I'd removed all the leads to my breadboard, so only the pins were showing.  And there wasn't a paper clip or wire shard visible (to me) that could have shorted the pins.
The shield still works, to the extent that the power led lights (on both the shield and the Arduino itself).
Link to shield board.

How did you verify the power strip is connected to V(IN)?

Excellent question.  I trusted the internet instead of metering it out.  DummyPoints++.  Taking meter in hand, power goes straight to +5v.  It doesn't go to Vin.  Much is explained!!!

I want to make this obvious to the casual reader:  Mega Sensor Shields -- all versions I've data on -- run the power connector to +5V.
The power connector is not power in, as defined by the base board.  In fact, there is no direct way to get to the base board regulator from the shield.  (A pin exists for Vin, but it isn't connected to anything on the shield.  It's mechanical support.)
It's intended to supply more current to devices connected via the shield than the base board does.
There is a jumper that disconnects the sensor shield +5 rail from base board power to allow independent +5 volts distribution to the shield attached devices.

If what i read is correct, then you've probably cooked your duino.
As for what exactly failed, i'm going to guess from your description, that one or both of the capacitors failed. Usually when they blow, you'll hear a loud snap like you describe.
I would suggest testing those, and replacing them if they are faulty.. This is no guarantee that other components weren't damaged, but it's a good place to start.
As for why the LED's may still light up, that could be any number of reasons really, and not a particularly good indicator of what exactly failed.

You're right, it's cooked.  Both chips got 12v right through Vdd/Vcc, cause I didn't verify that "power" meant Vin.  LEDs must be on because the chip pins/paths "melted" to ground.


text:
Connect GPS module with GPS antenna SIM39EA to Arduino Uno
I bought a GPS module with GPS antenna SIM39EA online.
The manual for the GPS module is here:
http://www.vis-plus.ee/pdf/SIM39EA_Hardware_Design_V1.00.pdf
I have an Arduino board. It has 3 ground pin, one Vcc and two input/output pin.
I want to know how can I connect this module to Arduino GPS module and get GPS coordinates?

Please post a link to the board datasheet, or at least some information about it. Which Arduino do you have?

here it is the manual of gps module please use this link to download manual   www.vis-plus.ee/pdf/SIM39EA_Hardware_Design_V1.00.pdf     I am trying to connect it  with Arduino UNO R3 board with DIP ATmega328P

Your data comes back via the GPS's UART port.
Use the softserial library to create a second serial port on your Arduino (means you can still use the normal serial to read the console).
Then write a program that sucks data from the GPS and squirts it out of the Arduino serial port back to your PC using printf.
I only had a quick flick through and didn't see the default serial speed, so start with 9600 and experiment.
What should come out is probably a line of comma separated values which is in NEMA format.  Google for the specification and you will be able to find out the bits of interest.
Hope that helps.


text:
HTTP POST/ METHOD to Emoncms doesn't work
So Ive setup the emoncms on my server and posted the example power1:100…power3:300 JSON POST and it logged in my INPUTS.
Now Im trying to send data from my arduino and it seems to post fine, but when I go to the INPUTS its not there for some reason.
Here is my code. Im just posting a temperature value to a new node:
#include "SoftwareSerial.h"
//For DHT22 Grove Pro
#include "DHT.h"
#define DHTPIN A1     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);

String ssid ="myssid";
String password="mypassword";
String server = "www.santiapps.com"; // www.example.com
String uri = "/emoncms/input/post.json";// our example is /esppost.php
#define EMON_APIKEY F("myapikey")

byte dat [5];
String temp ,hum;
String data;
char dataString[200];

SoftwareSerial esp(6, 7);// RX, TX

void setup() {
  esp.begin(9600);
  Serial.begin(9600);
  Serial.println("setup");
  reset();
  connectWifi();
}

void reset() {
  Serial.println("reset");
  esp.println("AT+RST");
  delay(1000);
  if(esp.find("OK") ) Serial.println("Module Reset");
}

void connectWifi() {
  Serial.println("connect to wifi");
  String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
  esp.println(cmd);
  delay(400);
  while (esp.available()){
     String inData = esp.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }

  if(esp.find("OK")) {
    Serial.println("Connected!");
  } else {
    connectWifi();
    Serial.println("Cannot connect to wifi"); }
}

void start_test () {
  //For DHT22 Grove Pro
  static char outstr1[15];
  static char outstr2[15];
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  dtostrf(t, 8, 2, dataString);
  Serial.println(dataString);
}
void loop(){
  Serial.println("loop");
  start_test();
  httppost();
  delay(100000);
}

void httppost () {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
  if( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }
  delay(1000);
  String postRequest="POST " + uri + " HTTP/1.0\r\n"+"Host: " + server + "\r\n" + "Accept: *" + "/" + "*\r\n"+"Content-Length: " + strlen(dataString) + "\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n"+"\r\n" + "&node=fortnite&data={a:" + dataString + "}" + "&apikey=" + EMON_APIKEY;
  Serial.println(postRequest);
  String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.
  esp.print(sendCmd);
  esp.println(postRequest.length());
  delay(500);
  if(esp.find(">")) {
    Serial.println("Sending..");
    esp.print(postRequest);
    if(esp.find("SEND OK")) {
      Serial.println("Packet sent");
      while (esp.available()) {
        String tmpResp = esp.readString();
        Serial.println(tmpResp);
      }
      // close the connection
      esp.println("AT+CIPCLOSE");
    }
  }
}

Here is my Serial Monitor:
setup
reset
connect to wifi
Got reponse from ESP8266: AT+CWsetup
reset
Module Reset
connect to wifi
Got reponse from ESP8266:
Got reponse from ESP8266: CLOSED
Got reponse from ESP8266: WIFI DISCONNECT
Got reponse from ESP8266: `BԄQR���ȤRN�ɤRN�H��OAT+CWJAP="tha
connect to wifi
Got reponse from ESP8266: %J:E
Got reponse from ESP8266: HըRP=“myssid”,“mypassword”
Got reponse from ESP8266: busy p…
connect to wifi
Got reponse from ESP8266: AT+CWJAP=“myssid”,“mypassword”
Got reponse from ESP8266: busy p…
Got reponse from ESP8266:
Got reponse from ESP8266: O
connect to wifi
Got reponse from ESP8266: AT+CWJAP=“myssid”,“mypassword”
Got reponse from ESP8266: WIFI DISCONNEC
Connected!
Cannot connect to wifi
Cannot connect to wifi
Cannot connect to wifi
loop
31.00
TCP connection ready
POST /emoncms/input/post.json HTTP/1.0
Host: www.myserver.com
Accept: /
Content-Length: 8
Content-Type: application/x-www-form-urlencoded
    &node=fortnite&data={a:   31.00}&apikey=mykey
    Sending..
    Packet sent

    +IPD,422:HTTP/1.1 200 OK
    Server: nginx
    Date: Tue, 02 Oct 2018 21:38:18 GMT
    Content-Type: application/json
    Connection: close
    X-Powered-By: PHP/5.4.16
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    Pragm

Here is a snapshot of the posted data when I used this URL directly in my browser:

http://santiapps.com/emoncms/input/post?node=emontx&fulljson={"power1":100,"power2":200,"power3":300}&apikey=mykey
￼=========
Based on jose's suggestion:
I changed this code to:
void httppost () {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
  if( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }

//  //CODE USED TO BUILD COMPLETE STRING
  String apiKeyString="apikey=";
  apiKeyString.concat(EMON_APIKEY); //JOIN PARAMETER LITERAL STRING => String Object
  //Serial.println(apiKeyString); //THIS IS NOW A STRING OBJECT
  String nodeData="&node=fortnite&data={\"a\":";
  String combinado=apiKeyString+nodeData; //COMBINE BOTH PREVIOUS STRING OBJECTS
  String finalData=combinado + dataString + "}"; //COMBINE STRING OBJECT WITH CHAR[]
  Serial.println("finalData");
  Serial.println(finalData);
  //unsigned int tamano = strlen(dataString);
//  char postThis[100] = finalData;
//  //ADDING THIS TO POSTREQUEST +finalData; && changing length for strlen(finalData)

  delay(1000);
  String postRequest="POST " + uri + " HTTP/1.1\r\n"+"Host: " + server + "\r\n" + "Accept: *" + "/" + "*\r\n"+"Content-Length: " + finalData.length() + "\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n"+"\r\n" + finalData;
  Serial.println("postRequest");
  Serial.println(postRequest);
  String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.

but now I dont even get the HTTP200OK response.  The result is:
loop
31.30
finalData
apikey=myKey&node=fortnite&data={"a":31.30}
postRequest

Your Serial monitor output shows the content of the POST as:
&node=fortnite&data={a:   31.00}&apikey=mykey
I can't tell if the & are actually in your serial monitor, or if your copy/paste did some kind of HTML format attempt, but & is wrong and should be &
Your JSON data is not proper JSON
{a:   31.00}
should be
{"a": 31.00}

Strangely, your serial monitor output also writes Host: www.myserver.com, which doesn't match your code, where server was assigned www.santiapps.com, so that makes it difficult to trust that the serial output you show actually came from the code.

Ok I fixed the & format issue, it was indeed copy/paste problem.  It is the proper output, I just went through it and replaced ssid, password, apikey and server name.  Everything else is the same.  How do I get the "" around the letter a?  Im trying this: "&node=fortnite&data={" + "a:" + dataString + "}"; but I get this => &node=fortnite&data={a:29.00}

You can escape the quote character with a backslash: "&node=fortnite&data={" + "\"a\":" + dataString + "}"

Thanks, one last thing, it was brought to my attention that my Content Length for the POST request needs to be the length of everything from &node....up until the json data...{"a":29.40}.  Could that be the cause of the post not working?

You send a content-length generated by strlen(dataString). This is not quite right. The HTTP Post payload portion is found in this part of your code: &node=fortnite&data={a:" + dataString + "}" + "&apikey=" + EMON_APIKEY. Calculate the length of that to find the content-length. I also noticed that you start your POST content with &, but you don't need one at the beginning. It is just to separate fields, like node=fortnite&data={a:" + dataString + "}" + "&apikey=" + EMON_APIKEY

I added my most recent try but it also fails to post.


text:
Normally-Open opto-coupler board
I'm looking for a Normally-Open optocoupler board for arduino. I need to control power of a device (DC 12v, 500mA).
I tried to use TLP281 board, which works, except that it inverts the output: device is powered when there is no control signal (i.e., it is Normally-Closed).
For this reason, the TLP281 board is not useful in my project.
This is picture and schematics for TLP281 board:

I need an optoisolator board which works analogous to normally open mechanical relay: when there is no signal, device must not be powered; and when there is signal, device must be powered.
NOTE: workaround by inverting the control signal in microcontroller firmware is not permitted, as the device must not be powered when microcontroller is off

@JaromandaX Do you know a schematic which explains how to create Normally-Open relay based on TLP281 (or any other opto-isolator)?

@JaromandaX I tested it and I can say for sure that this board inverts the signal (on low input, there is power on output, on high input, there is no power on output).

I think every driver does what you want, only this one has it inverted. What is the device? A motor? Do you need pwm to control the speed? This could be a normal driver: https://www.aliexpress.com/store/product/Mosfet-MOS-Optocoupler-Isolation-Driver-Drive-Module-Field-Effect-Transistor-Trigger-Switch-PWM-Control-Controller-Board/612195_32860424049.html There are similar modules for 4 and 8 channels.

@Jot the device is Panasonic KX-TCD245, I need just to turn it on or off.

@JaromandaX the links that you give are for the same board which is in OP - it is Normally-Closed - I need Normally-Open

@JaromandaX let's use just the terms "Normally-Open" and "Normally-Closed" - that would be less confusing

looking closely at the circuit diagram .... if nothing is connected to INx or INx is "LOW", then OUTx will be at HGND - when INx is "HIGH", OUTx will be HVCC... this is exactly what you want  - there's no "open" or "closed" - if it's not working, then it's how you've connected your circuit to that board that is the problem - i.e. the circuit you haven't shown is the problem - the "relay" you've shown looks wrong because there's only two connections to it - so perhaps that's another problem

is hacking the TLP281 board an option for you?

@jsotola I don't mind hacking the board if I understand how

talking about only one channel here, repeat 4x if needed ....... basically, insert the photo-transistor in series with the base pullup resistor of Q1, and add a pulldown resistor to the base of Q1 .... that way Q1 turns on when input signal is present ......... cut the trace between Q1 and R2/IC1_pin16 ...  disconnect IC1_pin15 (emitter) from GND and connect to Q1 base ..... connect 5kΩ pulldown resistor between Q1 base and GND

I don't think there is a need for a specific "normally-open" opto-coupler. Same result can be easily achieved by using "normally-closed" opto-coupler and making a slightly modified "NOT" logic gate using three resistors and NPN transistor.

1. When INPUT is LOW:
Base of Q1 is shorted to ground through R1 so Q1 not letting the magic pixies go through. This makes OUTPUT show 5V and be in HIGH logic state.
2. When INPUT is HIGH:
Base of Q1 is powered by voltage divider R/R1. R needs to be much lower than R1 to keep Q1 saturated. This makes Q1 to be passing current and setting OUTPUT to LOW state by creating a voltage divider R2/Q1(collector-emitter resistance) This means that value of R2 should be much higher then c-e resistance of Q1.
3. When INPUT is floating (microcontroller is turned off):
Any voltage on INPUT caused by imperfections of the hardware, E-M noise induction, static electricity, etc. should be discharged to ground by resistors R+R1 keeping INPUT in LOW state. (This means that R+R1 cannot have to high value or the discharge speed might be to slow)

There is a problem with your solution: microcontroller is powered from USB, so the "5V" in your scheme will not be there when microcontroller is off. Thus, changes must be made to "output" side of optocoupler, not to "input" side.

If you use tougher npn transistor (for example the same one as uour opro-coupler) and higher resistor values (similar values as your opto-coupler) you can use this with 12V power source. You can remove R1 then because right side is never floating.

If I understand you correctly, you are suggesting something like this, right? http://www.ti.com/lit/ds/symlink/uln2003a.pdf

Actually I was suggesting that you simply get S8050 transistors (100 for 1 USD) and 5.1K resistors (100 for 0.70USD) and make a NOT gate with identical load bearing properties to the opto-coupler you shown. I assumed that you use that opto to steer a MOSFET since anything spiking above 500mA could burn it anyway (S8050 used in opto is rated for max 500mA)

For those, who are stumbling over this old thread and @igor-liferenko, since this board is still quite common:
This board definitely does NOT invert the inputs.
The comment of Igor Liferenko "tested it and I can say for sure that this board inverts the signal (on low input, there is power on output, on high input, there is no power on output)." is wrong. I don't know what he has tested, but both the schematics and tests show, that the board does not invert (or actually inverts twice -- once by the TLP281-4 itself and once by the following S8050-transistors).
So: low on input -> low on output; high on input -> high on output.


text:
Why does timer1 not generate correct period on CTC mode with a resolution of 5us?
I have defined my code to generate an interrupt over each 5μs on CTC mode using timer1 but the output shows a time of ~15μs.
Following the equation to set the counting number to achieve the desired time
(# timer counts + 1) = (target time) / (timer resolution)

I've got OCR1A = 79 for a desired time of 5μs using no prescaler and a source clock of 16MHz on Arduino Uno.
My code is as follows:
// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>

#define LEDPIN 9

void setup()
{
    pinMode(LEDPIN, OUTPUT);
    digitalWrite(LEDPIN, HIGH);

    // initialize Timer1

    cli();          // disable global interrupts

    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    OCR1A = 79;

    // turn on CTC mode:
    TCCR1B |= (1 << WGM12);

    // Set CS10 bit for no prescaler:
    TCCR1B |= _BV(CS10);

    // enable timer compare interrupt:
    TIMSK1 |= (1 << OCIE1A);

    sei();          // enable global interrupts

}

void loop () {}

ISR(TIMER1_COMPA_vect)
{
  digitalWrite(LEDPIN, !digitalRead(LEDPIN));
}

This is the output from my logic analyzer:

Is it a limitation of the Arduino or am I missing something?
My idea is to generate a PWM manually to control a servo motor using timer1 and precisely increase the period by 10μs during "on" time and get the desired angle.
After some experiments, I have discovered that my motor (MG996R) has a range from 0.6ms to 2.1ms during "on" time to move from 0 to 180 degrees.
I have tried the Arduino's Servo library but it goes far than 180 degrees (I don't know why). That's why I am building my own code for that purpose.

79 clock cycles might no be enough to execute all the ISR code.

@Gerben, do you any idea how to solve it instead?

I got it working just analyzing time consumption of digitalWrite and digitalRead functions. They took around 13us to execute (each one), so this added up a few extra undesired microseconds to the final period.
Instead, I set up digital output using DDRD for configuring and PORTD for setting the desired output, which results in approximately 1us to set the output value (HIGH or LOW).
I changed the prescaler to 8 and the code below shows how to get a 100kHz wave output with 5us duration of "on" time using timer1 CTC mode.
void setup()
{
    DDRD = B00001000; // pin 3 as output
    PORTD &= ~_BV(PORTD3);   // set 3 as LOW

    // initialize Timer1

    cli();          // disable global interrupts

    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    OCR1A = 9;

    // turn on CTC (Clear Timer on Compare Match) mode:
    TCCR1B |= (1 << WGM12);

    // Set CS10 bit for clk/8 prescaler:
    TCCR1B |= _BV(CS11);

    // Output Compare A Match Interrupt Enable
    TIMSK1 |= (1 << OCIE1A);

    sei();          // enable global interrupts

}

ISR(TIMER1_COMPA_vect)
{
  PORTD = ~PORTD;
}

Glad to see you got it working.


text:
Servos don't move
I made simple code for a robotic arm, but the servos don't seem to be reacting at all. I made debug code before all the if statements, and those aren't working. I made sure my wiring was good and it is.
#include <Servo.h>

Servo release1;
Servo release2;
Servo updown;

int pos = 64;    // variable to store the servo position
int pos2 = 85;
int val = 0;
int val2 = 0;
int val3 = 0;

void setup()
{
    release1.attach(8);
    release2.attach(9);  // attaches the servo on pin 9 to the servo object
    updown.attach(10);
    release1.write(pos2);
    release2.write(pos2);
    updown.write(pos);
}

void loop()
{
    val = digitalRead(4);
    val2 = digitalRead(5);
    val3 = digitalRead(6);
    pos++;
    pos2++;
    if(val = LOW){
        pos = pos + 15;
    }
    if(val2 = LOW)
    {
        pos = pos - 15;
    }
    if(val3 = LOW)
    {
        pos2 = 180;
    }
    if(val3 = HIGH){
        pos2 = 0;
    }
    release1.write(pos2);
    release2.write(pos2);
    updown.write(pos);
}

I'm using this code and it still wont work.
/* Sweep
 by BARRAGAN <http://barraganstudio.com>
 This example code is in the public domain.

 modified 8 Nov 2013
 by Scott Fitzgerald
 http://arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  for(pos = 0; pos <= 180; pos += 1) // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 180; pos>=0; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Have you tried debug the digitalRead function? Start with just one value and see if the motor moves. Maybe the position variable is changing too fast. Make sure the servo gets to the desired position by giving it some time.

Look at my edit.

This is the basic code for servos, it works okay for my Arduino UNO. Have you selected the right arduino before burning the code? Try changing the pin, maybe it is not working properly. It seems a board issue.

How are your connections to the servo motor? Usually the red is +5V, brown is GND and orange is the signal you connect to the attached pin in the code.

Did some test, all pins seem to be working fine, and yes the connections are right.

What is the model of your motor? Are you using enough power supply for it? In some cases just Arduino's 5V output is not enough... You need an external power supply.

SG90 motor, so im using plenty of voltage for it, it moves when I first plug it in but thats its.

5V is enough for it. Have you tried different digital pins to attach in the Servo library? Another way is to check if the signal is correct by testing with logic analyzer.

I used different pins for it, I never heard of a logic analyzer, what is it and how would I use it for an arduino/servo?

It is a device where you can plug in digital signals and analyze some behaviors. For example: see periods, frequencies and then debug you application. In this case you could see if the PWM generated to control the servo is based on the correct frequency accepted by the servo. They work using a specific period during "on" time and that could indicate where your problem is located.

Well I dont have one I used arduino 1,0 and that didn't work either, I will try with another computer later.

Try another board and update the IDE's version as well.

Have you tried the servo without using the Arduino ?

I made debug code before all the if statements, and those aren't working.
if(val2 = LOW)
{
  pos = pos - 15;
}
if(val3 = LOW)
{
  pos2 = 180;
}
if(val3 = HIGH){
  pos2 = 0;
}

That's because they are coded wrongly. Doing val2 = LOW assigns LOW to val2 and then tests it (which means it will fail the test). They should read:
if(val2 == LOW)
{
  pos = pos - 15;
}
if(val3 == LOW)
{
  pos2 = 180;
}
if(val3 == HIGH){
  pos2 = 0;
}

I tried uploading on a computer with windows 8 freshed installed and it still wont work, i tried serval differn't servo motors, looks like the arduino it self is broken.


text:
cannot convert 'bool' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus) on Arduino Uno Rev 2 Wifi not working
I am a newbie to micro controllers and struggling to figure out how to fix this issue. When using an older Arduino micro controller it works fine, but when I use a new board (Arduino Uno Rev 2 Wifi) it gives me this error:
cannot convert 'bool' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus)'

At this line :
digitalWrite(pin_enable_line, !digitalRead(pin_enable_line));

Library I am using is: ReceiveOnlySoftwareSerial.

Can you show us the sketch you are using?

nice. the MegaAVR core use the new common Arduino API and it has enum for pin status. use HIGH and LOW, not bool. so digitalWrite(pin_enable_line, (digitalRead(pin_enable_line) == HIGH) ? LOW : HIGH); (value is still LOW 0 and HIGH 1)

The digitalRead method doesn't return a Boolean value. It returns an Integer.
From what I remember inside Arduino.h values of LOW and HIGH are defined as being simply Integer 0 and 1.
#define HIGH 0x1
#define LOW 0x0

I think that was changed to an Enum called PinStatus but Enum can be treated as an Integer.
This means that you have to store results of digitalRead inside Integer variable.
int value = digitalRead(8);

It was designed that way to easily cast values between Integer and Boolean. By (very smart) design choice Integer value of 0 (LOW) will be cast to false and every other value (for example 1 or HIGH) will be cast to true.
The operator ! (Boolean NOT) can be used only with Boolean variables so the compiler needs to perform several "implicit casts". When it's smart enough it will assume you are know what you are doing and it will add the cast by itself.
By reading the error I see that the issue is happening when compiler tries to convert Boolean value into Integer. So this is implicitly evaluated correctly as a Boolean value
!digitalRead(pin_enable_line)

But when you try to put it inside a place for PinStatus you get the exception
cannot convert 'bool' to 'PinStatus'

Try adding an "explicit cast" to PinStatus:
digitalWrite(pin_enable_line, (PinStatus)!digitalRead(pin_enable_line));

It should fix the issue.
But I suggest splitting the code into several lines and adding a temporary variable. It makes debugging much easier. Trust the code optimizer that's built into the compiler. It will understand what you want to do and actual machine code will be the same.

if you write an answer, why you don't try it? the cast to int doesn't compile

@Juraj Strange. Line digitalWrite(9, (int)!digitalRead(8)); works perfectly in Tinkercad.

for megaAVR core (Uno WiFi 2) with PinStatus enum?

@Juraj You got me. I was reading wrong source code, and tested it on wrong simulator. Post answer about using ternary operator and I will delete mine.

cast to PinStatus could work. it compiles, but I would like to know if it works. but I don't have a board which would use the updated Arduino API. but the enum could be tested on it's own.

I did a little simulation and Serial.println((TestEnum)false); prints 0 and Serial.println((TestEnum)true); prints 1 so cast looks good. I will adjust my answer. If it will fail on OPs board I will delete it.


text:
Digital Potentiometer (TPL0501) Control Issues
I'm using SPI library in my code for controlling a digital potentiometer (TPL0501) with Arduino Mega.
The code I have is:
#include <SPI.h>
byte address = 0x80;
const int CS = 53;
int SCLK = 52;
int i=0;

void setup()
{
  SPI.begin();
  pinMode (CS, OUTPUT);
  pinMode (SCLK, OUTPUT);
  SPI.setBitOrder(MSBFIRST);

}

void loop()
{

     for (i = 0; i < 256; i++)
    {
      digitalPotWrite(i);
      delay(100);
    }

    delay(5000);
    for (i = 255; i >= 0; --i)
    {
      digitalPotWrite(i);
      delay(100);
    }
}

int digitalPotWrite(int value)
{
  digitalWrite(CS, LOW);
  delay(100);
  SPI.transfer(address);
  SPI.transfer(value);
  delay(100);
  digitalWrite(CS, HIGH);

}

Following the datasheet, I think the code is correct because this is what the datasheet says:

Can someone help me identify the error in my code, if any, because when I try to read the resistance with an ohmeter, I do not get the expected values.

what is expected and actual value, can you provide any example for this?

@Vaibhav the end to end resistance is 100kOhms. It's supposed to give me output in that range, increasing values first, then decreasing. I'm using the component alongside a buck-boost converter, but am currently trying to only test the potentiometer alone.

Are you floating all H, L and W terminals? The voltage relative on this pins should not exceed GND-VDD range. Connect L to GND then measure the resistance again.

What is SPI.transfer(address); supposed to achieve? SPI has no "address" concept, unless it's for selecting registes within a chip - and that chip has none.

try and measure the voltage drop between pin W and L if H is floating or between H and W if L is floating.


text:
Can arduino interrupts occur in a middle of if statement?
I got an issues from few days, got some code which reset millis time on successful i2c communication, if not it restart an relay after specified period of time. Here is part of the code:
 if ((unsigned long)(i2c1Millis1 - i2cpreviousMillis1) >= i2cset1 )  // check if not restarted soon
        {

i2c1Millis1 are updated every run of the loop and on successful i2c communication.
i2cpreviousMillis1 is updated on successful i2c request (coming from interrupt)
I manage to debug when false restart occur and looks like i2c1Millis1 is lower than i2cpreviousMillis1
So question is: can an interrupt occur while those two millis are compared when value of i2c1Millis1 is taken for compare and then come interrupt where i2cpreviousMillis1 is updated to current millis and it become greater and trigger the condition?
(I already modified my code i2cpreviousMillis1 is updated with i2c1Millis1  value on successful communication to prevent that, but it is not working, from time to time it made false restarts).

Did you declare i2c1Millis1 as volatile?

nope,never used that, when you mention that i read about that, looks like it not gonna help since millis is long.

You should still use it!!! I think that's more likely to cause the issues you have. Both are problems, but one is more likely to occur than the other.

After I moved millis update out of interrupt function, all works stable now.

You then might want to add the volatile to the flag set in the interrupt.

it is ok that way, when use the flag i prevent updating millis while comparing it, that fix it, nothing more is neccessary, this question is not about how to fix my problem, but to understand how interrupts may accur. When I understand that, there is lot of ways to fix it.

Yes. And it's even worse. Because your variables are longs, they are 4 bytes long, and most Arduinos are only 8-bit processors, the code only checks one byte at a time. So for example, after checking the first byte, an interrupt could occur, changing the 2nd, 3rd, and 4th byte. So you end up comparing the first byte of the old value, and other bytes of the new value.
To prevent this you could disable interrupt for a very short time, and make a copy the variable.
cli();//disable interrupts
unsigned long temp = i2c1Millis1;
sei();//enable interrupts

Or use the util/atomic.h macros
#include <util/atomic.h>

...

ATOMIC_BLOCK(ATOMIC_FORCEON)
{
  unsigned long temp = i2c1Millis1;
}

I have too many disable interrupts at my code, if increase them too much gonna start to mess with i2c communication, I changed code,raising a flag (byte variable) to trigger updating millis in main loop, not inside interrupt routene, so far works stable

Depending on how large i2cset1 (<250) you could use single byte variable, instead of 4-byte longs. That way there is no need to disable interrupts.

@user3503519, so you you used the flag recommendation from chrisl's answer and accepted Gerbens answer

1st i read this answer and got idea to use a flag and do it. after that i read other anwers

You can change the accepted answer to chrisl's, if I'm not mistaken.

Yes, an interrupt can occur at any time and can change the values during a calculation. And since you work with unsigned long variables (which are 4 bytes as I remember), it is also possible, that the calculation uses the old value for the first bytes and the new value for the other bytes, meaning that the used value for calcuation is totally garbage.
To prevent that your checks must either be atomic (meaning consisting only of 1 base instruction, which cannot be interrupted, e.g. handling only 1 byte) (that is not possible here), or you must prevent the calculation from being interrupted. For this you can turn off all or only the corresponding interrupt. To turn off all interrupts you can use noInterrupts() and interrupts() to turn them on again.
But it is questionable, why you need to update this time directly in the ISR. Instead you could only set an atomic flag (1 byte) and check this flag in the loop. If the flag was set, reset it and save the millis value. If you loop runs fast enough (which seems the case, since you already use it to set a millis timestamp) that should be sufficient
Both ways can be used and it depends on you, if it's ok to turn of interrupts for a short time, since you might miss an I2C interrupt this way.

Yes. An interrupt can occur pretty much anywhere.
Interrupts are processed between each assembly language instruction. That if will be made up of many many ASM instructions, so there are many many places where an interrupt can occur.
To avoid it you use what are called critical sections where you disable interrupts before performing some operations, then enable them again afterwards.
It is recommended to keep critical sections as short as possible to avoid breaking your interrupts. For this reason most critical sections generally involve copying values to or from local variables before then doing operations on them.
noInterrupts();
uint32_t localPreviousMillis = i2cpreviousMillis1;
interrupts();

if ((unsigned long)(i2c1Millis1 - localPreviousMillis) >= i2cset1 )  // check if not restarted soon

On an 8-bit system even assigning a simple value like that can be interrupted. A 32-bit value is made up of four 8-bit values, and an interrupt can occur between the copying of any of those 4 bytes.

thank you for your answer, mentioning assembler I remind old Apple ][ days where I used to write in assembler and basic :)