text:
Extend Pyduino over wireless network
I followed a guide to control my arduino uno using a python web server API (flask), and it works like a charm using the COM port on my PC. I would like to extend this over the network with an ESP8266 module so i can have a web server handling my project's event scheduling and hard work using python/html/css/js (anything supported/needed) and have the arduino as a client receiving the server data and acting accordingly. I am not limited to this method as it seems pretty hard to generalize over the network (Use a virtual COM port on the server side and forward the arduino using the router?//i  have to specify where the arduino port is located) so any other way to setup a Web server handling the event triggering and sending the ON/OFF information to my arduino (i just need to trigger a relay) is accepted.

There are many example how to set up a webserver on an Arduino using an ESP and also about doing this directly with an ESP (since most ESPs are more capable than most Arduinos). When you have a webserver running on the Arduino, sending information to it is nothing more than a web request. Have you looked into this? If yes, why is it not fitting for you?

I was thinking about using the arduino as a web client listening directly to my server and couldn't find exactly what i wanted but then i thought about what you said. I guess i can setup arduino/esp as a web server that handles requests and have another website that sends the requests when certain events are triggered.

I quickly searched for "arduino web request ESP" and found some promising sites. If think, you should look more into it. You write something about a virtual com port over wifi in your question, but honestly I think you would be going the hard way trying that. On a TCPIP network it is the easiest thing to simply do web requests.

I cant understand whats the best way to deal with my problem. Can i set up the arduino to constantly "listen" to a website for a specific event or do i have to use it as a server, port forward it and send the triggered events that way


text:
Input current for L293D shield
I am a newbie in arduino working on a bot with L293D shield. But I have a  question as what would be the input current to drive all 4 dc motors and 2 servo motors.  I can see that it can supply 0.6Amp current for the four motors.
I am considering the amount of electrons flowing in per unit time is equal to the electrons flowing out of the circuit, as an simplistic aprach. So practically the input current should be greater than or equal to 2.4Amp.
As I have 6 motors in total so I was thinking about making a 12V 3Amp DC supply for a better performance. Should I do it like that? will it damage the board or shield?

Buying a power supply with more amps doesn't hurt the circuit

But there should be a limiting current, right? otherwise it can burn it or parts of the shield? isn't it?

No, the circuit will draw as much current, as it needs. Nothing ever burns, because you provide too much current. It burns, because you draw too much power. If you draw more current, than your power supply can supply, the power supply might get fried. If you draw more current through a  motor driver, than it can handle, it might get fried.

That is great! I completely mised it. Thanks @chrisl

In fact you should buy a power supply that provides 20% - 50% more than you think you need, to allow for surprises.

@chrisl you should post your response as an answer. You might want to state it a little more broadly. Something like: "If you feed a device the correct voltage, it won't draw more current than it needs unless it is faulty. Having a power supply that is able to provide more current than you need should not damage anything (except for components like LEDs that require external current limiting, but that's the exception.) On the other hand, if you try to draw more current from a power supply or other current source that it is designed to provide, you can damage the current source.

I will write an answer, when I'm home again, with a computer. Writing a longer answer on the smartphone is really annoying >.<

Here the proper answer:
The vast majority of devices are constant-voltage devices. They need a constant operating voltage to work correctly. Microcontrollers are such devices. When operating, they will try to draw as much current from the power source, as they need, but not more. Much like a simple resistor with an applied voltage will draw a specific amount of current (calculable with Ohm's law), complex devices like microcontrolelrs have something like an overall impedance/resistance, that is depending on their specific operation. So also here the device only draws as much current, as it needs. (I wrote about an overall impedance to emphasize the fundamental principle. No one would really specify an overall impedance for such a device, because this would only be a value calculated by the voltage and current needed, not a real resistance.)
This means, that burning parts are not due to the power supply supplying more amps. They get burnt, because something draw too much power trough them.
Let's look at some examples:

Imagine, that you create a short between 5V and ground on your Uno. A short means, that a high current can flow, since the resistance is very low. Now you are drawing a high current from your 5V pin to the ground pin. The Arduino's 5V pin is connected to a voltage regulator (for if you use Vin) and over a diode to USB. Both parts are only rated for a maximum current (depending on the version of the board between 200mA and 1A). The high current, that you draw, will flow through one of these parts, depending on your input source. This part will get fried, because a way to high current will flow through it, just because you draw the current.
A strong motor, that needs more current, than the board is rated for, would result in a similar problem like the short circuit. Indeed every device, that needs more current, than the board is rated for, might result in frying the mentioned parts.

But what happens, if you draw more power from the power supply itself, than it is rated for? The power supply electronic is similar to the Arduino board. When you draw too much current from the power supply, some parts of it might get fried and stop working. Thus, you should not try to draw more current from it, than it can provide. Often power supplies have a protection circuit, that will either lower or directly cut the voltage, if too much current is drawn. This is for the safety of the supply and should not be used for current limiting your own application normally.
So, you should always calculate, what current you expect to need, and then take a power supply, that can provide more current than that. You should consider a significant headroom, so that you can add more parts, if you want to extent your project. For example, if I calculate 2A for my project, I would use a power supply in the range of 3A.

Addition:
Above I wrote about constant-voltage devices. There are also constant-current devices, for example LEDs. An LED has a specific constant forward voltage. Under that voltage it will not conduct current. Over that voltage, the current rises exponentially. The voltage over the LED will always stay the same, as it was designed. This is the reason, why you need to add a current limiting resistor to a LED. But in the vast of devices, LEDs (or in fact every diode) is an exception.

That is a great explanation and very eleborate one. Thanks for the time and effort. But I have some doubts. So I can use a 10 amp source with anything? as long as the circuit is not drwaing any more than its limit it should be okay. is that correct?

That's correct. The amperage doesn't matter, as long, as it is more, than needed. You could connect a source, that can provide 100A and it would be the same. But of course you should be careful, when changing your circuit. Providing enough power to drive motors does also mean, you are providing enough power, that the circuit can destroy itself, if you do something wrong.

Think about how a smartphone is charged. These days you can find many  different standards like Quick Charge etc. These are only ways to tell the smartphone, that it can draw more current from the charger, than normal. So the charger always provides the higher power, but the smartphone also has to actually use it. Otherwise you would still charge the slow way, with lower current. And the smartphone never breaks with chargers, that have different amperage output.

Yes I got it. The transformer in the hand made DC supply does not generally get damaged but other components like diodes, capacitors get burned as they are not capable of hadling the current over their rated values. As the transformer can supply as much current as the load draws but the components are not able to tolerate the heat over the specified value.

This entire comment answer made the loading effect much clear. I forgot it too.

source: Stack Exchange

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

sort: votes


text:
json format in esp32 with arduino json
I am using an ESP32 module for bluetooth connection and scaning wifi network. But I cannot format the json using arduinojson library in the way I want.
void scanWifiNetworks() {
  //creating json
  DynamicJsonDocument jsonDoc(1024);
  char jsonBuffer[512];
  JsonObject wifiJsonObject = jsonDoc.createNestedObject("wifiList");
  wifiJsonObject["ssid"];
  Serial.println("scan start");

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

      wifiJsonObject["ssid"] = WiFi.SSID(i);
      serializeJsonPretty(jsonDoc, SerialBT);
      serializeJsonPretty(jsonDoc, Serial);
      delay(10);
    }
  }
  Serial.println("");

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

The output is like this
scan start
scan done
5 networks found
{
  "wifiList": {
    "ssid": "quark"
  }
}{
  "wifiList": {
    "ssid": "Airtel_Zerotouch"
  }
}{
  "wifiList": {
    "ssid": "NETGEAR77"
  }
}{
  "wifiList": {
    "ssid": "Itobuz-technologies"
  }
}{
  "wifiList": {
    "ssid": "Nokia 6.1"
  }
}

what I want is something like that
{
      "wifiList": {
        "ssid1": "quark1",
         "ssid2": "quark2"
     }
}
I know I am looping in a wrong way but could not figure it out. if possible please pointing out the right direction will help a lot.

crate array not object. createNestedArray("wifiList")

You are repeatedly overwriting the ssid property of the same object.
Instead, you want to write different properties, like
wifiJsonObject["ssid" + String(i+1)] = WiFi.SSID(i);

Then, only serialize the document once, when it is complete.
That being said, I strongly concur with Juraj in that the correct way to
represent a list in JSON (and wifiList is clearly meant to be a list)
is by using an array:
void scanWifiNetworks() {
    DynamicJsonDocument jsonDoc(1024);
    JsonArray wifiList = jsonDoc.createNestedArray("wifiList");
    int n = WiFi.scanNetworks();
    for (int i = 0; i < n; ++i) {
        JsonObject wifiNet = wifiList.createNestedObject();
        wifiNet["ssid"] = WiFi.SSID(i);
    }
    serializeJsonPretty(jsonDoc, SerialBT);
    serializeJsonPretty(jsonDoc, Serial);
}

This should produce a JSON document that looks like this:
{
  "wifiList": [
    { "ssid": "quark" },
    { "ssid": "Airtel_Zerotouch" },
    { "ssid": "NETGEAR77" },
    { "ssid": "Itobuz-technologies" },
    { "ssid": "Nokia 6.1" }
  ]
}

Edit: Note that, if it's clear from the context (e.g. a request URL)
that you are transmitting a list of WiFi networks, then you can get rid
of the outer object and the "wifiList" label, and use the array as the
JSON document:
[
  { "ssid": "quark" },
  { "ssid": "Airtel_Zerotouch" },
  { "ssid": "NETGEAR77" },
  { "ssid": "Itobuz-technologies" },
  { "ssid": "Nokia 6.1" }
]

As suggested by Jaromanda X, if you are never going to extend the inner
objects with extra information, you can further simplify the document by
removing those objects and just listing the SSIDs in the array:
[
  "quark",
  "Airtel_Zerotouch",
  "NETGEAR77",
  "Itobuz-technologies",
  "Nokia 6.1"
]

Thank you. The array concept was not clear to me.

since all objects in the array are ssid - you can further simplify (and shrink) the output by changing wifiList to an array of just the ssid strings

@JaromandaX: Indeed – edited the answer. I initially assumed the OP might want to later add other properties to the entries (signal strength, channel...).

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


text:
OTA update for ESP32 in Arduino ide from a different nework
I am trying to use the OTA to update my code in esp32. I have used Web updater so far and it has worked perfectly. But I want to update the code even when I am not connected in the same network with my esp32. Say, the esp32 have an ip from my phone Ap : 192.168.1.43 and I am connected in a different one say, 192.168.25.12 As both of them are class C ip having default subnet mask then we are in different network.
I have found this following question
OTA updating the ESP32 from a separate server
It did not clarify things to me.

I know nothing about OTA updates, but isn't this just a routing problem between the networks?

then it is better to download he update with the HTTPUpdate library

there's 3 different OTA routines i've seen, (IDE, self-hosted web, WWW) maybe more exist. the one where your bin files are on a web server should work across different nets, as long as they have internet.

dandavis by self hosted do you mean the bin file and esp32 are connected in the same network?? And by www, in other networks??


text:
SIM800L LED is not blinking
I am using a SIM800L Module with esp32. I am using a 3.7V 2800mAh lipo battery to power the sim800L but the LED is not blinking. I am lookng for answers in web but evryone seems to have a different problem than mine. In other case the sim800l is at least blinkng or blinked once.
I have tested the led with multimeter and it glows so hopefully the board is okay.
Is the power supplied by the battery is not sufficient? I followed this tutorial
I am sure about the sim card as it is a working sim card in INDIA (of IDEA) and works fine in my smart phone.

According to the linked tutorial, the power source is OK. Did you see the warning that, the GND must be connect before any other pin (especially the VCC). Otherwise the device could be destroyed. A working LED is no guaranty that the board is OK too. Most probably you destroyed the device or you made a mistake when connecting the device or the batteries lifetime is at its end or the battery is not fully loaded. You did not add a picture of your setup, so I can not help further with an eventually false connected setup.

okay I shall add the picture once I am home but just give me an idea of how to check the battery. While I check the voltage with multimeter I get 3.8V steady. If the battery is not fully charged then shouldn't it drop the voltage?

Ignore the LED. Have you managed to establish communication with the SIM800L over the UART port?

I thought it needs power to start a communication. Okay let me try that.

So I Finally sort out the problem. Both Battery and Module was completely fine. The problem was with the connecting wires. The connecting wires for some reason was not capable to hold the 2amp current. As a solution what I did was, cut the legs of some  quarter watt resistance and solder them to the wire exiting from the battery and fed them directly to the vcc and ground of the module. This way it works perfectly fine.
Even it seems a weird problem with no proper explanation but this solution works for me.
-----------Editing for a better explanation-------------
So my problem was with the connecting wires. For some reason the wires I primarily used could not deliver the the current from battery terminals to the module. May be those wires had a higher resistance for which the current flowing through those could not stay at 2 ampere magnitude and by the time it traveerses the wires and reached to the module, it was no longer at 2 ampere and might be lesser than a certain value which could not trigger the module and so the module did not work.
what I did was cut some legs of a few quatter watt resistance (the metal leads getting out from the carbon resistance from both sides:pic added) and sholder them to the battery terminals. Since I knew the metal legs of quatter watt resistances had a very less resistance from my course that trick worked and delivered 2amp current through them to the module.
I am trully sorry for not attaching picture as I have already submitted the project and currently have no way to replicate the situation.

Can you please explain this part again? if possible,upload image!
As a solution what I did was, cut the legs of some quarter watt resistance and solder them to the wire exiting from the battery and fed them directly to the vcc and ground of the module. This way it works perfectly fine

Hi @Patel and welcome to the Arduino Stack Exchange. This answer is unclear and needs clarification.

@Patel Let me edit my answer. This would help in a better way. and sorry for the delay, was busy with covid.


text:
Using interrupts to facilitate time-keeping
I am making a clock on an Arduino Mega using interrupts to facilitate time-keeping. The following is my timer breakdown:

Timer0: Used for my calls to millis() which allows me to determine when a second has passed.
Timer1: Used to interrupt at 8000Hz and play a sound sample on the fast PWM pin.
Timer2: Used for fast PWM in order to approximate sound.

My time seems to be accurate for roughly 15-25 minutes and then it starts to lag behind the phone time I am using as a comparison. I am wondering if this is bound to happen using interrupts to keep track of time, or if there is something I am doing in my ISR that might be slowing things down. My ISR looks like the following:
ISR(TIMER1_COMPA_vect) {
  // re-enable global interrupts so that other ISRs can execute (millis can keep incrementing)
  // As per: https://forum.arduino.cc/index.php/topic,46133.0.html#4
  sei();

  test_time = millis();
  if (test_time - start_time >= 1000) {
    start_time = test_time;
    // ... play some audio
  }
}

Setting up Timer1 is done as follows where SAMPLE_RATE = 8000:
void  init_timer(void) {
  noInterrupts (); //  Disable  all  interrupts

  //  Clear  Timer1  register  configuration
  TCCR1A = 0;
  TCCR1B = 0;

  //  Configure  Timer1  for  CTC  mode (WGM = 0b0100)
  bitSet(TCCR1B , WGM12);

  //  Disable  prescaler
  bitSet(TCCR1B , CS10);

  // Set  timer  period , which is  defined  as the  number  of
  // CPU  clock  cycles  (1/16 MHz) between  interrupts  - 1
  OCR1A = (F_CPU / SAMPLE_RATE) - 1;

  //  Enable  timer  interrupts  when  timer  count  reaches  value in  OCR1A
  bitSet(TIMSK1 , OCIE1A);

  //  Enable  interrupts
  interrupts ();
}

What drift are you experienceing? It might just be the inaccuracy of the crystal and not the interrupts counting wrong.

I have just been eyeballing the drift. After about 30 minutes I notice that it has lagged ~1 second.

Hm over ~-550ppm drift is pretty bad, crystal oscilators I've looked at have about +/-100ppm. Have you done a negative test, like doing just a minimal sketch without your ISRs which prints millis() and tracking the drift? Also would an external RTC (like DS3231) be an option?

@MaximilianGerhardt: The Mega is not clocked off a crystal: it uses a ceramic resonator instead. 555 ppm is consistent with the accuracy you can expect from a ceramic resonator. C.f. http://jorisvr.nl/article/arduino-frequency

The resonator accuracy can be as bad as 0.1% ( 1000 ppm ) but should be rather consistent with stable temperatures. If you increment odd seconds every 999 ms, and even seconds every 1000 ms, you should be fine currently :) Your error will be less by one magnitude (factor 10) ( A second off per ~4 hours). But there are more accurate external time signals (RTC, NTP). BTW: Long term accuracy is great for the power grid frequency, and available everywhere,

Thank you all for your help :). I am aware of RTC and NTP, I am just trying to avoid using them for this project.


text:
need at least 5 volts but 3.7 lithium polymer battery does not supply enough Voltage
I am building a device using an Arduino Nano, an OLED display and infrared thermometer sensor. I want to make it rechargeable so I am using a 1 cell lipo battery and a tp4056 circuit protection board, which cuts power at 4.2 V and 2.5 V. The OLED runs in the 5.0 V port and the sensor runs in the 3.3 V port in the Arduino. Of course the system does not work since the battery only delivers 3.7 V and when I measure the voltage in the Nano, it is actually seeing around 2.6 volts in each port (I'm assuming this drop is due to internal resistance of the cables and the protection circuit). Having said that I was thinking about using a boost converter but everything I find online says that the input voltage for the boost converter should be at least 3.5 V for it to deliver a constant 5.0 V output. This would not work since as I mentioned, the protection circuit will cut the power at 2.5 V which is well below the 3.5 V mark. Is there another practical solution I could use for this system to work with 1 cell lipo battery. I don't want to use 2 cell battery pack since it would make it more expensive and bigger in size. Also, I ran the project with a 9.0 V battery and it worked perfectly fine.

This is exactly why the typical LiPO battery shield includes a boost converter.
I'm not sure where you saw the unusually high (3.5V) low-voltage limit, but that isn't typical of most converters.

Correction I meant 3 V, but this still does not solve the problem since the tp4056 cuts power at 2.8 volts according to data sheet. Please do correct me if I am wrong. Thanks in advance.

I'm not sure what you perceive the "problem" to be. Most boost regulators will shut down once they can no longer maintain regulation. If this happens at a voltage that is higher than the level that would actually cause battery damage, that isn't really a problem -- it actually helps extend the overall life of the battery, even if the amount of use per charge is slightly less.

I would recommend using a display that does not require 5v to run.  Using a lower voltage display like an led based one will simplify the system.  My favorite thing to use is the adafruit feather huzzah8266 with the charlieplex display board on top.  They fit together via header pins and it has a built in lipo charging circuit and battery connector.  You can then wire your sensor in and voila.
https://www.adafruit.com/product/2821
https://www.adafruit.com/product/3134


text:
need to compare if a byte is less than 80 hex
I am using an infrared sensor called OTI301. In its data sheet it says that in order to obtain object temperature and ambient temperature values I need to extract the binary information from the sensor and use the binary information in given formulas. I have done all that but for some reason I am not getting the right values for the object temperature. The ambient temperature seems to work well but when I put a hot object, more than 320 F, the formula returns a random negative number. Also the the sensor can go up to 780 F so I know the temperature has not been capped. Please see pictures for important data sheet information, or here are the links for the complete data sheets
https://drive.google.com/file/d/1XMRDCNzY3fn0q6lkGejs5D-pqksfRuZ8/view?usp=sharing.
https://drive.google.com/file/d/1mmdkHkNbwC5VgQxGMrq07XolajNvgBkN/view?usp=sharing. Lastly, here is the part of the code where I extract the information and apply formulas.
     void loop()
 {
   if (Wire.read()) // On success, read() will return 1, on fail 0.
   {
     buttonState = digitalRead(button);
     //Serial.println(buttonState);
     Wire.beginTransmission(DEVICE_ADDRESS);
     Wire.write(0x80);  // readout command
     Wire.endTransmission(false);
     Wire.requestFrom(DEVICE_ADDRESS, 6); // request 6 bytes
     uint8_t data[6];
     for (int i = 0; i < 6; i++) {
         data[i] = Wire.read();
     }

      //Calculate Object Temperature
     if(data[5] < 0x80) {
       TA = (data[3]+ data[4]*256+data[5]*65536)/200;
     }
     else {
       TA = (((data[3]+ data[4]*256+data[5]*65536)) - 16777216) /200;
     }

     //Calculate Ambient Temperature
     if(data[2] < 0x80) {
       TA = (data[0]+ data[1]*256+data[2]*65536)/200;
      }
     else {
       TA = (((data[0]+ data[1]*256+data[2]*65536)) - 16777216) /200;
     }

What data type is TA?

on a nano, int calculations are 16 bit. A multiplication by *65536 wont work as expected if you don't force it into 32bit arithmetics.

@Majenko I defined TA as a float.

When you calculate TA you are doing integer math. Try as DataFiddler wrote and cast the numbers to long, so that the result cannot overflow

@DataFiddler: A multiplication by 65536 will work as expected, because 65536 is a 32-bit long int.

You said "I defined TA as a float." That doesn't matter. In C/C++, expressions are only "promoted" to a larger/different data type AFTER they are evaluated. Your calculations are being done using 16-bit ints, which overflow, and then cast to a float.
(C/C++ evaluates expressions from the inner-most outward, and if one of the operands to an operator is a larger type, it will "promote" the other operand to the larger type before doing a calculation. It won't notice that a calculation will overflow and promote the operands to fix that problem however.)
Try this:
   TA = (data[3]+ data[4]*256+uint64(data[5])*65536)/200;

That version of the code forces data[5] to an unsigned long before multiplying it by 65536.
Do the same thing to the value that you multiply by 65536 in all of your expressions and you should avoid overflow.

Thank you all. problem solved!

On the Nano, uint64 (I guess you mean uint64_t) is not the same as unsigned long: the latter is 32-bits only. 2. The overflow happens with data[4], not with data[5]. 3. Your formula gives grossly bad results for temperatures larger than 163.84 °C (try data = {0,0,0,0,128,0}).

overflow on data(4)? Is data an int or a byte?

The rules of integer arithmetics are tricky in C++. There are rules that
give the type of integer literals:

256 and 200 are of type int, which is the default type for
integer literals. On the Nano, this type is 16-bits, and covers the
range from −32,768 to +32,767.
65536 being too large for the int type, it is implicitly
considered a long int. This type is 32-bits on the Nano, and covers
roughly ±2.15×109.

Then there are rules for the types used in arithmetic operations. No
computation is ever done on a type smaller than int: anything smaller
is promoted to int. Then, if you combine two operands of different
types, the larger type “wins” and the compiler implicitly converts the
other operand to the larger type. Note that if two types have the same
bit size, the unsigned one is considered “larger”.
Let's go now through your formula, and see the types of the different
terms:
data[3]       = uint8_t
data[4]*256   = uint8_t * int → int
data[5]*65536 = uint8_t * (long int) → long int

Now you may see the problem. Your calculation will eventually overflow,
but the overflow is not in data[5]*65536, as one may naively expect.
What happens is than when the temperature reaches 163.84 °C (≈ 327 °F),
data[4] becomes 128, and data[4]*256 is 32,768, just too large for
an int. The result overflows to −128, hence the negative values you
see.
The simplest solution is to force 256 to be a long int, by appending
the L suffix to the number. Then the multiplication will be performed
with the long int type, and there will be no overflow:
TA = (data[3] + data[4]*256L + data[5]*65536) / 200;

On a final note, it is worth noting that the numbers 256, 65536 and
16777216 used in the formula are all powers of two. Even powers of 256.
You may notice that, save for the division by 200, what this formula
describes is the coding of an integer as a 24-bit, little-endian, two's
complement number. This format (two's complement little-endian) is
exactly what the Arduino uses internally for representing numbers. You
could then avoid all those calculations and get your result by just
telling the compiler that what those memory cells are actually holding
is a 24-bit integer:
float TA = *(__int24*)&data[3] / 200.0;

This works for both positive and negative temperatures, but it has the
drawback of breaking some C++ rules (aliasing rules), and using the
non-standard type __int24. A safest way to achieve the same is to
build a 32-bit integer by putting the bits in place using bitwise
operations. But note that then a sign-extension byte is needed to
convert the 24-bit number to 32 bits:
uint8_t sign_extension = data[5] & 0x80 ? 0xff : 0x00;
int32_t reading = (uint32_t) data[3] <<  0
                | (uint32_t) data[4] <<  8
                | (uint32_t) data[5] << 16
                | (uint32_t) sign_extension << 24;
float TA = reading / 200.0;

int32_t reading = (int32_t)(int8_t)b[5] <<16 | (uint16_t)b[4] << 8 | b[3] ; the highbyte just has to be signed, then it's still tricky but a bit simpler.


text:
Extract binary numbers from infrared sensor that uses I2C bus
I have an infrared sensor(OTI 301) which in order to display the desired temperature I need to apply a formula that depends on 3 binary numbers extracted from the sensor itself. I have tried different approaches but no success yet to extract these binary numbers. Please see link for the data sheet of the sensor where you can see useful information regarding the formula and the binary numbers. https://drive.google.com/file/d/1XMRDCNzY3fn0q6lkGejs5D-pqksfRuZ8/view also here is the code I have tried in the Arduino IDE. Also, attached picture are the needed commands to extract the data from the second data sheet, https://drive.google.com/file/d/1mmdkHkNbwC5VgQxGMrq07XolajNvgBkN/view.
#include <Wire.h>
byte val[2] = {0x20,0x80};
void setup() {
Wire.begin(0x20);        // join i2c bus (address optional for master)
Serial.begin(9600);  // start serial for output
}

void loop() {

  //master writter
  Wire.beginTransmission(0x20); // transmit to device
  Wire.write(val,2);
  //Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  //master reader
  Wire.requestFrom(0x20, 6);    // request 6 bytes from slave device

  while (Wire.available()) { // slave may send less than requested
  Serial.println("H");
  char c = Wire.read(); // receive a byte as character
}

delay(500);
}

There are likley two problems:

An invalid device address is used. The device address is 0x10 and the Arduino Wire library expects it that way (and not in the shifted version with read/write bit).
Your code uses two separate transactions, however the datasheet specifies a single transaction with a repeated START condition for separating the write and read part.

So an improved version looks like so:
#define DEVICE_ADDRESS 0x10

void loop() {
    Wire.beginTransmission(DEVICE_ADDRESS);
    Wire.write(0x80);  // readout command
    Wire.endTransmission(false); // stop sending without ending transaction (repeated START)
    Wire.requestFrom(DEVICE_ADDRESS, 6); // request 6 bytes
    uint8_t data[6];
    for (int i = 0; i < 6; i++) {
        data[i] = Wire.read();
    }
}


text:
Reading FAN tachometer/RPM on 4 wire fan using arduino
I am following the wiring and code at https://playground.arduino.cc/Main/ReadingRPM but using pin 9 to read the speed instead of pin 2 and I have added a 10K pull up resistor between pin 9 and +5V as well; I dont see any interrupts firing even though the fan is running;
The fan is a standard intel cpu fan with 4 wires(black, yellow, green, blue) and the green wire is the sense/tach wire and I have connected it to pin 9 as well;
Need some help or expert advise; I am not sure if the approach works fine or not;

There are no interrupts on pin 9 (unless you are using Pin Change interrupts...?). You have to use pin 2 (interrupt 0), or pin 3 (interrupt 1) (also, on the Mega: 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2)).

I am using arduino mega and using the digitalPinToInterrupt(9) when passing the value to attach/detach interrupt calls; not sure if thats same as what you meant;

RTFM: External Interrupts: 2 (interrupt 0), 3 (interrupt 1), 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2). These pins can be configured to trigger an interrupt on a low level, a rising or falling edge, or a change in level. See the attachInterrupt() function for details.

Thanks; I am using pin 19 now since other pins are occupied and the code seems to read and print RPM values;

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


text:
Having a problem where the previous letter flashes after a space
im currently working on a stranger things letter board with an arduino and ws2811 leds and im having an issue where ever there is a space, the previous letter will be displayed. Ive tried going in and finding where it makes this duplicate, but i am rather inexperienced. Heres my code:
#include <FastLED.h>

#include <HashMap.h>

#define DATA_PIN 6 //this is the data pin connected to the LED strip. If using WS2801 you also need a clock pin

#define NUM_LEDS 50 //change this for the number of LEDs in the strip

#define COLOR_ORDER RGB

CRGB leds[NUM_LEDS];

CRGB colors[5];

int myleds[25];

int last_letter = 0;

CRGB white = CRGB(255, 255, 255);

CRGB red = CRGB (255, 0, 0);

CRGB green = CRGB (0, 255, 0);

CRGB blue = CRGB(0, 0, 255);

CRGB off = CRGB(0, 0, 0);

const byte HASH_SIZE = 28;

HashType<char, int> hashRawArray[HASH_SIZE];

HashMap<char, int> charToLed = HashMap<char, int>( hashRawArray , HASH_SIZE );

void setup() {

  FastLED.addLeds<WS2811, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS); //setting up the FastLED

  randomSeed(analogRead(0)); //seeding my random numbers to make it more random.

  myleds[0] = 47;//A

  charToLed[0]('a', 47);

  myleds[1] = 45;//B

  charToLed[1]('b', 45);

  myleds[2] = 43;//C

  charToLed[2]('c', 43);

  myleds[3] = 42;//D

  charToLed[3]('d', 42);

  myleds[4] = 40;//E

  charToLed[4]('e', 40);

  myleds[5] = 38;//F

  charToLed[5]('f', 38);

  myleds[6] = 37;//G

  charToLed[6]('g', 37);

  myleds[7] = 34;//H

  charToLed[7]('h', 34);

  myleds[8] = 32;//I

  charToLed[8]('i', 32);

  myleds[9] = 16;//J

  charToLed[9]('j', 16);

  myleds[10] = 18;//K

  charToLed[10]('k', 18);

  myleds[11] = 20;//L

  charToLed[11]('l', 20);

  myleds[12] = 22;//M

  charToLed[12]('m', 22);

  myleds[13] = 24;//N

  charToLed[13]('n', 24);

  myleds[14] = 26;//O

  charToLed[14]('o', 26);

  myleds[15] = 28;//P

  charToLed[15]('p', 28);

  myleds[16] = 29;//Q

  charToLed[16]('q', 29);

  myleds[17] = 31;//R

  charToLed[17]('r', 31);

  myleds[18] = 15;//S

  charToLed[18]('s', 15);

  myleds[19] = 13;//T

  charToLed[19]('t', 13);

  myleds[20] = 11;//U

  charToLed[20]('u', 11);

  myleds[21] = 9;//V

  charToLed[21]('v', 9);

  myleds[22] = 7;//W

  charToLed[22]('w', 7);

  myleds[23] = 4;//X

  charToLed[23]('x', 4);

  myleds[24] = 2;//Y

  charToLed[24]('y', 2);

  myleds[25] = 0;//Z

  charToLed[25]('z', 0);

  colors[0] = white;

  colors[1] = red;

  colors[2] = green;

  colors[3] = blue;

  colors[4] = off;

  reset();

  abcs();

}

void loop() {

  type("My world would be upsidedown if i went to homecoming without you");
  delay(3000);
  type("andificant");
  delay(100);
  jog();

}

void beforejog() {
  FastLED.clear();
  leds[0] = CRGB (0, 255, 255); //aqua
  leds[10] = CRGB (0, 255, 255); //aqua
  leds[20] = CRGB (0, 255, 255); //aqua
  leds[30] = CRGB (0, 255, 255); //aqua
  leds[40] = CRGB (0, 255, 255); //aqua
  leds[1] = CRGB (153, 50, 204); //dark orchid
  leds[11] = CRGB (153, 50, 204); //dark orchid
  leds[21] = CRGB (153, 50, 204); //dark orchid
  leds[31] = CRGB (153, 50, 204); //dark orchid
  leds[41] = CRGB (153, 50, 204); //dark orchid
  leds[2] = CRGB (255, 255, 0); //yellow
  leds[12] = CRGB (255, 255, 0); //yellow
  leds[22] = CRGB (255, 255, 0); //yellow
  leds[32] = CRGB (255, 255, 0); //yellow
  leds[42] = CRGB (255, 255, 0); //yellow
  leds[3] = CRGB (0, 255, 127); //spring green
  leds[13] = CRGB (0, 255, 127); //spring green
  leds[23] = CRGB (0, 255, 127); //spring green
  leds[33] = CRGB (0, 255, 127); //spring green
  leds[43] = CRGB (0, 255, 127); //spring green
  leds[4] = CRGB (255, 165, 0); //orange
  leds[14] = CRGB (255, 165, 0); //orange
  leds[24] = CRGB (255, 165, 0); //orange
  leds[34] = CRGB (255, 165, 0); //orange
  leds[44] = CRGB (255, 165, 0); //orange
  leds[5] = CRGB (65, 105, 255); //royal blue
  leds[15] = CRGB (65, 105, 255); //royal blue
  leds[25] = CRGB (65, 105, 255); //royal blue
  leds[35] = CRGB (65, 105, 255); //royal blue
  leds[45] = CRGB (65, 105, 255); //royal blue
  leds[6] = CRGB (76, 0, 153); //dark purple
  leds[16] = CRGB (76, 0, 153); //dark purple
  leds[26] = CRGB (76, 0, 153); //dark purple
  leds[36] = CRGB (76, 0, 153); //dark purple
  leds[46] = CRGB (76, 0, 153); //dark purple
  leds[7] = CRGB (255, 105, 180); //hot pink
  leds[17] = CRGB (255, 105, 180); //hot pink
  leds[27] = CRGB (255, 105, 180); //hot pink
  leds[37] = CRGB (255, 105, 180); //hot pink
  leds[47] = CRGB (255, 105, 180); //hot pink
  leds[8] = CRGB (0, 128, 0); //dark green
  leds[18] = CRGB (0, 128, 0); //dark green
  leds[28] = CRGB (0, 128, 0); //dark green
  leds[38] = CRGB (0, 128, 0); //dark green
  leds[48] = CRGB (0, 128, 0); //dark green
  leds[9] = CRGB (255, 0, 0); //red
  leds[19] = CRGB (255, 0, 0); //red
  leds[29] = CRGB (255, 0, 0); //red
  leds[39] = CRGB (255, 0, 0); //red
  leds[49] = CRGB (255, 0, 0); //red
  FastLED.show();
  delay(50);
  FastLED.clear();
}

void jog() {
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  leds[31] = CRGB (255, 0, 0);
  FastLED.show();
  delay(2000);
  FastLED.clear();
  leds[11] = CRGB (255, 0, 0);
  FastLED.show();
  delay(2000);
  FastLED.clear();
  leds[24] = CRGB (255, 0, 0);
  FastLED.show();
  delay(2000);
  FastLED.clear();
}

void abcs() {

  for (int i = 0; i < 25; i++) {

    int t = myleds[i];

    leds[t] = white;

    FastLED.show();

    delay(250);

  }

  delay(10);

}

CRGB randomColor() {

  int t = random(4);

  return colors[t];

}

void reset() {

  for (int x = 0; x < NUM_LEDS; x++) {

    leds[x] = off;

  }

  FastLED.show();

  last_letter = 0;

}

void displayLetter(char letter) {

  if (isWhitespace(letter)) {

    last_letter = 0;

    delay(2000);

  }

  int lednum = charToLed.getValueOf(letter);

  if (lednum >= 0 && lednum <= 50) {

    if (last_letter == lednum) {

      delay(2000);
    }

    leds[lednum] = white;

    FastLED.show();

    last_letter = lednum;

    delay(2000);

    leds[lednum] = off;

    FastLED.show();

  }

}

void type(String message) {

  reset();

  message.toLowerCase();

  for (int i = 0; i < message.length(); i++) {

    displayLetter(message[i]);

  }

  reset();

}
void BLACKOUT() {
  int r = 0;
  int b = 0;
  int g = 0;

  for (int x = 0; x < NUM_LEDS; x++) {
    leds[x] = CRGB(r, g, b);
  }

  FastLED.show();
  delay(100);

}

Any help is appreciated. thanks.

What does lednum equal when letter is a whitespace character?
`int lednum = charToLed.getValueOf(letter);`

This will not fix your problem!
You said you were inexperienced, so I have taken you code and with no knowledge of what it does (that mean I may have made mistakes) I have refactored it slightly.
#include <FastLED.h>

#define DATA_PIN (6) //this is the data pin connected to the LED strip. If using WS2801 you also need a clock pin
#define NUM_LEDS (50) //change this for the number of LEDs in the strip
#define COLOR_ORDER RGB
#define HASH_SIZE (28)

CRGB Leds[NUM_LEDS];

int last_letter = 0;

enum ColourNames {White, Red, Green, Blue, Off};
const CRGB Colours[] = { CRGB(255, 255, 255), CRGB(255, 0, 0), CRGB(0, 255, 0), CRGB(0, 0, 255), CRGB(0, 0, 0) };

struct LED
{
    int myled;
    int led;
    char letter;
    LED(const int& m = 0, const int& l = 0, const char& let = 0)
        : myled(m)
        , led(l)
        , letter(let)
    {}
};
LED LedData[HASH_SIZE];

void setup()
{
    FastLED.addLeds<WS2811, DATA_PIN, COLOR_ORDER>(Leds, NUM_LEDS); //setting up the FastLED
    randomSeed(analogRead(0)); //seeding my random numbers to make it more random.

    LedData[ 0] = LED(47, 47, 'a');
    LedData[ 1] = LED(45, 45, 'b');
    LedData[ 2] = LED(43, 43, 'c');
    LedData[ 3] = LED(42, 42, 'd');
    LedData[ 4] = LED(40, 40, 'e');
    LedData[ 5] = LED(38, 38, 'f');
    LedData[ 6] = LED(37, 37, 'g');
    LedData[ 7] = LED(34, 34, 'h');
    LedData[ 8] = LED(32, 32, 'i');
    LedData[ 9] = LED(16, 16, 'j');
    LedData[10] = LED(18, 18, 'k');
    LedData[11] = LED(20, 20, 'l');
    LedData[12] = LED(22, 22, 'm');
    LedData[13] = LED(24, 24, 'n');
    LedData[14] = LED(26, 26, 'o');
    LedData[15] = LED(28, 28, 'p');
    LedData[16] = LED(29, 29, 'q');
    LedData[17] = LED(31, 31, 'r');
    LedData[18] = LED(15, 15, 's');
    LedData[19] = LED(13, 13, 't');
    LedData[20] = LED(11, 11, 'u');
    LedData[21] = LED( 9,  9, 'v');
    LedData[22] = LED( 7,  7, 'w');
    LedData[23] = LED( 4,  4, 'x');
    LedData[24] = LED( 2,  2, 'y');
    LedData[25] = LED( 0,  0, 'z');
    LedData[26] = LED();
    LedData[25] = LED();

    reset();
    abcs();
}

void loop()
{
    type("My world would be upsidedown if i went to homecoming without you");
    delay(3000);
    type("andificant");
    delay(100);
    jog();
}

void beforejog()
{
    static const int MaxColours = 10;
    const CRGB colours[MaxColours] =
    {
          CRGB(0, 255, 255)         //aqua
        , CRGB(153, 50, 204)        //dark orchid
        , CRGB(255, 255, 0)         //yellow
        , CRGB(0, 255, 127)         //spring green
        , CRGB(255, 165, 0)         //orange
        , CRGB(65, 105, 255)        //royal blue
        , CRGB(76, 0, 153)          //dark purple
        , CRGB(255, 105, 180)       //hot pink
        , CRGB(0, 128, 0)           //dark green
        , CRGB(255, 0, 0)           //red
    };

    FastLED.clear();
    for (int col = 0; col < MaxColours; ++col)
    {
        for (int r = col; r < NUM_LEDS; r += MaxColours)
        {
            Leds[r] = colours[col];
        }
    }

    FastLED.show();
    delay(50);
    FastLED.clear();
}

void jog()
{
    for (int l = 0; l < 7; ++l)
    {
        beforejog();
        delay(100);
        Blackout();
        delay(100);
    }

    static const MaxLights = 3;
    const int lights[MaxLights] = { 31, 11, 24 };
    for (int l = 0; l < MaxLights; ++l)
    {
        Leds[lights[l]] = Colours[Red];
        FastLED.show();
        delay(2000);
        FastLED.clear();
    }
}

void abcs()
{
    for (int i = 0; i < 25; i++)
    {
        Leds[LedData[i].myled] = Colours[White];
        FastLED.show();
        delay(250);
    }
    delay(10);
}

CRGB randomColor()
{
    const int t = random(4);
    return Colours[t];
}

void reset()
{
    Blackout();
    last_letter = 0;
}

void displayLetter(char letter)
{
    if (isWhitespace(letter))
    {
        last_letter = 0;
        delay(2000);
    }
    const int lednum = charToLed.getValueOf(letter);
    if (lednum >= 0 && lednum <= 50)
    {
        if (last_letter == lednum)
        {
            delay(2000);
        }
        Leds[lednum] = Colours[White];
        FastLED.show();
        last_letter = lednum;
        delay(2000);
        Leds[lednum] = Colours[Off];
        FastLED.show();
    }
}

void type(String message)
{
    reset();
    message.toLowerCase();
    for (int i = 0; i < message.length(); i++)
    {
        displayLetter(message[i]);
    }
    reset();
}

void Blackout()
{
    for (int x = 0; x < NUM_LEDS; x++)
    {
        Leds[x] = Colours[Off];
    }
    FastLED.show();
}

What I have tried to do is group similar variables into arrays (Colour).  I have also created a structure to hold your LED data, it makes it easier to read if it all appears on a single line.  I have added loops to some of the functions to reduce the line count.  And if you aren't changing a variable make it const, it will make no difference to the compiler, but its easier to read and understand.
I haven't compiled this, so there is probably a howler in there, but hopefully it will give you a different perspective on your code and a different (not better) way of doing things.  Oh and it should still have the problem you are asking about, which I think is you need to add an else into that function.

You can use the colors by name CRGB::White, CRGB::Red, CRGB::Lime, CRGB::Blue, CRGB::Black, etc.

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


text:
Arduino Nano v3: is it possible to PCM + AltSoftSerial?
I wonder is it possible to change PCM.h 's lib use of 16-bit timer1 to another 8-bit?
Now I'm getting
libraries\AltSoftSerial\AltSoftSerial.cpp.o (symbol from plugin): In function `AltSoftSerial::read()':

(.text+0x0): multiple definition of `__vector_11'

libraries\PCM\PCM.c.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1

when compiling
#include <PCM.h>
#include <AltSoftSerial.h>

An attempt to avoid XY problem: make AltSoftSerial work alongside with PCM-alike library on Arduino Nano v3 without SD.
I'm poorly familiar with timers and interrupts, so I'll be very grateful for any advice and suggestion!

It is not easy to make PCM sounds with the Arduino Uno or Nano. A few libraries can do that, but they use two timers: Timer1 and Timer2. Timer0 is already in use by Arduino. When using those libraries, the Arduino Nano is almost completely occupied to make sounds.
A software serial port also requires a lot from the Arduino Nano. The AltSoftSerial uses Timer1.
Those two will never work together. It is not possible.
For what do you need the serial port ?
Could that be done in a different way ?
The normal SoftwareSerial does not use a timer, but because it also occupies the Arduino Nano a lot, using SoftwareSerial together with a PCM sound at the same time will not work. Perhaps if you carefully design the sketch and never use them at the same time, it might work. I doubt if it will be reliable.
A better option is to swap the Arduino Nano for an Arduino Micro. Then you have a extra hardware serial port and you don't need the AltSoftSerial anymore. The library to make PCM sounds has to be compatible with the Arduino Micro. I suppose that not every PCM library is compatible.
The best option is to use a MP3 shield. Then you can send a command to play a MP3 sound. If you use a MP3 shield with a Arduino Micro or Arduino Leonardo or Arduino Mega 2560 or Arduino Zero or Arduino Due, then you have a extra hardware serial port and you don't need libraries that occupy the most of the Arduino board, and your sketch will be a normal sketch that does normal things.


text:
Upload sketch in multiple arduinos
How do I upload sketches in multiple arduinos from one supervisor Arduino using UART , cd4051 for Rx and TX separately and reset pin low

That greatly depends on the actual type of Arduino board. Please describe, which Arduino boards you are trying to program and what you are trying to achieve

@chrisl, tags are Uno, Nano

I am trying to upload program in 3 arduino nanos from 1 Arduino Uno by using cd4051 mux/demux for Rx and TX and setting reset to low when uploading to each one

it is not a trivial task. you have to implement the stk500 protocol or use a library which implements it.


text:
New OLED seems dead, how can I be sure?
I bought this 2.8" OLED from Aliexpress a few weeks ago: https://www.aliexpress.com/item/32988174566.html?spm=a2g0s.9042311.0.0.72304c4dAWcHG8
And after a ridiculous amount of searching for a datasheet, I came across this one that seems to match the board I bought: https://www.buydisplay.com/download/manual/ER-OLEDM028-1_Series_Datasheet.pdf
Wiring up pins 1 and 2 to ground and 3.3V on a breadboard, I'd expect something to happen with the display, but I get nothing. The display is in 8080 mode, so I wire everything up to a standard UNO board and power everything on. Still nothing. Try changing the power to 5V, no joy.
During my testing, I noticed the back of the display is getting hot. Not sure if that's a good thing or not yet.
So what's the best way to 1) determine if the datasheet I found is correct? 2) check if the OLED is just broken? I don't have a ton of experience with these displays yet, so I'm not sure if just powering the thing on should net some visual response.

What do your expect exactly? How are you driving signal to the screen?

Unlike LCD displays, OLED displays don't have a backlight. You probably won't see ANYTHING unless you send data to it to turn on some pixels. (Disclaimer - I've never tried to interface one, so my comment is based on theory. If I was designing the interface I'd make it do a self-test when it was first powered on, where it cycled all the pixels through red, green, and blue. so you could tell it was working and all the pixels lit up.)

Getting hot is not a good sign for such device!

@LotB I have a simple test I've used on other screens that uses the u8g2 library. I would expect a few sentences to show up. I'm using an UNO but in parallel, which should be fine, but I'm wondering if switching to 4-wire SPI might provide better results.

@SimSon I would agree. I suspect I've gotten something wired wrong, which is why I'm questioning the datasheet I found.

The datasheet is not for the same display. If you check the webpage for the display in the datasheet and look at the back of the PCBs and compare them you will see they are different. Thus you cannot assume that the IO connector is wired the same.

Better to buy from a reputable dealer (I always use buydisplay.com - they are very very good) where you get documentation and support, rather from some unknown junkyard that sells you complete crap with no clue what it is.

@Majenko Oh sure, I never expect much from the things I buy off Aliexpress. But the question remains: even if I did get something from buydisplay, how would I know it was functioning correctly? Do OLEDs light up with power applied? Or do they need data as well? Trying to use this as a learning experience when the next display is not working as expected.

You would only know it was working if you programmed your MCU to actively drive it in some way. You get nothing out of an OLED unless you tell it to display something. There's no glow, no flash, nothing. That's the beauty of OLEDs - black is truly black. Each pixel is an individual LED that is either on or off.

The datasheet you have found is not for the same display. Yes, it's similar, and yes, it has the same actual OLED display unit on the board, but the PCB is different. So you cannot assume that the pinout is the same.
The fact that it's getting hot tells me that you have probably wired something wrong and you are injecting voltage into it somewhere where voltage doesn't want to be injected.
To find if an OLED is working you have to actively wire it up.  With an LCD you can just give it power and you should be able to see some visual indication that it's working (back light, some shadowing of the display matrix, etc). But with an OLED you can't do that.  An OLED is made up of a matrix of LEDs which are either on or off. By default they are off, and when they are off it's no different to there being no power. That's the big benefits of OLED displays - low power consumption and true black.
To get any kind of indication that the display works you both need to wire it 100% correctly and program the Arduino in the right way to actively drive it by displaying something on the screen.  My usual test program when working with a new screen is to simply print millis() in the top left corner.

Thanks for the detailed explanation, Majenko. I've ordered a new display from buydisplay and will try this again in 7-40 business days ;)


text:
Use esp-01 relay with Nodemcu possible?
I'm building a simple mobile controlled relay switch. however, I'm out of relay modules, but I do have these esp-01 relays: https://ae01.alicdn.com/kf/HTB1VIKLeJLO8KJjSZFxq6yGEVXaW.jpg
I'm wondering if these can work with a nodemcu? So far no luck.

What do you mean by "work with a nodemcu"? You mean, can you connect a NodeMCU to them, or can you plug an ESP-01 into them and communicate to them with a NodeMCU?

the relay is on io 0 or io 2 of the esp-01 so give the relay board power and try to connect io 0 or io 2 with a resistor to ground or 3.3 V pin on the header  (the yellow header has the esp-01 pinout of course)


text:
Cannot flash Arduino Bootloader on SAMD21G with STLink via SWD programming and openOCD
I'm trying to flash the Arduino Bootloader on a bare ATSAMD21G with STLink via SWD programming and OpenOCD.
These are the steps that I took:

Create *.hex file to flash with ArduinoCore-samd repository
Connect SWD pins from ST-Link to the ATSAMD21G pins

Execute OpenOCD command
openocd -f interface/stlink-v2.cfg -c "set CHIPNAME at91samd21g18; set ENDIAN little; set CPUTAPID 0x0bc11477; source [find target/at91samdXX.cfg]" -c "init" -c "reset init" -c "load_image {/Path/To/ArduinoCore-samd/bootloaders/zero/samd21_sam_ba.hex} 0 ihex" -c "verify_image {/Path/To/ArduinoCore-samd/bootloaders/zero/samd21_sam_ba.hex} 0 ihex" -c "reset run" -c "exit"

Command Line output:
Open On-Chip Debugger 0.10.0
Licensed under GNU GPL v2

For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
Info : auto-selecting first available session transport "hla_swd". To override use 'transport select <transport>'.
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
none separate
adapter speed: 400 kHz
Info : Unable to match requested speed 400 kHz, using 240 kHz
Info : Unable to match requested speed 400 kHz, using 240 kHz
Info : clock speed 240 kHz
Info : STLINK v2 JTAG v17 API v2 SWIM v0 VID 0x0483 PID 0x3748
Info : using stlink api v2
Info : Target voltage: 2.922730
Info : at91samd21g18.cpu: hardware has 4 breakpoints, 2 watchpoints
target halted due to debug-request, current mode: Thread
xPSR: 0x61000000 pc: 0x00000f10 msp: 0x20007ffc
in procedure 'reset'
in procedure 'ocd_bouncer'
in procedure 'ocd_process_reset'
in procedure 'ocd_process_reset_inner' called at file "embedded:startup.tcl", line 248
in procedure 'at91samd21g18.cpu' called at file "embedded:startup.tcl", line 331
in procedure 'ocd_bouncer'

5824 bytes written at address 0x00000000
downloaded 5824 bytes in 0.132341s (42.976 KiB/s)
target halted due to breakpoint, current mode: Thread
xPSR: 0x61000000 pc: 0x2000002e msp: 0x20007ffc
verified 5824 bytes in 0.481737s (11.806 KiB/s)
in procedure 'reset'
in procedure 'ocd_bouncer'
in procedure 'ocd_process_reset'
in procedure 'ocd_process_reset_inner' called at file "embedded:startup.tcl", line 248
in procedure 'at91samd21g18.cpu' called at file "embedded:startup.tcl", line 331
in procedure 'ocd_bouncer'

Really unsure what steps I am missing as it does not seem to flash the bootloader at all. I cannot detect M0 on the USB port after trying to execute the OpenOCD command. Thanks!

Actually the verification message seems to indicate the code was flashed.  You may need to look at non-code configuration settings, possible errors in the code, clocking, board or electrical issues, etc.  Perhaps you should try using SWD to load a test program that flashes an LED or generatures actual UART output without a bootloader or needing USB to work.


text:
Floating-point without FPU
Since a Floating Point Unit (FPU) is not present in Arduino Uno, I wanted to know how float operations are performed. If it is simulated as integer operations, I want to know how exactly the simulation is done.

Floating point operations are implemented (rather than “simulated”) in software. You can disassemble any program using floats and see how it's done.

Implementing floating point in software would mean breaking the number into its mantissa and exponent components (represented as integers) and performing arithmetic on them. Is this correct?

Of course. The splitting is done by the function __fp_split3.

As I said in my comment, all float operations are implemented in
software. As a simple test, I compiled the following program:
volatile float x, y, z;

int main(void)
{
    z = x + y;
    return 0;
}

The compiler translated the sum operation into a call to __addsf3.
This function extends its arguments to flt40_t format (non-standard 40
bits float), calls __addsf3x to do the 40-bit addition, then calls
__fp_round to convert the result into the standard float format.
__addsf3x also makes a few library calls of its own. In the end, the
addition pulled the following functions into the compiled program:
__subsf3, __addsf3, __addsf3x, __fp_inf, __fp_nan,
__fp_pscA, __fp_pscB, __fp_round, __fp_split3, __fp_splitA,
__fp_zero and __fp_szero.
All these functions are provided by the avr-libc. You can find them in
the libm/fplib directory. See for example the files:

addsf3.S
addsf3x.S
fp_round.S

software emulation. The float is decomposed into sign, exponent and mantissa and then integer operations are used to do the actual math.
Addition and subtraction means shifting the mantissas to a common magnitude, adding/subtracting them and then checking the highest set bit for the new exponent.
Multiplication means adding the exponents and multiplying the mantissas. Division is subtracting.


text:
Can Arduino post multiple sensor data to one Google Spreadsheet?
Let's say I have one MQ5 gas sensor at home and one MQ135 gas sensor at the park. They are wirelessly hooked to Arduino.
My questions are:
Can Arduino post the data from two or more sensors to one Google Spreadsheet and organize it in two different charts?
Can only one Arduino accomplish this?
If not, what are the alternatives?

Perhaps you could do a web search before posting ?

I do this sort of thing for my solar plant, but I do it by pairing all my arduino-based sensors with a Raspberry Pi via Serial.  I keep the Arduino IDE on the Pi so I can reprogram them remotely via the same cable.  Pis are accessed via WiFi.  The Pis all have Internet access so this wouldn't be difficult to do it that way directly.  Myself, I have each Pi collect the readings into CSV files and also PNG plots (using gnuplot), then at midnight my main Linux machine uploads all the data for formatting.  I can't answer your question directly, but in my case, I do all Internet stuff in Linux.

Not directly but with addon service like Pushingbox, temboo and so on it can.
If you google on your topic there are a ton of ways to do it!


text:
How many Infrared sensor modules can be added to a single Arduino (eg;Uno)
I am looking to add block detection to my model railroad. I need approx. 40 infrared sensors to power 40 LED's on my control panel. No signals or other logic required yet, just the LED indications -LED- on=occupied  off=vacant.
How many Uno boards would I need to do this? I may, in the future, look at integrating several two (or three) aspect signals down the track. I am an absolute novice here, never having used an Arduino, nor done any coding of any sort.

One Arduino with "I2C I/O exoanders" is enough.

an infrared sensor would not be a good way of telling if an area is occupied or not, only that the occupation has changed at one snapshot in time. can you use super magnets and cheap hall sensors instead? look into reflective sensors and beam interupts as well.

The IR sensors power the LED's in the control panel. The underside of the train reflects the IR beam and the current from the detector lights the LED. Once the train has passed, the beam is uninterrupted and therefore no signal is detected, no lighting of LED. I am looking at using TCRT5000 reflective optical sensor switch for Arduino - I just need to know how many I can attach to a board...

Ahh, I assumed PIR, my bad. it depends on the code, but i doubt you need interrupt-quality timing for trains. With polling, you get at least 16, maybe a couple more without any other hardware. Make sure you have enough juice to power them all. if you get into expanders or ADCs or shift registers, one uno can handle 40

Being an absolute novice, I have no idea what polling is, ADC or shift registers mean...Given the TCRT5000 has four pins, how many can I run off one board? Can I wire them in parallel, with 6 IR modules per section of track..?

some of the 4 pins can be wired together in parallel. in fact you'll need to do that or you'll run out of power pins quickly. but reading over it all again, from what you describe, i don't think you even need an ardiuno if you buy the right sensor modules; you don't need processing.

If the TCRT5000 sensors work with the circuit i found, I don't think I will need an Arduino either. Once I receive them I will check

You just want to know how many you can attach to an Arduino board or how many Arduino Uno boards you need, but it does not work like that.
Some sensors with a led require 5mA or 10mA or 20mA. The reflective optical sensors use a IR (InfraRed) led. The Arduino Uno 5V pin can probably not supply enough current for 40 leds. Therefor you might need a seperate power supply.
I think the TCRT5000 is typically set at 10mA.
The Arduino Mega 2560 and the Arduino Due have many pins. But with 40 TCRT5000 sensors, the total current is too close to the limit.
In such situation often extra hardware is added. You can use one Arduino Uno board, with extra hardware for multiple inputs or outputs.
An "expander" is a chip or a module that connects to the Arduino with a few wires, but has many input and/or output pins. For example a "expander" with I2C interface to the Arduino Uno as mentioned by @matsk. Although a I2C expander has a slow I2C interface, they are sometimes smart and can tell which pin has changed by reading a single byte.
"Shift registers" are chips with for example 8 input pins or 8 output pins. The data of the pins is shifted into the chip with a data and clock signal. There are many examples for that: ShiftOut with a 74HC595.
A analog "multiplexer" or "mux" is a chip that can connect one common pin to one of 8 pins. The signal can go both ways. Nick Gammon about a multiplexer.
A "ADC" is short for "Analog to Digital Converter". The Arduino Uno has an internal ADC, but also a external ADC can be used. They have often more than one analog input.
"Polling" is when an Arduino is reading many inputs continuously one by one. If for example it takes 5ms to read a sensor, then 40 sensors take 200ms. That means that every sensor is read once per 200ms. If a train would pass within that 200ms, then it might be not detected.
The opposite of polling is with interrupts. If an external event happens, it could trigger an interrupt and the Arduino can react right then at that very moment. However, 40 interrupts is not possible.
Conclusion:
The best way depends on your hardware and software skills, on the maximum interval that you want to read the sensors, on the sensors themself, and how far apart the sensors are, and if you want 40 wires to a Arduino board.
The best Arduino board also depends on what you want to do with the data and what else the Arduino has to do.
Some sensors have a analog output and some a digital output. It depends on your situation and the way the train is detected.
If possible, then I would choose a solution where all the hardware can be easily be replaced. If the sensor has digital outputs, then I would connect them to a Arduino Mega 2560 or Arduino Due.

That's great information, thank you for going to the trouble of explaining everything clearly for me! After doing a bit more research, it looks like it may be possible to achieve what I am looking for without having to use an Arduino at all - depends on how well the TCRT5000 works with a circuit I have found. This uses resistors and an LM358 opamp, resistors and a trim pot to adjust sensitivity. Once I receive my TCRT5000 modules I will wire up on a breadboard and see how it goes.


text:
Arduino UNO vs NANO or MICRO with RPi3
I'm currently using an Arduino UNO with a raspberry pi 3b. I'm using the USB connector for both power and comms, i.e. the arduino is powered by the RPI via the USB cable, and also i use the same cable for serial communication between the pi and the UNO.
My question is, could i use the same code, and wiring if i were to change the UNO with a NANO or MICRO?
So for example, on the RPI side of things, could i still simply setup the arduino in my python code as
arduino = serial.Serial('/dev/ttyACM0', 9600)

and send commands with something like
arduino.write('2')

and on the arduino side of things, just check if there is serial data coming in and read it, like
if (Serial.available()) {
    command = Serial.read();

I know this may be a very stupid question, but to wrap it up, would anything change other than number of analogues, digitals etc, if i were to switch from an UNO to a MICRO or NANO?

The Nano uses the same chip (ATMEGA 328P) that is on the Uno.  So putting the same code on the Nano should work the same as the Uno.
The Micro uses a different chip.  Whether or not the code from your Uno will work on your Micro depends on what is in the code.  You chose not to show anyone the code so that can't be answered yet.

Thanks for the answer. Would i still be able to communicate with serial libraries from both sides? From RPI to arduino and vice versa? and simply using just one USB cable for power and comms? That's my only worry regarding the code.

Let me say it one more time.  The UNO and the Nano use the same chip.  The difference is the shape of the board they are on.  Code for one should work on the other.  You haven't given enough information to answer about the micro.

The Raspberry Pi has to recognize the serial chip on the Arduino Uno. The Uno and Nano use both the Atmega328p microcontroller, but that chip has not to do with the usb-serial. The usb-serial chip could be different. Arduino clones could have yet another usb-serial chip. The Arduino Micro uses the Atmega32u4 itself as usb-serial chip. So far I have not encountered a problem, but I'm not sure that all three will work. Give it a try and tell us which usb-serial is on the Arduino board and if it is recogned !


text:
Arduino analog pins not working
I am having a problem with pins of Arduino Uno. I have connected a LED to one of the analog pins (A0), and I want to light up the LED with different intensinty.
int ledPin = A0;
void setup() {
 // put your setup code here, to run once:
 pinMode(ledPin,OUTPUT);

}

void loop() {
 // put your main code here, to run repeatedly:
 analogWrite(ledPin,500);
}

The point is that even if I change the value of analogWrite, the LED lights up always with the same intensity.


text:
Arduino Yún as ISP to program Attiny - why is the sketch not working after successful upload?
I want to use an Arduino Yun as ISP to program an Attiny85. I have soldered a shield following the circuit that is depicted in many sites. You can see it in this page.
I have included a LED with a 1k resistor in series connected between pin 5 (PB0) and ground so that I can monitor.
I have setup my sketch environment (Arduino 1.6.12) with the definitions of the Attiny so that I can select this board (Attiny85) with it's associated parameters.
I have defined in Arduino 1.6.12 the board in this way:

Board: "ATtiny25/45/85"
Processor: "ATtiny85"
Clock: "Internal 1MHz"
Port: "192.168.1.109 (Arduino Yún)"

I use this port instead of the serial USB port as I had many issues with the serial USB port.
I have started with the Blink sketch modifying it to use pin0
The sketch is this one:
// the setup function runs once when you press reset or power the board
int LED = 0;  //0 para Attiny
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED, HIGH);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

The output of the sketch loading in verbose mode is this one:
El Sketch usa 672 bytes (8%) del espacio de almacenamiento de programa. El máximo es 8.192 bytes.
Las variables Globales usan 9 bytes (1%) de la memoria dinámica, dejando 503 bytes para las variables locales. El máximo es 512 bytes.
/usr/bin/run-avrdude /tmp/sketch.hex -v -pattiny85

avrdude: Version 6.1, compiled on Apr  8 2016 at 15:56:17
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/root/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : unknown
         Using Programmer              : linuxgpio
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    10     8    0 no       1024    8      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : linuxgpio
         Description     : Use the Linux sysfs interface to bitbang GPIO lines
         Pin assignment  : /sys/class/gpio/gpio{n}
           RESET   = ~18
           SCK     =  11
           MOSI    =  27
           MISO    =  8

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "0xFF"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xFF:
avrdude: load data lfuse data from input file 0xFF:
avrdude: input file 0xFF contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified
avrdude: reading input file "0xD8"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xD8:
avrdude: load data hfuse data from input file 0xD8:
avrdude: input file 0xD8 contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0xFB"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0xFB:
avrdude: load data efuse data from input file 0xFB:
avrdude: input file 0xFB contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: reading input file "/tmp/sketch.hex"
avrdude: writing flash (672 bytes):

Writing | ################################################## | 100% 0.40s

avrdude: 672 bytes of flash written
avrdude: verifying flash memory against /tmp/sketch.hex:
avrdude: load data flash data from input file /tmp/sketch.hex:
avrdude: input file /tmp/sketch.hex contains 672 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.57s

avrdude: verifying ...
avrdude: 672 bytes of flash verified

avrdude done.  Thank you.

What looks pretty normal for me. When the load is ongoing, I see the 1st thing that puzzles me: LED connected to pin 5 (PWM0) doesn't blink quickly. I have tested the polarity of the LED with a +5V connected to the physical pin of the chip and 0V connected to GND and it lights.
The second thing that puzzles me is that I get exactly the same output when I remove the programming shield (no Attiny at all) and I click on upload and the output is the same.  Is the Arduino IDE caching this output?
When I put the "programmed" Attiny in a breadboard and I power it and connect one LED to port 5, it doesn't blink as per the Blink sketch.
I am quite a newby with Arduino and ATtiny85. I only wan to be able to program this ATtiny85 with my Arduino Yún
What am I doing wrong?
Could you give some light to this darkness?

Thanks for the comment... it's somewhat strange, when I follow the link it leads to a page with this title: "Program an ATtiny with an Arduino Nano"

The link is fine - it goes to something that seems like it should be relevant, but actually isn't because of the differences between the Nano and the more Leonardo-like Yun, and then because the asker has ignored the serial interface used and mistakenly substituted the Yun's method of ISPing it's captive Arduino - which isn't going to work for an external target.

It's not programming a non-existent ATtiny, it's quite explicitly stating in the output that it is programming an ATmega32u4 - and that would be the "Arduino" part of the YUN.
It's not clear that the YUN is really intended to ISP other targets.
If you can get serial communication to the ATmega32U4, you could try to find a compatible variation of the ISP sketch to load on that, and in turn use it to program an ATtiny.
Or you could try to define a different set of programming pins, but this may be tricky.
Essentially, what you are trying to do is a bit unusual, and will likely require investing some real time in understanding the existing / available mechanisms enough to adapt them to a fairly unique goal.
Otherwise, just get an Uno or similar and use that to ISP your ATtiny.

I have followed your advice, Chris. I've got an Arduino UNO and the shield that I have created worked like a breeze! Now I can program my ATtiny85 / 85... :)
Thanks a lot for your answer.


text:
Can't activate Seeeduino port
I want to use Seeeduino, but I can't activate port connection for it.
To use Seeduino I installed Seeeduino from Board Manager in Arduino Studio.
And then installed USB Serial Driver from this binary.
http://www.ftdichip.com/Drivers/VCP/MacOSX/FTDIUSBSerialDriver_v2_4_2.dmg
But somehow there is no corresponding port in Tools -> Port.
How can I activate the port?

You shouldn't have to install FTDI drivers on a modern Mac.   As for why it's missing, check the USB devices list in the system report both with it connected and not connected (you'll need to re-open the report) for something missing.  Try a different cable or USB version adapter.  Try it with a hub.  Try it without a hub...

From the beginning the port didn't exist that's why I installed the driver. The port exists when I use Arduino Uno, so I don't think cable or hub is the cause of problem. And I don't know what is "system report". How can I check it?

The Mac's advanced USB port could easily work with one brand of simpler USB chip and not another, so it working with an Uno proves little.

did you get it to work? This may help: https://forum.seeedstudio.com/t/seeeduino-xiao-com-port-problems/254316


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

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

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

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

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

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

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


text:
Locating a fault in writing a variable
I'm writing this piece of code for Arduino Uno, which takes in input on pin 2 the value of a PIR sensor. In order to debug, in this moment I'm taking the signal on pin 2 from the 5V power supply:
int inputPinSensor1 = 2; // input pin for sensor 1
int sensor_1_State = LOW; // we start assuming no motion detected for sensor 1
int val = 0; // variable for reading the pin status

void setup() {
  pinMode(inputPinSensor1, INPUT); // declare sensor 1 pin as input

  Serial.begin(9600);
}

void loop(){
  detectChange(&inputPinSensor1, &sensor_1_State);
}

void detectChange(int* inputPin, int* pirState) {
  // read input value
  val = digitalRead(*inputPin);
  // check if the input is HIGH
  if (val == HIGH) {
    if (*pirState == LOW) {
      // we have just turned on
      Serial.println("Current detected");
      *pirState = HIGH;
    }
  } else {
    if (*pirState == HIGH){
      // we have just turned off
      Serial.println("Current ended");
      *pirState = LOW;
    }
  }
}

This code should detect the passage from a LOW value to an HIGH value on pin 2, and vice versa. In this way I'm expecting to have an HIGH value on pin 2 when I connect the jumper and a LOW value when I disconnect the jumper. But what I get is two possible behaviors: sometimes I get "Current detected" at the begin of the execution, after which there are no further messages, and sometimes I get a rapid alternation of "Current detected" and "Current ended".

You disconnect a wire? Disconnected does not equal LOW. Disconnected equals "Unknown". LOW is connected to GND.  What you have there is a "floating input".

As a side note, the input pins detect voltage, not current.

@Majenko [at]EdgarBonet Thank you for your answers. Yes, I was able to get the LOW value read when I connected the jumper to ground. Thank you!

As Majenko says in their comments, a pin that's not connected to anything "floats" and gives unpredictable results.
You either need to connect such a pin to ground through a "pull-down" resistor or to +5V through a "pull-up" resistor. (10KΩ is a good value to start with.)
If you connect the pin to +5V through a pull-up resistor then you would ground it to change it's state. In that case the pin reads HIGH normally, and drops to LOW when triggered. Note that the Arduino has a special mode, INPUT_PULLUP, that connects the pin to an internal pull-up resistor. In that case you don't need an external pull-up resistor.
In your case, connect the pin to ground with a 10KΩ restistor. Then when you want the pin to go high attach the pin to +5V. That will swamp the connection to ground and pull the pin up to just below 5V.


text:
Getting weird output for following object detection code using interrupts on HUZZAH ESP8266 and motor controller L293D along with 3 HCSR04 sensors
I am trying to implement a bot which can sense obstacle in front, left or right and post detection send interrupts. Which in turn will perform the appropriate motor function to avoid these obsticles. Any help would be highly appreciated.
It would be great if you could make changes in this code and post it so that I can actually run, simulate and find out where actually I have gone wrong.
My code
#define trigPin 14
#define echoPin 12
#define echoPin1 13
#define echoPin2 15

//Initialize Digital Pins
const int leftForward = 2;
const int leftBackward = 16;
const int rightForward = 5;
const int rightBackward = 4;

// Define variables:
long duration;
long duration1;
long duration2;
int distance;
int distance1;
int distance2;
boolean goesForward = false;
bool flag = false;
bool flag1 = false;
bool flag2 = false;

void f5(void){
  flag = true;
}

void f2(void){
  flag1 = true;
}

void f3(void){
  flag2 = true;
}

void inter1(){
    Serial.print("Distance1 = ");
    Serial.print(distance2);
    Serial.println(" cm");
    moveStop();
    delay(3000);
    moveBackward();
    delay(4000);
    moveStop();
    delay(3000);
    turnRight();
    moveStop();
    delay(3000);
}

void inter2(){
    Serial.print("Distance2 = ");
    Serial.print(distance2);
    Serial.println(" cm");
    moveStop();
    delay(3000);
    moveBackward();
    delay(4000);
    moveStop();
    delay(3000);
    turnRight();
    moveStop();
    delay(3000);
}

void inter3(){
    Serial.print("Distance2 = ");
    Serial.print(distance2);
    Serial.println(" cm");
    moveStop();
    delay(3000);
    moveBackward();
    delay(4000);
    moveStop();
    delay(3000);
    turnRight();
    moveStop();
    delay(3000);
}

void setup() {
  // Define inputs and outputs:
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(echoPin1, INPUT);
  pinMode(echoPin2, INPUT);

  // set control pins as Output
  pinMode(leftForward,OUTPUT);
  pinMode(leftBackward,OUTPUT);
  pinMode(rightForward,OUTPUT);
  pinMode(rightBackward,OUTPUT);

  attachInterrupt(digitalPinToInterrupt(echoPin), f5, RISING);
  attachInterrupt(digitalPinToInterrupt(echoPin1), f2, RISING);
  attachInterrupt(digitalPinToInterrupt(echoPin2), f3, RISING);
  //Begin Serial communication at a baudrate of 9600:
  Serial.begin(9600);
}

void loop() {
  // Clear the trigPin by setting it LOW:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);

  // Trigger the sensor by setting the trigPin high for 10 microseconds:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
  duration = pulseIn(echoPin, HIGH);
  // Calculate the distance:
  distance= duration*0.034/2;

  duration1 = pulseIn(echoPin1, HIGH);
  // Calculate the distance:
  distance1= duration1*0.034/2;

  duration2 = pulseIn(echoPin2, HIGH);
  // Calculate the distance:
  distance2= duration2*0.034/2;

  // Print the distance on the Serial Monitor (Ctrl+Shift+M):

  if (distance <= 20){
      attachInterrupt(digitalPinToInterrupt(12), f5, RISING);
    }
  else{
    moveForward();
  }

  if (distance1 <= 20){
    attachInterrupt(digitalPinToInterrupt(13), f2, RISING);
  }
  else{
    moveForward();
  }

  if (distance2 <= 20){
    attachInterrupt(digitalPinToInterrupt(15), f3, RISING);
  }
  else{
    moveForward();
  }

  if(flag)
 {
  inter1();
  flag = false;
 }

  if(flag1)
 {
  inter2();
  flag1 = false;
 }

 if(flag2)
 {
  inter3();
  flag2 = false;
 }

 delay(1000);
 /* // run forward

  digitalWrite(leftForward,HIGH);
  digitalWrite(leftBackward,LOW);
  digitalWrite(rightForward,HIGH);
  digitalWrite(rightBackward,LOW);

  delay(1000);

  // run left
  digitalWrite(leftForward,LOW);
  digitalWrite(leftBackward,LOW);
  digitalWrite(rightForward,HIGH);
  digitalWrite(rightBackward,LOW);

  delay(1000);

  // run forward
  digitalWrite(leftForward,HIGH);
  digitalWrite(leftBackward,LOW);
  digitalWrite(rightForward,LOW);
  digitalWrite(rightBackward,LOW);

  delay(1000);

  // run backward
  digitalWrite(leftForward,LOW);
  digitalWrite(leftBackward,HIGH);
  digitalWrite(rightForward,LOW);
  digitalWrite(rightBackward,HIGH);

  delay(1000);
  delay(50);
  */
}
void moveStop(){

  digitalWrite(rightForward, LOW);
  digitalWrite(leftForward, LOW);
  digitalWrite(rightBackward, LOW);
  digitalWrite(leftBackward, LOW);
}

void moveForward(){

  if(!goesForward){

    goesForward=true;

    digitalWrite(leftForward, HIGH);
    digitalWrite(rightForward, HIGH);

    digitalWrite(leftBackward, LOW);
    digitalWrite(rightBackward, LOW);
  }
}

void moveBackward(){

  goesForward=false;

  digitalWrite(leftBackward, HIGH);
  digitalWrite(rightBackward, HIGH);

  digitalWrite(leftForward, LOW);
  digitalWrite(rightForward, LOW);

}

void turnRight(){

  digitalWrite(leftForward, HIGH);
  digitalWrite(rightBackward, HIGH);

  digitalWrite(leftBackward, LOW);
  digitalWrite(rightForward, LOW);

  delay(500);

  digitalWrite(leftForward, HIGH);
  digitalWrite(rightForward, HIGH);

  digitalWrite(leftBackward, LOW);
  digitalWrite(rightBackward, LOW);

}

void turnLeft(){

  digitalWrite(leftBackward, HIGH);
  digitalWrite(rightForward, HIGH);

  digitalWrite(leftForward, LOW);
  digitalWrite(rightBackward, LOW);

  delay(500);

  digitalWrite(leftForward, HIGH);
  digitalWrite(rightForward, HIGH);

  digitalWrite(leftBackward, LOW);
  digitalWrite(rightBackward, LOW);
}

why are you asking us to guess what problems you are having?

What is your  "weird output"? Please show us by editing your question


text:
Using Millis instead of delay to reboot relay
I want to reboot relay (turn off , waiting 4 seconds and turn ON)
it works perfectly if I use delay(4000), but code is blocked while delay (4 seconds) and I cant start relay 2.
How can I use Millis instead of delay to reboot relay 1 and start relay 2 same time?
#include <SPI.h>
#include <Ethernet.h>
#include <Wire.h>
#include <EthernetUdp.h> //Load the Udp Library

//Ethernet
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; //Assign mac address
IPAddress ip(192, 168, 1, 178); //Assign the IP Adress
unsigned int localPort = 80; // Assign a port to talk over
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //dimensian a char array to hold our data packet
String datReq; //String for our data
int packetSize; //Size of the packet
EthernetUDP Udp; // Create a UDP Object                            //server port
String readString;

bool relayState = false;
//define relay pins
int relay_1 = 22;
int relay_2 = 24;

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac, ip);
  Udp.begin(localPort); //Initialize Udp
  delay(2000);

  //Initial state of the relay
  pinMode(relay_1, OUTPUT); digitalWrite(relay_1, LOW); //relay 1 is On
  pinMode(relay_2, OUTPUT); digitalWrite(relay_2, HIGH);//relay 2 is Off

}

void loop() {

  packetSize = Udp.parsePacket(); //Reads the packet size
  if (packetSize > 0) { //if packetSize is >0, that means someone has sent a request
    Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); //Read the data request
    String datReq(packetBuffer); //Convert char array packetBuffer into a string called datReq
    //Serial.println(datReq);

    if (datReq == "relay1reboot") { //reboot relay
      digitalWrite(relay_1, HIGH);//relay off
      delay(4000);
      digitalWrite(relay_1, LOW);//relay on

      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize packet send
      Udp.print("relay 1 reboot");
      Udp.endPacket(); //End the packet

    }
    if (datReq == "relay2on") {
      digitalWrite(relay_2, LOW);//relay 2 on
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize packet send
      Udp.print("relay 2 on");
      Udp.endPacket(); //End the packet
    }
    if (datReq == "relay1on") {
      digitalWrite(relay_1, LOW);//relay 2 on
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize packet send
      Udp.print("relay 1 on");
      Udp.endPacket(); //End the packet
    }
    // Use the snapshot to set track time until next event
    //previousMillis = currentMillis;
  }
}

//}
memset(packetBuffer, 0, UDP_TX_PACKET_MAX_SIZE); //clear out the packetBuffer array

}

reboot is a term that is specific to programmable devices, such as computers ... it does not apply to a simple relay ... it would make sense to say I want to cycle a relay

A general approach to remove a delay() is to replace it by some code
that:

takes note that some action (whatever follows the delay()) will have
to be performed in the future

takes note of the current time.

Then, somewhere else in loop(), you check whether that “some action”
has to be done right now and, if this is the case, does it.
In this particular case, I would add a global boolean variable named
relay1isRebooting. When it is true, that means that the relay has been
turned off and will have to be turned on in the near future.
bool relay1isRebooting = false;
unsigned long relay1rebootStarted;

void loop() {
  packetSize = Udp.parsePacket();
  if (packetSize > 0) { //we have received a packet
    // ...
    if (datReq == "relay1reboot") {
      digitalWrite(relay_1, HIGH); //relay off
      relay1isRebooting = true;
      relay1rebootStarted = millis();
    }
    // ...
  }

  // Switch back the relay 1 on if needed.
  if (relay1isRebooting && millis() - relay1rebootStarted >= 4000) {
      digitalWrite(relay_1, LOW); //relay on
      relay1isRebooting = false;
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      Udp.print("relay 1 reboot");
      Udp.endPacket();
  }
}

Please note that the test for whether the relay 1 should be turned back
on is performed outside the if (packetSize > 0) block. Also note that
relay1rebootStarted has a valid value only when relay1isRebooting is
true.

for advanced coders: I usually use only the variable for millis. if it is 0 the timer is not running. if (relay1rebootStarted && millis() - relay1rebootStarted >= RELAY_DELAY)

@Juraj: I dislike this approach. Zero is a legitimate return value for millis(), returned every 49.7 days.


text:
8266 get uint8_t PROGMEM array from uploaded file
I'm new programming arduino. I have connected an Adafruit thermal printer to an ESP8266 board.
I've the example code for use the board like a webserver that allow upload files. What i want is to upload a BMP file, convert it to an array of "uint8_t PROGMEM", and send the array to the printer in order the image would be printed.
Do you know any code i could use to convert the BMP file to "unint8_t PROGMEM"???. When i get the uploaded file it is an array of "unsigned char".
Thanks in advance.

why do you want the array to be in PROGMEM?

It's required to send it to the printer

All the examples I saw were in that way. Tell me other ways, please

add one of the examples to the question

Sorry Juraj, I think you don't know what we are talking about at all or you don't want to know. Bye

one day you will understand, that bytes are bytes and you can copy them from any input to any output. no matter if from PROGMEM or from SPIFFS to a terminal, printer or buzzer. so show me the function that takes a PROGMEM data and I tell you how to modify it for bytes from SPIFFS files. or I will take a look at the library you use and search for a function which takes a stream


text:
Attiny85 simple analog and digital output problem
I'm just lighting up an LED through a TIP31C, pin 0 goes through a 560kohm resistor to the tip's input pin
pin 1 goes through a 750 ohm resistor to the tip's input pin
^i'm not sure this information is really relevant
The reason I am doing this is so i can sleep the attiny85 while having pin 0 set to HIGH to have the led at a very low brightness, kind of like a standby function
void setup() {

}

void loop() {
  digitalWrite(0, HIGH);//works ONLY the first time
  delay(500);
  digitalWrite(0, LOW);
  delay(500);

  analogWrite(1, 15);//always works
  delay(500);
  analogWrite(1, 0);
  delay(500);
  /*it's like as soon as i've used an analogWrite, i can no
    longer output with digitalWrite
  */

  //pinMode(0, OUTPUT);//didn't help
  digitalWrite(0, HIGH);//never works
  delay(500);
  digitalWrite(0, LOW);
  delay(500);
}

is there a problem of some kind?

@jsotola yes, I've put comments in the code explaining it

Try doing the pinMode in setup method. This is where it's supposed to be.

@FilipFranik I've tried that, it still doesn't work

There are a number of issues here:

You state you have a 560kohm resistor, this is too high a value. With 5V it will restrict the current to 8.9uA.

This is too low to drive the LED, which probably requires up to 20mA (5V / 0.02A = 250Ohm at least)
This is also too low for for the base of the transistor (I'm not completely sure if my understanding of transistor gain is correct, but I think if you feed 1mA into the base of the TIP31C, it's gain of 25 will allow upto 25mA between the collector and emitter.) Based on this, 5V / 0.001A = 5kOhm.

You do need pinMode(0, OUTPUT); and pinMode(A1, OUTPUT); in setup. It will work, except you won't notice the effect with your 560kOhm resistor.
You also need to check the pins of the atTiny85.

As you can see, the only analog outputs are on physical pins 2, 3 and 7. You need to refer to these (for connection to pin 7) as:
pinMode(A1, OUTPUT);
analogWrite(A1, 15);

Below is a rough idea of what the schematic should look like

simulate this circuit – Schematic created using CircuitLab
And below is an (untested) example of the code:
void setup() {
  pinMode(A1, OUTPUT);
}

void loop() {
  analogWrite(A1, 15);
  delay(500);
  analogWrite(A1, 0);
  delay(500);
}

I think you confused the "analog output" (actually the Attiny85 does not have a real analog output, meaning DAC, Digital to Analog Converter. It can only output PWM voltages to mimick analog signals) with the pins of the ADC (Analog Digital Converter), which is basically an analog input.


text:
Attiny85 PB4 works for analog output but not PB3?
I can get PB4 to work but not PB3 on my ATtinny85.  I'm just lighting up an led (with 150 ohm resistor) (using internal 16mhz)
void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);

}
void loop() {
  analogWrite(3, 15);//does not work
  analogWrite(4, 15);//works
  delay(500);
  analogWrite(3, 0);//does not work
  analogWrite(4, 0);//works
  delay(500);
}

According to the diagram, only PB0 and PB1 support PWM (purple).

The hardware PWM is only suported on pins with output compare altenate function on it. The pinout in your question shows Attiny13 but the rest of your question is about Attiny85, which has different capabilities from Attiny13

As you can see, only pins with PWM capability are PB0, PB1 and PB4

ohhh, thank you, i didn't even realize i was looking at the 13a pinout by mistake


text:
Minimum separation of MOSFET
I have three MOSFET in a row, each separated about 2.5mm apart with the backs facing each other. Is this a good idea?
N.B
Each MOSFET will be sinking 20mA and 60 mA in total for all three MOSFET. I am using an IRF540. The schematic below is for ONE MOSFET.

yes it's fine. worse-case, one switches the other on if they get bent.

Arduino's are often used to drive MOSFETs to sink current for higher loads, so this seems perfectly on topic to me.  I even made a board with 4 shift registers and 32 1A MOSFETs http://www.crossroadsfencing.com/BobuinoRev17/ for driving LED strips and small motors from an Arduino.

@CrossRoads Arduino was created in Ivrea, Italy. Does this mean that on arduino.stackexchange travelling questions to Italy are on topic?

Power dissipation is only a couple of milli-watts. So heat is not an issue.
Just make sure the metal tabs can’t touch each other. Personally I might add some Kapton tape. Electrical tape would work in this case, but feel wrong to me.