text:
Is the use of malloc() and free() necessary in my Kalman noise Filter function?
I had a code that implements Kalman noise filtering on Arduino, and there is a use of malloc() and free(). I'm wondering if this will affect the Arduino or not (for example, the program will not function as I wanted, ...).
This is because when I got all raw (unfiltered) data and wrote the same Kalman Noise Filter function on Matlab, the filtering works well. However, when I write this FKalman function directly in Arduino, it doesn't work like it did on Matlab.
The Kalman Noise Filter is based on this article: http://www.bzarg.com/p/how-a-kalman-filter-works-in-pictures/
Here is the code (just have a look at the function Fkalman and the tick, ignore the other parts):
#define START_MSG

#define NBDATASEND 6
#define NBBYTE2SEND (2*NBDATASEND)

char StartMessage[] = "START";
char StopMessage[] = "STOP";
uint8_t byteRead;
uint8_t StartAsked = 0;
uint8_t StopAsked = 0;
unsigned long previous = 0;
int mod_11k = 12;
int mod_17k = 13;
uint8_t Header = 174;
uint8_t tab_1[NBBYTE2SEND]={0,0,0,0,0,0,0,0,0,0,0,0};
uint16_t data_toSend[NBDATASEND]={0,0,0,0,0,0};

float P1[4];float P2[4];float P3[4]; float P4[4];float P5[4];float P6[4];
float xprec1[2];float xprec2[2];float xprec3[2];float xprec4[2];float xprec5[2];float xprec6[2];
float *sol1;float *sol2;float *sol3; float *sol4;float *sol5;float *sol6;
float Te;
float Tbeg;

void setup() {
  pinMode(mod_11k,OUTPUT);
  pinMode(mod_17k,OUTPUT);
  digitalWrite(mod_11k,LOW);
  digitalWrite(mod_17k,LOW);
  //Start serial port with Gumstix
  Serial1.begin(115200);

//Initialize KF
 P1[0] = 0.05; P1[1] =0; P1[2] =0; P1[3] = 0.05;
 P2[0] = 0.05; P2[1] =0; P2[2] =0; P2[3] = 0.05;
 P3[0] = 0.05; P3[1] =0; P3[2] =0; P3[3] = 0.05;
 P4[0] = 0.05; P4[1] =0; P4[2] =0; P4[3] = 0.05;
 P5[0] = 0.05; P5[1] =0; P5[2] =0; P5[3] = 0.05;
 P6[0] = 0.05; P6[1] =0; P6[2] =0; P6[3] = 0.05;
 xprec1[0] =0; xprec1[1] =0;
 xprec2[0] =0; xprec2[1] =0;
 xprec3[0] =0; xprec3[1] =0;
 xprec4[0] =0; xprec4[1] =0;
 xprec5[0] =0; xprec5[1] =0;
 xprec6[0] =0; xprec6[1] =0;

  //Wait for start message
#ifdef START_MSG
  //Waiting START message to begin
  StartAsked = 0;
  while (StartAsked == 0)
  {
    if (Serial1.available() >= strlen(StartMessage))        //?????
    {
      //Serial.write("Bytes available");
      // verifiy that the received stream is well the start stream
      for (i = 0; i < strlen(StartMessage); i++)
      {
        byteRead = Serial1.read();
        if ((uint8_t)StartMessage[i] == byteRead)
        {
          StartAsked = 1;
        }
       // Serial.println(byteRead);
      }
    }
    delay(1);
  }
  Serial1.write("START");
  //Serial.write("START");
#endif

//KF first time
    Tbeg = millis();
    digitalWrite(mod_11k,HIGH);
    delayMicroseconds(2000);
    data_toSend[0] = analogRead(0);   //phi1 11k
    data_toSend[1] = analogRead(1); //phi2 11k
    data_toSend[2] = analogRead(2);
    digitalWrite(mod_11k,LOW);
    delayMicroseconds(200);
    digitalWrite(mod_17k,HIGH);
    delayMicroseconds(2000);
    data_toSend[3] = analogRead(0);
    data_toSend[4] = analogRead(1);
    data_toSend[5] = analogRead(2);
    digitalWrite(mod_17k,LOW);
    delayMicroseconds(200);
    xprec1[0] = data_toSend[0];
    xprec2[0] = data_toSend[1];
    xprec3[0] = data_toSend[2];
    xprec4[0] = data_toSend[3];
    xprec5[0] = data_toSend[4];
    xprec6[0] = data_toSend[5];
    Te = (millis() - Tbeg)/1000;
    sol1 = Fkalman(xprec1,data_toSend[0],P1,Te);
    sol2 = Fkalman(xprec2,data_toSend[1],P2,Te);
    sol3 = Fkalman(xprec3,data_toSend[2],P3,Te);
    sol4 = Fkalman(xprec4,data_toSend[3],P4,Te);
    sol5 = Fkalman(xprec5,data_toSend[4],P5,Te);
    sol6 = Fkalman(xprec6,data_toSend[5],P6,Te);
    Tbeg= millis();
}

void loop()
{
    tick();
}

void tick() {
    //Previous value for filtering
    P1[0] =sol1[2]; P1[1] =sol1[3]; P1[2] =sol1[4]; P1[3] =sol1[5];
    P2[0] =sol2[2]; P2[1] =sol2[3]; P2[2] =sol2[4]; P2[3] =sol2[5];
    P3[0] =sol3[2]; P3[1] =sol3[3]; P3[2] =sol3[4]; P3[3] =sol3[5];
    P4[0] =sol4[2]; P4[1] =sol4[3]; P4[2] =sol4[4]; P4[3] =sol4[5];
    P5[0] =sol5[2]; P5[1] =sol5[3]; P5[2] =sol5[4]; P5[3] =sol5[5];
    P6[0] =sol6[2]; P6[1] =sol6[3]; P6[2] =sol6[4]; P6[3] =sol6[5];
    xprec1[0] =sol1[0]; xprec1[1] =sol1[1];
    xprec2[0] =sol2[0]; xprec2[1] =sol2[1];
    xprec3[0] =sol3[0]; xprec3[1] =sol3[1];
    xprec4[0] =sol4[0]; xprec4[1] =sol4[1];
    xprec5[0] =sol5[0]; xprec5[1] =sol5[1];
    xprec6[0] =sol6[0]; xprec6[1] =sol6[1];

    free(sol1);
    free(sol2);
    free(sol3);
    free(sol4);
    free(sol5);
    free(sol6);

    //Get data
    digitalWrite(mod_11k,HIGH);
    delayMicroseconds(2000);
    data_toSend[0] = analogRead(0);   //phi1 11k
    data_toSend[1] = analogRead(1); //phi2 11k
    data_toSend[2] = analogRead(2);
    digitalWrite(mod_11k,LOW);
    delayMicroseconds(200);
    digitalWrite(mod_17k,HIGH);
    delayMicroseconds(2000);
    data_toSend[3] = analogRead(0);
    data_toSend[4] = analogRead(1);
    data_toSend[5] = analogRead(2);
    digitalWrite(mod_17k,LOW);
    delayMicroseconds(200);
    Te = (millis() - Tbeg)/1000;

    //Filter
    sol1 = Fkalman(xprec1,data_toSend[0],P1,Te);
    sol2 = Fkalman(xprec2,data_toSend[1],P2,Te);
    sol3 = Fkalman(xprec3,data_toSend[2],P3,Te);
    sol4 = Fkalman(xprec4,data_toSend[3],P4,Te);
    sol5 = Fkalman(xprec5,data_toSend[4],P5,Te);
    sol6 = Fkalman(xprec6,data_toSend[5],P6,Te);
    Tbeg= millis();

    data_toSend[0] = sol1[0];
    data_toSend[1] = sol2[0];
    data_toSend[2] = sol3[0];
    data_toSend[3] = sol4[0];
    data_toSend[4] = sol5[0];
    data_toSend[5] = sol6[0];

    //Send data
    Codage(data_toSend,tab_1);
    HeaderSendnUInt8_RS232(tab_1,NBBYTE2SEND,Header);
}

void Codage(int16_t *d_send, uint8_t *tab_Send)
{
    int i;
    for(i=0; i<NBDATASEND ;i++)
    {
       d_send[i]=d_send[i]+8192;
       tab_Send[2*i]= (uint8_t) ((d_send[i] & 127));              //lấy 7 bit đầu
       tab_Send[2*i+1]= (uint8_t) ((d_send[i] & 16256)>>7);       //lấy 7 bit sau
    }
}

uint8_t HeaderSendnUInt8_RS232(uint8_t *ToSend, uint8_t NbToSend, uint8_t Header)
{
    Serial1.write(&Header,1);         //Header đâu phải pointer??
    return(Serial1.write((const uint8_t*)ToSend, NbToSend));
}

float *Fkalman(float xprec[2],float ymes,float P[4],float Te){
                     // Filtre proprement dit
    float *sol = NULL ;
    sol = (float*) malloc (sizeof(float) * 6);
    float xpred[2];
    float Ppred[4] ;
    float Kf[2] ;
    int q = 0.05;
    int r = 100;

    //x prediction
    xpred[0] = xprec[0] + Te*xprec[1];
    xpred[1] = xprec[1];

    //P_pred = F.P.F'+Q
    Ppred[0] = q + P[0]+ Te*(P[2] +P[1]+Te*P[3]);
    Ppred[1] = P[1] + Te*P[3];
    Ppred[2] = P[2] + Te*P[3] ;
    Ppred[3] = q+ P[3];

    //Kf = (P_pred.C').inv(C.P_pred.C'+R)
    Kf[0]  = (Ppred[0]/(r+Ppred[0]));
    Kf[1]  = (Ppred[2]/(r+Ppred[0]));

    //X_est
    sol[0] = xpred[0] + Kf[0]*(ymes-xpred[0]);
    sol[1] = xprec[1] + Kf[1]*(ymes-xprec[0]);

    //P_est = (I-Kf*C)*P_pred
    sol[2] = Ppred[0]*(1-Kf[0]);
    sol[3] = Ppred[1]*(1-Kf[0]);
    sol[4] = -Kf[1]*Ppred[0]+Ppred[2];
    sol[5] = -Kf[1]*Ppred[1]+Ppred[3];
    return sol;
  }

If you find any problem related to the Fkalman function or my loop function, please tell me. Thank you!!

It's not recommended, however you're only working with small amounts, and the same amount each time (6 floats per "sol" and 6 "sols", so 36 floats, or 144 bytes). Since it's always the same amount I would expect the same block of memory to be allocated each time.
Personally I would use local array variables in the calling function and pass them as a parameter to the function(s) that manipulate them, rather than returning a pointer to an allocated array.
float sol1[6];
Fkalman(xprec1,data_toSend[0],P1,Te,sol1);

....

void Fkalman(float xprec[2],float ymes,float P[4],float Te, float *sol){

etc.
However I can't see it causing an issue, so if you would clarify "doesn't work as well" we may be able to point you in a better direction.

As Majenko already explained it is only 144 bytes. You can use local variables as he proposes.
If you need to keep the values over multiple calls to the Fkalman function, create the space as a variable of an array for each of the calls (if the function is called a fixed number of times).
Besides this, malloc cost some time and for performance reasons it is better to do this during start up once, so the loop function is not hindered by mallocs and free.


text:
Arduino Serial Port. COM1 does not exist
Hello everyone I'am new to this site so please bear with me.
I have an Arduino Uno that I'm using in my simple project using VS 2008. I got this error says The Port COM1 does not exist. The flow of my project is after inserting a coin into the coin slot the arduino will pass the data into my project and it will display into a Label or Textbox the value of the inserted coin.

This error is not on Arduino side but on the PC side (.NET code or configuration), hence off-topic here. Voting to close it.

Probably it is on another COM port. When I checked my IDE (from Arduino) the Arduino was found at COM3.
You probably have to iterate through the (PC) COM ports to find out where the Arduino is connected to.

Thakns. I inspect my PC Manager and I don't an arduino driver

Never used Visual Basic but:

There is no such thing as Serial1 on Arduino Uno. There is only Serial. (Serial1, 2, 3 are available on ArduinoMega) Reference: Arduino
For COM port you should check your device manager. Often it appears at COM3 so probably you should check this issue.

Just for curiosity: Why VB? Is it only your choice or it use less ram or memory, works faster or anything?

The Serial1 is from the design built-in in VS 2008 or 10. Just for curiosity: Why VB? A: don't know how to use another language yet

Can you program an Arduino?  If so you know the basics of C C++ and C#(.Net).  Switch from VB to C#, its better, trust me, and won't take much learning.

source: Stack Exchange

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

sort: votes


text:
I2C Wire.write function doesn't seem to work
Using the simplest code possible to test the library:
#include <Wire.h>

void setup()
{

  Wire.begin(); // join i2c bus

  Wire.beginTransmission(44); // transmit to device #44 (0x2c)
                              // device address is specified in datasheet

  Wire.write(0xA);             // sends value byte
  Wire.write(0xA);             // sends value byte
  Wire.write(0xA);             // sends value byte

  Wire.endTransmission();     // stop transmitting
}

But my data (three test byte of 0xA) is not getting sent. See image. As you can see, I get start bit, address, and then the stop bit. No data. Where am I going wrong?

Are you sure you've got ACK? The beginTransmission expects unshifted device address (it might need address 22 instead of 44). (It's the address without R/W bit)

I'm trying it without a device attached to check the data first. Does the ACK need to be present in order to send the remaining data? That is a NACK on the 9th bit.

Without an ACK from a device at that address the transfer will abort. It's not like SPI - it's a SEND-ACK-SEND-ACK-SEND-ACK protocol.

It looks like you have code for an I2C master. Sending to a slave involves sending the slave address, and waiting for an ACK from the slave (that is, the addressed slave pulls the data bus low).
You can see that in a graphic from my page about I2C:

At the 100 µs mark you can see that the slave pulls SDA low, which is an ACK. Thus the master knows that the addressed slave exists. Without that, the slave is not there, and there is no point in sending any further data.

According to the captured communication NACK was received (confirmed in comments) and according to the Wire library twi_stop will be called (and sent) in this fault scenario.
case TW_MT_SLA_NACK:  // address sent, nack received
  twi_error = TW_MT_SLA_NACK;
  twi_stop();
  break;

You can also test the return code from Wire.endTransmission(). https://www.arduino.cc/en/Reference/WireEndTransmission

This is good information. I'll try putting the device on the bus and see if that makes a difference. Thank you!

OK, I figured out what was going on...
An example program that I downloaded to test the hardware was sending a "self address" command to the chip, which was causing the address to get set to 0x03 and I didn't notice this. This new address stays in memory. So, when I went back to test the library code, I was sending 0x00 (default from factory) instead of the new address (0x03). The NACK after the address byte should have been a clue, but hey, live and learn.
Thanks for all the responses. Hopefully my pain will help someone else.

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


text:
Arduino using delay in I2C receiveEvent
I have read before that you can't use delay() inside I2C receiveEvent because it is an ISR.
What I want to do is as follows: I have a servo connected to my Arduino Uno and I want to control that using an I2C signal. Since I want to decrease the speed of the servo, I was previously using a loop with delay inside, which doesn't work when the function is called by I2C.
This is the code that I used before to control the servo:
void setServo(bool status) {
    if (status) {
        for (int pos = 0; pos <= 180; pos += 5) {
            servo.write(pos);
            delay(50);
            Serial.println(pos);
        }
    } else {
        for (int pos = 180; pos >= 0; pos -= 5) {
            wasteFlapServo.write(pos);
            delay(50);
            Serial.println(pos);
        }
    }
    servoStatus = status;
}

How could I still control the speed of the servo even if I use I2C? Thanks for your help.
Kind regards,
Moritz

You are using 2 servos : servo and wasteFlapServo  ?

Note that Serial.println() is another no-no during an ISR. Any sort of serial communication is quite slow.

@DuncanC Though there the problem is more with the serial data not getting send. print() just places the data in the buffer. The actual transmission is done via ISRs, which place each byte into the UART hardware register. So all the data would fill the buffer, untils it's full. And the data would only get send, when going out of the ISR. I think in the newer core versions print will also not block at full buffer, when inside an ISR, though I don't remember, where I read that

The general way of doing long things triggered by an ISR is to simply set a flag insode the ISR, which then gets checked inside void loop().
volatile byte flag = 0;

void loop(){
    if(flag){
        // Do something here
        flag = 0; // reset the flag
    }
}

void receiveEvent(int howMany){
    flag = 1; // set flag, if correct data was received
}

Here keep the following in mind:

The loop() needs to run fast to react fast. Long delays are doing other long stuff there will impact the responsiveness of the code. Depending on your plans for the exact behavior, the usage of delay() is generally not good. You should look into the BlinkWithoutDelay example, that comes with the Arduino IDE. It is worth learning that rather early.

flag mus be declared volatile, to tell the compiler, that is may change at any time. Otherwise it might optimize the variable away.

flag is of type byte here. It is imprtant, that this flag only has a single byte, because reading and writing of a single byte cannot be interrupted. Multi-byte variables get read or written in multiple COU cycles, thus it would be possible, that the interrupt writes parts of the variable, while you are reading it in the main code. That would lead to garbled data. By using a single byte, you avoid using critical sections for keeping the reading in main code save. For a flag thats way simpler.

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


text:
How to convert RGB values to Intensity
I made an arduino color sensor with tcs3200 and arduino uno. I have coded the arduino to find the RGB values when I place the color paper below the sensor. How can I derive the intensity using the RGB values.

How do you define "intensity"?

I remember a formula that calculated luminance (perceived brightness) using simple weights applied to the red, green, and blue values in a light source.
This formula allows for the fact that the human eye is most sensitive to green light and least sensitive to blue light.
The Wiki article on HSV/HSL has these different weightings for R,G, and B. (In all of the following, Y' is the computed brightness value.)
Y' = 0.2989 • R + 0.5870 • G + 0.1140 • B
Y' = 0.2120 • R + 0.7010 • G + 0.0870 • B
Y' = 0.2126 • R + 0.7152 • G + 0.0722 • B
Y' = 0.2627 • R + 0.6780 • G + 0.0593 • B

All of them weigh green more than the other 2. I didn't read the article closely enough to understand the different weightings of the different formulas. Perhaps they convert colors using different color models like Adobe RGB and sRGB.
See the link at https://en.wikipedia.org/wiki/HSL_and_HSV for more information.

There is no simple way to have a formula from the RGB values to intensity.
Also, there is intensity that can be measured with an intensity meter/sensor, but what people (humans, or each individual) consider more intensity (perceived intensity) is not fully related.
However, some things I found when I had a similar problem:

Typically a LED value of 0 is OFF, 1 is shining a little and 255 a lot. However, the difference in (perceived) intensity between value 1 and 10 is much higher than between e.g. 100 and 255.
Also, each LED color has a different intensity, e.g. red seems more bright than blue or green, with the same R, G or B value for the DMX lights I have, as can be read from the remarks from Duncan C and Majenko below, red is less bright than others.
Also, it depends on the physical device probably (it could have an internal algorithm to convert an RGB value to some power driven to the LED(s)).

What you can do is measure for each value and color the intensity with an intensity meter or sensor.
Or, in case you are more interested in the perceived intensity, manually check two LEDs with values to and create your own intensity algorithm.
I ended up having 3 arrays (for R, G, B), having for each value from 0-255 an 'intensity' value. I did it partly by measuring, partly by manually checking.

Red seems more bright?!? That doesn't sound right. The human visual system is most sensitive to green light. Red and blue wavelengths are much less visible at the same intensity.

Red is used for night-time illumination as the eyes are less sensitive to it and doesn't cause the irises to contract ruining your night vision. Green is used for night vision because the eyes are more sensitive to it.

Maybe 'my' Chinese DMX light has already some kind of algorithm inside because red is more bright than others, but in general it is not. I will change my answer

@Majenko: red is used for night-time illumination because the L cone cells in the retina are sensitive to it, while the rods are not. The rods are responsible for night vision and, since the can't see the red light, that light doesn't inhibit them.

@MichelKeijzers That's probably more down to lensing than brightness.

@EdgarBonet too technical...

@Majenko Could be true ... anyway I made these RGB tables to make the brightness (according to me) better.

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


text:
Arduino Joystick Library not Recognized by Games (Steam)
I have an Arduino Pro Micro running code that uses the Arduino joystick library to act as a gamepad.  I'm just doing testing right now so there's a single button wired up and configured in the code.
Windows recognizes the gamepad just fine and I can read button presses in the properties dialog for that controller.  However the gamepad doesn't work in games that work with a usb gamepad normally (I testing using Rocket League).
I would like to get my Arduino to act just like a normal gamepad (i.e. an xbox controller).
There is lots of discussion on the internet about making custom USB devices (which is what I'm trying to do) but they never seem to get answered very well or at all.  I want to achieve this on the hardware/firmware/driver side rather than having some windows application running on the computer.  If I have to write firmware on the Arduino, buy a USB PID, and/or write a USB driver for the computer, I'll do whatever it takes.

I don't know if Windows needs this, but on Linux I usually need to use the steam controller configuration to map my generic gamepad to an xbox controller emulation mode to get it working.

Hello did you get any solution? The library cited is not commercial. I am also looking for answers.

There is an Arduino Xbox 360 (XInput) library. But I do not use Steam so I have
no idea if this works.
https://github.com/dmadison/ArduinoXInput


text:
Is it possible to program an AVR chip (atmega328p) via i2c?
Currently I am using avrdude and I'm programming my atmega328p chip via the spi pins by pulling the RESET pin low (spidev programmer).
In my project I'm using predominantly i2c and this the only place where spi is used. I was wondering whether it is possible to program the chip via the i2c protocol and remove the spi connections altogether?
My searches were unsuccessful.

Are you really programming over SPI (communicating via SPI with a bootloader) or are you programming via ISP (same pins)?

@chrisl I thought I was using SPI, but now I'm not sure, lol. I'm using avrdude (-c linuxspi) to flash a .hex file over the spi pins and using the reset pin as slave select.

If you haven't changed the bootloader via ISP before doing that, I think you were using ISP, which means you were communicating with the ISP hardware of the Atmega328p directly, not with a bootloader running on it. Though I would ask, why you want to eliminate the SPI/ISP connection? Normally you use this only while developing and once for programming on production. You can even program the controller outside of your project and only put it into the target circuit after programming. That way your project circuit doesn't need any SPI/ISP connection headers.

@chrisl Well then, I suppose I'm using ISP. I want to be able to flash new firmware to my controller at any time, thus I need the programming connections, it was just going to be nice if I could reduce the number of connections if there was a simple way but it seems like too much work.

From section 27.2(*) of the Atmega328xx data sheet (emphasis mine):

In ATmega88A/88PA/168A/168PA/328/328P the Boot Loader Support provides
a real Read-While-Write Self- Programming mechanism for downloading
and uploading program code by the MCU itself. This feature allows
flexible application software updates controlled by the MCU using a
Flash-resident Boot Loader program. The Boot Loader program can use
any available data interface and associated protocol to read code and
write (program) that code into the Flash memory, or read the code from
the program memory. The program code within the Boot Loader section
has the capability to write into the entire Flash, including the Boot
Loader memory. The Boot Loader can thus even modify itself, and it can
also erase itself from the code if the feature is not needed anymore.
The size of the Boot Loader memory is configurable with fuses and the
Boot Loader has two separate sets of Boot Lock bits which can be set
independently. This gives the user a unique flexibility to select
different levels of protection.

You may need to re-write the input section of the bootloader, but it sure sounds like Atmel intended it to be doable.
[*] My data-sheet is dated 2018; the relevant section, Section 27, is titled "Boot Loader Support – Read-While-Write Self-Programming", in case a later revision has different section numbers.

Yes, as JRobert pointed out, I have no doubt - it is possible!
You need just 3 things:

a Bootloader that supports uploading the firmware via I2C
an Upload-Software that supports uploading the firmware to the bootloader mentioned in 1.)
an physical connection from the system the upload software is running on to the actual I2C bus of your device

Actually the physical interface is not the problem - there are USB<>I2C interfaces available widely, you can also re-use an arduino itself to be such.
Let's look at the bootloader.
Actually I found a german site that claims having a working I2C bootloader for Atmega8 including an upload tool (use Deepl.com to translate it). It may or may not work for other Atmegas as is.
There is also another project at github.
There will be more if you google for it. Actually I have not investigated any of them.
But chances are good than any of those might work for you.


text:
ATMega328P U Query - does it work straight away on Uno R3
Quick query (I hope).
I have an Arduio R3 board with ATMega328P U on board. It works fine. I bought some new MCUs, ordered with bootloader. Same IC designation. Before I dive into my new project I want to confirm they are okay.
So ...............I take the original MCU out of the Arduino R3 and replace it with a new ATMega328P U. Should it work fine straight away? i.e. can I upload simple sketches like Blink?
My problem is that I've done this and none of them work. I get two flashes on the Rx LED on the board, then ArvDude gives me a string of "not in sync" error messages. If I put the original MCU back in then everything works okay again. I don't want to go through the hassle of burning bootloader on chips that supposedly have it, I'd rather send them back.
Are my new MCUs duff? Or is there any other easy way to check them?
Many thanks

An atmega328p "with bootloader" might have something different than the current optiboot preloaded. Choose a "Nano with old bootloader" as your arduino target.

The MCU on the Uno R3 comes with a specific bootloader (Optiboot) and
fuse configuration (external clock, clock prescaler disabled, bootloader
enabled...). You may find some ATmega328Ps on the market that have been
specifically configured as drop-in replacements for the one on an Uno.
Those should “just work”. If the ones you bought come with a different
bootloader or fuse configuration, you may have to re-flash or
reconfigure them.


text:
I need an example of how to send AT COMMANDS to SIm7000E GPS+LTE module from ESP32 and reading those response in Serial monitor
Actually I need to make HTTPS post request using SIM7000 and ESP32 but the available libraries don't have a function for HTTPS post request, I wanna make this request using AT Commands. I need a example code to send AT Commands to sim7000e using esp32 hardware serial or software serial whichever is the best.
I am using the botlectics library but it has function only for HTTP GET/POST not HTTPS. I am looking for HTTPS request using Sim7000. As there is no function for HTTPS in botletics I thought of sending AT Commands using hardware serial from esp32 to SIM7000 . For example,
HardwareSerial mySerial(1) ,
mySerial.begin(9600,Serial_8N1,13,12)
And I have connected SIM7000 TX RX with esp32 GPIO 13,12.
then I send AT commands like
mySerial.print("AT+HTTPINIT\r");
And I connect FTDI to UOR AND UOT of esp32 which makes Serial.... So no anything done with Serial is with esp32 and writing to mySerial means Sim7000.
I have done this before but with arduino and GSM module through Software Serial and it worked fine.
I think I am missing something in case of ESP32 and Sim7000. In which I need help.

You mean you have already done a HTTPS POST on the Sim7000 using an Arduino? Sound like that to me. The AT commands are the same, irrelevant, if they are sent by an Arduino or an ESP

See there's a difference between http post request and https post request right. I used botletics Adaruitfona library for Sim7000 and it has a function for HTTP post request but not the HTTPS post request.  Now I wanna make HTTPS post request with AT commands because there's no function in that library I stated above. I am new to this world and I am facing issues sending AT Commands to SIM7000 from esp32. It was fine when I used software serial for GSM module and arduino but I am not able to do it with esp32 and sim7000. Regarding this I need help.

Hi @VanshSethi , I read SIM7500/7600/7800 shall work with SSL/HTTPS. Check here: https://simcom.ee/documents/SIM7X00/SIM7500_SIM7600_SIM7800%20Series_SSL_AT%20Command%20Manual_V1.00.pdf

The AT+HTTPINITcommand suite can't be used for HTTPS, you need to use the AT+SHCONF suite. See this Gist for a walkthrough


text:
Can we use UART COMMUNICATION with MCP23017?
I am using MCP23017 as a GPIO expander with Arduino in my project. I have too many serial devices and no pins left on Arduino for UART communication.
I am wondering if I can use this MCP23017 GPIO expander pins for UART communication or not?

with SoftwareSerial? no

I can think of one way.
In theory you could use the GPIO pins of the mcp23017 to control a couple of 2-way multiplexers. With these multiplexers you could split your Rx/Tx pins to more than one serial bus.
May it be obvious that you cannot used the split busses at the same time. So depending on your specific use-case this may or may not be a solution.

No. No you can't. Serial takes precise timing and fast reactions. Things you can't do with a remote device like that.
Instead there are SPI UART devices specifically for the job, such as the MAX3107.


text:
If the code used for Arduino can be embedded into a permanent , callable memory, is there a way to create an OS for Arduino that runs on call?
This thought came into my mind on thinking about smartwatches.
Although those I saw on YouTube are really good, they don't seem to provide a real experience of a real smartwatch - one that has an OS embedded in it. If some code in Arduino C/c++ can be compiled into some binary code that works on being called from the flash memory (where the main program resides), is there a possibility that we will be able to make an OS for Arduino ?

see Wear OS https://wearos.google.com

Sure, but you have a very small footprint in which to write this OS.  You only have a very small amount of memory in which to store that code.  So it will have to be a very small OS with very little functionality.

An AVR-based Arduino is a poor choice for writing an "OS" in the modern sense. It's just too resource constrained. It doesn't have enough RAM, it doesn't have enough flash memory, it's too slow, it doesn't have protected memory or paging, it doesn't have video display, it doesn't have a file system, and on and on.
If you look at an Apple II, something like Apple DOS or ProDos gives you an idea of the sort of thing you can do (minus the video output.)
If you want to develop something like a smart watch an ARM processor is a much better choice. It packs a lot more performance into a small package. You might pick an ARM based Arduino, but you would be fighting against the lack of an OS, the lack of preemptive multi-tasking, etc.
As an alternative, a Raspberry Pi has just about everything you need. It doesn't have as many hardware interfacing options as an Arduino, but a LOT more processing power. Likewise, UNIX is a better choice as the basis for the OS for such a device. It is a protected memory OS that is made to run on relatively modest hardware.

If anything an ARM will have more hardware interfacing options as it has more modern peripherals and protocols embedded in it.

Sorry, I was conflating ARM with Raspberry Pi. I edited my answer to treat ARM-based Arduinos sepereately from Pis.


text:
What exactly does the return type do in a function?
something I've never understood and still don't is, what does the return type do specifically? Everyone in tutorials just say that void returns nothing and int returns int, etc. But what does that mean? Where is it returning to?  I can't seem to understand what everyone's talking about when they discuss functions.

it's the same as declaring a variable as the result of the function instead of a hard-coded literal.

It returns it to whatever the function is being assigned to.
Take the function:
int plus(int a, int b) {
    return a + b;
}

That function takes two integers, adds them together, and "returns" them as an integer.
You can then do:
int c = plus(3, 4);

and c will be handed the value 7 by the function.
Equally you can do:
Serial.println(plus(3, 4));

And the Serial.println() function will be handed the value 7 for printing.
The type of the return defines the kind of data that can be returned.
Oh, and void doesn't mean "returns nothing", but means "doesn't return anything" - which means you can't assign it to anything since there's nothing returned to assign.

To add to And the Serial.println() function will be handed the value 7 for printing. Especially, it will be handed an int value of 7, which will eventually produce a different output than other data types.

The reason is that a function is evaluated just as any other expression would be. Every expression - `(x**x - 3*x + 5), for instance - has a value and a type (unless the type is void, then it has no value, or not a defined one), and that includes functions. The compiler needs to know the type of every element of the expression in order to know how to use that element in an operation (arithmetic or other kinds). Sometimes a value has to be converted from one type to another to combined with another element or assign to a variable, and knowing the type of each element is the only the compiler knows how to accomplish this.
Here is an example:
float squareroot(float x); could declare a function that takes a floating point number and returns its square root as a floating point number. If you assign that value to an integral of variable, the compiler needs to see that the functions does not return an integer but a float, so it includes the appropriate code to convert the float to an integer (by truncating the fractional part, in this case).
If the function could be written without declaring its return value type, the compiler would be unable to make the conversion, or even to know whether one will be needed.


text:
Achieving nanosecond accuracy with MKR Vidor 4000
Can I achieve nanosecond accuracy with Arduino Vidor MKR 4000? Has anyone experience? Obviously by using the FPGA it has on it. I do not find much support on this module on google search...

do you know what frequency is involved in 1 ns time interval?

I think so..., but we are talking for FPGA here...I think they have different rationale than CPUs, don't they?

what are you trying to build?  ... do you know what an FPGA actually is?

No. You can't.
To achieve 1ns precision you need a 1GHz clock. That can't happen.  The MKR Vidor 4000 uses an FPGA with an "A7" speed grade. That means that (according to Table 20 here) you can't run at any more than 402Mhz internally (200MHz is all Arduino are rating it for).
Not even half.
Around 5ns precision would be the absolute maximum precision you could get if you stick to the Arduino clock specs.


text:
Installing Pyserial
I will be running my CNC Via Arduino UNO R3, so i have found out that it runs on GRBL and that i need to load Python and Pyserial and a graphic interface.
Loaded Python 3.5.2, no problems, opened dos window typed Python, got the python >>> prompt, so far so good, downloaded/unzipped/copy/paste Pyserial  into c:/python35/lib/site-packages/pyserial.
at this point, at the dos prompt i type >>>python setup.py install. All i get is a syntax error.
I have included the dos script for comment
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Goblin>python
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> import os
>>> os.getcwd()
'C:\\Users\\Goblin'
>>> os.chdir("/users/")
>>> os.getcwd()
'C:\\users'
>>> os.chdir("/../")
>>> os.getcwd()
'C:\\'
>>> os.chdir("/python35/lib/site-packages/pyserial/")
>>> os.getcwd()
'C:\\python35\\lib\\site-packages\\pyserial'
>>> python setup.py install
  File "<stdin>", line 1
    python setup.py install
               ^
SyntaxError: invalid syntax
>>>

This is about the 7th attempt.
I seem to be following the instruction correctly but it wont install ....HELP Please, this is so frustrating, what have I done wrong.
Thanks in advance
Doug

Dont do this within the python environment. Its meant to be run from the system command line. Navigate with 'cd' in Command Prompt to the pyserial folder and then run this command again.

I'm pretty sure that what you are trying to do is actually call 'python setup.py' within the python script itself. Which you cannot do. The easiest way to install pyserial is via pip like so. (Windows)
python -m -U pyserial --upgrade

Now if you still want to use setup.py or you don't have pip installed. Make sure that you meet all of the package dependencies. Which in pyserial there are no others. Try exiting out of the python interpreter and just running
python setup.py install

In the same folder location as the extracted zip (use cd to change directories)

not exactly related to Arduino but here it goes...
First check if you have pip installed:
pip --version

if not installed go here and download the get-pip script.
then on directory where you saved get-pip run on console:
python get-pip.py

this will install pip into your system which makes installation of packages in python way more easy.
if installed but not latest version ( at momment 8.1.2) do an upgrade before:

On Linux or OS X:

pip install -U pip

On Windows:

python -m pip install -U pip

after install pyserial using pip:
pip install pyserial

Did it work?
If not, try:
python -m pip install pyserial

if it still doesn't work install from source. Get the latest version here extract it and in the dir where you extrated run:
python setup.py install

PS: change to dir first, no need to do it inside python.

Thanks All...by running the command at a std DOS prompt I was able to install the Pyserial.py file.
i have since seen comments that some of the 3.x.x series Python has glitches,(I am running Windows7). I have gone to 2.7 Python as a program i would like to use doesn't appear to run under 3.x.x   bCNC likes the earlier versions, not sure why, but it does run under 2.7  . for those interested JCNC, EFL CNC, Grbl Controller seem to run OK under 3.x.x


text:
Arduino autorestarts when powered externally
I'm trying to finish  building an alarm system with relays, leds  and bluetooth. I finally made it working but when externally powered (12v source) after about 10 seconds it starts to reboot continuously.
This issue comes with no pc connection.

And how toasty does the 5v regulator get...?

Very much, could be this a sort of heat protection?

Most regulators have thermal protection, yes. You will need a better power supply arrangement.

https://www.arduino.cc/en/Main/ArduinoBoardUno
Majenko has a good lead,
12V is just within spec of the voltage regulator.
Though this may be different per manufacturer or different in your environment.
To battle overheating you can:

Create beter airflow
Add a heatsink
Draw less current

But you should try a 9V source, that can deliver enough current (not the 9V "block" batteries).
Also check if the system draws excessive current, maybe the circuit has a low resistance or power hungry part (on the 5V rail)
If nothing works, you could try and use another Arduino board, maybe the regulator is faulty/damaged.

I added an additional power supply 5v for the sensors, relays, etc. Now the arduino regulator is cooler and I don't experience reboots anymore.
Thank you Paul


text:
Help with reading and storing data from sim module
I'm using a sim800C module and an Arduino Uno. I want the code to send back an SMS to a number which sends it the password. So, if the sim module receives 'abcd' I want it to send back an SMS, saying 'ok'. Where I'm stuck is actually storing the read SMS. Since I need to check the SMS with a pre-defined password, I need to store the SMS the module received somehow. Please help ? Here's the code so far:
#include <SoftwareSerial.h>
SoftwareSerial sim(10, 11);
int _timeout;
String _buffer;
String number = "+000000000000"; //-> change with your number
String incoming;

void setup() {
  //delay(7000); //delay for 7 seconds to make sure the modules get the signal
  Serial.begin(9600);
  _buffer.reserve(50);
  Serial.println("System Started...");
  sim.begin(9600);
  delay(1000);
  Serial.println("Type s to send an SMS, r to receive an SMS, and c to make a call");
}

void loop() {
  char inChar[5];
  if (Serial.available() > 0)
    switch (Serial.read())
    {
      case 's':
        SendMessage();
        break;
      case 'r':
        RecieveMessage();
        break;
    }
// this is where the sim module spits back the received SMS to the serial monitor. How do I store it ?
  if (sim.available() > 0) {
    Serial.write(sim.read());

  }
}

void SendMessage()
{
  //Serial.println ("Sending Message");
  sim.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);
  //Serial.println ("Set SMS Number");
  sim.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message
  delay(1000);
  String SMS = "GPS-cordinates";
  sim.println(SMS);
  delay(100);
  sim.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  _buffer = _readSerial();
}

void RecieveMessage()
{
  Serial.println ("SIM800C Read an SMS");
  delay (1000);
  sim.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
  delay(1000);
  Serial.write ("Unread Message done");
}

String _readSerial() {
  _timeout = 0;
  while  (!sim.available() && _timeout < 12000  )
  {
    delay(13);
    _timeout++;
  }
  if (sim.available()) {
    return sim.readString();
  }
}

i think that the problem lies in you not realizing that your question is not about a SMS, but about serial communication ... there is lots of info on the internet about handling serial comm


text:
Arithmetic types in Arduino
I'm looking for a complete list of the arithmetic types in the Arduino framework.
On the Internet I found various incomplete lists: sometimes there is short, sometimes word, but other types are missing.
Could someone please provide an exhaustive list of the arithmetic data types in Arduino, including the C/C++ types and the Arduino-defined types (or aliases, e.g. the one created among others in Arduino.h with typedef uint8_t byte;) with a short description? If two types are identical please include both names in the list but making clear that they are the same.

You have integers in 8, 16, 32 and 64 bits, both signed and unsigned. You have float and double, which can be the same thing on some systems.
There are many names given to those variable types, some standard or ubiquitous, some vague or unique, or change depending on which type of CPU you are working with.
The names aren't important, since they only exist in the source code. All that matters is the underlying size. Names of the same underlying size and signedness are interchangeable at will.
For example:

uint8_t = unsigned char
int32_t = long = int on 32 but systems
uint16_t = unsigned short = int on 8 bit systems

As you can see int changes depending on the system you are on. So it is best to stick to specifically named types. I always use the [u]int[N]_t types.
So you have:

uint8_t
int8_t
uint16_t
int16_t
uint32_t
int32_t
uint64_t
int64_t

And:

float
double (if the compiler supports double on the platform you are compiling for, otherwise it is just float).

Arduino itself provides some more unique variable names that are completely nonstandard, such as byte for unsigned char.
In short (pun intended), stick to variables that specifically define their type if you are worried about how big they all are, and avoid all the rest.
For overloading the compiler will automatically "upscale" the variables to the best fitting available function (known as type promotion) unless functions are flagged as explicit, so you can have a function with a long parameter and pass any integer variable up to and including a long in size. The same with float / double types - if your function takes a double you can pass it a float. Useful when you don't know if the target provides a real double or not - just use double and it will work regardless with either double or float.

And all the _Fract and _Accum types in avr-gcc 4.8+.

GCC has introduced all sorts of weird and wonderful types for special jobs. I have never seen any of them actually be used. People tend to use assembly or DSP instructions for optimisation instead of strange types.

The Arduino "language" is actually C/C++. GNU GCC and tool chain are used. The Arduino IDE uses a preprocessor to make it easier for beginners by removing some of the C/C++ requirements such as forward declaration of functions.
The GNU AVR GCC data types and representation, and the answer to your question can be found on the project Wiki page; https://gcc.gnu.org/wiki/avr-gcc
For C/C++ there are build-in data types but also a set of standards. One of the standard header files with data types is stdint.h. http://www.nongnu.org/avr-libc/user-manual/group__avr__stdint.html
Arduino.h and additional header files within the Arduino core libary contains the extensions or redefinitions made. The complete reference list; https://www.arduino.cc/en/Reference/HomePage
Cheers!


text:
Why are begin() functions needed to initialize hardware (if they are)?
I'm writing a program for an ATmega microcontroller using the Arduino framework.
While implementing an hardware-related class (one to manage LEDs), I put some hardware initialization code such as pinMode(OUTPUT) in the class constructor. Then I realized that in all Arduino libraries I know the hardware initialization is done in a begin() or init(), so I created one for my Led class as well and moved pinMode() there.
Now I'm wondering if I really should define such initialization funcitons, i.e. why they are needed - or, if they are not, why so many libraries have them. I played around a bit and found that for example this code works on an ATmega1284 (it makes the LED on pin 28 light up).
struct Test {
  Test() {
    pinMode(28, OUTPUT);
    digitalWrite(28, HIGH);
    // other stuff
  }
  // ...
};

Test test;

void setup() {
}

void loop() {
}

I presume that this code is somehow ill-conceived, letting alone the fact that it lights up a led without any code in the main function (or maybe that is exaclty the problem?), but if so I can not see why. What did I not consider?
Should the code above be rather writte as in the following snippet, as the existence of all these begin() functions leads me to believe?
struct Test {
  Test() {
    // other stuff
  }
  void begin() {
    pinMode(28, OUTPUT);
    digitalWrite(28, HIGH);
  }
  // ...
};

Test test;

void setup() {
  test.begin();
}

void loop() {
}

Although Arduino API styleguide recommends to use begin() to set thing up. To me both are works and is a design consideration, provided that you know what have been configured and initialised by the Arduino.h and variants for a particular boards, and what you are trying to do in the construct will not be overrided by the init() within the Arduino Core main(). For example, you see many library use the construct to set thing up like LCD lcd(SDL, SDA);.

To your question about setup() and loop(), see the source code of Arduino Core main.cpp for better understanding.

It's all to do with the order of execution.
Constructors are executed before normal functions. That includes the main() function which eventually calls setup() and (repeatedly) loop(). One of the other things that main() does is call init() (or some variant of) which configures the hardware.
Since that happens after any global constructors have been run anything that the constructor did to the hardware could potentially be undone.
Thus it is normal to defer any hardware configuration until after main() has done the work of setting things up, and the convention is to use a begin() function to do it.

Thanks for the answer! And what is actually this init() function? Where is it defined? And, by the way, where is the main() function in an Arduino project?

It's all in the core. Read the cores source code.


text:
Determine whether a variable is of an arithmetic type
Is there a way to determine whether a variable is of an arithmetic type or not?

arithmetic: integer, floating point numbers, boolean values
not arithmetic: pointers, references; e.g. strings, and probably all other implementation- and user-defined types. However if someone for some reason defines typedef int myInt myInt should be considered arithmetic as well (because it is!)

In a normal C++ program I could use std::is_arithmetic<T>::value, where T is the type I need to check, but this doesn't seem to work in the Arduino environment. (Am I wrong? If it works, could someone please tell me how to use it?)
I imagine I could make a list of allowed types, e.g. as described in this answer to a similar question (I'm referring to the second option, the Alternative). But given that I don't need to exactly know the type of T I was wondering whether there is a more elegant and flexible solution...

What are you actually trying to do?

There are some ports of the std library for Arduinos, but I'm not sure if they have this in.  You could just look at the code and work out how its done and port it yourself.

I simplified the function I'm working on: template
bool myFunc (int a, T b) {
if(a*b > 100) return true;
}     --- EDIT: sorry, I forgot that code won't format in comments... I hope it's simple enough to be readable.

@noearchimede In comments, put the code in backticks. Read this for more info: https://arduino.stackexchange.com/editing-help#comment-formatting

@Majenko Actually I'm writing a set of functions (in a library) that operate on arithmetic values, and it doesn't make sense to call them with non-arithmetic types (it's like writing pow("two", "four"). However given that I'm using the library in many different projects, and also other people will use it, I would like to be able to catch such stupid errors (either at compile time or at runtime, that makes no difference (those functions all print text, so they could print "not a valid number")). If I can't do that I'll write a long list of overloaded functions instead of using templates.

Ok, that makes sense.  For Arduino code overloading is probably the simplest method. It's used throughout the core for things like print() etc. And you would only need to overload for the types you actually want to handle - then other types that don't "add up" you would just get a compilation error.

I don't think Arduino IDE supports boolean arethmatic

Thanks, I didn't think about that... but if there is an arduino-compatible way to determine whether a variable is of an arithmetic type it should automatically not include bool, right?

Is there a way to determine whether a variable is of an arithmetic type or not?

no. end of the day, those are just bit pieces and it only makes sense to the computer with the right context. Another way to put it, the same bit pieces can and will mean different things under different situations.

I know that reading 4 bits representing a float as a long will give a valid but meaningless value. But the computer must somehow know how to interpret those bits, right? Either at compiletime or at runtime the type of each variable/set of bits must be known, and the property arithmetic/not arithmetic must also be known somehow: don't I get an error message if I try to do myClass + aString? (btw., may this be a solution to my problem? Try do do some arithmetics on the variables passed by the caller and output an error if it isn't possible to do so? Could that work, and if yes what could be...

...an elegant implementation? (I mean, an error like "unable to do myclass+astring" wouldn't be very clear to someone who doesn't know the implementation of the function he is calling)


text:
writing very long function
I'm writing an Arduino program, and I need to write a function to input some numbers trough a computer connected to it trough the serial interface.
This function should perform many different and well-defined tasks, e.g.: obtain data (characters) from the computer, check if the characters are valid, transform the characters in actual numbers, and many others. Written as a single function it would be at least 500 lines long. So I'll write a group of shorter functions and one "main" function that calls the others in the only meaningful order. Those functions will never be called in the rest of the code (except of course the main function). One last thing - the functions need to pass each other quite a lot of variables.

What is the best way to organize those functions? My first tough was to create a class with only the "main" function in the public section and the other functions and the variables shared by different functions as private members, but I was wondering if this is good practice: I think it doesn't respect the C++ concept of "class"... for example to use this "group of functions" I would need to do something like that:
class GetNumbers {
    public:
        //using the constructor as what I called "main" function
        GetNumbers(int arg1, char arg2) {
            performFirstAction();
            performSecondAction();
            ...
        }
    private:
        performFirstAction() {...};
        performSecondAction() {...};
        ...

        bool aSharedVariable;
        int anotherVariable;
        ...
};

And where I actually need to input those numbers from the computer:
GetNumbers uselessName (x,y);

Making the "main" function a normal class method (and not the constructor) seems to be even worse:
GetNumbers myClass;
myClass.getNumbers(x,y);
...
//somewhere else in the same scope
myClass.getNumbers(r,s);

And what is wrong with just using one big function? It sounds like, in this case, splitting it into multiple functions won't make it easier to read/understand. Just add plenty of comments, and add some extra newline between different sections.

Maybe it's my background of old C programmer but... I would just write
plain functions, no classes, like in C. And I would keep all this stuff
in a single file, to provide some form of encapsulation:
my_parser.h:
some_type get_numbers(int arg1, char arg2);

my_parser.cpp:
static int performFirstAction(float arg1, int arg2, char arg3)
{...}

static bool performSecondAction(long arg1, void *arg2, int arg3)
{...}

some_type get_numbers(int arg1, char arg2)
{...}

Note that there is only one function declared in the .h: this is the
“interface” to your module. Note also that all the other functions are
defined as static. This tells the compiler to keep them hidden from
the linking phase, so they do not pollute the global namespace. And
finally, note that there is no global shared variable: everything is
passed as arguments to the functions.
The rationale for the last point is that this helps the compiler
optimize things. A static function that is called only once is almost
guaranteed to be inlined by the compiler. Which means there is no
overhead in passing the arguments. On the other hand, if you use global
variables and the compiler doesn't manage to optimize them away, you
will incur the cost of RAM access.


text:
Arduino UNO not sending serial data to ESP32
Lately I've been struggling with Serial communication between Uno and ESP32. I'm trying to send a simple string (In my case "100") from my Uno to my ESP32. I made a voltage divider and I'm using HardwareSerial Serial2(1) for the Serial reading on the ESP32's side. On my Uno's side, I use Pin 9 for sending data a.k.a Pin 9 goes to the voltage divider and links with RX2 (GPIO16) on my ESP32, like in the picture below.
My Uno code is:
void setup() {
Serial.begin(9600);
}

void loop() {
Serial.print("100");
delay(2000);
}

and on the other side, ESP32's code:
#define RXD2 16
#define TXD2 -1

HardwareSerial Serial2(1); // Use UART channel 1

void setup() {
Serial.begin(9600);
Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
}

void loop() {
if(Serial2.available() >= 1){
Serial.print(Serial2.read());
}
else {
Serial.print("Not sending");
}
delay(2000);
}

I'm not receiving the data and I get "Not sending" all the time.
My question is: Should I use TX pin from my Uno instead of pin 9? Or there's something wrong with my code?
Thank you in advance

Need to use serial pin TX 1 in Arduino

As I suspected, this fixed the issue. Thank you so much :)


text:
Uno to ESP32 - HardwareSerial repeats value on ESP32's side even though Uno is disconnected
I have an Arduino UNO connected to ESP32 through voltage divider with TX0 from Uno to RX2 to ESP32. My goal is to send data from my Uno to my ESP32 through HardwareSerial. Here's my code for the Uno:
void setup() {
Serial.begin(9600);
}

void loop() {
int t = 100;
String myString = String(t);
Serial.println(t);
delay(5000);
}

Here I assign an int to 100 and then cast it to String so I can send it on my ESP32's side. My code for ESP32 is:
#define RXD2 16
#define TXD2 -1

HardwareSerial Serial2(1); // Use UART channel 1

void setup() {
Serial.begin(9600);
Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
}

void loop() {
if(Serial2.available() >= 1){
Serial.print("Data received:");
Serial.print(Serial2.readString());
}
}

The serial monitor on ESP's side is printing only "100" on every 5 seconds but if I disconnect the Uno from my Port, the ESP's monitor keeps printing "100" even tho it shouldn't.
However, IF I type Serial.println("100"); then I get "Data received: 100" on ESP's side and if I unplug the Uno, the ESP's monitor doesn't print anything or with other words it works properly. Is there a way I can fix this?

The whole String thing is irrelevant. You're not using it. You're printing the integer. Delete the string rubbish.

you print to Serial. Serial prints to Serial Monitor. on what port is your Serial Monitor listening?

I'm well aware of that but my goal here is to "pass" a variable to the Serial communication. With the String thing, the ESP's side doesn't act properly and that's what I'm trying to fix.

Uno's port is COM3 and ESP's port is COM4 @Juraj

the output you see depends on which COM port is in Serial Monitor, not on code changes. the port changes as you change it for upload

Thank you, I think I fixed my problem now @Juraj


text:
Initializing an object as class member resulting in linking error?
I'm a little dumbfounded as to why this isn't working. I keep getting the following linker error:
In file included from src\ac.cpp:1:0:
src/ac.h:9:21: error: expected identifier before numeric constant
 #define RECEIVE_PIN 0
                     ^
src/ac.h:14:26: note: in expansion of macro 'RECEIVE_PIN'
     static IRrecv irrecv(RECEIVE_PIN);
                          ^
src/ac.h:9:21: error: expected ',' or '...' before numeric constant
 #define RECEIVE_PIN 0
                     ^
src/ac.h:14:26: note: in expansion of macro 'RECEIVE_PIN'
     static IRrecv irrecv(RECEIVE_PIN);
                          ^
*** [.pio\build\esp32cam\src\ac.cpp.o] Error 1
*** [.pio\build\esp32cam\src\main.cpp.o] Error 1

I am simply trying to initialize the IR receiver with static IRrecv irrecv(RECEIVE_PIN);, but the compiler is refusing to link it together.
#ifndef _AC_H_
#define _AC_H_

#include <Arduino.h>
#include <IRremoteESP8266.h>
#include <IRrecv.h>
#include <IRutils.h>

#define RECEIVE_PIN 0

class IR
{
public:
    static IRrecv irrecv(RECEIVE_PIN);
    static decode_results results;
    void initRecv();
    bool waitForIR();
};

extern IR ir;

#endif

If I do static IRrecv irrecv; it successfully compiles, but I'm unsure if I can pass the pin variable after the fact.

https://stackoverflow.com/questions/5019856/initialize-static-variables-in-c-class

what happens if you use RCV_PIN? ... looks like RECEIVE_PIN is a macro

@Mat It doesn't seem to be possible to change the value after initializing it

@jsotola I've rewritten it in various formats. I've tried all kinds of data types, names, and initializing it as irrecv(0) as well.

Static data members have to be defined outside the class declaration.
The initialization happens at the point where the members are defined:
file ac.h:
//...

class IR
{
public:
    // Static data members are declared only:
    static IRrecv irrecv;
    static decode_results results;
    void initRecv();
    bool waitForIR();
};

file ac.cpp:
#include "ac.h"

#define RECEIVE_PIN 0

// Definitions and initializations of static data members:
IRrecv IR::irrecv(RECEIVE_PIN);
decode_results IR::results;


text:
Use timer0 without affecting millis() and micros()
I'm writing a library which needs an ISR to turn off an LED some time after it was turned on. Since it's all about turning an LED on and off it doesn't need to be very precise. On the other hand I would like to use this library in a program where timer1 and timer2 are given out to other (more important) tasks, and I also need the millis() and micros() functions. Last, I'm using an ATmega328P microcontroller, which only has 3 timers (and I can't easily replace it with another one).

So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions, and – if that can be done – what would be the restrictions of such an ISR (e.g. I suppose I could not use all the timer/interrupt modes...) and the disadvantages or side effects in using this timer in a non-Arduino library and the Arduino millis() and micros() functions.
Thanks in advance for any answer!

Why do you feel you need to use an interrupt for such a simplistic and not time-critical operation?

I fact I'm currently using a 'checkLed()' function, and it works fine. But 1) the program main loop is sometimes quite long (e.g. sometimes it has to execute other loops), and it were easier for me if I didn't need to care about turning off the LED (which is not time-critical but quite important), 2) now I'm quite curious about this question in general ;)

Fair enough. TBH I have just been writing a routine that does exactly that, but on a different MCU that has a different timer structure (it controls the TX and RX LEDs to indicate USB activity - RX interrupt and TX functions turn the LEDs on, timer turns them off 50ms later), so I can understand the need.

Related: Atmel / Arduino: ISR(TIMER0_OVF_vect) won't compile (“first defined” in __vector_16) (providing your own handler for Timer0 and still use the Arduino environment).

So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions,

Yes. A few ways, depending on your level of comfort:

You can declare the stock Arduino Timer0 OVF "weak" and write your own where you can insert your ISR. But you have to handle the interaction between the millis() / micros() related variables.
You can modify the stock Arduino Timer0 OVF to insert your own ISR.
And – if that can be done – what would be the restrictions of such an ISR (e.g. I suppose I could not use all the timer/interrupt modes...)
The stock ISR would look like this:
ISR(TIM0_OVF_vect) {
    ...
    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;

    //insert your isr here
    _mytmr0_isrptr();
}

Where _mytmr0_isrptr() is a function pointer to your own ISR handler.
The simplest is probably to use the output compare interrupts. You can get it to behave like a virtual timer and can do lots of other stuff.

Obviously, you can think of tons of other ways and this is just a starting point.

What are those interrupts? How can I use them? –

Timer0 has three interrupts associated with it: overflow and compare channel A and channel B. The overflow interrupt is already being used by the timing functions millis() and micros(), as shown earlier.
The compare channel A/B interrupts are unused. And this discussion is about using them for timing purposes.
The general ideal is demonstrated in blog post Using Spare Output Compare Channels as Timers – the Collection.
The task there is more complicated than what you are trying to do here, but the basic ideal is the same. To do what you wanted here it is much simpler than that.
If you still cannot figure it out, I can provide you with code pieces to get you started.

Sorry, i didn't understand the third option... What are those interrupts? How can I use them?

Thank you, now I got it! I've implemented it in my library and it works.

I'm glad you have a solution that works for you. The key here is to recognize that output compare is essentially a timer: it generates an interrupt on match, vs. Timers doing so on overflow or underlie.

Once you recognize that you can make a lot of virtual timers out of output compare channels . for most mcus that means 2x to 8x virtual timers per hardware timer.

I think the first solution suggested by dannyf's answer is wrong as ISR in AVR GCC can't be defined as weak function (why).
I think the best solution is to add handler (AKA hook) functions using function pointer to the Timer0 ISR inside the core wiring.c source file shipped with Arduino core, and assign latter (attache) this function pointer to any desired function in the other library/class or in the main application code.
More about this trick in this article here.

So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions ...

No, because those functions use an already-attached interrupt.

it doesn't need to be very precise ...

Just test for the current time (eg. using millis or micros) in your main loop.

the program main loop is sometimes quite long (e.g. sometimes it has to execute other loops) ...

Restructure so that it doesn't do that. You can use the state machine concept to do things from time to time, without getting stuck in inner loops for a long time.

It's not possible with TIMER0_OVF interrupt, but there are also TIMER0_COMPA/TIMER0_COMPB interrupts and these should be free to use. Only downside is that analogWrite on corresponding pins moves the time when the interrupt happens.

@KIIV So using timer0_compx I couldn't use analogWrite on the corresponding pin any more?

@noearchimede You can. Just the interval will move according to that. But if you don't need precise timing, it won't be a problem. Just for sure you can test all PWM values just to be sure it's working everytime.

@KIIV I've just written a new version of my library using TIMER0_COMPA and it works exactly as I wanted.May I ask you to write a complete answer with your suggestions, so that I can mark the question as answered?

@noearchimede It's already here in dannyf answer (third option)

@KIIV Yesterday I didn't understand his third option so I forgot it, but now it is clear to me. Thanks to you and all those who answered!

An interrupt can only have one interrupt service routine. The only way you can do something else using an interrupt that is already handled elsewhere would be to modify that existing interrupt handler to also call your code. Not something that is practical for a library.
I can see no practical way of doing it short of modifying the entire millis() system in the main API to allow hooking of callback functions, which would be a really nice facility (chipKIT has a similar system with the Core Timer interrupt on the PIC32) and submitting it back to Arduino for inclusion in the main core - which would set a baseline version for compatibility of your library of course.

And there is no way to kind of override the ISR of the millis system without modifying the API files, right?

Correct. If you define a second ISR you will get vector conflicts. You will just have to decide on another interrupt to use. Some libraries provide #define macros etc to select which timer to run with.


text:
IDE does not create prototypes
I'm running Arduino IDE 1.6.10 on Mac OS X 10.12.1.
I read on the Arduino official sote that the IDE should create function prototypes for me, and it always did. But now I'm writing a 1500 lines program, with dozens of functions, and this tool wold be quite useful (although I obviously don't really need it)... and it doesn't work.
Is that a known issue?

Do yourself a favour and dont rely on those automatic tools.
Type your code and know every line you typed.
And give PlatformIO a try instead of the Arduino IDE. You will save yourself and coworkers a lot of grief.

There are some times when it can't make prototypes, and some when it just gets it plain wrong. It struggles if you do fancy things with any of your functions, such as adding attributes or using anything that's even slightly out of the ordinary.
Also sometimes it places the prototypes in completely the wrong place, especially if you are working with structs, etc.

Unfortunately various things make the prototype generation fail. I think they run a regexp on the code which doesn't detect all cases. Examples are:

Function definition split over multiple lines
Use of templates
Use of user-defined types in a function definition

Here is one bug report:
https://github.com/arduino/Arduino/issues/472
It's not that hard to take your function definition and make a prototype out of it. It's good practice anyway to get into the habit of it. If you get into larger projects where functions are in different files you need to do this anyway.


text:
Using multiple RTC libraries in one program
There are multiple RTC libraries available, can I load several RTC libraries into my code and then use the functions I like from each one?  Will there be some conflict if for example I include DS1307.h   and RTCLib.h and other RTCXXXX.h libraries as well?

I think that in case of the RTCs it might actually work, but it's not advised, and may introduce some really weird problems.

Thanks guys, the real issue is that the functions available from just one RTC library are often lacking. I haven't found a "super" RTC library that incorporates the best ideas of the many libraries out there. I don't feel like writing or editing a library so I'll just convert my sketch to deal with the present best of breed.

can I load several RTC libraries into my code and then use the functions I like from each one?

It will depend on the libraries. Most likely they had some persistent variables, global to the routines, that help information exchange. If only some of the routines are used and others not, values in those variables may not be consistent.

Will there be some conflict

That will depend on the way those libraries are implemented. No way of telling without seeing the code.
The point of doing this is a little bit suspect. It is not clear to me why you would want to have more than 1 RTC in an environment. If you are thinking about giving your program the option to function with multiple RTCs (but using one RTC at any given time), you can use either macro (at compile time) or wrap the RTCs in a logic layer (at run time).
For example, you can have a rtc_init() to reset different RTCs; and rtc_read() to return the time from the rtc. rtc_read() can be implemented based on which RTC is detected during initialization...

If you want to load multiple RTC libraries I guess you are connecting to multiple RTCs.
If they use the same interface to communicate, i.e. I2C there is a possibility you will initialise the bus multiple times.
You should be OK with the functions not clashing, because they are within classes, but its possible some of the referenced structures/ classes my clash.  You might be able to resolve this by namespacing the libraries.
An alternative might be to write your own library that handles all of the RTCs that you are interested in.  This will force you to consider what each RTC requires and identify problems.
At the end of the day I agree with what Gerben is saying.  Don't do it unless you really have to.


text:
Cheapest way to change digital output source
Powering at 5 volts, atmega328 output ~4.7 volts. I need to output between 12 and 24 volts @ 2 amp. I'm currently using relay but they are costly. Is there a way to do it with transistors or any thing cheaper?
Thanks

Yes, but it depends on WHAT you are powering.

Something like a mosfet.

As @Gerben said in the comments, I would also recommend an N-channel MOSFET.  OnSemi has a great application note on how to determine what type of MOSFET you would need based on your given load requirements and how to use it as a switch.  You can find that app note here.
The basic idea is to provide an enable signal from your atmega328 to the gate of the MOSFET to drive it into saturation or to turn it off.  You would connect your 12/24V supply to the drain of the MOSFET and connect your load to the source of the MOSFET.  The basic circuit can be seen in the application note.
Hope that helps!


text:
Arduino Pro Mini interrupts timer not working
i am trying to make an arduino pro mini sd card serial logger.The arduino should log the data that comes over the uart and write it to an sd card and if it is no data on the serial for 25 seconds to save automatically the data into the file.Each file are named diffrent every time they are saved(for example datalog0.txt, datalog1.txt and so on).I am creating also at the start of the sketch an config(config.txt) file where the number of the file present of the sd are stored and if the file already exist than a new one will be created, this option works good.Now, after the 25 seconds past and it is no more  data over the serial the arduino dont close the datalog.txt file , so the next data will be saved in the same file, this is the problem i have, even in the config file the file number will be increased.I will attach the sketch and expect patient from you, ai am still newbie.I forgot to mention that it was working good for some time but not anymore, the only thing i did was to upload the bootloader from ide and since than is not working anymore.
Regards.
//#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>
#include <SoftwareSerial.h>

            int i;
            int incomingByte = 0;
//int data[512];
            File myFile;
            unsigned char bytes,flag_again;
            unsigned int fileNo,timer_count;
            String s_fileNo,filename,filename_master;
            char comanda;

            void Timer1_InIt()
        {
            TCCR1A = 0;
            TCCR1B = 0;
            TCNT1  = 0;
            OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
            TCCR1B |= (1 << WGM12);
                TCCR1B |= (1 << CS12) | (1 << CS10);
                //TIMSK1 |= (1 << OCIE1A);
            }

ISR(TIMER1_COMPA_vect)
{
    timer_count++;
    if(timer_count > 25)
    {
        timer_count = 0;
        TIMSK1 &= ~(1 << OCIE1A);
        myFile.close();
        fileNo++;
        myFile = SD.open("config.txt",FILE_WRITE);
        myFile.seek(0);
        myFile.print(fileNo);
        myFile.close();
        //software_Reset() ;    //reset the sketch
    }
}
SoftwareSerial mySerial(4, 5); // RX, TX

void setup()
{
    cli();
    Timer1_InIt();
    sei();

    mySerial.begin(9600);
    Serial.begin(10752,SERIAL_8E2);
    //mySerial.print("Initializing SD card...");

    if (!SD.begin(10))
    {
        //mySerial.println("initialization failed!");
        return;
    }
    Serial.println("initialization done.");

    myFile = SD.open("config.txt",FILE_READ);
// mySerial.println("Config file created");
    if(!myFile.available())
        bytes = 0;
    else
    {
        bytes = myFile.available();
        for(i = 0; i< bytes ; i++)
            s_fileNo += (char)myFile.read();
    }
    myFile.close();
    fileNo = s_fileNo.toInt();
// mySerial.print("file no:");
    //mySerial.println(fileNo);

    filename = "datalog";
    filename += fileNo;
    filename += ".txt";

    myFile = SD.open(filename,FILE_WRITE);
    if (myFile)
    {
        //mySerial.print(filename);
        //mySerial.println(" File Open...");
    }
}

void loop()
{

    if(!myFile)
        myFile = SD.open(filename, FILE_WRITE);

    while(Serial.available())
    {
        incomingByte = Serial.read();
        /*if(incomingByte == 0 || incomingByte < 15 )
        {
          Serial.print('0');
          myFile.print(0,HEX);
        }*/
        //mySerial.println(incomingByte,HEX);
        myFile.println(incomingByte,HEX);
        // myFile.println(incomingByte);
        timer_count = 0;
        flag_again = 1;
    }
    if(!Serial.available() && flag_again)
    {
        TIMSK1 |= (1 << OCIE1A);
        flag_again = 0;
    }

}

Doing these kinds of thing inside the ISR is asking for problems. Just store the timestamp (millis) of the last time you received serial data, then if the time difference between the current time and that timestamp is more that 25000ms create a new file.

Thank you very much for your answer,can i ask you to give an example to my sketch?i am not very experienced Regards.

Also filename is never changed, so it wouldn't even work properly.

In untested (pseudo-)code
unsigned long lastSerialInput = millis();

void loop()
{

    if(!myFile)
        myFile = SD.open(filename, FILE_WRITE);

    while(Serial.available())
    {
        incomingByte = Serial.read();
        myFile.println(incomingByte,HEX);

        lastSerialInput = millis();
    }

    // check for 25 seconds of inactivity
    if( myFile && (millis()-lastSerialInput > 25000 )
    {
        myFile.close();
        fileNo++;
        filename = "datalog";
        filename += fileNo;
        filename += ".txt";

        //save new fileNo to config.txt (though I'd personally find the file with the largest number in setup instead of relying on a config.txt file)
    }

}


text:
Who makes this cool Arduino display shield, and what model is it?
Anyone recognize Mfgr/model of this display that reads: "Wireless Internet Of Things".  The Arduino board is a WIOT.
I've been looking and looking for a source for Arduino display like this, but cannot find.

If you google for "Arduino OLED Blue" you get hundreds of similar displays.

That will be an SSD1306 based blue OLED display with SPI interface. There's lots of them around by lots of different people. Some are I2C interface, and some of those have a "broken" I2C interface that doesn't send ACKs (especially cheap ones on eBay) and need a special ACK-less Software I2C implementation.
The SPI ones, of course, won't suffer from that problem.
They are generally 0.96" diagonal, and that one, I think, is 96x39 pixels (or it may be 128x64).


text:
Is Arduino WiFi101 library fully compatible with Arduino MKR1000 with WiFi HW?
Will all the classes in this library work with the MKR1000 with wifi hardware?
The guide mentions "wifi shield".
So, does the library work exactly the same with the Arduino MKR100 (with the onboard wifi HW) as it does with the wifi shield?
WiFi101 library reference


text:
How to attach Arduino MKR1000 to a shield meant for Arduino UNO?
I have an Arduino MKR1000 and need to interface it to an Adafruit Music Maker shield, which has pinouts for an Arduino UNO.
Maybe I'll have to attach female headers, and then jumper pins over.
Which pins on MKR go to which pins on Music Maker?
I have to use the MKR1000 because I'm getting the audio from wifi (using MKR1000) and then sending it to Music Maker.

This sort-of sounds like your 1st Arduino project.  The jump from using a Atmel ATmega328P processor to an Atmel ARM processor, in my experience, is not free from problems. Let alone the differences in the boards.  I would suggest you prototype your project using the intended host, the Arduino Uno.  Then try using the MKR1000.  You obviously can't do everything with the Uno.  But I would at least talk to the Music Maker using a Uno then try it with the MKR1000.  Add more features and repeat the test until you have exhausted what you can do on the Uno platform.

The intended host is MKR1000, not UNO.

Yes yes, I'm suggesting, if you are having problems with the MKR1000, to try small parts of your code on the Uno - the intended host of the Adafruit Music Maker PCB.  If the code, Uno and Music Maker board work and switching to the MKR1000 does not, then you know you either have a wiring problem or switching from the ATmega328P processor to the ARM processor is causing unexpected difficulties.  As to which pins go where, if the MKR1000 is touted as 100% Arduino compatible, then the pin labeling should match.  Be sure to check if both boards are designed for the same voltage (5v or 3.3V)!

Wowa, did you read this?: "Warning: Unlike most Arduino & Genuino boards, the MKR1000 runs at 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. "   Double check how the Adafruit Music Maker board is put together!  There's some talk on the Adafruit Music Maker product page about level shifting but it sounded a bit vague.  Since both these items are on the Adafruit web site you might post a Music Maker / MKR1000 compatibility question directly to them on one of their forums.


text:
Can MP3 be sent to SPI of Adafruit Music Maker Arduino shield instead of from its SD card?
Can uncompressed MP3 audio data be sent from Arduino board, by SPI, to Adafruit Music Maker shield instead of from the SD card on the Music Maker?
Instead of using SD card on Music Maker board, I want to send the compressed MP3 data from a Particle Photon board on the Particle shield shield, by SPI, to the VS1053B codec chip on Music Maker board, and then to amplifier for speakers.
Particle Shield Shield is attached to Particle Photon board, which has STM32F205RGY6 120Mhz ARM Cortex M3.
Particle Photon board uses its WiFi to receive uncompressed MP3.

There's no such thing as "uncompressed MP3". MP3 is compressed. What format are you really sending? Raw 16-bit signed samples?

Majenko:  You are correct -- pardon my redundancy.  The MP3 data will come from an iPhone's music library, by WiFi to the Arduino (probably Adafruit Feather M0)

As far as I can see the SD card on the shield isn't read by the VS1053 directly, but by the arduino, which sends it to the VS1053.
So as far as I can see, you should be able to do what you want.


text:
Is Adafruit Arduino Feather M0 WiFi compatible with Adafruit Music Maker shield?
I want Arduino to receive MP3 by WiFi (from iPhone), and then send to Music Maker codec and amplifier.
I want to use Arduino IDE and library software from Adafruit for the Music Maker, so I need an Arduino board 100% compatible with the library for Music Maker.

Sounds like a question for Adafruit or at least adding links to the product descriptions, circuits, etc.

No, it is not.  Adafruit Feather boards are only compatible with Feather 'wings' and not Arduino shields.


text:
how do I wire a 2nd Adafruit TMP117 board to my Adafruit Metro by I2C?
I want to connect two TMP117 boards to one Metro (ie. Arduino).
(the first, addressed at 48 the 2nd at 49.)
Should 2nd board's 4 wires simply attach (ie. solder) in parallel to 1st board's 4 wires?
(ie. 3.3v, gnd, SCL, SDA)
background...
I want to read temperatures from two boards at once, in near real time and write to Windows file.

yes ...........

You are correct almost. Connection in parallel is correct however you cannot read both at once, the bus supports talking to only device at a time. You will need to read one then the other. I do not know for sure if it is possible to get them to synchronize conversion but I think not.


text:
Is Sparkfun's MicroView OLED Arduino module a shield?
I'm getting confused by the Arduino terminologies:  shield, breakout, module.
Is this MicroView an Arduino compatible shield that will plug into Arduino's or Adafruit's Uno?

From the project page: The MicroView is a chip-sized Arduino with a built-in OLED.

BTW, it started as a kickstarter project.

No, MicroView is not an Arduino shield, so you can't plug that into any Arduino. Arduino Uno and MicroView are developed based on Atmega328 controller. So it is 100% code compatible with Arduino Uno, means the code that runs on an Arduino Uno will also be able to run on the MicroView.

Can shields plug into the MicroView?

I would say no because not all the Arduino Uno pins are exposed on the Arduino MicroView.  The MicroView only has 16 pins.  However, if you take the time to find out if the pins used for a particular shield are exposed on an Arduino MicroView and you create an adapter as the pins are likely in different physical locations, then you might get the Arduino MicroView to work with an Arduino Uno shield.

No,  you can't plug in Arduino shields to MicroView. Pin arrangements of Microview  and Arduino shields are different so it is not possible.


text:
is the Arduino shield pinout a standard, so that any Arduino shield can work with any Arduino board
I'm new to Arduino and dying to delve in.
There are lots of Arduino base board vendors, and lots of shield vendors.
In general, should I be able to plug any shield into any Arduino board, even with existing shields?

No, they are not standard - not entirely - although there have been some attempts to make them more standard.
Some things to watch out for:

SPI

The Uno originally had SPI on pins 10-13
The Mega had it on another COMMS header instead

SPI has now been standardized to the 6-pin ICSP header, though not all shields honour that, and still use pins 10-13 instead, so they won't work on boards like the Mega

I2C

The Uno has I2C on pins A4/A5
The Mega has it on the COMMS header instead

I2C has now been standardized on a special pair of pins added to the end of the digital IO header (pins 8-13 + GND + AREF) though many shields still look for it on pins A4/A5, so they won't work on boards like the Mega
Some other boards, like the Leonardo, also have these (and other) functions on other pins, so may not work with some shields that don't use the SPI / I2C headers.
The basic functions, though, i.e., digital IO and analog inputs and UART 1 are all in the same places on the majority of boards, and most have PWM in the same places too. But you can't rely on any thing more than that between any two boards.

Most shields will fit most of the "regular sized" boards. the obvious exception is the boards like the nano which are tiny. Shields are going to have the best compatibility with the Uno, just because that one is the most common, so if you are going to get one arduino and a bunch of shields, get an uno. Some shields (the gen 1 ethernet and wifi shields in particular had an issue where they could not be used on Megas because the mega listens to SPI on pins 50+ which simply were not connected to the shield, however most of the newer shields will connect to the 6-pin block in the center now-adays to allow Mega usage.
The next thing you want to look at is if you are stacking shields, if they will collide on pin usage (SPI gets around this through multiplexing) and some of the 3.3 volt devices may have conflicts with 5-volt shields. Although the 3.3v devices do provide 5v power-out pins in the same locations as the Uno, it becomes more of an issue with trying to read a 5v on a 3.3v pin, which could damage the microchip.
the best thing to do is to check the documentation of the shields and check which pins they use, what voltages they need/supply, and comparing this with the particular arduino you are using.

Also a great answer


text:
Ams1117 worked fine on battery, up in smoke with 12v power supply
I have a circuit that worked fine on a a 12v lead acid battery for a day. Once connected to a 12v 3a power supply it didn't work properly and then the ams1117 5v burned up and so did a 3.3v one within a few minutes.
The 12v power supply is a cheap Chinese model from eBay. My meter shows 12.3v but I don't have a scope.
I understand that ripples in the output of the power supply have probably caused this but what does that mean and how has it exceeded the rating of the converter? Is there a simple fix so I can use the power supply?
Would a 12v motor or relay be susceptible to the ripples?
I'm going to run my esp8266 from a different source but I'd like to keep using the power supply for the motor and 12v relays.

Full and detailed schematic?

The 12v power supply is a cheap Chinese model from eBay - probably has **** poor mains isolation then.

What does poor mains isolation mean?  No coil? No Diodes? Does that mean there's 240v on the 12v line?

There may well be some 240v component on the output, yes. It is common for the transformer insulation to be very poor, and the class X capacitor across it to be the wrong type or even non existent.

You should take a look at some of BigClive's teardowns of cheap Chinese usb chargers on YouTube to see how bad they can be.

Once you let out that magic smoke it probably is done for.  That's what makes it work, and usually you can't get it back in.

#SDsolar I spent most of today trying to get it back in again! #Majenko, BigClive was a terrific recommendation.

Running an Arduino board with 12V is almost always too much. With only a few leds the voltage regulator on the Arduino boards gets too hot.
The best voltage is 7.5V. Then the voltage regulator has only little power dissipation and it is just high enough to turn off the USB 5V power.
Or power the Arduino board with a 5V (from a USB charger, or USB power pack) to the USB connector.
Never use a power supply that is not certified. It is a safety risk that can be avoided with a few dollars more.
The cheap power supply can have ripples, but it can for example have noise in the MHz range, or a voltage spike when turned on, or voltage overshoot when more current is required.  There can also be a coupling to the mains as @Majenko wrote. I have had a few of those. Nasty stuff!
Even with a scope, you can not tell if the power supply is really okay.
If you have a unreliable power source or a voltage that is too high, then a DC-DC converter can convert it into a nice steady voltage.
However, you should first get rid of that cheap power supply and buy a good one.

Aside from certification (i'm not even sure what a sound certification in Australia would be), how would you evaluate a power supply?

With a table full of equipment and a qualified test person. For example with a temperature controlled box to test the temperature range. With a FLIR camera. With a power analyzer (to test in what way it gets it current from the mains). With equipment that simulate different loads. Inrush currents, transient tests, and so on, and so on.

ripples in the output of the power supply have probably caused this

probably not. calculate the power dissipation on the regulator and check against its datasheet to see how much temperature rise it was going through. that would help you avoid the same mistake next time.

I will look at the power versus the data sheet but I hadn't because it worked fine for a day on a lead acid battery. How could that change based on the type of power source?


text:
Problems with ACS758 Hall Effect Current Sensors - Calibration and no Signal
I purchased 3 ACS758 Hall Effect Current Sensors datasheet on ebay. A 50,100 and 200A, all three are bi-directional. They look like this.
With no current the 50A outputs 477 on the analogue input (2.33v), the 100A outputs 509 (2.48v) and the 200A outputs 512 (2.50v). At no current they should all be at exactly mid range i.e. 512 (2.50v). The datasheet says they're factory calibrated as such. I've tested them one after the other, both with 5v from the Audrino and with a separate 5v supply. As I've tested one after the other it's not likely to be stray magnetism or VCC.
I've then put them in a circuit drawing about 9amps. Accounting for the offset of zero amps the 50A and 100A measured the increased voltage correctly. The 200A doesn't change.
Is there any other tests I can do to see if I'm doing something dumb or are they all damaged?

Thanks for the reply Nasha. I will try measure VIOUT with my cheap multimeter, I don't have a precision one. I (think) I understand your point about noise. With zero load I'm getting quite a consistent reading, just a different one from each device. It should be 2.50v from each device and instead it's 2.33v and 2.48v (according to the arudino). Even if they're not the correct voltages they're different to each other. The chip is supposed to come factory calibrated to 2.50v for zero load. Do you think noise or ADC accuracy could be the cause of the calibration problem?

Thanks again! For the calibration measurement I did take hundreds of readings and they were very consistent (within 1/1024). I checked VIOUT with my cheap multimeter and I got the same 2.33v and 2.48v. VCC was 4.98v. The board has a 0.1µF capacitor right next to the chip, I bought the whole board but just looked and they are.

I contacted Allegro they were really helpful which was pleasantly surprising.
The 200A has almost certainly failed. The 2.48v is within tolerance and the 2.33v is probably out.
I've been able to better understand the datasheet sections on 0A calibration. "VIOUT(Q) may drift over the lifetime of the device by as much as ±25 mV." and there is an electrical offset voltage noted. @25C it's +/-5mv. It's +/-20mv between 0c and 50c. So still only 45mv. Even allowing for noise it's only 55mv.
About 2.445V at zero amps would be the limit.

Annoyingly the 200A was the one with the perfect calibration but ......"I've then put them in a circuit drawing about 9amps. Accounting for the offset of zero amps the 50A and 100A measured the increased voltage correctly. The 200A doesn't change." .... The 200A was perfect at zero amps and stayed at 2.50v regardless of current.... completely broken.


text:
MQTT bridging with Arduino and ESP8266 - What software should I use?
Sorry for the vagueness in my question, I am just looking for ideas to point me in the correct direction please...
I wish to connect many (read: 20+) different sensors to a local wifi network and have them all datalogged and controlled by a single server on the network. Pretty standard stuff for the home automation people etc. Some sensors are connected to esp8266 boards directly, others communicate via serial and will employ an 8266 to provide wifi.
I am having trouble deciding which direction to go or which software / firmware to combine since its changing rapidly and a fair number of tutorials are around but all have different approaches and end goals.
This must be entirely contained offline - I have a raspberry pi, a wireless router, and the various sensors (mostly arduino based).
Now from research it would seem I need to setup a serial to MQTT 'bridge' - and have the esps 'talk' to the pi by MQTT. And that the pi should be running 'mosquitto' if I wish the MQTT to be bi-directional (i.e. I can receive serial data AND send serial commands. I have never dealt with MQTT so I am trying to learn as I go.
I have been working for a time with 'ESP-Link' software and had success using it as a simple serial to tcp-ip bridge and using virtual serial ports to communicate with the attached device. However using virtual serial ports on the server is clunky, unreliable and not what I wish to do - does anyone know if it can be setup so I can send 'raw' serial messages over TCP to the server for use? And from the server to control the connected devices? Or if there is an easier way? I cannot modify all of the serial devices I wish to connect, so just want to get the data out/in and have it manipulated by the server where necessary.
In essence I wish to end up with several sensors all connected to the router, and logged / controlled through a web interface hosted on the PI, all 'offline' and contained. Eventually I would like the server to be able to recognize what devices it can 'see' automatically, however at this moment I simply wish to gain insight into how I can most easily achieve this? Or even if I am completely mistaken in my approach?
Thanks

esp-link has some mqtt support

MQTT is perfectly suited to this application. Here is an overview of a possible configuration. You should be able to find tutorials about each piece of the system.
On the Raspberry Pi:

Setup a Mosquitto server that can receive messages published by the ESP devices.
Write and run a MQTT client on the RPi that subscribes to the messages published by the ESP devices. This client would then store the data in some sort of permanent data store (database, flat files, whatever).
Write and run on the RPi a web app that reads and presents the data from the data store.

On the ESP devices:

Connect to the same wireless network as the RPi (or set up the RPi as an access point and have the devices connect to it)
Read data from the sensors and publish it to the MQTT server on the RPi.

If you want to push data to the ESP devices -- have them subscribe to certain messages (topics) on the MQTT server and then publish messages in those topics on the server.  Your web app could do this.
All of this can be done on an isolated network.

As you also asking about hardware I would recommend the following setup:
For sensors that only need to send data I would go with a
ATtiny85. It has very low power consumption, is very small and easy to program. If you use 10-N of them then a programming board and only the micro controller will be cheaper and even smaller.
For sensors that have some logic on it, maybe multiple attached sensors I would go with a Wemos D1 Mini. It has build in WIFI, you can debug it, it is still very small and there are a ton of extension (shield) boards for it to speed up your development.
For the communication part I would go away from WIFI since 20+ devices can generate quiet some traffic. Also WIFI costs you a lot in terms of power consumption since it is not optimized for IoT (small data packages). I would add a 433mhz Mini Low Power RF Receiver/Transmitter to my IoT hardware and communicate through that. It has a long range and has a very small power footprint.
Additionally you could think about using a Wemos as MQTT gateway between your 433mhz devices and the WIFI instead of your proposed Raspberry Pi solution. The nice benefit is that you will have a dedicated device managing an MQTT gateway that is far less error-prone as a Linux server (Raspberry Pi) and you don't need to update as often as with the Pi to keep it secure. There is a Wemos D1 Mini Pro that has a better WIFI antenna and a little bit more power that could be perfect for this use case.
The MQTT protocol is perfect for a sensor network since it is optimized for low bandwidth, high latency, and fragile connections. It supports Quality of Service (QoS) and you can configure what shall happen if a device disconnects/is not reachable anymore. There are a lot of library's already available for MQTT so that the setup is very quick. HiveMq has a nice how to get started with MQTT guide for further reading.