text:
How to write a library that support both HW and SW Serial communication and allow user to chose which one to use?
I'm working on a library for Arduino/ESP8266/Teensy that use serial to send AT commands. I want to make it as customizable as possible, so I avoided to hardcode the serial and I ask for a reference in the startup method:
void MyClass::init(HardwareSerial* hwSerialPtr)
{
   _serialPtr = hwSerialPtr;
   ...
}

On some devices, it will be useful to use SoftwareSerial instead of the HW one, due to only one serial is available and so keep it for debugging purposes or other features.
So my question is: how can I accept both types? I read both HW and SW serial have Stream as base-clase, but it does not have methods like begin() etc.
A possible solution I though is so have two pointers (one for HWSerial and one for SWSerial) then wrap some methods like begin(), println(), ... in my class and, ond the base of which pointer has been set, use one or the other.
Something like this:
class MyClass{
   public:
      void init(HardwareSerial* hwSerialPtr);
      void init(SoftwareSerial* swSerialPtr);

   private:
      HardwareSerial* _hwSerialPtr;
      SoftwareSerial* _swSerialPtr;

      void begin(long baud);
      void println(const String &s)
};

then
void MyClass::begin(long baud)
{
   if( _hwSerialPtr != null ){ _hwSerialPtr->begin(baudrate); }
   else if( _swSerialPtr != null ){ _swSerialPtr->begin(baudrate); }
}

...etc...

but this solution seems to me very tricky and not optimized.
Any better ideas?

and the way WiFiEsp library examples use is not good?  https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClient/WebClient.ino

why do you want to handle begin in the library? and alternative software serial implementations exist

The trick here is to go "up a level".  Both HardwareSerial and SoftwareSerial inherit from the Stream class.  It is that class that provides the majority of the interface that you actually use.
So you can provide a constructor with a Stream object alone and use that:
class Foo {
    private:
        Stream *_dev;

    public:
        foo(Stream *dev) : _dev(dev) {}
        foo(Stream &dev) : _dev(&dev) {}

        void begin() {
            _dev->println("I am ready");
        }
};

Foo myFoo(Serial1);
SoftareSerial btSerial(11,12);
Foo myOtherFoo(btSerial);

What the Stream class doesn't provide, though, is .begin() for setting the baud rate. It has to be left to the user to configure the port before using it.
Serial1.begin(115200);
myFoo.begin(); // --> "I am ready" on Serial 1

or:
btSerial.begin(9600);
myOtherFoo.begin(); // --> "I am ready" on Software serial pins 11/12.

This is known as polymorphism, where an object is seen as one of the parent classes in the inheritance chain and is one of the most powerful aspects of object-oriented programming.
Not having begin in your library is no big deal really. It increases the flexibility (a user can more easily select their baud rate), and it means you don't force them to include SoftwareSerial if they don't need it.
There are other things that inherit Stream, as well, such as a networking Client. So instantly you class can be used with network connections as well as just serial.
So stick to using Stream. It's the accepted way of doing things, and perfectly normal. For example, it's how my ICSC library handles serial objects.  (I used to use the multiple pointer method, but it really really got messy when trying to support other platforms. I ended up with HardwareSerial, SoftwareSerial, USBSerial, Client... a real mess. So much simpler to just use Stream.)

BTW, before you ask, I have two constructors with very slight differences so that you can construct an object either by passing a Stream object by reference (as I do in the examples) or as a pointer (which can be great if you want to use this in another class which itself has a pointer to a Stream object).

Another option is to combine the Stream pointer with a dynamic_cast to try and identify the type of object being passed.
void Foo::begin(int baud) {
    if (HardwareSerial *hs = dynamic_cast<HardwareSerial *>(_dev)) {
        hs->begin(baud);
    } else if (SoftwareSerial *ss = dynamic_cast<SoftwareSerial *>(_dev)) {
        ss->begin(baud);
    } else {
        // We don't know what to do here
        // so do nothing?
    }
}

In this way dynamic_cast is being used like Java's instanceof operator to work out what kind of object it is that is being used.
Of course, that then means that you're really restricting the library to only working with those two types of object, but it is still possible to pass other class types as long as the user pre-configures them before calling your begin function. Which gets confusing - which type does the user need to .begin() and which types have .begin() called for you? It's just cleaner to always have it as the user must call .begin() themselves - there's no ambiguity then.

I second Majenko's advice: inherit from Stream and let the user handle
the call to begin() if at all possible. However, if you really insist
in calling begin() from your class, then I suggest you make your class
a template, like this:
// T is the type of the serial port, typically HardwareSerial or
// SoftwareSerial.
template<class T> class MyClass {
    public:
        MyClass(T& port) : port(port) {}
        void begin(unsigned long baud) { port.begin(baud); }
    private:
        T& port;
};

Your user would then instantiate it as
MyClass<HardwareSerial> myObject(Serial);
MyClass<SoftwareSerial> myOtherObject(mySerial);

Of course, it doesn't look nice, and it may confuse your users, but it
has the advantage that it can work with anything that remotely looks
like HardwareSerial, e.g. AltSoftSerial or other alternative
software serial implementations.


text:
Shift Register 74HC595 circuit working weirdly
I built the circuit from the arduino ShiftOut tutorial, but it is not working as expected. I made a simulation model and that one isn't working either.

The code I used is from the tutorial:
// SH_CP; 11
const int clockPin = 9;
// DS; 15
const int dataPin = 8;
// ST_CP; 12
const int latchPin = 10;

void setup() {
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(latchPin, OUTPUT);

  Serial.begin(9600);
  Serial.println("reset");
}

void loop() {
  for (int number = 0; number < 256; number++) {
    Serial.println(number);
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, number);
    digitalWrite(latchPin, HIGH);
    delay(500);
  }
}

Any idea as to what's wrong?

I presume that you are referring to this tutorial, and this code.
The clockPin of Arduino should be connected to pin 11(SH_CP) of 595, dataPin to pin 14(DS), and latchPin to pin 12(ST_CP).
Swap the values of clockPin and latchPin in your code, and you should be good to go.
// SH_CP; 11
const int clockPin = 10;
// DS; 14 (not 15)
const int dataPin = 8;
// ST_CP; 12
const int latchPin = 9;

source: Stack Exchange

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

sort: votes


text:
How do I code delay inside a ISR?
I have built a basic obstacle avoidance robot. When the sensor senses an obstacle it gives a RISING interrupt to pin 2. At this moment I want the robot to come back for 2 seconds and turn right for 2 seconds.
I have code to turn back and rotate right but I cannot use the delay() function inside the ISR so how do I code this?

An ISR should be kept as short as possible, since while it runs, no other interrupts can be handled (including the one powering the delay() function. Thus you cannot delay that easy inside an ISR and you shouldn't do it either.
Instead you should set a simple flag variable in the ISR and then check this flag inside your loop() function. If the flag is set, you can execute the corresponding code inside the main code instead of inside an ISR.
A typical flag definition is a single byte (since then every read/write action is atomic and cannot be interrupted by an ISR). Be sure to set it volatile, so that the compiler knows, that this variable may change any time.
volatile byte interrupt_flag = 0;

In the ISR you can set this variable to 1 for example and then in your main loop() function:
if(interrupt_flag){
    // Do whatever you need to do here
    interrupt_flag = 0; // reset the flag variable
}

In that case, the robot won't stop immediately when the interrupt is given, it will run the forward function and when it comes out of that function it will poll for the interrupt flag and then stop.

If your code has to react quickly, you have to speed up loop() and the functions you call there. ISR are NOT intended for this purpose. Probably you do not need an ISR at all.

If you write your code without delays, the time between interrupt trigger and flag polling is so short, that you don't see it. Refer to the BlinkWithoutDelay example to learn the principle of doing timed things without blocking other code with delay.

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


text:
What is the correct way to interpret the built-in Analog-to-Digital Converter output?
When using the built-in analog to digital converter of the Arduino Uno Rev 3's Atmega328P with a reference voltage of 5V, what is the appropriate function to interpret the output? There is conflicting information on the Arduino website and in the datasheet for the Atmega328P (Arduino Uno Rev 3's chipset).
A lot of code examples on the internet indicate that the appropriate conversion factor is 5V/1023 (including the Arduino website: float voltage= sensorValue * (5.0 / 1023.0);).
Per the Atmega328P's datasheet, it indicates the conversion factor is 5V/1024:

If Vin and Vref are 5V, then the ADC reading would need to be 1024 in order to have a true reading of 5V, which is not possible since 1023 is the max output of the ADC. The closest reading to 5V we can get from this equation is ~4.9951 (5V*1023/1024).
With the Arduino example's conversion factor of 5V/1023, we get 5V for an ADC output of 1023.
Additionally, since the information from both sources is in conflict, it got me thinking a little more: The ADC is inherently sampling, and I am not sure if the ADC rounds up/down to the nearest value, so perhaps the closest approximation of Vin is an equation like the following that splits the difference:
Vin = (ADC+(ADC+1))/2 * 1024/Vref
Using the above equation, an ADC reading of 0 with Vref=5V would give Vin = (0 + (0+1))/2 *1024/5V = ~0.00244. This equation never gives a reading of 5V or 0V, but rather a value that splits the difference between samples.
Perhaps I am splitting hairs since the absolute accuracy of the ADC is "±2 LSB absolute accuracy", but I would still like to know which is the best equation to convert an output from the ADC into a voltage measurement.

You're overthinking things here. It really doesn't matter if you use 1024 or 1023 - the ADC isn't that accurate anyway.

Besides, you divide by the maximum value, not the number of steps - so 1023 is the correct one. The two would be the same if counting started at 1, but it doesn't - it starts at 0

@Majenko Even if the ADC isn't that accurate, I would still like my readings from it to be as accurate as possible and not introduce unnecessary error by use of the wrong equation. Also, if you are confident that 1023 is the correct value, then you are confident it is just a persistent typo that it appears in multiple AVR chipset datasheets (including ATmega2560, ATtiny85, ATmega1284)?

It's an argument that has been raging for years and years. The difference between the two is so minor that it is dwarfed by the inaccuracy of the ADC. It really is pointless. Use whichever you feel happiest with.

@Majenko Unfortunately, my research prior to asking this question did not turn up any such arguments. Can you provide some insight into the arguments as an answer? Microchip claims  ±2 LSB accuracy and the difference between  ±2 LSB and +1 LSB/-3LSB (or +3LSB/-1LSB) is important enough for me in my application to understand as part of tolerance stackup. Therefore, choosing the correct equation is important. I am using the ADC as a gross-check of a value, but I would like to understand all sources of the tolerance stack-up so I can shrink my expected error bounds as much as possible.

Well, it can also be argued that both results are perfectly valid and correct. Since each LSB covers a range of voltages the question arises: do you care about the upper bound or the lower bound of the quantisation? Either is as accurate or inaccurate as the other.

I am not sure I follow, the step size of the quantization is not the same in this case between the two methods, 5/1023 != 5/1024. With regards to the question "do you care about the upper bound or the lower bound of the quantisation?", I care about minimizing the error in my measurement to attain the stated absolute accuracy of ±2 LSB.

Here's one thread of the argument. As I say, it's been raging for years. https://forum.arduino.cc/index.php?topic=303189.0

the Atmega328P's datasheet, it indicates the conversion factor is
  5V/1024 [...]

Indeed. And the datasheet is the only authoritative source. All the
other sources are second-guessing.

If Vin and Vref are 5V, then the ADC reading would need to be 1024 in
  order to have a true reading of 5V

You can't get a true reading of 5 V. As per the datasheet (emphasis
mine): “0x000 represents analog ground, and 0x3FF represents the
selected reference voltage minus one LSB”.
Any input voltage larger that the maximum representable voltage will
read as 0x3ff (i.e. 1023), just like any negative voltage (within
the forward voltage of the protection diode) will read as zero. Thus,
reading either 0 or 1023 should be interpreted as a saturation
of the ADC, meaning the actual voltage is unknown.

The ADC is inherently sampling, and I am not sure if the ADC rounds
  up/down to the nearest value

In principle it should round to the nearest value. The transition in the
reading from 0 to 1 should ideally happen at
Vref/2048. C.f., again, the datasheet, subsection “ADC
Accuracy Definitions”: “Offset: The deviation of the first transition
(0x000 to 0x001) compared to the ideal transition (at 0.5 LSB).”
A little bit further in the page it is stated that the ideal position of
the last transition (1022 to 1023) is “at 1.5 LSB below maximum”.

Perhaps I am splitting hairs since the absolute accuracy of the ADC is
  "±2 LSB absolute accuracy"

Indeed. If you really care you should probably calibrate your ADC. See
Response of the Arduino ADC.
Edit: in a comment you mention that the factor 1024 could
conceivably be “a persistent typo that it appears in multiple AVR
chipset datasheets”. It may be an error, but certainly not a typo, as
the datasheet contains multiple independent statements that confirm the
factor 1024.

The calibration curves are interesting -- looks fairly straight, but the slopes differ.  On could do much of the calibration by looking for the ratio that gives ADC==1 and ADC==1022 and fitting just those points.

As others have said, the difference between 1023 and 1024 is quite small.
However, the fact is that your input range for the ADC is 0 to 1023. (That's 1024 steps, but since it starts at 0, it won't go up to 1024)
You'll get 0 at the minimum input, and 1023 at the maximum value.
If you're using a 5.0V reference voltage and no voltage dividers, that means you will get 1023 at 5V (ignoring measurement error.) If you want your output value to be the VOLTAGE measured, you would want Vin / 1023.0 * 5.0. That would give you a value of 5.0 at the max input of 1023 (representing 5.0 volts) and 0 at 0 volts input.
Edit:
Since my posting, I read the threads on this, and there is a raging debate on the subject. I am now less clear that there is "right" way to do this.
The issue is that the ADC value doesn't give you a certain reading, it indicates a range. When you get a value of 1024, the ADC is tellling you that the measured voltage is in the top 1/1024th of voltages, from about 4.995V to 5V (or above, for that matter.)
The steps are actually in 1024ths. That argues that you should divide the measured value by 1024, and then return a range of possible voltages:
value = analoglRead(pin);
float lower_value = value / 1024.0 * 5.0;
float upper_value = (value + 1) / 1024.0 * 5.0;

For an analog reading of 0, that would give you a range of 0.0v. to 0.0048828125v.
For an analog value of 1023, that would give you a range of 4.9951171875v to 5.0v

After reading through various arguments for use of different transfer functions, this is my summary:
In order to achieve the manufacturer-stated absolute accuracy of ±2 LSB, you should use the manufacturer's equations and published guidelines on usage to ensure that accuracy (e.g. ensuring appropriate ADC clock speed / sampling time and implementing noise reduction techniques).
It may be possible to achieve better results using another transfer function by calibrating specific to each individual circuit. If you go this route, all of the responsibility of ensuring accurate calibration across the range of expected operating conditions (including offset/gain drifts due to environmental factors) are your responsibility to characterize and account for when developing the transfer function. This is where the transfer function Vin = 5V/1023 * ADC fits in. This transfer function may in fact be a better representation of the actual outputs for a specific chip. However, use of this transfer function shifts responsibility onto its user to verify that it actually produces better results.
A couple of important notes:

Manufacturer's claims are not always accurate. However, they are likely based on a large statistical sample size and if the manufacturer's published statements are wrong, this potentially opens the manufacturer up to lawsuits depending on the impact of an incorrect published specification. For this reason, I tend to trust manufacturer datasheets from large chip makers until proven otherwise.
The question assumed a perfect 5V reference for simplicity of discussion, however the actual value of a real voltage reference is almost impossibly a true 5V and has some degree of noise affecting its stability which should also be considered when attempting to read a true voltage value. Ideally, if you are trying to read a sensor value and can create a circuit in which the voltage reference cancels out of the final measurement, that will help with accuracy of the sensor reading.

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


text:
Can't get constant reading with load cells
I'm really a newcomer to arduino and I'm trying to build a scale with four SEN-10245 load cells and a HX711. My issue is that I can't get constant readings in the serial monitor and I'm not sure if my coding is right or if I did the right setup.
I made the following setup, based on some examples I found online:

The code I'm using is as follows:
    #include <hx711.h>
    Hx711 scale(A1, A0);
    void setup() {
    Serial.begin(9600);
    }
     void loop() {
     Serial.println(scale.averageValue());
     delay(200);
    }

link for the library github: https://github.com/aguegu/ardulibs/tree/master/hx711
Please help me, i'm a total beginner.

What is your power supply?

What are the readings you get? How much do they vary?

by now my only power supply is my computer.

@Miguel can you clarify what you mean by "constant readings"? Is it moving from 100 to 1200 or form 395 to 396?

Ihave the same problem can you help me

Assuming everything is hooked up correctly, your issue is likely related to electromagnetic noise (aka electromagnetic interference, EMI). Load cells output very small voltages, which is why you need the HX711 amplifier. Your long wires are essentially acting as antennas, picking up the electromagnetic noise in the room. One easy way to reduce the noise is to twist the wires together. You can also shield the wires by wrapping them with aluminum foil and attaching the foil to ground.
Making the wires much shorter would likely also help. That would be a good test to see if it helps.
The power supply could also be creating noise. I have found that the 5v line coming from a computer is often quite noisy. This is harder to fix, but an easy way to test if this is the issue is to power the Arduino with a 9V battery. Just make sure you plug it into the Vin pin, not the 5V pin, because the 9V needs to be regulated down to 5V.

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


text:
send sketch to arduino via wifi
I'm pretty new to arduino and need some help.
My task is to connect my UNO R3 to wifi AND then send data (sketch for blinking led) to it.
I successfully connected my arduino with my wifi, but how do I send the sketch?
I didn't find a tutorial for this. Do you know a good one or can you help me, please?

I would prefer you to use a simple Adafruit EZ Link that provides you serial communication with a reset line with the help of Bluetooth. Well the solution that Majenko gave is also applicable but that will need a bit of work.

Once you involve wifi, an ATmega-based Arduino is rarely the right choice.  You'd be better off figuring out how to get an ESP8266 to reprogram itself, or using a Linux-based router chip which can load a new "OTA" image to its external SPI flash store.  Both solutions will be cheaper than Arduino + Ethernet Shield.

There is a difference between communicating via WIFI while a sketch is running or to send the sketch itself ... for the latter, I don't think there is an easy solution; you probably have to write your own AVR programmer, receiving the sketch via WIFI and store it on the Flash memory.

Given the bootloader, there's not as much difference as you think, if you have a wifi adapter that functions as a mostly transparent bridge, but ideally can also be commanded to toggle a modem status line to reset the ATmega.

You can't with a normal Arduino and WiFi shield.
However it is possible (if you are cunning) to do it with the ESP8266.
The basic idea is that you program an ESP8266 module to act like a transparent TCP/IP to UART bridge. Connect it to the TX and RX pins of the Arduino, listen on a port number of your choice, then when you connect to it (with telnet, netcat, socat, etc) all data is forwarded directly back and forth to the UART interface. If you monitor the connection state as well and use that to drive an equivalent of the DTR pin you can reset the Arduino automatically when you connect.
There is an example in the ESP8266 core that does it all apart from the connection monitoring, which is easy enough to add.
Then it's just a case of getting your computer to connect a virtual serial port with the remote socket on the ESP8266 and you have OTA programming for your choice of target board.
On Linux you can use socat for that:
root@foo:~# while `true`; do echo "ready"; socat pty,link=/dev/ttyACM99,raw,wait-slave,user=youruser,group=dialout tcp:192.168.0.16:24; done

(yes, you have to run it as root).
Quite how you'd go about that on other operating systems I don't know. I think socat is available on OS X. Windows is anyone's guess though.

Can we use a Adafruit Bluetooth EZ Link ?

No idea. If it can be a serial port, has the facility to reset the target MCU, and can be used without needing an active sketch on the Arduino (it is configured separately to the Arduino) then possibly.


text:
SIM800C, CPIN: NOT READY (ERROR CODE : +CME ERROR: 10)
I'm using a SIM800C module, and usually it works fine, but lately it has started giving the error "+CPIN: NOT READY" with ERROR CODE : +CME ERROR: 10(SIM NOT INSERTED). As soon as I get this message, the voltage on SIM_VDD drops to 0V. The problem is intermittent (i.e. it happens only sometimes).
I have read all related posts on here. Here is some info on my setup:
-Schematics is designed according to SIM800C documentation.
-I use 6-pin SIM connector.
-Adding decoupling caps on SIM_VDD, on input power, and on VBAT (for SIM900) does not help.
-Signal strength is fine (about CSQ=20).
-I tried reinserting different SIM cards, nothing helped
The "+CPIN: NOT READY" is sent at different times, however, often quite soon after power on.After removing battery & attaching it again, starts working again. why this issue is occuring..?

The antenna is too close to the module. You probably used the spiral antenna. Try using the PCB antenna with long (10cm) cable.
Had the same problem, solved with the antenna.

Definitely related to poor antenna matching. This is complex stuff and should preferably be fixed by changing antenna matching (e.g. by a matching circuit or simply trying out a different antenna). I have also seen that it helps to wait until you get the unsolicited modem response "Call Ready". Until you get this message, it can disturb the modem to receive any AT command.


text:
NodeMCU ESP8266 disconnected from WiFi after several hours running
I tried to test NodeMCU ESP8266 with this code from here
                #include <ESP8266WiFi.h>
                #include <WiFiClient.h>
                #include <ESP8266WebServer.h>
                #include <ESP8266HTTPClient.h>

                /* Set these to your desired credentials. */
                const char *ssid = "dummy";  //ENTER YOUR WIFI SETTINGS
                const char *password = "12345678";

                //Web/Server address to read/write from
                const char *host = "192.168.43.128";   //https://circuits4you.com website or IP address of server

                //=======================================================================
                //                    Power on setup
                //=======================================================================

                void setup() {
                  delay(1000);
                  Serial.begin(115200);
                  WiFi.mode(WIFI_OFF);        //Prevents reconnection issue (taking too long to connect)
                  delay(1000);
                  WiFi.setSleepMode(WIFI_NONE_SLEEP);
                  WiFi.mode(WIFI_STA);        //This line hides the viewing of ESP as wifi hotspot

                  WiFi.begin(ssid, password);     //Connect to your WiFi router
                  Serial.println("");

                  Serial.print("Connecting");
                  // Wait for connection
                  while (WiFi.status() != WL_CONNECTED) {
                    delay(500);
                    Serial.print(".");
                  }

                  //If connection successful show IP address in serial monitor
                  Serial.println("");
                  Serial.print("Connected to ");
                  Serial.println(ssid);
                  Serial.print("IP address: ");
                  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
                }

                //=======================================================================
                //                    Main Program Loop
                //=======================================================================
                void loop() {
                  HTTPClient http;    //Declare object of class HTTPClient

                  String ADCData, station, postData;
                  int adcvalue=analogRead(A0);  //Read Analog value of LDR
                  ADCData = String(adcvalue);   //String to interger conversion
                  station = "A";

                  //Post Data
                  postData = "status=" + ADCData + "&station=" + station ;

                  http.begin("http://192.168.43.128/c4yforum/postdemo.php");              //Specify request destination
                  http.addHeader("Content-Type", "application/x-www-form-urlencoded");    //Specify content-type header

                  int httpCode = http.POST(postData);   //Send the request
                  String payload = http.getString();    //Get the response payload

                  Serial.println(httpCode);   //Print HTTP return code
                  Serial.println(payload);    //Print request response payload

                  http.end();  //Close connection

                  delay(5000);  //Post Data at every 5 seconds
                }

It was running well and posted data to Database after a few hours. Then It was disconnected from WiFi somehow . Of course I reset power supply again It's connected.
How should I do to fix with that code to reconnect WiFi right after that accident Or any other Solution  for that ? Thank you

don't use String this way. https://majenko.co.uk/blog/evils-arduino-strings

What you need to do is leave the board connected to your computer and watch the serial monitor to capture the output during the crash.  If the board has a true crash it will output a bunch of information which may tell you why you it is crashing.  It could be a strings/heap problem or maybe a memory issue since you are declaring a new http object every 5 seconds.  Maybe try putting the HTTPClient http; line up where you declare the host variable so that it is a global variable and not a local variable.
Since your loop doesn't test to make sure the wifi connection is still good then if you get a disconnection then the program will just fail and never try to re-connect.  So at the start of your main loop put the same wifi testing logic that is also in the setup function. If the connection is down then reset and start from the very beginning to re-establish the wifi connection.
if (WiFi.status() != WL_CONNECTED) {
    ESP.reset()
  }

Thank you . I declared HTTPClient http ; outside of loop method. However It's still get the same errors .  Assume that It could be a strings/heap problem or maybe a memory issue. How should  I do please ?

That worked for me ! Thank you

I also had the same issues. I've looked for some posting like here.
You can try these codes
void loop()
 {
 WiFiClient client;

 Serial.printf("\n[Connecting to %s ... ", host);
if (client.connect(host, 80))
{
Serial.println("connected]");

Serial.println("[Sending a request]");
client.print(String("GET /") + " HTTP/1.1\r\n" +
             "Host: " + host + "\r\n" +
             "Connection: close\r\n" +
             "\r\n"
            );

Serial.println("[Response:]");
while (client.connected() || client.available())
{
  if (client.available())
  {
    String line = client.readStringUntil('\n');
    Serial.println(line);
  }
}
client.stop();
  Serial.println("\n[Disconnected]");
 }
 else
 {
  Serial.println("connection failed!]");
  client.stop();
 }
 delay(5000);
 }

The seconds thing as @tavis said you can try from here.
It sounds ESP.restart(); is recommended rather than ESP.reset();
It seems our issue is very hard.

Thanks for sharing


text:
Arduino, Serial and wrapper class
I am working on an Arduino project, that would use HardwareSerial object reference stored in a class and call methods on it. However, there is problem with writing output using the reference.
Minimal use case to demonstrate behavior is in following files:
main.ino
#include <Arduino.h>
#include "testclass.h"

TestClass testClassInstance(Serial);

void setup() {

}

void loop() {
    testClassInstance.print("Hi There\r\n");
    delay(1000);
}

testclass.h
#ifndef TESTCLASS_H
#define TESTCLASS_H

#include <Arduino.h>

class TestClass {
public:
    TestClass(HardwareSerial &serial);
    void print(const char * text);

private:
    HardwareSerial _serial;
};

#endif

testclass.cpp
#include "testclass.h"

TestClass::TestClass(HardwareSerial &serial) : _serial(serial) {
    _serial.begin(9600);
    _serial.print("Initializing\r\n");
}

void TestClass::print(const char *text) {
    _serial.print(text);
}

After reset, there are only two characters sent: "In"
In the example above, initialization is done before setup() method and Serial's state is probably reset before calling it. Having changed that to dynamic allocation in setup method did not change this behavior as well.
modification of main.ino
TestClass *testClassInstance;

void setup() {
  testClassInstance = new TestClass(Serial);
}

There might be problem with passing the reference to Serial, but in that case I would expect to not have any output at all.
Any help is greatly appreciated.

You can't do complex tasks (or anything that relies on the Arduino API in any form) in your constructor. Simply because that all gets called before the Arduino API initializes, and in so doing the serial port gets disabled.
Instead you should do your complex operations and API-based operations in .begin(), which is why 99.99% of all libraries (including HardwareSerial) have a .begin() method.

This looks reasonable. Does begin() method exist in main file next to setup() and loop() functions? Or does it have to exist on my wrapper class and be manually called in setup()? Additionally, is there some manual that specifies how Arduino API is initialized and what happens then, so I could RTFM? :)

.begin() is a function you must write in your class. The user then calls it from setup(). No, I am not aware of any generic documentation - simply because it is different for every core. Just assume that nothing bar setting some variables / flags can be done in the constructor - that's the safest way.

I have debugged deeper and the problem was somehow passing HardwareSerial to constructor as parameter with HardwareSerial &serial.
When changing it to pointer HardwareSerial *serial and using access via pointer-type variable, everything works.
Many thanks for suggestions.


text:
Unexpected results and hard crash when modifying and addressing arrays & variables within a struct
I'm trying to use a 2D array inside a struct on my arduino to store sensor readings. I'm having two main problems:
1: My Arduino is crashing and resetting when I try to access certain directories in my Array
2: My arraysize variable doesn't seem to be incrementing the way I'm expecting it to.
I've attached snippets of my code that I think are relevant.
struct calibration
{
  float NTU[];
  unsigned int readings[][28];
  unsigned int arraysize = 0;
};

//Main
void loop() {
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Waiting...");
  if (digitalRead(inputPin) == HIGH)
    TakeReadings();
  delay(50);
}

//after taking many readings from a sensor and averaging...

Calibration.readings[Calibration.arraysize][0] = average;
Calibration.arraysize++;
PrintMatrixToSerial();

//serial print function

void PrintMatrixToSerial() {
  Serial.print("1.9,1  3.8,1  7.5,1  15,1   30,1   60,1   120,1");
  Serial.println();
  for (int i=0; i<Calibration.arraysize; i++) {
    for (int j=0; j<7; j++) {
      Serial.print(Calibration.readings[i][j]); Serial.print("   ");
    }
    Serial.print('\n');
  }
}

When trying to assign values to my Calibration.readings array in certain directories, the Arduino hard crashes. For instance, a crash happens when the arduino tries to execute:
Calibration.readings[Calibration.arraysize][2] = average;

Secondly, after running my TakeReadings() function only once, I expect Calibration.arraysize to be equal to 1, therefore the PrintMatrixToSerial() function should only print one row of data; however, the serial monitor prints many rows. The following is an example of the output:
1.9,1  3.8,1  7.5,1  15,1   30,1   60,1   120,1
11   298   0   65292   779   1284   6
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
0   167   167   167   167   4245   40853
167   167   167   167   167   167   167
319   167   167   167   167   167   167
Is there an issue with my struct, or array declaration? I'm stumped at the moment, so any help would be appreciated.

You're not allocating any memory to your readings array. Give it a size.

Thank you, that fixed both problems. I was under the impression that declaring the size of the first array in a matrix wasn't required, is that wrong for all cases?

You can skip the first one IF AND ONLY IF you supply a list of initializers in braces as part of the definition.  In that case the compiler will count the number of things in the list for you.

@Majenko - comments on questions are for clarifying the question. Please make a proper answer, especially as the system will throw this up as an unanswered question if you don't.

@NickGammon Many times I am using my phone and the android SE app. Writing answers on that is a real pain in the sphincter. So I get the OP up and running with a quick comment. Later on, when back at my PC (sometimes the next day) I convert my comments to a real answer. I do not need telling every time by you. I know how the site works.

You are not specifying a size for your readings array:
unsigned int readings[][28];

That is not saying "Give me an array of an unknown number of chunks, each of 28 values", it is actually saying "Give me a pointer to a block of memory (which I will provide later) which is arranged in rows of 28 values".
In C you must either provide a size for an array, in which case the memory is statically allocated for you, or manually allocate the memory at a later date.
unsigned int readings[16][28]; // 16 rows of 28 int values

Or, for dynamic allocation:
unsigned int readings[][28];

// allocate the memory ...
blah.readings = malloc(16 * 28 * sizeof(int));
// do things with your array ...
// and free up the memory when finished:
free(blah.readings);

On an embedded system it is generally to know how many readings you will be taking beforehand. That way you can allocate the correct number of rows to the array before you compile the program, which makes many things more efficient.


text:
5V 1A vs 5V 5A power supply for 6 LED + Arduino
If I want to power up 6 normal 3mm LED with the appropriate series limiting resistor, do I need the 5V with 1A or 5A power supply? Same goes to the Arduino, if I want to power it externally, do I go for the 1A or 5A?

Both will work, but using a 5A one is quite a bit of overkill.

If I'm using 5A, will be voltage drop of the resistor be more or less? Should it be more since it needs to resist more current, hence more voltage drop

@Jason "series limiting resistor" will limit the current.

The 5A refers to the maximum current it can supply. If you draw less, it will supply less. As long as the voltage is the same, there will be the same amount of current flowing through the led.

Depending on your led, it will draw 10 to 20mA for a standard led. Thats 0.010 to 0.020A. Multiply this by 6 and you see that a 1A power supply will be enough.
Your arduino, when driving those leds, will also use a few mA. So you can power everything with a 1A power supply.

Both will work, but go with 1A!!!
It is more forgiving if a short happens.
A 5A short circuit will make sparks that might be dangerous.


text:
5V power supply negative terminal connection
I am currently developing some basic led board using Arduino Uno R3. Basically,
the LEDs are connected in parallel so that 5V DC supply can light up about 3 LED. Each LED has its resistor and its connected to 3 Arduino digital pin where I ground it by using digitalWrite(pins, LOW). Each ground on the schematic is the Arduino digitalWrite(LOW). My question is where should the negative of the 5V should be connected?
Also, if I wanted to measure the voltage of the LED, where should I connect my probe so that analogRead() can read the voltage?
Thanks and sorry if my explanation is not correct since it's my first time using this site.

simulate this circuit – Schematic created using CircuitLab

The Arduino common, normally referred to as ground, although it is usually only accidentally grounded through external connection. In general ALL connections should have a common "ground".
You can not measure voltage across the LED given the circuit you have listed. (You could read the voltage at both ends and subtract.)
If you swap the LED and resistor you can get an approximation of the LED voltage (actually LED + Arduino pin) from the junction of LED and resistor.

Thank you. What if I have a dual power supply 5V and 12V, lets say D3 needs 12V to work, and the others need 5V to work, should both the power supply's negative port be connected to Arduino GND as well?

@Jason Your comment is imprecise. All electrical circuits need some reference connection. If it is a "dual power supply" it presumable has a common. If you have 2 independent power supplies they both need a reference connection - this is conventionally 0V, but any reference is acceptable. If you really intend using 12V, you should rethink your circuit, and NOT connect directly to the Arduino. I really don't see why you would want 1, let alone 2, external supplies to switch a few LEDS. The Arduino can only switch 40mA max (20mA recommended) without extra circuitry.

@Milliways, the  “it is usually only accidentally grounded through external connection” part seems false.

@jwpat7 If you power with most switch-mode power supplies (such as the plug packs used as phone chargers)  which are double insulated, the Arduino will be floating WRT ground, unless you connect to a grounded device.


text:
Can external power supply above current limit lead to errors/shutdown arduino?

I have an Arduino Due that is connected both over native USB to PC and a 12v power supply in the Jack.
Mounted on the Arduino I have a custom PCB that drives 3 motor drivers. The Motor drivers are powered via the arduinos VIN Pin with 12v.

As Ive read elsewhere the arduino automatically chooses the 12v powersupply in this case. My question is: If the 3 motor drivers exceed the 1amp that the powersupply can supply, will the arduino encounter errors/shutdown or automatically switch back to USB for power supply?
If so, is there a way I can force the arduino to take the USB 5v even though 12v are connected through the Jack?
Also, how much current can I safely drive through the VIN Pin?
Thanks!

If the incoming voltage drops below 6.6V the MOSFET will activate for the USB power and that will become available. But it's not perfect.
The MOSFET is always "partially" active - that is, the "body diode" is always available, so if the 5V rail drops below the USB voltage minus the forward voltage of that body diode the USB power will take over regardless of what else is happening. That 5V rail then feeds the 3.3V regulator, and
since the ARM chip on the Due is a 3.3V chip, even a dip of a volt or so on the 5V rail should have no effect on the MCU.
So theoretically the chip should keep running fine all the time regardless of what happens with the power.

Is there a way I can force the arduino to take the USB 5v even though 12v are connected through the Jack?

Not really, no.  You can remove the 12V from the jack though and just power from USB. Connect the 12V to your motor drivers, and link its ground to the Arduino ground. The motors will use the 12V supply, and the Arduino the 5V supply.

Also, how much current can I safely drive through the VIN Pin?

The diode inline with the barrel jack is rated at a maximum sustained current of 1A. Any more than that and you risk blowing that diode.


text:
Wiring a potentiometer to control a 9V battery powering 2 LEDs in series
I am trying to build an array of LEDs where their brightness is controlled by a potentiometer.  The LCD will display the percentage of brightness based on the potentiometer.  I am able to successfully control the brightness of a circuit with only one LED.  However, I am having trouble with 2 two LEDs in series (which are in parallel with other sets of 2 LEDs in series).  And I believe the problem is that the Arduino is only supplying enough voltage to power one LED (maybe < 5V).  How can I properly wire a 9V battery to this circuit in which the potentiometer can control the amount voltage coming from this battery?  Are Arduinos only capable of controlling <5V with a potentiometer?
Here is my code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int potPin = A0;
int ledPin = 6;
int potValue = 0;

void setup() {
  pinMode(potPin, INPUT);
  pinMode(ledPin, OUTPUT);
  lcd.begin(16, 2);
  lcd.print("Potentiometer");
}

void loop() {
  potValue = (analogRead(potPin)/10.02);
  analogWrite(ledPin, potValue);
  lcd.setCursor(0,1);
  lcd.print(potValue);
  lcd.print("%");
  delay(100);
  lcd.print(" ");
  delay(1);
}

And here is a picture of my circuit setup:

Yes, Arduino is a 5V microcontroller, meaning it can directly control 5V circuits only. You might incur in problems also trying to deal with 3.3V circuits, even if Arduino is pretty friendly to 3.3V counterparts.
That does not mean though you cannot control higher voltage circuits, just not directly. Actually if anything above 6V is connected to an Arduino PIN you will blow that pin and potentially others which are logically connected within the MCU, so be aware.
To control higher voltage circuits you have multiple options, in your case you are probably interested into using a BJT transistor, an 2N2222 might do.

simulate this circuit – Schematic created using CircuitLab
Please note the values of R1 and R2 must be adjusted to the LEDs you are using depending on their Vf (forward voltage drop) and the maximum current you want to provide.


text:
How to control a DC Motor with Hall Encoder using Arduino and Motor Driver?
I'm using a DC motor with Hall Encoder. I bought it from DX.
I have made all the connections to motor driver and arduino and I suppose all are correct. I've connected m1 and m2 pins of motor to that of motor driver, encoder A phase and B phase to arduino pins 3 and 11, and GND of motor to GND of Arduino and 3.3V pin of motor to 3.3V pin of Arduino. Also motor driver is also connected to arduino.
The problem is that I'm unable to run the motor but I can count the rotations made by the motor. Please help me with the working code. Thanks.

What are the "m1" and "m2" pins you mention?
On the diagram I see on that link, the pins "1-M1 motor -" and "6-M1 motor +" should be connected to the motor driver. The other four pins should go to the Arduino only.
You can probably test the motor by disconnecting it and connecting pins 1 and 6 to a 9-12V battery or similar, to see if it turns.
By the way I guess the two Encoder Phase connections would be set up on the Arduino using PinMode setting "INPUT_PULLUP". But as you can already read the positions, that part may not matter.

m1 and m2 are the pins that you mentioned in 2nd paragraph.

I'll try connecting the motor pins to battery today and see if it turns.

It is not running when I connect 1st and last pin of the motor to the power supply. But if I connect another DC motor to the same power supply it runs.

Unfortunately it sounds like that motor has something wrong with it... I would get a meter (if possible) and measure the resistance across those two pins. If it's extremely high (mega ohms) or extremely low (below say 5-10 ohms) I'd say there's something wrong. You could also follow the traces on the board and measure at the two large solder "blobs" where they connect to the motor...

You know what...I connected those two large blobs to 12V power supply and the motor ran!!!! But I've run into some other problem...1 of my motor runs at a speed faster than the other one. When I pickup my bot above the ground both rotate but at different speed. But if I keep them on ground one does not rotate at all. I guess it is not able to generate enough torque. Please help!


text:
ESP8266 stuck in flash mode?
I have the setup described here: https://learn.adafruit.com/esp8266-temperature-slash-humidity-webserver/wiring
I currently have the reset pin set to float and the GPIO0 pin grounded, which should make it execute the uploaded program, but instead I get the flash mode output:
    writing flash
...................................................................................................................................................................................................................................................

How do I put it into execution mode?

Try putting a pullup on Reset and GPIO0.

GPIO0 pin grounded, which should make it execute - no, GPIO0 grounded is how to put the thing into programming mode

What is the correct configuration then?

I was stuck in a similar scenario. I managed to exit programming mode by floating GIPO0, then grounding RST for ~3 seconds, then floating it. If you power off the esp, and now turn it on, it should have exited programming mode. Powering it off is actually optional.


text:
How do I reset an ESP8266 with an FTDI and no reset button?
How do I reset an ESP8266 with an FTDI and no reset button? I assume that it has something to do with the reset pin on the ESP8266, but I cannot find a step-by-step usage of the pin online.

There is both a "reset" and a "program" pin on the ESP8266. You need both to reprogram it.

But how specifically do I reset it?

there are lots of different esp8266 boards, and several kinds of modules. Which one in particular?

also, are you asking how to do it under program control?

https://www.sparkfun.com/products/13678

No, just how to do it manually.

Pull the reset pin up by connecting it to 3.3v with a 10k ohm resistor, then to reset the ESP you temporarily ground the pin, bringing it down to 0v/GND.
I'd recommend putting in a button for that :)


text:
Real time Cross Correlation...?
I saw the one of your Answer that dated the 13th May 2015, i want to cross- correlate the vibration signal (with Predefined Signal) to remove the unwanted signals.But i want to do that real time so can we use the Arduino or have to use the Another platform. please advise .
Kaveendra Sampath

What answer? Link please. Please read How do I ask a good question?.

You will have to be a lot more specific if you want any kind of useful answer. What type of Arduino? Sampling rate? Length of the reference signal? What does that reference signal look like? What information do you want to extract from the cross-correlation?

Please add more details to your question. It is not really answerable as you've written it.

The way worded your question only allows for this type of answer: "If you are only cross correlating a few bytes then you might be able to use an Aruduino Uno at low sampling speeds.  If you want to do more then you need a more powerful Arduino like a Intel Galileo."

authors: Евгений Макжанов


text:
Is it possible to connect a 36 pin 4 digit 7 segment display on an Arduino Uno R3?
First of all,here's the datasheet of the 4 digit 7 segment display that I'm using:
http://www.kingbrightusa.com/images/catalog/SPEC/ca56-11ewa.pdf
How can I make a counter or a clock out of this particular led display,considering the fact that I don't have enough digital pins to manipulate led's pins?

https://miguelpynto.github.io/ShiftDisplay/

I recently played with a seven segment LED clock display https://github.com/jandrassy/lab/blob/master/KitchenTimer/KitchenTimer.ino

Only need 4, or 5 pins; SCK (D13), MOSI (D11), slave select (D10).
Maybe PWM (D9) for brightness.
D12 not used, but is tied up as part of SPI bus.
Connect the Anodes to +5.
Connect the cathodes, with a current limit resistor per cathode, to the outputs of 4 TPIC6C595, or TPIC6B595.
For the resistor, assume worst case voltage drop of 2V and 20mA current draw:
(5V - 2V)/.02A = 150 phm.
Use a PWM output pin to drive the OE/ pin of the '595s for brightness control.
Then shift data into the daisychained shift registers as an update is needed.
byte dataMap[] = {
0b00111111, // 0 with bits representing DP,g,f,e,d,c,b,a
0b00000110, // 1
0b01011011, // 2
// etc
};

where segments are layed at as
   a
f     b
   g
e     c
   d      DP or colon

then call the array in loop(), make it a function if you want.
digitalWrite (ssPin, LOW); // D10 on Uno, used as Latch signal
for (x = 0; x <4; x=x+1){
SPI.transfer (mapArray[digit0]); // digit0 value mapped to segments
SPI.transfer (mapArray[digit1]);
SPI.transfer (mapArray[digit2]);
SPI.transfer (mapArray[digit3]);
}
digitalWrite (ssPin, LOW); // outputs update on this rising edge

I wonder where DP5, DP6, which make the colon, are? I don't see them in the pinout.

595 shift registers don't use SPI. they can be handled ye the SPI peripheral but I think they predate SPI. I use shiftOut Arduino function. https://www.arduino.cc/en/Tutorial/ShiftOut

I use SPI to load them all the time, goes way faster then shiftout() does. Can even set the SPI clock to 8 MHz (up from the default speed of 4 MHz) to load them crazy fast.  Be sure to have a 0.1uF cap at the VCC pin of each device. I usually have the Clear line connected to +5, and OE/ connected to GND unless I am using PWM on the outputs.

You actually only need 12 pins for that display.
The display is made up of 4 separate common anode LED displays, and you can use that to your advantage.
Since the 4 anode clusters are separate you have the ability to switch an entire digit on or off. And as a result all the cathodes of the segments can be commoned together (that is, the cathodes of all the segment As can be commoned, and the cathodes of all the segment Bs, etc), which is then 8 clusters of 4 cathodes.
That means you can have 4 outputs controlling the for anodes (ideally through PNP transistors or P-channel MOSFETs to handle higher current), and 8 outputs to control all the cathodes (each through a resistor and ideally an NPN transistor or N-channel MOSFET to handle higher current).
The you rapidly switch between each digit displaying the right segment combination for that digit.
Here's a partial example showing 4 digits but just segments A and B. Youd expand this out for segments C through G.  GPIO_A1 to GPIO_A4 are activated to select which digit is being displayed. GPIO_CA through GPIO_CG would be to select the arrangement of segments on that digit.

simulate this circuit – Schematic created using CircuitLab

Though it should be mentioned, that multiplexing the displays like this will affect the brightness.

@chrisl True, but with the reduced duty cycle comes the ability to run the LEDs at a higher current, thus somewhat compensating for that.

@Majenko Are GPIO_A1,GPIO_A2,GPIO_A3 and GPIO_A4,and GPIO_CA,GPIO_CA the NPN,respectively the  transistors that you are referring to?If so,I still don't understand how they actually work such that it can manipulate all 4 digits without even turning even one of them off.Also how do I simulate properly your circuit?And I'm asking this because I have never never worked with such online tool before.

Ignore the "simulate this circuit" thing, it's meaningless. The sequence is: 1 .Turn on GPIO_A1. 2. Turn on combination of GPIO_C*. 3. Turn off all GPIO_C*. 4. Turn off GPIO_A1. 5. Turn on GPIO_A2. 6. Turn on combination of GPIO_C*. 7. Turn off all GPIO_C*. 8. Turn off GPIO_A2. Etc...

If you just want to try out multiplexing. You can leave out all the transistors, and use resistors of at least 1.2kOhm. That way you'd never exceed the 20mA per IO pin on the Arduino, even if all segments of a digit are lid. The downside will be that it will be less bright. Connect all the four common anodes for the four digits (22,23,31,32) to 4 Arduino pins. Then connect all A segments (20,25,29,34) together, and connect that, via a 1.2k resitor to an Arduino pin. Repeat for all segments and the DP. You'd end up using 8 resistors and 12 Arduino pins.

As Juraj mentioned, you can use shift registers, such as 74HC595 which uses the SPI protocol.
To elaborate slightly on this:

You can cascade 4 shift registers, totaling 32 pins for output
If you need 36, you can use the remaining 4 as normal pins (this is probably the easiest solution)
Or you can use the Chip/Slave Select feature of SPI to control two chains of shift registers. So e.g. one chain is doing 4 * 8 = 32 pins, the other (single shift register) using 8 pins (from where 4 pins are used only).

To make a clock, use a RTC (Real time clock) module/IC, a counter (unless very high frequency) does not need an external IC.

for 4 digits two 74HC595 are enough

True … wonder where the 36 pins come from (7 digits + 1 dot maybe, is 8 * 4 = 32 pins, one for VCC/GND, but other two ?)

@MichelKeijzers by 36 I mean:4X7=28 segments 4X1=4 dots,and the other 4 remaining are the pins for the common anode for each digit.

In that case, 32 pins need to be controlled by the shift registers, so 4 shift registers will suffice, and no need for CS/SS, just cascade them.

1 and half shiift registers. one for 7 segments and dot and one for digit select. two registers can handle 8 digits. see the tutorial.

@Juraj that's even easier indeed


text:
Send RAW IR code with ATtiny85
I am looking for a ATtiny85 send RAW IR code using a ATtiny85.  I have it sending HEX code just fine, but just cannot find something for RAW. I have IRsend RAW IR running just fine on a NANO. Problem is will not compile on a ATtiny85. ATtiny85 does not have Timer2, and it seems most of the code written uses Timer2. ATtiny has only Timer 0 and 1, both 8 bits wide. I tried to port it over from NANO to ATtiny85 by fooling with the IRLib2, but just do not have enough experience to make it happen..HELP
Thanks
Darryl..

what does this mean? sending HEX code just fine

The IRremote library for Arduino does support of using different timer, all you need is correctly configure it of the board you use. As far as I can see is that it does support ATtiny85, all you need is to configure it correctly. You can run IRremoteInfo example sketch to confirm if you have the correct setup.

The definition of the timer to be used and how to generate the 38kHz clock for each MCU type is defined in boarddefs.cpp

When i say HEX, one of the IR Libs uses HEX instead of RAW  Example = 0x1CE318E7 (SANYO Mute .  Raw is a series of numbers representing Carrier on time and carrier off time


text:
Part identification
This may be a dumb question but i would like to know what this part is. Anyone who knows?

Create a full picture (who knows what's behind your fingers), dimensions, any textual identification, where and in what device you found it (and what brand, model).

maybe something like that?
https://www.aliexpress.com/item/32847035065.html

We cannot see anything on that image. About 99% of that image is not showing the part

Maybe something like this (just kidding): https://nl.123rf.com/photo_73468723_rustieke-houten-plank-met-nagels-geïsoleerde-bruine-plank-.html

it looks like an index finger and the middle finger ... the item taking up most of the image is a wall

This looks like something out of an Arduino n-part “sensor kit”. It’s hard to tell because the quality of the image is not very good.
My guess is, this is an analog temperature sensor, like in this link, part number 18. You can also find an example sketch there.


text:
How to properly pass struct as argument?
This is my first question! i'm sorry if i'm doing something wrong.
I'm trying to write a code that blinks some leds, but i cant quite work out how to use structs as arguments.
This is the code:
void setup(){
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  //digitalWrite(2,HIGH); //debugging

}

struct Timer {
  unsigned long DutyCycle;
  unsigned long LastTime;
};

void SwitchPin(int pinn, bool ledstate,Timer timer) {
  if (millis() - timer.LastTime >= timer.DutyCycle) {
    if (ledstate == LOW) {
      ledstate = HIGH;
    } else {
      ledstate = LOW;
    }
    digitalWrite(pinn, ledstate);
  }
}

void loop()
{

}

When i try to verify it says:
exit status 1
'Timer' has not been declared

among other rubish.
I'm very new to programming in general, so probably i'm doing something very wrong without noticing it.
I would be very glad if you can explain exactly what im doing wrong, so i know what to do in the future.

BTW (regarding your question) : void SwitchPin(int pinn, bool ledstate, const Timer& timer) were a better signature for your function.

I just tried compiling your code - it compiled with no errors.

i have same problem, what you do for it.


text:
How do I combine a variable and characters into a string with Arduino?
I am building some sensors with Arduinos, which each have a unique integer address from 1-9 (This address is an int variable stored in a struct 'Matrix', the variable name is Matrix.Address). The sensors will all be connected to a PLC via SoftwareSerial (BitBanging) through an RS232 converter. Since all of the Sensors will be connected to the same RX & TX ports on the PLC, I need a way to address each sensor through a unique string.
My plan is the following:
*If the PLC wants a reading from sensor #1, it will send the string: "1,read"
All of the sensors should receive this string, but I only want the sensor with address '1' to respond.
*What I am trying to do is come up with a line of code similar to the following:
    if (plcCommand == (Matrix.Address + ",read<CR>")) {
  mySerial.print(GenerateEquation());

Basically, I need to insert that 'Matrix.Address' variable into a string which will be compared to the incoming string.
It seems like a very simple thing to do, but I am having trouble coming up with a solution.
Any help would be appreciated!

what type are those variables?

You're thinking backwards. Instead of building up one string and comparing it to another, you should instead be splitting down the string you are being sent and dealing with the different parts of it separately.
Say you are being sent the string 32,read\r. Instead of making another string 32,read\r and comparing it to what you have received you should instead be splitting the incoming string up.
That way you then have a string containing 32 which can be converted to an integer, and a string containing read. It now becomes very simple to do your comparisons without messing with building strings in RAM wasting precious memory.

it will send the string: "1,read"

Fairly simple:
1) the dumbest would be to use serial print to print the number, and then ",read".
2) a close 2nd (in terms of dumbness) is to use s/printf(): simple but costly on a mcu.
3) a smarter approach is to convert the number to a string - you can use standard c routines if your compiler supports them, or hand-roll your own.
4) if the number of sensors are limited, a look-up table or a switch/case statement would work well.

If the PLC wants a reading from sensor #1, it will send the string: "1,read" All of the sensors should receive this string, but I only want the sensor with address '1' to respond.

Is your question about sending the "1,read".  If you're using a serial line like you say then there is no difference between sending that as a single string in one print command or sending first the number and then the text part using two print commands back to back. The exact same thing will end up going out over the wire either way.  So just use two separate print commands.


text:
Is it safe to short two pins together for conditioning a sketch?
I want to make a sketch which behaves differently, i.e.:
pinMode(pin1, OUTPUT);
digitalWrite(pin1, HIGH);

pinMode(pin2, OUTPUT);
digitalWrite(pin2, LOW);

pinMode(pin3, INPUT);
// And a user decides to short pin3 with pin1 or pin2

if (digitalRead(pin3) == HIGH) {
  // behavior 1
} else {
  // behavior 2
}

But, I wonder whether shorting two pins with/without a resistor safe or not. If it is dangerous, what is an alternative way to do such a thing?

I would pinMode(pin3, INPUT_PULLUP);, this way you condition the sketch on the pin being either grounded or not. You can then connect a switch between pin 3 and GND to have the switch control the behavior.

Firstly, why would you?
All you are doing is connecting the input pin 3 to either VCC or GND, since that is what setting a GPIO to HIGH or LOW gives you - why would you waste two GPIO pins for that purpose?
"shorting" an input pin with VCC or GND is what you do with a button or switch anyway. The resistor in that case is used to hold the pin in the opposite direction when the button isn't being pressed. The same effect can be created using a two-way switch connecting the pin to either VCC or GND with no resistor required.
So yes, you can "short" the input pin with an output pin safely - as long as that input pin never becomes an output pin at any time (hint: never use pin 13 on an Uno for this - it becomes an output to flash the LED during the bootloader over which you have no control. The same goes for the TX pin.)


text:
Should BLK and GRN of Pro Mini be connected to upload sketch?
Is the following connector is valid for Arduino Pro Mini (no BLK and GRN)?

I was told to make a certain Arduino application, and got some Arduino Pro Mini  (ATmeag328 3.3V 8 MHz) with the connector above.
Everytime I tried to upload an example sketch 'Blink', the IDE complains (verbose enabled):
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x83
...
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x83

resp may differ (I saw 0x1f and 0x83)
But, according to the official document,  I think that I should use some FTDI thing, which has 6 pins including BLK and GRN.
I wonder whether I can use the existing 4-pin connector, or whether I must use 6-pin FTDI connector.

BLK and GRN sound like Wire colors and those may vary from product to product.  Look at what the function of the wires are and not the colors.

You need a DTR signal to connect to reset to enter the bootloader, of manually enter the bootloader at the right time by pressing the reset button.

Thank you for comments. I realized that BLK and GRN are not relevant in my case. After compiling, I press reset button manually, start upload, release the button, and upload succeeds. It's somewhat inconvenient. I need to get some board to do it automatically.

"After compiling, I press reset button manually" <-- That's due to missing DTR connection.   If your USB TTY adapter does not expose a jumper for DTR, you may be able to solder one on by tracing where the DTR pin is on your particular USB-TTY chip.

If you look at the picture in your link, you would see that BLK is ground (GND) and GRN is DTR, that is used to reset the board and enter the bootloader for programming.
As Majenko said, without DTR you will need to press the reset button at the right time, to enter the bootloader.


text:
Arduino Micro not providing regulated power
I have an arduino micro that works fine off USB. I need to power it from an external 12V power supply. When I connect the 12V supply to the adjacent VIN and GND pins, the arduino will not power up. When I measure the power at VIN, it's 12V. When I measure power at the 5V pin, it's also 12V. If I disconnect the external power and go back to USB, it powers up.
Blown regulator?

Or unconnected ground? Otherwise I can't imagine 12V on 5V without blowing MCU.

In comparing this with another Arduino Micro, it appears that the regulator is malfunctioning.

Is this actually an Arduino product, or some unspecified knock-off?

Actual Arduino. I certainly won't rule out that I fried it at some earlier point, but it's clear that the regulator is not working.

It may blow the entire board. Feeding 12V into the regulated 5V line would likely damage the CPU and various other subsystems.


text:
NodeMCU and expected ';' before wrong ' " '
I am creating a home weather station but the Arduino IDE shows
"expected ';' before 'viewport'".

It detects wrong quotation marks. My code:
     String message2 = "<!DOCTYPE html>";
  message2 += "";
  message2 +=  "<title>Bootstrap Example</title>";
  message2 += " <meta name="viewport" content="width=device-width, initial-scale=1">";
  message2 += "<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">";
  message2 +=  "";
  message2 +=  "";
  message2 += "";
  message2 += "";
  message2 += "
";
  message2 +=  "
Teplotná Stanica
";
  message2 +=  "
Teplota:";
  message2 +=  dht.readTemperature();
  message2 +=  "
";

  server.send(200, "text/html", message2);}

Can someone tell me what´s wrong?
I am using Arduino IDE

Have you looked at your quotes yet? All of them?

In C you can not use quotation marks inside quotation marks (thus nested).
Replace
message2 += " <meta name="viewport" content="width=device-width, initial-scale=1">";

to
message2 += " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">";

By using the escape character \  it means that \" is a character (")  instead of the beginning or start of a string.


text:
Arduino and big servo
My dad told me, if i can mount some servo (to control 4 way ventil of heating) to his arduino-controlled home. But there is a problem... The servo does not have a normal 3 cables but 6 and I have no idea how to control. So i start some research about it and i found web site of manufacturer. There was also a Datasheet, but i dont understand it :D. So here is a link to the Manufacture´s web: http://www.mutmeccanica.com/prodottomutmeccanica.php?p=207
And link to datasheet: http://www.mutmeccanica.com/download_file.php?file=downloads/scheda_V70.pdf
And I have a question: Is any hope to connect this to arduino? Is there some shield for it?

I can see only 4 or 5 pin in that datasheet, not 6 pin.

In the Arduino world, a servo motor is a RC servo motor. It runs at 5V or 6V and most of them can rotate 180°.
In an industrial environment or with the central heating in a house, the valves are often 24V AC. The most common voltages are 12V and 24V, and most of them with work with DC as well.
Sometimes the term "servo" is used for them, that is for example for a controller for valves with multiple positions.
To control them with an Arduino, the easiest way is with a number of relais.
Some intelligent valve controllers have an input signal. That is the one that you have.
The link to that datasheet is for a valve controller for 24V or 230V AC mains voltage. It has inputs to control it. Depending on the type, the input signal can be 0...5V, to 10V or to 20mA. Which one do you have ?
When that valve is in a central heating, it is possible to cause damage. First of all the central heating is tuned to the house. The valves work together with the pump, and not every system has a automatic overpressure-loop-valve.


text:
Using a separate power supply?
I'm new to the operation and applications of the arduino and have a question. I would like to run 6 x 4 bit seven segment displays from an arduino controller. How do I connect an external supply to the displays to ensure I don't overload the arduino please?
Regards

Here's a tutorial from Sparkfun that shows how to drive an LED using a transistor to switch the LED. Where the transistor is connected to +5v, that should be to your external 5v supply. The pin labeled "Control" is connected to one of your Arduino pins. Connect the external supply's ground to the Arduino's ground.
Done this way, the Arduino's pin driver only needs to supply enough current to switch the transistor; the current to power the LED is provided by your external power supply.


text:
If-statement gets ignored?
I'm kind of stuck with strange behaviour of my code and I really hope, someone could help me..
Objective
I'm trying to build a (multiple) magnetic stirring device with which I can either control the speed via potentiometer or via serial commands from a python script from pc (usb).
When the speed is set via serial, it shouldn't be possible to interfere with the potentiometer unless a button is pressed to unlock it.
Code
// Constants

const int FanPin[7] = {2,3,5,6,7,8,9}; // PWM Pins 2,3,5,6,7,8,9 for fan
const int PotiPin[7] = {A0,A1,A2,A3,A4,A5,A6}; // Analoge Pins 0,1,2,3,4,5,6 for potentiometers
const int SwitchPin[7] = {30,31,32,33,34,35,36}; // Digital Pins 30, 31, 32, 33, 34, 35, 36 for switches

// Variables
boolean ManualLock = false; // will be true if locked by serial input
int Fan[7][2] = { // [x][] for number of fan, [][0] for fan speed, [][1] for ManualLock
  {0, ManualLock},
  {1, ManualLock},
  {2, ManualLock},
  {3, ManualLock},
  {4, ManualLock},
  {5, ManualLock},
  {6, ManualLock}
};
int temp = 0; // Variable for temporary data
int FanSpeed[7] = {0,0,0,0,0,0,0}; // Variable fan speed
int PotiVar[7] = {0,0,0,0,0,0,0} ; // Variable for saving poti-input
byte bfr[2] = {7,7}; // Buffer for serial data

void setup() {

TCCR2B = TCCR2B & 0b11111000 | 0x01; // Timer2 (Pin 9, 10) @ 31000Hz
TCCR3B = TCCR3B & 0b11111000 | 0x01; // Timer3 (Pin 2, 3 und 5) @ 31000Hz
TCCR4B = TCCR4B & 0b11111000 | 0x01; // Timer4 (Pin 6, 7 und 8) @ 31000Hz

Serial.begin(9600);
delay(100);

// Declaration of Pin Modes
for (int i = 0; i < 7; i++){
  pinMode(FanPin[i], OUTPUT);
  pinMode(PotiPin[i], INPUT);
  pinMode(SwitchPin[i], INPUT);
  }
}

void loop() {
for (int i = 0; i < 7; i++){
  // ManualLock not active -> manual mode
  if (!Fan[i][1]){
    //Serial.print(i);
    //Serial.println(" ManualLock not active");
    PotiVar[i] = analogRead(PotiPin[i]);
    Fan[i][0] = map(PotiVar[i], 51, 1023, 60, 255);
    //Serial.println(Fan[i][0]);
  }
  //ManualLock active -> unlock by pressing button
  if (Fan[i][1]){
    temp = digitalRead(SwitchPin[i]);
    if (temp == HIGH){
      Serial.print(i);
      Serial.println(" ManualLock will be deactivated");
      Fan[i][1] = false;
      Serial.print("Fan[i][1]: ");
      Serial.println(Fan[i][1]);
    }
  }

  // fan off @ low poti setting
  if (PotiVar[i] < 50){
    Fan[i][0] = 0;
  }
}

// look for serial data

if (Serial.available()){
  Serial.println("Something's there!");
  Serial.readBytes(bfr, 2);
  delay(1000);
  Serial.print("Serial data: ");
  Serial.println(bfr[0]);
//  Serial.flush();
}

//Serial.print("before loop bfr[0]: ");
//Serial.println(bfr[0]);

for (int i = 0; i < 7; i++){
  if (i == int(bfr[0])){
    Serial.print("i: ");
    Serial.println(i);
    Fan[i][0] = int(bfr[1]); //set fan speed variable
    Fan[i][1] = true; // activate ManualLock variable
    byte bfr[2] = {7,7}; // clear buffer
    Serial.print("bfr[0]: ");
    Serial.println(int(bfr[0]));
  }
}

for (int i = 0; i < 7; i++){
  analogWrite(FanPin[i], Fan[i][0]); // write fan speed
  }
}

Error(s)
When I send a command via my python script, the speed is set correctly and I get the following output:
Something's there!
Serial data: 0
i: 0
bfr[0]: 7
i: 0
bfr[0]: 7
...and again and again and again...

Which means, although i "reset" my buffer variable to something that should prevent entering the if-statement, it will somehow fulfill the "if (i == int(bfr[0]))" condition.. but why?
If any further information is needed, i'll happily provide that.

This (inside your for loop) does not do what I think you think it does:
byte bfr[2] = {7,7}; // clear buffer

You think it sets the contents of the bfr array you declared at the top to {7,7} but what it actually does is declare a new byte array in that scope, containing the values {7,7}. It's not used and is immediately thrown away again.
I would expect the compiler to warn about it -- does it?  (If so, take it as a lesson not to ignore compiler warnings!)
I think you want to replace it with
bfr[0] = 7;
bfr[1] = 7;

or something equivalent.

unfortunately, there was no warning.
but now it works! thank you so much!


text:
Figuring out IR sensor PWM frequency with Arduino
I'm trying to verify the pulse width of an IR receiver I "borrowed" from one of those cheap RGB controllers (like thisone) with an arduino nano. But the data I'm getting right now is about 3.4KHz and not the 38KHz I expected.
I'm trying to measure it by connecting the data pin of the IR on INT0 and listening for any change, if the pin goes low I start a measurement, if it goes high I stop the measurement and read out the value.
I'm using Timer1 and no prescaling
My code is as followes
#include <util/delay.h>

#define inpin 1 << PIND2
#define timeron 1 << CS10 //timer no prescale

bool wasTiming = false;
short i = 0;

volatile short timings[20];
volatile bool print = false;

volatile short seconds = 0;

int main()
{
    USART.begin();

    _delay_ms(500);
    USART.writeln("Arduino online");

    DDRD = 0;

    TCCR1A = 0; //no compares, normal counter mode
    TCCR1B = 0; //clock off

    EICRA = 1 << ISC00; // Any change INT0 (PD2)
    EIMSK = 1 << INT0; // INT0 interrupt enable

    sei();

    char buff[20];
    for (;;)
    {
        if (print)
        {
            print = false;

            for (short j = 0; j < 20; j++)
            {
                sprintf(buff, "% 6d ticks", timings[j]);
                USART.writeln(buff);
            }
        }
    }
    USART.end();

    return 0;
}

ISR(INT0_vect)
{
    if (PIND & inpin) //pin high
    {
        if (wasTiming)//
        {
            TCCR1B = 0; //timer clock off
            timings[i] = TCNT1;
            TCNT1 = 0; //empty timer register
            wasTiming = false;

            i++;
            if (i == 20)
            {
                print = true;
                i = 0;
            }
        }
    }
    else // pin low
    {
        if (!wasTiming)
        {
            TCCR1B = timeron; //timer clock on
            wasTiming = true;
        }
    }
}

and the output data is
 13902 ticks
  8865 ticks
  9961 ticks
  8877 ticks
  9968 ticks
  9842 ticks
  8506 ticks
  9896 ticks
  9585 ticks
  9865 ticks
  9541 ticks
  8853 ticks
  9545 ticks
  8888 ticks
  9885 ticks
  9954 ticks
  8515 ticks
  9885 ticks
  8909 ticks
  9874 ticks

on average that looks like about 9500 ticks, which leads me to the following calculation: (16,000,000 / 9,500) * 2 = 3,368.4Hz
Am I doing something wrong here? Or is the data that I'm getting correct, in which case, how would I go about turning that into 1's and 0's?
I'm not really looking for off-the-shelf solutions, half the fun of doing this is figuring it out myself. Eventually I'm gonna build my own RGB controller with this to replace that cheapo thing I already have (it has a few flaws I would like to correct).

You need to evaluate the IR waveforms using an oscilloscope. Without this you are running blind. Also consider that the IR remote control is likely to be outputting various pulse widths as part of the protocol that it uses.


text:
Creating and Arduino synthesizer without the tone library
I am thinking about trying to make an Arduino synthesizer using the true analog output on the Due. However I would like to be able to play multiple notes at the same time on a single buzzer. Is this possible and how would I do it?

what is buzzer? .... is it able to produce different tones?

You just have to add the waveforms. For example, if you want to play
pure tones (the simplest and most boring timbre), you generate a sine
wave for each of them and add them together:
struct Note {
    float frequency;
    float phase;
    bool is_active;
} notes[MAX_NOTES];

void output_sample()
{
    static uint32_t previous_time;
    uint32_t now = micros();
    uint32_t elapsed_time = now - previous_time;
    previous_time = now;
    float output = 0;
    for (int i = 0; i < MAX_NOTES; i++) {
        Note *note = &notes[i];
        if (note->is_active) {
            output += cos(note->phase);
            note->phase += 2*M_PI*note->frequency*1e-6*elapsed_time;
            if (note->phase >= 2*M_PI) {
                note->phase -= 2*M_PI;
            }
        }
    }
    analogWrite(DAC_PIN, 2048 + round(output * (2047.0 / MAX_NOTES)));
}

The function output_sample() should be called as frequently as
possible. You can change the notes array any time to add, remove or
change notes.
There is some room for optimization here, like:

storing 2*M_PI*note->frequency*1e-6 as the “frequency” in order to
save some calculations
using a wave table instead of the cos() function (I don't know how
good is the Due at transcendental math)
replacing elapsed_time by a constant if you can manage to output the
samples at a fixed rate.

Edit: I wrote “You can change the notes array any time to add,
remove or change notes.” Here is how to start or stop a note, i.e. to
add or remove it from the list of active notes:
// Start a note. Returns an index to be used with stop_note(), or -1 if
// we couldn't start the note because we are already outputting the
// maximum number of simultaneous notes.
int start_note(float frequency)
{
    int i;  // index of the note in the notes[] array

    // Find a free slot in the array.
    for (i = 0; i < MAX_NOTES; i++)
        if (!notes[i].is_active) break;  // found

    // Couldn't find a free slot?
    if (i == MAX_NOTES) return -1;

    // Setup the note parameters.
    notes[i].frequency = frequency;
    notes[i].phase = 0;
    notes[i].is_active = true;
    return i;
}

// Stop the note with the given index.
void stop_note(int index)
{
    if (index >=0 && index < MAX_NOTES)
        notes[index].is_active = false;
}

How would I add notes here? I am not extremely familiar with structs.

@Someone: You find a cell in the array where is_active is false, and you set the desired frequency, and set is_active to true.

how would I add an item to the note array?

Sound is nothing else than a multiple simple waves combined in to one. So, theoretically you can play as many sounds (tones) as you like on a single pin. If you want to go true analog than you probably want to use a sin wave to generate sound. However, in that case you can do the following:
Either make a function that would be capable of generating a sin wave of your desired frequency. In case of true analog this would probably be done by calculating actual sin values and using the map() function mapping 0 - 1 to 0 - 1024 and writing to the pin. The frequency can be adjusted by changing the delay between each step of changing the voltage or DAC value. However, this will not allow for multiple frequencies.
Alternatively for multiple frequencies to be played at the same time you would need to calculate the Fourier inversion of all the waves you want to play and send the results of that to the DAC.

And you would need to use a speaker instead of a buzzer, since they can produce a single tone at a time.

“Fourier inversion” is needless math jargon for what is simply the sum of the tones.

@EdgarBonet yes, it's basically a sum.

How would I go about doing this?

@Someone Writing code that would preform the above described. I've included hyperlinks to help understanding what is meant and how to use it. Also, visit the https://www.arduino.cc/reference/en/ page that includes much information on how to perform mathematical and logical operations in the Arduino language as well as how to control the hardware of the Arduino.

Mixing sounds is not as simple as summing them mathematically (nor summing and averaging to bring the level back down). I made that mistake once years ago, and the results were crap. Once I found a proper sound mixing function I never looked back...


text:
Arduino audio frequency reader
I have a simple project for my arduino : light some leds when i send a certain frequency from my smartphone through the jack output . For example ,
 I play a simple audio file generated with a frequency generator (it generates sinwaves, sawtooth, quadrate waves...) at 1kHz --> a red led turns on
I play another frequency (5kHz) --> a green led turns on.
I read similar questions , but they needed a precise reading of the signal frequency, so they had to convert from AC to DC and from 700mV to 2,5V, is it necessary in my case ? I can also prepare a track with a program called audacity with the current remaining always positive but oscillating between 0 and 0,7 mV.
How can i realize my project in the simplest way possible ?
Thank you

It might be easier use a single frequency, and turning this 'sound' on and off in a certain pattern. E.g. sound on for a second is red, sound on for half a second is green.

With a relatively clean source like a direct connection, timing the zero crossings in software should be simple.  The main issue is that you need to build a network which turns the audio signal into a digital one, by biasing it to cross the threshold, ideally rapidly.  Some ideas to consider are utilizing the ATmega's built-in comparator pin, bias resistors and a DC block capacitor, or even using a tiny audio transformer to create a high impedance signal that rapidly swings across the full logic range, and then clip it to safe levels.  This is a problem that has been solved many times before.

@ChrisStratton,  do you have a link to this  “tiny audio transformer”?  I haven't been able to find any that are tiny.  Small, yes; eg EI14 Audio Transformer 1300 : 8 Ohm about 12 mm on a side; but tiny, no.

That is the kind of thing I meant, yes.  Compared to the radios of the era where it was used, it was tiny.  Congrats on even still finding one - they used to be all over the place, but with the change to class D IC amps they are mostly relegated to history... struggled to find even one to experiment with when I wanted to try mis-purposing one a few years ago.

Connect the signal to an analogue input on the Arduino, via a DC blocking capacitor, with a potential divider centring it around 2.5v.  Make sure the voltage swing is within range, which it should be.
Keep the frequencies of the signal low, under say 2KHz.  For example, use 500Hz, 1000Hz, 1500Hz, 2000Hz.
Sample (analogRead()) the signal as fast as you can (which is about 10KHz) for a short while, recording the min and max values.  From this, you can find the centre value, 1/4 value and 3/4 value.
Now to find your frequency, sample until the signal goes above the 3/4 value.  Get the time with micros().  Sample until the signal goes below 1/4, and then sample until it goes above 3/4 again and get the time with micros().  Do this a few times and average them.  The difference between the two times is approximately your sample period, so you can easily find the frequency.
Determine which of your chosen frequencies most closely matches the frequency you've sampled.

If you can properly bias your signal, say with a cap and a pot, you
could read it with a digital input. You can then time the rising edges
with micros(), either by polling the pin or using an interrupt. You
could achieve greater accuracy by using the “input capture” feature of a
16-bit timer, if you are using an AVR-based Arduino and are not afraid
of getting your hands dirty with low-level programming.
You need to get the right voltage range for this to work though. On an
Arduino Uno, for example, the thresholds for the input switching from
HIGH to LOW and back are typically around 2.1 and 2.6 V
respectively, so you must make sure that your signal amply covers this
range. If you can get 1 V peak to peak, that should be enough, and
you can then use the pot to tune the offset.


text:
why leonardo bootloader is bigger than UNO?
Apparently leonardo and UNO are very similar boards.
However, despite that both have the same flash memory size, Leonardo bootloader is considerably bigger than UNO bootloader (4KB vs 0.5KB).
what would be the reason? it is there any way to use smaller bootloader in leonardo?
Uno specs: https://www.arduino.cc/en/Main/ArduinoBoardUno
Leonardo specs: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo
Thanks!

Apparently leonardo and UNO are very similar boards.

No, they are very, very different.
The Uno uses an external USB-UART bridge. This means that the bootloader code only has to read from the UART in order to program the device.
The Leonardo has USB support built into the MCU. This means that the bootloader must contain an entire USB Device stack in order to process the USB packets and then pass the payload to the programming routines.


text:
Convert float to char array on ATtiny85
I'm having a hard time trying to convert a float into a char array so it's stored like '7.125' just like the float looks.
I'm trying to communicate with an ATtiny85 (slave) and a program on a Raspberry Pi (master) over I2C.
The master expects 31 bytes from the slave when data is sent to it.
When I use this code on the ATtiny85 everything works as it should, the Pi gets the data correctly.
    char computerdata[35];
    computerdata[0] = '3';
    computerdata[1] = '.';
    computerdata[2] = '8';
    computerdata[3] = '7';
    computerdata[4] = '7';

    TinyWire.send(1);
    TinyWire.send(computerdata,30);

Of course I need to put a float variable in the array and not define numbers like I have for testing and this is where it breaks.
When I do something like this, it doesn't work, the Pi reports parsing error yet when I do this on the Due with Serial prints the char array looks good but something is different about it.
  sprintf(computerdata, "%2.32f", pH);

OR

  snprintf (computerdata, 35, "%f", pH);

What am I missing? Any ideas?
Thanks

Just to complement Michel Keijzers’ answer: sprintf() or snprintf()
are normally the right solution. On the AVR platform, however, float
conversions are left out of their default implementation, because they
take quite a lot of flash space, even when not used. On the other hand,
the avr-libc provides the non-standard function dtostrf()
for doing this conversion. The program
void setup() {
    float f = 3.877;
    char str[35];
    dtostrf(f, 0, 3, str);
    Serial.begin(9600);
    Serial.println(str);
}

void loop(){}

outputs
3.877

perfect, thank-you!

The reason is that the library which implements snprintf and sprintf can be dependent on the compiler used for your MCU, so in your case it's not supported.
If you always need the form %2.32f why not put it in directly, like:
int i = int(3.877 * 1000.0); // Assuming f of form a.bcd, i will be 3877
char str[6];
str[0] = (i / 1000) % 10;
str[1] = '.';
str[2] = (i / 100) % 10;
str[3] = (i /  10) % 10;
str[4] = (i      ) % 10;
str[5] = '0';

It will be much faster too.

Thanks for the answer but that wouldn't compile, got this error. Edgar's worked good.
sketch_feb28b.ino: In function 'void setup()':
sketch_feb28b:21: error: invalid operands of types 'double' and 'int' to binary 'operator%'
sketch_feb28b:22: error: invalid operands of types 'double' and 'int' to binary 'operator%'
invalid operands of types 'double' and 'int' to binary 'operator%'

True, I changed it, now it compiles (did not check it on an Arduino).
I will keep it despite dtostrfis better in most cases.

works good now. :)

Thanks for the confirmation

On an attiny85, the real question is why you got a float in the beginning. :)

@DataFiddler Because you need one (?) … or do you mean it's normally better to avoid floats and multiply a float value to an integer with some specific digits (e.g. use an integer value * 1000, to have 3 digits in form a.bcd ?)

You convert the float to an int. Probably it became a float by * 5.0 / 1023 or similar nonsense

@DataFiddler that's for the op to answer I guess.


text:
Run servo when image is capture
I am trying to create a program when the camera capture the servo will rotate in 90 degrees continously, but my code will stop in print output 2 any idea to run the servo continously?
Here's the Code
import numpy as np
import cv2
import serial
import struct
import time

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

x=0

while(True):

 # Capture frame-by-frame
    cap = cv2.VideoCapture(0)
    #framerate = cap.get(5)
    ret, frame = cap.read()
    cap.release()
    # Our operations on the frame come here

    filename = 'C:/Users/DELVO/Desktop/tryTest/bruises/main/images' +  str(int(x)) + ".png"
    x=x+1
    cv2.imwrite(filename, frame)
    print(ser.write(x))
    time.sleep(5)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

Arduino Code
#include <Servo.h>
int data_x = 0;
int data_y = 0;
int data[1];
Servo myservo_x;
Servo myservo_y;// 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() {
  Serial.begin(9600);
  myservo_x.attach(7);  // attaches the servo on pin 9 to the servo object
  myservo_y.attach(10);
  myservo_x.write(90);
  myservo_y.write(90);
}

void loop() {
  while (Serial.available() >= 2) {
    //    data_x=Serial.read();
    //    data_y=Serial.read();
    for (int i = 0; i < 2; i++) {
      data[i] = Serial.read();
    }

    myservo_x.write(data[0]);
    myservo_y.write(data[1]);

    Serial.println(data[0]);
    Serial.println(data[1]);
  }

}

"code will stop in print output 2" Where is "print output 2" exactly? I don't understand your problem. Please describe it more. What is the code actually doing and what did you expect it to do?

did you use my program? when the output 2 print the servo will stop

No, I did not. We are first trying to find an error by looking at the code. Also I don't have a free pi with cam lying around, so I cannot test your code. So you mean, when 2 gets printed on the Pi

no no im just using arduino anyway my main problem is when the 2 gets printed the servo will stop.

is the arduino code giving error because you have initialized the array data with length of 1 (int data[1];) and in the for loop the length is exceeding the allocated length of the string: for (int i = 0; i < 2; i++) {
  data[i] = Serial.read();
                       }

How to do it? that my servo won't stop if im not close the program.

@TrialAndError Have you tried writing int data[2]; instead of int data[1];? That is your first step, since it is the obvious error

I see. Thank you.


text:
Arduino connection websocket always fails
I am using the Arduino Websocket Client library to connect my Arduino Uno to a Socket.IO server. But the connection always returns 0 (fail) after the handshake.
Anyone has used this library before? How could I debug this?
#include "Arduino.h"
#include <Ethernet.h>
#include <SPI.h>
#include <WebSocketClient.h>

byte mac[] = {0xB8,0x27,0xEB,0x7E,0x2D,0xC9};
char server[] = "labathome.rexlab.ufsc.br";
int port = 8001;
WebSocketClient client;

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac);
  Serial.println(client.connect(server, port));
  client.setDataArrivedDelegate(dataArrived);
  client.send("Hello World!");
}

void loop() {
  client.monitor();
}

void dataArrived(WebSocketClient client, String data) {
  Serial.println("Data Arrived: " + data);
}

PS: I tested the server and it works fine, and I also tested with a normal WS server instead of the Socket.IO, and nothing :(

Wireshark is a nice tool for protocol analysis.

I know nothing about this library but it looks like the setup of your Arduino is incorrect.  What IP address has your Arduino got?  Where is the DNS server to resolve the server's address and how are you telling the Arduino this? Does it work if you use the IP Address rather than the name for the server?

And like @MikaelPatel says, download wireshark (or similar) and verify that the Arduino is connecting to the server.  (You might be able to see the server's logs).  I suspect it isn't.

@MikaelPatel how could I forget about wireshark! Thanx

@Matt oops, true. I am using DHCP (I'm printing the IP got by the Arduino here), and I usually use IP addresses rather than the name, my bad.

With the help of the library developer, I found out that it was a problem on the handshake version. So, I just downgraded my socket.io app from 1.0 to v 0.9.11 and it worked.

What version were you using?  (What version has the handshaking problem?) - Useful in case anyone searches and lands on this thread.  Also its OK to accept your own answer.