text:
Arduino leave PWM on
I am doing an aquarium light sunrise/sunset. Till now programming wise I only did the sunrise. After running the code the light starts to rise up fine, than  at full brightness, it turns off. I want to keep it on after it reaches the 100% pwm and than starts decreasing when it's time to get off. Any help on how to leave the pwm at 100% and than starts to dim when it's time to turn off? I am still new to coding arduino, so explanation need to be for a beginner :P Thanks before hand.
#include <DS3231.h>

//Set Variables
int fadeTime = 15; //Fade Time
int onHour = 12; //Light On Hour
int onMin = 00; //Light On Minute
int offHour = 19; //Light On Hour
int offMin = 00; //Light On Minute
int led = 9; //Set pinout with with PWM

DS3231  rtc(SDA, SCL);
Time t;
void start();

void setup()
{
  pinMode(led, OUTPUT);
  rtc.begin();
}

void loop()
{
  t = rtc.getTime();

  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  if (t.hour == onHour && t.min == onMin) //Check Time
  {
    start();
  }

}

void start()
{
  // Fade script
  for (int i = 0 ; i <= 255; i++)
  {
    analogWrite(led, i);
    delay(((fadeTime * 60000)/306));
  }

}

You need to have the program remember whether the light are ON or OFF. That way you can check the see if they are already on, before calling start.

The PWM is not supposed to turn off all by itself: last thing you wrote is 255, and it should stay at that level. It looks to me like this is not a software problem, but rather a hardware issue. Just for testing, replace your LED by a low power one (a standard 3 mm or 5 mm LED) in series with a resistor in the 220 Ω – 1 kΩ range. If it works with this setup, then you know it is a power supply issue.

Why not create a global brightness variable (e.g. cBrightness) so that you can adjust the brightness accordingly when the time comes? With a global variable, you can still maintain the brightness of the LED even after it exits the start() function.
For the start() function, you can include one argument (int/bool type variable) in the function to determine when to perform the brightening or dimming of the light depending on the RTC timing.
void start(int st)
{
  if(st==0)
  {
     //Brightness decrement function here
  }else if(st==1)
  {
     //Brightness increment function here
  }
}

For the brightness decrement function, it is the opposite of the increment function:
for (int i = 255 ; i >= 0; i--)
{
    analogWrite(led, i);
    delay(((fadeTime * 60000)/306));
}

To summarize, the code could look something like this:
#include <DS3231.h>

//Set Variables
int fadeTime = 15; //Fade Time
int onHour = 12; //Light On Hour
int onMin = 00; //Light On Minute
int offHour = 19; //Light On Hour
int offMin = 00; //Light On Minute
int led = 9; //Set pinout with with PWM
int cBrightness = 0;  //Current brightness

DS3231  rtc(SDA, SCL);
Time t;
void start(int st);

void setup()
{
  pinMode(led, OUTPUT);
  rtc.begin();
}

void loop()
{
  t = rtc.getTime();

  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  if (t.hour == onHour && t.min == onMin) //Check Time
  {
    start(1);
  }else if (t.hour == offHour && t.min == offMin)
  {
    start(0);
  }
  //Maintains brightness
  analogWrite(led, cBrightness);

}

void start(int st)
{
  if(st==0)     //Will decrement in brightness
  {
   for (int i = 255 ; i >= 0; i--)
   {
    analogWrite(led, i);
    delay(((fadeTime * 60000)/306));
   }
   cBrightness = 0;

  }else if(st==1)   //Will increment in brightness
  {
   for (int i = 0 ; i <= 255; i++)
   {
    analogWrite(led, i);
    delay(((fadeTime * 60000)/306));
   }
  cBrightness = 255;
  }
}


text:
Read pc volume percentage?
is there a way to read the current pc volume? This is going to be a part of a project that I have in mind that is essentially reading curent pc volume value and giving it an RGB value (green=>30, yellow=<30>60, red=<60) and lighting up an RGB led accordingly.

Please describe a little better what you want to read. pc = PC = Personal Computer (maybe with Windows)? Do you want to read if the volume slider is set i.e. to 30% or do you want to "read" how much noise comes out of the speakers?

I'm voting to close this question as off-topic because the capabilities of PC operating systems are not on topic here - and doubly so when the operating system in question has not been identified.  Needless to say, if you obtain a number by some means, you can transmit it to your embedded system.  And no, Nick Alexeev, this is not an Arduino question either - it is a PC operating system question, and at presently too broad even for a site about those.  SE policy prohibits the migration of unanswerable questions and requires that they be closed at the source.

You guessed it the system is windows and I want to read the precentage that windows has in volume manager I know there are many HID librarys that can increase or decrease the volume but I have not seen any that can be used to pull the value. @chris Stratton https://www.reddit.com/r/ProgrammerHumor/comments/2zp22c/how_im_sure_most_firstposters_on_stackoverflow/

No, I stated the operating system was unspecified.  And irrelevant here.  How to obtaining settings information for PC operating systems, regardless if they are identified or not, is not a a permitted topic on this site, full stop.  SE sites are not traditional discussion forums, they are an intentionally narrow format, strictly separated by topics not permitted to overlap.

Well aren't you just a perfect specimen of the SE community and reputation

It seems like SE is not right for your needs.  And indeed, there is more than does not fit within this system than the very narrow set of things which does.  But that's what this is about.  Doesn't mean I agree with that, but it is what it is.  There's a whole remainder comprising merely... every non-SE site on the global Internet to satisfy other needs and approaches.

The easiest way would be writing a program, that runs in the PC and sends the current volume and any change to the Arduino via Serial. Investigate how to interface system volume in the PC with your chosen programming language (for example python).

@ChrisStratton This question is perfectly on topic. It may not be worded well, but the question is essentially "Can the Arduino be programmed to do X" where the answer is "No, it can't, but there are other routes you could investigate".  The question is not "How do I program the PC to do X", which would be off topic.

@Majenko - sorry, but you are completely wrong.  Read the question again "is there a way to read the current pc volume?"  That has nothing to do with Arduino.  If the poster could do that, then sending the result to an Arduino could be on topic, (if utterly trivial) but that's not the question that was asked.  Instead, a question about an unidentified PC operating system was asked.

@ChrisStratton Whatever. If my reading of the question is so wrong, how come my answer is accepted as correct? If you paid attention to the kind of questions asked here you'd know that people often ask about the Arduino querying information from the host PC in this kind of manner. You have to learn to read between the lines with Arduino users.

This question had a number of well deserved close votes from people who actually understand the rules of this site.  Those should not have been wiped out.

@ChrisStratton: when the highest rated guy on the site (by 2x) corrects you about site practice, consider he might know somewhat more than you about the site...

There is no way for any hardware device, Arduino or otherwise, to request information like that from a computer.
HID is a protocol which (when used as a keyboard) allows you to send keypresses, including "media keys", which tell the computer to change the volume (amongst other things). There is no provision, other than three status LEDs, for getting any data back from the computer.
You will have to write software for your computer to query that information using whatever API may be available for your operating system, and pass that information through whatever communication channel you choose to the Arduino (such as through serial).
Some pointers:

C# get master volume level/precent
Windows 7 Master Volume
Arduino: Sending and Receiving Multi-Digit Integers

There are external devices that show the volume, but you need a driver for that. I don't know if there is an open source driver which you could adapt to send the volume via a serial port to the Arduino.
The Windows PowerShell has the possibility to get the volume and transmit it to a serial port. You could do that a few times per second. In linux it might even be easier, a bash script with gawk with "amixer sget Master".
Another problem is to select the right serial port for the Arduino. I don't know how to automatically select the right port.

source: Stack Exchange

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

sort: votes


text:
How do I clear previous values while using strcat() to add strings?
Is there any other function to add strings into buffer and updating values as well.
This is the problem I am coping with while using strcat()

char temp[2] = "A";
char temp_end[2] = "a";
char buf_adc[20]="alok";
char buf_hum[20]="lok";
char buf_temp[20]="vjf";
char buf[100];
void setup() {
Serial.begin(115200);

}

void loop() {
  strcat(buf,buf_adc);
strcat(buf,temp);
strcat(buf,buf_hum);
strcat(buf,temp);
strcat(buf,buf_temp);
strcat(buf,temp_end);

Serial.println(buf);

}

strcat always concatenates to the end of the string. Instead, for your first strcat you should really be using strcpy, which copies one string over the top of the other - that is, it places it at the start of the string, effectively starting a new string.
However, unless you really need the data in a string for some specific reason, you don't need to build a string up - just print each part to serial separately with its own Serial.print function.

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


text:
Can you use both 3.3v and 5v
Can you use an Arduino EtherMega's 3.3v and 5v pins with two sensors, one requiring 3.3v and the other 5v and a sketch that combines both?

Yes. As long as you take into account that the outputs of the Arduino will be 5V so you may need to reduce that to 3.3V for the 3.3V sensor (if it has any connection to an output).

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


text:
Bluetooth and another sketch
I uploaded a bluetooth sketch from IDE (File->Examples->Firmata->Standard Firmata) to Arduino Duo.
Now if I have a sensor attached to this Arduino, I can use bluetooth from another device (Raspberry pi or mobilephone) to read the sensor.
But what if I want to do something in the arduino itself? I see only one option
which is to edit the standardfirmata to read the sensor and do something. So multiple sketches running in one sketch.
Am I correct?

If you programmed the Arduino to read the sensor and the do something else, what would you do if a second request to read the sensor came in before you had stopped doing something else?
I don't know anything about Firmata.  Could you add two sensor's, so the Pi could select to read from sensor 1 or sensor 2?  If you could do that then you alter the 'readSensor2()' function so it did 'Something else'.  This way you are exploiting any control/synchronisation logic within Firmata.  If you need 'readSensor1()' to automatically 'do something else' ever time it was called then couldn't you just tag it onto the end of 'readSensor1()'.

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


text:
Logic level converter not working?
I'm trying to connect a 3.3v depth sensor to an Arduino uno. The logic level converter does not seem to send any current over (the sensor does not work and the voltmeter reads nothing). I tested the depth sensor separately, so I know it works, meaning it must be the converter. Why wouldn't it be working?
I've tried two logic level converters so far, but neither seems to work. This is basically how I connected it:

Here's the LLC:

Did I mess something up soldering it or by plugging it in wrong earlier?

Try again with the photo. That could be anything. Put the gadget down on a table and hold the camera steady.

Welcome to Arduino SE.  Be sure to take the tour:   https://arduino.stackexchange.com/Tour

Based on your schematic, you need to provide a 3.3v power source to the 3.3v side of the logic level converter. You can use the 3.3v pin on the Arduino.
Also, it's really hard to evaluate your soldering with such a shaky picture. Just make sure none of the pins are connected. A visual inspection usually will do, but if you want to be sure, use your multimeter's continuity function. Test all adjacent pins to confirm they are not bridged.

Agreed. The logic-level converter doesn't manufacture 3.3V - you need to supply it.


text:
Determining state of charge using current sensor (ACS758) with arduino uno
I am working on a university project and I am struggling with estimating the state of charge of our batteries, by using coulomb counting.
Background: We are supposed to build a power supply for a mostly constant load of 100 W (can go up to 140 W) which will be placed outdoors for two years. The plan is to have a small wind turbine plus some solar PV connected to a large battery assembly. The system has to run close to 24/7 with limited downtime.
I have bought some ACS758 50A bidirectional current sensors as well as an Arduino UNO. I am extremely new to Arduino and I would really appreciate some help with the coding. The plan is to have the arduino do the sampling of current and integration, which is then translated to SOC as a percentage and sent to a Raspberry Pi which will send email alerts if the SOC is below a certain level.
I have been looking at sample code describing how to extract the raw data from the ACS sensor: https://www.dfrobot.com/wiki/index.php/50A_Current_Sensor(SKU:SEN0098) as well as sample code that performs integration (Integrating an analog signal using ARDUINO UNO SMD), which is what I would use for coulomb counting.
What I need is most likely a combination between the two, however I do not even know where to start from.
Thanks in advance!

I'd just measure the voltage, and use that to calculate the charge level. Or at least use it to "reset" the current, when the battery is full. Just measuring the current in and out will eventually lead to some drift. Due to self discharge of the battery and/or losses.

Why not do both?

Is there any progress on this project ? It would be a great help if there is because our project is somehow like this.

Instead of using a separated component for each thing you can use a proper solution that is itself already a combination of both: the DS2438's integrated current accumulator. This link explain it pretty well, also here is a library to use it with arduino. They are pretty cheap (a few dollars) and will perform very well!
Although, in your place I would consider choosing a different approach. I don't know which kind of battery (Li-ion, LiPo, Lead-acid..) you are using, but in many cases if you monitor the battery voltage, you can have enough information about the battery state. I can't ask you in comment yet beause I'm new here and don't have enough reputation, but if you can describe better the kind of battery you are using and what you intend to monitor which your circuit, I can edit this post to offer you a better solution.

Hi there, I appreciate the help. We are using some Rolls 4000 series, 12kWh total (http://www.windandsun.co.uk/products/Batteries/Rolls-Batteries#.WPNJtmmGPIU). Both the solar PV and the wind turbine have charge controllers, and together with the battery they will all be connected to a positive and negative bus. What we want is to monitor  battery SOC to ensure that if the battery level goes below a certain level, a warning is sent to someone. We will also attempt to estimate SOC via voltage measurement (what Gerben suggested) however doing coulomb counting is a project requirement :(

Which is the voltage of your battery bank?

you should probably determine the soc using both current integration and open circuit voltage method.It is possible to cover the weakness of both techniques and provide an accurate monitoring technique.I can provide you the codes if you need,
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int mVperAmp = 100;const float chargingdfficiency= 0.7;
int RawValue= 0, ACSoffset = 2500;
double Voltage = 0, Amps = 0;
double g,q;
int m=0,c=0,d;
void resett(){
digitalWrite(8,LOW);
digitalWrite(7,LOW);}

void setup() {
pinMode(A0, INPUT);pinMode(A1, INPUT);
pinMode(7,OUTPUT);pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
Serial.begin(9600);
delay(10);lcd.begin(20, 4); delay(10);}

void loop() {
resett();
double vini=analogRead(1);vini = vini*5/1023;
vini=5*vini;Serial.print(vini,3);vini=vini/6;
double soc=((666.6667)*vini)-1300;delay(10);
q=soc*.42;
if(soc<30){m=1;resett(); digitalWrite(7,HIGH);} //charging
if(soc>=100){m=0;resett();digitalWrite(8,HIGH); } // DISCHARGING
if(m==0){resett();digitalWrite(8,HIGH);}
delay(10);
while(1){
RawValue = analogRead(0);
Voltage = (RawValue / 1024.0) * 5000;
Amps = ((Voltage - ACSoffset) / mVperAmp);Amps=-Amps;
if((Amps<.098)&&(Amps>-.098)){Amps=0;}
if(Amps>9){
resett();
lcd.clear();
lcd.display();
lcd.setCursor(1,0);
lcd.print("Overload");digitalWrite(9,HIGH);
while(1);}
if(m==0){
if(Amps<=1.5){g=1.183;}
else if(Amps<=2){g=0.042*Amps+1.12;}
else if(Amps<=4){g=0.028*Amps+1.148;}
else if(Amps<=5){g=0.032*Amps+1.132;}
else if(Amps<=6){g=0.03*Amps+1.142;}
else if(Amps<=7){g=0.325*Amps-0.628;}
else if(Amps<=7.5){g=0.066*Amps+1.185;}
else if(Amps<=8){g=0.028*Amps+1.47;}
else if(Amps<=10){g=1.694;}
soc=(q-Amps*g*0.0002778)*2.38095; q=soc*.42;
if(soc<5){m=1;resett();digitalWrite(7,HIGH);} }
if(m==1){
soc=(q-Amps*chargingdfficiency*0.0002778)*2.38095;
q=soc*.42;
if(soc>=100){m=0;resett();digitalWrite(8,HIGH);}}
lcd.clear();
lcd.display();
lcd.setCursor(1,0);
lcd.print("Soc = ");
lcd.setCursor(13,0);
lcd.print(soc,1);
lcd.setCursor(19,0);
lcd.print("%");
lcd.setCursor(1,1);
lcd.print("Amps= ");
lcd.setCursor(13,1);
lcd.print(Amps,1);
if(m==1){lcd.setCursor(1,2);lcd.print("Charging");}
else{lcd.setCursor(1,2);lcd.print("Discharge");}
lcd.setCursor(1,3);lcd.print("Normal");
Serial.println((vini),3);
Serial.print("Amps = ");
Serial.println(Amps,9);
Serial.print(" Soc = ");
Serial.println(soc,9);

for(d=0;((Amps==0)&&(d<=1200));d++){RawValue = analogRead(0);
Voltage = (RawValue / 1024.0) * 5000;
Amps = ((Voltage - ACSoffset) / mVperAmp);Amps=-Amps;
if(d==1200){vini=analogRead(1);vini = vini*25/(6*1023);
soc=((666.6667)*vini)-1300;d=0;}}

delay(1000);
}
}


text:
Arduino Nano, nodeJS serial
I tried to make a 2 way communication between my Arduino and a PC(running linux mint) using NodeJS:
My Arduino code:
void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()) Serial.println(Serial.readString()+"\r");
}

My NodeJS code:
var SerialPort = require('serialport');
var port = new SerialPort('/dev/ttyUSB0',{
  baudRate: 9600,
  parity: 'none',
  stopBits: 1,
  flowControl: false,
  parser: SerialPort.parsers.readline('\r\n')
});

port.on('open',function(){
  setInterval(() => port.write('Test'),1000);
});

port.on('data',(data) => console.log(data.toString()));

There is possible encoding error, but I cannot seem to find and fix this. Thanks in advance

What error do you get?

Basicly it outputs "TestTestTest" with random length

What's more if I use Arduino code to send the data like Serial.println("Test"), and use readline('\n') I get correct results

Weird. For me, Arduino's Serial.println() plays well with serialport's readline("\r\n").

Is this your code, or the above?

You don't need to revert to sending single bytes. Line oriented
protocols work well with both Arduino and Node.js. The only difficulty
is that you have to decide what line terminators you want to use, and
then consistently use them.
I tend to use CR for the PC → Arduino stream and CRLF for Arduino
→ PC. Using different line terminators is kind of odd, but this
convention plays well with terminal emulators: the emulator usually
sends CR when you hit <Enter>, and expects CRLF in return. Also,
Arduino's Print::println() sends CRLF.
Here is a simple test demonstrating this convention. Node.js side:
var SerialPort = require('serialport'),
    port = new SerialPort('/dev/ttyACM0', {
        baudRate: 9600,
        parser: SerialPort.parsers.readline('\r\n')
    });

port.on('open', () => setInterval(() => port.write('Test\r'), 1000));
port.on('data', console.log);

Notice the different line terminators in readline() and write().
The Arduino side:
void setup() {
    Serial.begin(9600);
}

void loop() {
    static char buffer[128];
    static size_t pos;

    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\r') {                       // line terminator
            buffer[pos] = '\0';                // terminate the string
            Serial.print(F("Arduino received: "));
            Serial.println(buffer);            // echo received message
            pos = 0;                           // reset buffer position
        } else if (pos < sizeof buffer - 1) {  // regular character
            buffer[pos++] = c;                 // buffer it
        }
    }
}

Here you may notice that Arduino has no equivalent of
parsers.readline(), so I had to implement it (comparing the incoming
character to '\r'). Note that explicit buffering of the incoming
message is a standard way of handling line-oriented protocols on
Arduino. Stream::readString() does not work well for this purpose, as
it waits for incoming bytes until it times out.
Stream::readStringUntil() may work better, but I prefer to avoid it
just because it returns a String, which relies on heap allocation.

Well, this code works great, but you forget that the content of the "previous" buffer stays in the array, which results in results like: "Arduino received: Testest"

@Berrigan: Oops! I forgot to properly terminate the string. Fixed. Now it works. The previous content of the buffer is now irrelevant, as only the contents before the first '\0' is considered to be part of the "string". After a complete string is received, the buffer is reset by the statement pos = 0;.

Ok, I solved the issue by using pure bytes, and then casting the response to the string in nodeJS, I post the codes in case anyone needs them:
var SerialPort = require('serialport');
var port = new SerialPort('/dev/ttyUSB0',{
  baudRate: 9600,
  parity: 'none',
  stopBits: 1,
  flowControl: false,
//  parser: SerialPort.parsers.readline('\r\n')
});

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}

port.on('open',() => {
  setInterval(() => port.write('Test'),500);
});

port.on('data',(data) => {
  console.log(ab2str(data));
});

And the Arduino code:
void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()) Serial.write(Serial.read());
}

authors: Руслан Выхрущ


text:
My mega only works on 1.0.1 IDE
My mega usb/serial adapter died some time ago, so I bought an external FTDI programer wich I got working on 1.0.1 IDE. I can load any program to the mega, even complex led matrix driver I wrote myself so the ATmega works fine and the external FTDI board does too. Strangely enough I if I want to update the IDE (tried once on 1.0.5 and yesterday downloaded 1.6.5) I get an
 avrdude: stk500v2_getsync(): timeout communicating with programmer

When this problem occurs, I see that the programmer board recieves something (it has Rx and Tx LED's) the Mega resets but never sends any data back, which does happen on 1.0.1 IDE.
This happens on my pc, and on a laptop son no pc related problems.
I'd keep using this version but now I got an OLED display I want to drive (SSD1306 from waveshare) but I can't compile u8glib on 1.0.1 but I can on 1.6.5, however I can't get a simple blink example to upload with this IDE.
I suspect the DTR pin (reset pin) is handled differently and that makes the mega stay resetting until it times out.
What can be the problem here? How can I get more info from the console to solve this?

How have you wired your FTDI board?

Do you mean if the programmer is correctly wired to the Mega? Yes, it is. Since it can upload sketches to it on the 1.0.1 IDE

No, I didn't ask you if you thought it was wired correctly. I asked you to tell me how it is wired. Never assume it's correct just because it's been working. Something is wrong, so let's start with that.

Good point. I don't have it in front of me right now so I'll tell you as I remember. Also note that a few hours ago I re

(Pressed enter by mistake)
Good point. I don't have it in front of me right now so I'll tell you as I remember. The FTDI chip provides 5V, GND, Rx, Tx, DTR and CTS pins. 5V and GND are connected to the power rails of the Mega (powering it with an external wall-wart PS changes nothing). Rx and Tx are conected crossed to the Rx0 and Tx0 port on the Mega. And finally the DTR is connected to Reset pin on the Mega. CTS is not connected. I believe it is connected correctly and running both versions of the IDE side by side one does upload and the other doesn't.
By the way, thank you for your help!

As I suspected - your wiring may well be wrong.  You need to add a 100nF (0.1µF) capacitor between DTR and RESET so it generates a pulse instead of a constant LOW all the time the port is open.

I'll try that as soon as I get back home in a few hours! But then again, I can still upload correctly on the older IDE without doing any modifications to the wiring...
Anyway, that's it for now. Thank you very much!

The older IDE uses an older version of avrdude. The newer version of avrdude with the newer IDE has extra code for manually manipulating DTR to get around some issues with new versions of the FTDI drivers.

Ok so I got it working perfectly. Thank you very much! If you'd like to submit an answer then I would mark it as the correct answer. Thanks again!
Regards, Rodrigo.

You need to add a 100nF (0.1µF) capacitor between DTR and RESET so it generates a pulse instead of a constant LOW all the time the port is open.
The older IDE uses an older version of avrdude. The newer version of avrdude with the newer IDE has extra code for manually manipulating DTR to get around some issues with new versions of the FTDI drivers.


text:
Connection bluetooth master and slave with Android
I send a date from my android to arduino without problem, but also i want send date from arduino to android later of received the date from android.
I have time trying it, but i can not yet, help me.
My codec of arduino
char enter;
#include <SoftwareSerial.h>
SoftwareSerial conect(10,11);

void setup()
{
 pinMode(8,OUTPUT);
 conect.begin(9600);
 digitalWrite(8,LOW);
}

void loop()
{
 if(conect.available()>0)
  {
   enter=conect.read();
   if(entrada=='1')
   {
    digitalWrite(8,HIGH);
    conect.print("1");
   }
 }
}

And in the side from android this is my handler for drive the the date that arrive.
 Handler mhandler=new Handler(){
    @Override
    public void handleMessage(Message msg)
    {
        super.handleMessage(msg);
        switch (msg.what)
        {
            case CONECTADO:
                //ManejarDatos msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                break;
            case MENSAJELEYENDO:
                byte[] readBuf = (byte[])msg.obj;
                String string = new String(readBuf,0,msg.arg1);
                Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
                break;
        }
    }
};

And on my class for read and write i have this
private class ManejarDatos extends Thread
{
    private final OutputStream salidadatos;
    private final BluetoothSocket sockk;
    private final InputStream entradadatos;
    public ManejarDatos(BluetoothSocket socke1)
    {
        sockk=socke1;
        OutputStream temporalsalida=null;
        InputStream temporalentrada=null;
        try
        {
            temporalentrada=socke1.getInputStream();
            temporalsalida=socke1.getOutputStream();
        }catch (IOException e){}
        salidadatos=temporalsalida;
        entradadatos=temporalentrada;
    }
    public void run()
    {
        byte[] espera;
        int esperaalmacen;
        while (true) {
            try {
                espera=new byte [1024];
                esperaalmacen=entradadatos.read(espera);
                mhandler.obtainMessage(MENSAJELEYENDO,esperaalmacen,-1,espera)
                        .sendToTarget();
            }catch (IOException e){break;}
        }
    }
    public void escribe(byte[] bytes)
    {
        try {
            salidadatos.write(bytes);
            //handler.obtainMessage(MENSAJE_SALIDA,-1,-1,bytes).sendToTarget();
        }catch (IOException e){
            //Log.e(TAG, "....Error al enviar dato" + e.getMessage() + "...");
        }
    }
    public void cancel()
    {
        try{
            sockk.close();
        }catch (IOException e){}
    }

}

When i push button, send a date to arduino, here my codec of button(i send 1 for bluetooth)
        Enviar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String salida="1";
            msjre.escribe(salida.getBytes());
        }
    });

What is entrada? Replace entrada with enter in your arduino code and try again. Also try this run() code instead:
public void run()
{
    byte[] espera = new byte[1024];
    int esperaalmacen;
    while (true) {
        try {
            esperaalmacen=entradadatos.read(espera);
            mhandler.obtainMessage(MENSAJELEYENDO,esperaalmacen,-1,espera)
                    .sendToTarget();
        }catch (IOException e){break;}
    }
}

Entrada is from my class Connection(other class), that i did use when i would want connect my device with arduino

First try
if(conect.available()>0)
 {
enter=conect.read();
if(1)
{ digitalWrite(8,HIGH);
 conect.print("1");
}
 }
 }
If that works,  think about what entreda is and that exactly you're trying to do there.

Sorry, your idea is the same that i have in my codec :(


text:
Reading data from Adafruit SGP30 Air Quality Sensor
I am trying to conect  Adafruit SGP30 Air Quality Sensor to arduino nano and get values from it,  but it seems that my code is not working properly. I followed instruction on the adafruit webpage, installed the Adafruit_SGP30 library and uploaded to my microcontroller.
But surprisingly when I open serial monitor text appears: SGP30 test,        but no data.
Does anybody know where I made mistake?
This is my code:
#include <Wire.h>
#include "Adafruit_SGP30.h"

Adafruit_SGP30 sgp;

void setup() {
Serial.begin(115200);
Serial.println("SGP30 test");

if (! sgp.begin()){
Serial.println("Sensor not found :(");
while (1);
}
Serial.print("Found SGP30 serial #");
Serial.print(sgp.serialnumber[0], HEX);
Serial.print(sgp.serialnumber[1], HEX);
Serial.println(sgp.serialnumber[2], HEX);
}

void loop() {
sgp.IAQmeasure();
Serial.print("TVOC "); Serial.print(sgp.TVOC); Serial.print("\t");
Serial.print("eCO2 "); Serial.println(sgp.eCO2);
delay(1000);
}

Did you run a i2c scanner? Do you have an other i2c sensor to check if the bus is working? Can you be more precise what the output is to the serial monitor? Is it only "SGP30 test"? then it might get stuck inside sgp.begin, that means the i2c bus is not working, perhaps shorted somewhere or the sensor module has no power.

Do you have pullup resistors on the I2C bus lines?

I have the same problem as yours.


text:
Serial data showing incorrect values
I am sending data over USB Serial to my Uno in a specified format and printing the values after they are read
void loop() {
    if(Serial.available()){
        while(Serial.available()){
            int pos = Serial.readStringUntil(':').toInt();
            Serial.println(pos);
            int r = Serial.readStringUntil(',').toInt();
            Serial.println(r);
            int g = Serial.readStringUntil(',').toInt();
            Serial.println(g);
            int b = Serial.readStringUntil(';').toInt();
            Serial.println(b);
        }
    }
}

This is how the data is being sent
0:255,255,255;1:255,255,255;2:255,255,255;3:255,255,255;4:255,255,255;5:255,255,255;6:255,255,255;7:255,255,255;8:255,255,255;9:255,255,255;10:255,255,255;

format is {position}:{Red value},{Green value},{Blue value};
When I send this string to the device through the serial monitor it prints wrong values
0
255
255
255
1
55 //should be 255
255
255
2
55 //should be 255
255
255
3
55 //should be 255
255
255
4
55 //should be 255
255
255
5
255
255
255
6
255
255
255
7
255
255
255
8
255
255
255
9
255
255
255
10
255
255
255

Why is the data wrong?
Is it just the serial monitor that isnt showing it right but the values are actually right?

it probably will not help, but four times parseInt() would do. parsing ends on non-digit character and skips leading non-digit characters

do you send the data as one line?

@Juraj yes one line

@Juraj parseInt actually seems to help I just have to add in some extra logic so it does not keep trying to read after the last number

you don't know the count of rgb sets on the line?

Yes I do so in this example what I do is I check the position as the last thing in the while and if the position is the last expected rgb value I just read until available is zero

I don't think your problem is with your code. I ran it (at 9600, 115200, and 230400 baud) and and got proper-looking results. I used the Arduino built-in terminal in line mode - copy/pasting your sent-data example into the terminal input line and clicking 'Send'.

It looks like you are parsing the incoming data for a string of 4 numbers, pos+r+g+b.  To avoid data loss as well as improve speed (if you need it), it may be better to send the data as bytes:
: 0x01 0xFF 0xFF 0xFF : 0x02 0xFF 0xFF 0xFF : 0x03 0xFF 0xFF 0xFF ... etc

This can be done with Arduino serial monitor via a hex to ASCII converter.  For example https://www.branah.com/ascii-converter
Type in hex (missing 0x, where 0x3a=':'): 3a01FFFFFF3a02FFFFFF3a03FFFFFF3a04FFFFFFFF
Get ASCII: :ÿÿÿ:ÿÿÿ:ÿÿÿ:ÿÿÿ
Copy this into the Arduino serial monitor
Also, try to do all of the serial prints in one go, don't interleave reading and writing unless you absolutely have to.  Sometimes bytes get dropped that way, too.
byte pos, r, g, b;

void setup(){
// serial begin
}

void loop() {
    if(Serial.available()){
        while(Serial.available()){
            Serial.readStringUntil(':');
            pos = Serial.read();
            r   = Serial.read();
            g   = Serial.read();
            b   = Serial.read();
            Serial.write(pos);
            Serial.write(r);
            Serial.write(g);
            Serial.write(b);
         }
    }
}

If you need a more elegant way to do the serial write, you will find plenty of answers already on stack exchange (too many to suggest only one).

Technically I dont need the delimiters, I was just using them as a way to know what I was reading by separating the values

@MichaelT, how do you send bytes from Serial Monitor to be read by read()? I don't think the Serial Monitor converts hex to bytes

The Arduino serial monitor allows character input.  You can use other programs either to convert byte to char (and copy/paste into the IDE), or do the entire serial reading and writing (like Qt, matlab, mathematica).

but the question implies Serial Monitor as input and output. your answer is good and true, only add some intro about sending and receiving with a computer program

I have given an example of how to send hex with Arduino serial monitor.  If it works for you please accept/upvote.


text:
SAMD21 Programming with Atmel ICE Fail to Write
I am trying to program my Adafruit M0 with the SAMD21G18 chip with Atmel studio and the Atmel ICE programmer. I have pin 1 on the ICE connected to 3.3V on the M0, pin 2 connected to SWDIO, pin 4 to SWDCLK, pin 10 to Reset, and pins 3, 5, and 9 to ground. This was all according to the ARM SWD connection section of the Atmel ICE manual. In Atmel Studio, I can read the device signature, but when I go to program the chip, I get the following error:
Timestamp:      2017-04-20 22:03:32.563
Severity:       ERROR
ComponentId:    20100
StatusCode:     131103
ModuleName:     TCF command: Modules:writeToMemory failed.

Failed to write segment at 0x0 to target for memorytype

I have searched the internet for hours, finding no solution to this problem.

Whats is the fuse setting of NVMCTRL_BOOTPROT?
it should be:
NVMCTRL_BOOTPROT = 0x07
which will set your memory location to 0x00 (no bootloader).
NVMCTRL_BOOTPROT sets the amount of space to allocate for the bootloader in flash memory. Setting this fuse to 0x07 tells the chip you are not allocating space for a bootloader and the programmer will start to write at address 0x00, which is the beginning of flash memory. If you are programming with an Atmel ICE, you are not using a bootloader.

Worked like a charm! Thanks! Did you find this in the Atmel ICE manual?

Happy to help. No in the Samd21 datasheet. There is a whole section on NVM and boot allocation.


text:
Design vehicle tracking device
I want to create an Arduino based vehicle tracking device which will be moved into a production board without Arduino later. Right now I have a few questions:

What GPS module should I use for a best result (little time to fix from a cold start and high accuracy locations)? It will be good if support GLONASS. I want to detect when the car is turning (using HMC5983). I've bought Ublox NEO-6M GPS module and tested it into the car, but it cannot find a location.
What MCU I should buy? I also want to communicate with OBD II port of vehicle over the CAN protocol (using MCP2551 + MCP2515). For now i choose ATMega328.
How to power all elements ?

PS: Data from the vehicle and the GPS locations will be send over GPRS with SIM800l module.
Cheers

This is not on-topic for a good Arduino question.  Generally we want to see a goal, then your attempt to meet that goal, showing parts, photos, code, etc.  Then a very specific question that is also in the title about something that is holding you back from completing the project.  We can't design a project for you.  I highly recommend you read the tour at https://arduino.stackexchange.com/Tour to get the most of this site.  I am voting to keep this open to give you an opportunity to either edit it completely based on what you see in the tour, or delete it yourself.  You are welcome here.

There are some SIMCOM modules with GPRS + GPS, for example: SIM968
In addition to GPS, it also supports GLONASS/Galileo/QZSS.
As for the MCU, you will need something more powerful than ATMega328, because 2KB RAM is not enough for multi-threading + GPS code + GSM/GPRS code + CAN + etc. Also it hasn't CAN peripheral. You will need MCU with ARM core. From Arduino line, Arduino Due looks suitable: has 96KB RAM, multiple HW serials, CAN. There is also compatible CAN library here. Also worth looking on STM32F103 (or STM32F407 with Cortex M4) which also can used be with Arduino IDE with some extra effort (STM32 MCUs usually more cost effective than Atmel counterparts, and have higher performance).


text:
Arduino core structure and timer usage
I needed to use TC1 for input capture, but also analogWrite() and an approximate 1 ms interrupt to poll the user interface (encoder, button).
The Arduino Nano's ATmega328p (datasheet, beware: a lot of bit symbol typos) has three timers:

TC0
TC1
TC2

It is not easy to find information on the "Arduino core" structure and it's use of peripherals. The Arduino Reference does not seem to refer to any information. Nor does Arduino Hacking.
Some info can be found on
https://arduino-info.wikispaces.com/Timers-Arduino
but I am not sure it's up to date. For instance, I find disabling TC2 also disables the analogWrite() PWM.
Trying to use TC0 results in an error, as TIMER0_OVF_vect is already being used ("multiple definition of `__vector_16'").
How can I use the timers (and their interrupts) that are already used for the core?

The overflow vector might be used, but both compare match vectors A and B are free. You can schedule comp interrupt anytime in period so it's not fired at the same time as OVF interrupt.

@KIIV Yes, but the CMs might be used by analogWrite on their respective output pin (the answers explain why).

Luckily it just changes "when" the interrupt happens. The period will be different once(or twice) after the change. But for polling buttons and encoder it doesn't matter.

Here is a summary of all this. On an ATmega328P (Arduino Uno, Nano,
etc.), the Arduino core library uses the timers as follows:

Timer 0

timing and delay functions, using the TIMER0_OVF interrupt
“fast” PWM at 980 Hz on pins 5 and 6 (PD5 and PD6)

Timer 1

“phase-correct” PWM at 490 Hz on pins 9 and 10 (PB1 and PB2)

Timer 2

“phase-correct” PWM at 490 Hz on pins 3 and 11 (PD3 and PB3)

All three timers have their prescalers set to 64. TIMER0_OVF is the
only timer interrupt enabled by default.
Note that libraries can use the timers for their own purposes. Servo
for instance uses Timer 1 for doing interrupt-based PWM.

"Reimplementing" the interrupt handlers to free Timer/Counter resources would require changes to the Arduino core firmware.
But there may be a workaround:
The source code shows how init() and loop() are used:
https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/main.cpp
and the basic timer initialization is here:
https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring.c#L45
and init() is there as well, which also configures all the other timers for phase-correct PWM...
analogWrite() is in https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_analog.c
I thought that at just 490/980 Hz it might use software-PWM, but in fact it selects the corresponding timer output compare pin (that also means the CPU can be powered down while the PWM still is being generated).
It does that via a runtime lookup in the board header's digital_pin_to_timer_PGM, e.g. https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/variants/standard/pins_arduino.h
which seems to be a (conditional) list of all pins.
So there is a limited, indirect choice on which timer is being used for PWM:
PD5 and PD6 are served by TC0, so using one of these as analogWrite() output pin frees TC2 for my purposes (~1 kHz polling).
Works for me!


text:
Can i create a function inside of void setup()?
Can i create a function inside of void setup()
to recall in loop() function

No. You do not create functions within functions.
You can create a function, and then call it both from setup() and loop() if you so wish.

Defining a function within a function is not supported in C or C++. If it were supported in a way consistent with the rest of the language, the inner function would be local to the outer function, just as local variables are, so not callable or even visible from outside the outer function.
Your loop() function (or any other function) could, however, call the setup() function as long as you want to execute setup() again in its entirety. That means that any initialization you perform in setup() would be repeated each time you call it.

You can create functions within a function if the particular c compiler supports it - gcc, the compiler used by arduino,  does. But not all c compilers support that.
Whether you can create a function within a function that recalls loop() depends on your meaning of "recall".

Can you cite a source or show an example? Local functions aren't part of the C or C++ languages (excepting private member-functions of a class). They would be very useful in a few situations.

@JRobert: https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html

You have asked two questions here.  In the title, can you define a function inside of setup():  Yes.
But that is the "scope" of where it can be used.
In Loop() it won't exist, ("xxx undefined in this scope") so the answer to what you ask in the text is No.

authors: Сергей Шевцов


text:
Help with a Memory Issue
Below is some code that I'm writing to concurrently run "animations" on the same strip of NeoPixels. When I try to make use of the Serial monitor to control the program functions, I just get a bunch of garbled garbage and often, a reboot. I have similar code to this that is actually smaller that runs from a Bluetooth module attached to the same Arduino and has worked for years. Is there some obvious memory issue I'm missing, could my Arduino's SRAM finally be starting to eat it?
#include "TripCycling.h"
#include "CycleLight.h"
#include "Alternate.h"
#include "Collision.h"
#include "FluidColor.h"
#include "ColorRandomizer.h"
#include "StreamAnimation.h"
#include "StreamControl.h"
#include <MemoryFree.h>

#define MAX_STRIPS 1
#define MAX_ANIMATIONS 6

#define control Serial

static Adafruit_NeoPixel** strips = new Adafruit_NeoPixel*[MAX_STRIPS];

static uint32_t colors[] = {LEDUtils::red, LEDUtils::orange, LEDUtils::yellow, LEDUtils::green, LEDUtils::blue, LEDUtils::purple};

static Animation** animations = new Animation*[MAX_ANIMATIONS];

static int8_t stripIDs[MAX_STRIPS];

static String temp = "";
static char val;
static String strings[12];

void setup() {

  Serial.begin(9600);
  Serial.println("Free Memory: " + String(freeMemory()));

  strips[0] = new Adafruit_NeoPixel(42, 9);
  stripIDs[0] = 1;

  strips[0]->begin();
  strips[0]->clear();
  strips[0]->show();

  control.println("Setup finished!");
}

void loop() {
  Serial.println("Free Memory: " + String(freeMemory()));

  if(control.available())
  {
    if(control.find('~'))
    {
      temp = control.readStringUntil('~');

      val = LEDUtils::split(strings, temp, ':');

      if(strings[0].equals("CLR"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          LEDUtils::clearSection(*strips[arrayPos], strings[2].toInt(), strings[3].toInt());

          if(strings[4].equals("True"))
          {
            strips[arrayPos]->show();
          }
        }
      }
      else if(strings[0].equals("ALL"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          LEDUtils::setAll(*strips[arrayPos], strings[2].toInt(), strings[3].toInt(), strings[4].toInt());
        }
      }
      else if(strings[0].equals("MAT"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          int8_t findValue = getNextAniPos();

          if(findValue == -1)
          {
            control.print("ERR:Max animations reached~");
          }
          else
          {
            uint16_t startPixel = strings[2].toInt();
            uint16_t stopPixel = strings[3].toInt();
            long updateTime = strings[4].toInt();
            uint16_t refNum = strings[5].toInt();

            uint32_t colors[val - 6];

            for(uint8_t i = 6; i < val; i++)
            {
              colors[i - 6] = strings[i].toInt();
            }

            animations[findValue] = new Alternate(*strips[arrayPos], refNum, startPixel, stopPixel, colors, val - 6, updateTime);
            animations[findValue]->start();
          }
        }
      }
      else if(strings[0].equals("CRZ"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          int8_t findValue = getNextAniPos();

          if(findValue == -1)
          {
            control.print("ERR:Max animations reached~");
          }
          else
          {
            uint16_t startPixel = strings[2].toInt();
            uint16_t stopPixel = strings[3].toInt();
            long updateTime = strings[4].toInt();
            boolean fade = strings[5].toInt() ? true : false;
            uint16_t refNum = strings[6].toInt();

            uint32_t colors[val - 7];

            for(uint8_t i = 7; i < val; i++)
            {
              colors[i - 7] = strings[i].toInt();
            }

            animations[findValue] = new ColorRandomizer(*strips[arrayPos], refNum, startPixel, stopPixel, colors, val - 7, fade, updateTime);
            animations[findValue]->start();
          }
        }
      }
      else if(strings[0].equals("TCL"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          int8_t findValue = getNextAniPos();

          if(findValue == -1)
          {
            control.print("ERR:Max animations reached~");
          }
          else
          {
            uint16_t startPixel = strings[2].toInt();
            uint16_t stopPixel = strings[3].toInt();
            long updateTime = strings[4].toInt();
            uint32_t color1 = strings[5].toInt();
            uint32_t color2 = strings[6].toInt();
            uint16_t tripSize = strings[7].toInt();
            uint16_t refNum = strings[8].toInt();

            animations[findValue] = new TripCycling(*strips[arrayPos], refNum, startPixel, stopPixel, tripSize, color1, color2, updateTime);
            animations[findValue]->start();
          }
        }
      }
      else if(strings[0].equals("CLI"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          int8_t findValue = getNextAniPos();

          if(findValue == -1)
          {
            control.print("ERR:Max animations reached~");
          }
          else
          {
            uint16_t startPixel = strings[2].toInt();
            uint16_t stopPixel = strings[3].toInt();
            long updateTime = strings[4].toInt();
            uint32_t color1 = strings[5].toInt();
            uint32_t color2 = strings[6].toInt();
            uint16_t refNum = strings[7].toInt();

            animations[findValue] = new CycleLight(*strips[arrayPos], refNum, startPixel, stopPixel, color1, color2, updateTime);
            animations[findValue]->start();
          }
        }
      }
      else if(strings[0].equals("COL"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          int8_t findValue = getNextAniPos();

          if(findValue == -1)
          {
            control.print("ERR:Max animations reached~");
          }
          else
          {
            uint16_t startPixel = strings[2].toInt();
            uint16_t stopPixel = strings[3].toInt();
            long updateTime = strings[4].toInt();
            uint32_t color1 = strings[5].toInt();
            uint32_t color2 = strings[6].toInt();
            uint16_t refNum = strings[7].toInt();

            animations[findValue] = new Collision(*strips[arrayPos], refNum, startPixel, stopPixel, color1, color2, updateTime);
            animations[findValue]->start();
          }
        }
      }
    }
  }

  for(uint16_t i = 0; i < MAX_ANIMATIONS; i++)
  {
    if(animations[i]->getRefNum() != 65535 && animations[i]->isStarted())
    {
      animations[i]->update();
    }
  }

  delay(1);
}

int8_t getArrayPosByID(int8_t id)
{
  for(int8_t i = 0; i < MAX_STRIPS; i++)
  {
    if(stripIDs[i] == id)
    {
      return i;
    }
  }

  return -1;
}

int8_t getNextAniPos()
{
  for(int8_t i = 0; i < MAX_ANIMATIONS; i++)
  {
    if(animations[i]->getRefNum() == 65535)
    {
      return i;
    }
  }

  return -1;
}

Note that the includes above are all based on classes I designed to represent the animations, each one has some information in them like the strip to use (passed by reference), the starting pixel, stopping pixel, colors, how long there timers should wait before executing the next animation step, etc. And they are all subclasses of the parent class Animation. I cannot seem to find what is causing the garbling to happen, if I remove references to Serial and just hard-code animations in, everything works fine, and I have around 1KB of SRAM (out of 2K) for other stuff running 6 different animations on one strip of 42 LEDs. At this point I don't make it through the Free Memory println before stuff starts coming up weird and normally the Arduino will just hang and do nothing or keep transmitting the last garbled character over and over as fast as it can. Am I missing something?

There was a very major issue with the amount of Strings I was storing in RAM. Moving Strings out of RAM and into PROGMEM using the F() macro has helped significantly. Going at things step by step helped me see where the issue was.

In short:

Lots of new, no delete.
Constant strings like Serial.print("something") can be stored in flash memory by Flash Helper Serial.print(F("something")).
Maybe too wide color spectre. You can save 1Byte per pixel if you use struct with 8b R/G/B. (or you can use even 16b depth colors - but it is little bit harder).
And maybe, if you were storing some instructions only and prepare pixels into ledstrip directly, you can save a lot. However it takes some time to prepare it, so you have to count with it. Something like fill(color, from, to), gradient(...), move left/right...
Using Arduino framework is memory and cpu extensive too.

Anyway crashing as you described sounds like stack overflow or memory corruption.

See but that's the thing, I have code extremely similar to this, it makes use of BOTH SoftwareSerial and Serial to control a Bluetooth module and provide constant debug feedback when testing. That code runs no problem, this code, which is broken up into classes, not separate methods like the Bluetooth code is, is what's having the issue. In fact, the Bluetooth code on compile time uses more memory by default, I would think this code would at the very least run, because initially nothing beyond some pointers, text, and the same strip used for the Bluetooth code are being loaded into memory.


text:
Which tft works on both Arduino Uno and Raspberry pi
Ideally I'd like a 2.8 inch and it to be touch screen.
But most of all I'd rather it work on both boards without much hassle.

Uno works at 5V and Pi at 3.3V, keep that in mind. A display with SPI, I2C or uart is likely to work on both, given the right circuitry for the difference in voltage.

Well any display can work on both of the boards if you can adjust the voltage levels right there is a display which was made for old Nokia phones and it is called nokia-5110-3310 and  is dirt cheap display and it can be used with both Arduino or raspberry pi or any other board which support the protocol here is a link for quick reference.
Adafruit link to the library

adafruit has a resistive touch screen which is 2.8" and works on most boards. Its 30 dollars and works well. It has instructions and all and libraries which you can use. Plug it into a breadboard, connect the jumpers and you're all set.
https://www.adafruit.com/product/1770
on the other hand, Elegoo has made a very similar product, which can also be used on most boards if you plug it into a breadboard, but it is specially designed for the UNO. You can plug it straight into the UNO board, without the need of breadboards. This comes with a instructional DVD and is only 12 dollars on Amazon. It is also a resistive screen and basically the same product.
https://www.amazon.com/gp/product/B01EUVJYME/ref=oh_aui_detailpage_o04_s01?ie=UTF8&psc=1
Good luck!


text:
How to make the compiler ensure that local variables memory allocation won't cause any RAM overflow during execution?
Upon compiling a sketch using the Arduino IDE, a message like the following gets displayed in the console:
Global variables use 1540 bytes (75%) of dynamic memory, leaving 508 bytes for local variables. Maximum is 2048 bytes.

In addition, it seems that if the global variables use exceeds around 75% of total dynamic memory, the following message gets displayed in addition:
Low memory available, stability problems may occur.

So, it seems that by using the IDE in a regular way, the compiler does not ensure that local variables memory allocation won't cause any RAM overflow during program execution. Instead, it just displays a warning message when little RAM is left for local variables.
This can lead to program malfunctions at execution time, if local variables happen to take up more space than the remaining RAM.
How can one have the compiler detect whether local variables memory allocation will cause RAM overflow during execution or not, and warn the user at compile time only in those specific cases?

the compiler knows nothing about the program's logic

How do you expect the compiler to guess what might happen in your program that relies on external stimulii to control its operation?

@Majenko I don't in general; yet there are many cases in which it should be obvious for the compiler that local variables are necessarily going to cause RAM overflow at execution time. I expect the compiler to be at least able to produce a compilation error in those obvious cases (cases that do not depend on any external stimulus).

and why do you ask it here on Arduino SE?

@Juraj Where else do you suggest?

maybe GCC developers mailing list

The underlying GCC might have an option to check during runtime whether the stack runs into used RAM, depending on its version. But I have no idea how to add such a potential option in the Arduino IDE. Please note that it slows down your sketch, because this check is most probably done each time the used stack space increases, that is at function/method calls or local variable allocations.

the compiler can detect early problems. running out of var space is a late problem. ex. at coding time, you can reserve 20 bytes for a user's name but then Hubert Blaine Wolfeschlegelsteinhausenbergerdorff Sr. comes along and your well-laid plans don't pan out.

Look at it like this. If you have 2kB of RAM and 2 functions, a() and b(), each of which dynamically allocate 1.5kB, you may be OK. It depends.
It is definitely bad luck if b() calls a(), a() calls a() etc. If a() and b() are never active simultaneously it may work. If b() calls a() depending on user input at runtime, the compiler can't see that.

You are describing "memory profiling" and is not typically a feature of C or C++.  It is more common in higher level languages, such as Java, but C is a considered a much lower level language.
Typically such profiling is done at runtime using external tools such as valgrind and massif.
It's not really possible for the compiler to work out what your program will be doing when it is using external data and inputs to control how it works. Any such tests at compile time would be pretty much meaningless since any that pass in testing may still cause problems at runtime depending on what else may be happening at the same time, or even what may have happened in the past (see heap fragmentation).


text:
Arduino Uno's Timer maximum frequency using Timer Compare Interrupt, not Timer Output Pins (e.g. OC0A)
I want to achieve the generation of a custom binary signal over a digital pin at the highest possible frequency on Arduino Uno.
Using Timer's output pins (e.g. OC0A), one can get a pin to toggle at a maximum frequency of 16MHz (which corresponds to a sqaure wave of frequency 8MHz), as described here:
Maximum frequency of digital signal in Arduino Uno?
However as far as I understand, Timer's output pins are only useful if one needs to generate a repetitive waveform such as a PWM or square wave, so it cannot serve my purpose which requires the generation of a custom binary signal.
Using the following code, I was expecting digital pin 9 to toggle at a frequency close to 16MHz too, since I use no prescaler and set the Compare Match Register value to 0:
void setup()
{
    DDRB = 1 << 1;  // Set D9 as OUTPUT

    cli();
    TCNT0 = 0; TCCR0A = 0; TCCR0B = 0;
    TCCR0A |= (1 << WGM01);  // CTC mode
    TCCR0B |= (1 << CS00);  // no prescaling
    OCR0A = 0;  // Highest timer overflow frequency possible
    TIMSK0 |= (1 << OCIE0A);
    sei();
}

ISR(TIMER0_COMPA_vect)
{
    PORTB ^= 1 << 1;  // Toggle D9; this allows to measure the toggle frequency, however this could be replaced by some code to generate a custom binary signal
}

void loop(){}

However in fact it appears to toggle at a frequency of only approximately 410kHz (which corresponds to a square wave of frequency 205kHz), as the below image shows:

I used Timer0 but I get the same frequency with Timer1 and Timer2.

How can one explain that using this code I get this toggle frequency on the digital pin ?
How can I generate a custom binary signal over a digital pin at the highest possible frequency ?

I realize this is peanuts compared to the greater issues which are outlined in Majenko's answer, but if you do want to toggle PB1, you can PINB = 1 << 1; rather than PORTB ^= 1 << 1 to save a couple of cycles.  The construction may look weird, but they've designed the AVR GPIO hardware so that you can toggle pin be writing 1 bits to their bit positions in the PINx registers; writing 0-bits have no effect.  If you take the writing in a tight loop outside of an interrupt suggestion, this may have some impact.

Thanks, I didn't know you could do it more efficiently that way; this would be impactful in some situations indeed.

How can one explain that using this code I get this toggle frequency on the digital pin ?

Code takes time to execute. Your ISR, when compiled, looks like:
ISR(TIMER0_COMPA_vect)
{
 124:   1f 92           push    r1
 126:   0f 92           push    r0
 128:   0f b6           in  r0, 0x3f    ; 63
 12a:   0f 92           push    r0
 12c:   11 24           eor r1, r1
 12e:   8f 93           push    r24
 130:   9f 93           push    r25
    PORTB ^= 1 << 1;  // Toggle D9; this allows to measure the toggle frequency, however this could be replaced by some code to generate a custom binary signal
 132:   85 b1           in  r24, 0x05   ; 5
 134:   92 e0           ldi r25, 0x02   ; 2
 136:   89 27           eor r24, r25
 138:   85 b9           out 0x05, r24   ; 5
}
 13a:   9f 91           pop r25
 13c:   8f 91           pop r24
 13e:   0f 90           pop r0
 140:   0f be           out 0x3f, r0    ; 63
 142:   0f 90           pop r0
 144:   1f 90           pop r1
 146:   18 95           reti

That's 18 assembly instructions, each needing between 1 and 4 clock cycles to execute.  Referencing the datasheet you can count the exact cycles needed and sum them up, yielding 31 clock cycles.
Toggling at maximum speed that would be 16MHz / 31 = 516kHz.
And then you have the rest of the code running between each call to the interrupt, so it's slower than that.

How can I generate a custom binary signal over a digital pin at the highest possible frequency ?

By not using interrupts, and writing a tight loop in assembly language.

How did you get the exact assembly out? Is it possible to do that with the Arduino IDE or did you have to use the Atmel IDE?

That actually addresses the question quite well.
My understanding of what is happening is the following: the first Timer Compare Interrupt occurs. Before the ISR has finished running, a second Timer Compare Interrupt occurs, but is queued because the previous ISR has not finished running. As soon as the first ISR has finished running, the second ISR is allowed to run. And that goes on and on is such a way that the ISR is running at a frequency equal to (or at least close to) the inverse of its duration.
What do you say about this interpretation?

How can I use assembly language to achieve a higher toggle frequency than with the Timer Compare Interrupt ? In fact, how can I use assembly language to achieve my goal without using a timer interrupt (which as you showed is slow)?

@Tri I used avr-objdump -S <filename.elf> on the compiled elf file from the Arduino IDE (actually arduino-cli as I hate the IDE).

@Ramanewbie That's a good interpretation, yes. Writing assembly language can be a bit of a black art. You would need to code delay loops to get the timing you want, along with toggling of the IO pin and looking up of the data sequence. Not a fun task. Another option could be to stream the data out using the SPI port, where the speed will be relative to the resolution you desire - maximum 8 MBits/s (4MHz square wave)

"You would need to code delay loops to get the timing you want, along with toggling of the IO pin and looking up of the data sequence"

With that approach, you would need to count the number of clock cycles that your IO tasks take to execute, in order to deduce by substraction the duration needed for the delay loop so as to get the wanted operation frequency, right ?

@Ramanewbie That is correct, yes.

Let us continue this discussion in chat.


text:
ACS712 inacurrate reading. Wild jumping
I'm trying to use my 30A ACS712 on my OSD (it has ATMEGA16L).
But it is very unstable, 0 amps goes from 450 to 445, but that isn't that bad, but when I put 10A of current through it jumps from 440 to 380.
I already searched on google and tried to add filter cap between acc and gnd, but it didn't help and acs712 and osd have different power supply than the load.
Any help is welcome.

Are you trying to sense AC or DC current? (yes, I know that's RAS Syndrome)

DC and I connected acs712 directly to atmega16l

This is not a simple chip to use.  These parts of the data sheet may help you understand what is happening.  It is internally an analog device and needs clean power.  I would highly recommend you download the Allegro data sheet, it has a lot of information that will help you.  Below is a short section of the data sheet, The first paragraph should give you a hint that the output voltage will be about 2.5V with a 5V unipolar power supply.
"Quiescent output voltage (VIOUT(Q)). The output of the device
when the primary current is zero. For a unipolar supply voltage,
it nominally remains at VCC⁄ 2. Thus, VCC = 5 V translates into
VIOUT(Q) = 2.5 V. Variation in VIOUT(Q) can be attributed to the
resolution of the Allegro linear IC quiescent voltage trim and
thermal drift.
Electrical offset voltage (VOE). The deviation of the device output
from its ideal quiescent value of VCC / 2 due to nonmagnetic
causes. To convert this voltage to amperes, divide by the device
sensitivity, Sens.
Accuracy (ETOT). The accuracy represents the maximum deviation
of the actual output from its ideal value. This is also known
as the total output error. The accuracy is illustrated graphically in
the output voltage versus current chart at right."
I realize this does not answer your question but it does give you a good starting point to resolve your problem.  Hopefully you or a buddy has some analog experience, that will help a lot.  Oh Yes clean power supplies are imperative for this to work.


text:
SHT30 activating Fan control
I've a working hardware setup and two codes 1 to read the sht30 and push the data to my tft screen.
And 2 a code to set a fan (2fans) on and off.
I want to combine these whenever the humidity is over 50% the fans should go on.
3 issues arise.

less important my serial.println() doesn't print anything anymore
my second if loop doesn't get printed not in serial or in display
Fans are not getting activated by the code.

My searching leads me to think I need to convert my sht30.humidity into an int before making the if loop.
Or it could be something entirely else ofcourse.
#include <WEMOS_SHT3X.h>

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

Adafruit_SSD1306 display(1);
#if (SSD1306_LCDHEIGHT != 32)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

SHT3X sht30(0x45);

void setup() {
  Serial.begin(115200);
  pinMode(14, OUTPUT);
  // initialize with the I2C addr 0x3C
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.display();
  delay(1000);
  Serial.print("start");
  // Clear the buffer.
  display.clearDisplay();
}

void loop() {

 // Clear the buffer.
  display.clearDisplay();
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.setTextColor(WHITE);

  if(sht30.get()==0)
  {
    display.setCursor(35, 10);
    display.println("T: ");
    display.setCursor(50, 10);
    display.println(sht30.cTemp);
    display.setCursor(35, 20);
    display.println("H: ");
    display.setCursor(50, 20);
    display.println(sht30.humidity);
  }
  else
  {
    display.setCursor(35, 10);
    display.println("Error!");
    Serial.println("error");
  }
  display.display();
  delay(1000);

  Hcheck();
  Serial.println("checking humidity");

}

void Hcheck() {
  delay(5000);
  Serial.println("============ Check Humidity ===============");
  display.clearDisplay();
  display.setCursor(35, 10);
  display.println(sht30.humidity);
  display.display();
  delay(1000);
  Serial.println(sht30.humidity);

  if(sht30.humidity <= 50 ) {
    digitalWrite(14, HIGH);
    display.clearDisplay();
    display.setCursor(35, 20);
    display.display();
    delay(500);
  }else {
    digitalWrite(14, LOW);
    delay(500);
    Serial.println("Air is dry");

  }

  }

Are you sure, that the I2C communication works? You can check, if the lines are HIGH most of the time. If one of them is constant low, the problem is a stuck I2C bus

are you saying that start does not print when you reset the ESP8266?

If my sht30 works and the tft screen works I2C must work correct? It's the pwm signal that doesn't work. @jsotola Nope not a single serialprintln works so I guess something else is wrong here...?

put Serial.print("start"); right after Serial.begin .... try to narrow down where the program hangs up


text:
Running dual Adafruit GPS at 10Hz on a Teensy 3.2
Excuse the crudity of this question but I'm having quite the trouble trying to run the two Adafruit Ultimate GPS v3 modules at 10Hz on the Teensy 3.2 board. The modules are connected over the hardware serial ports 1 and 3. There is also an IMU (MPU6050) connected over the I2C interface.

Aim:
-To determine the difference between the course over ground and the body attitude (yaw) of a vehicle
Issues:
-By default, the GPS modules only run at 1Hz and at 9600 baud. I'm sending the required PMTK commands over their respective serial ports
  1 and 3 to increase those to 10Hz and 115200 baud. I'm using hardware
  serial because the SoftwareSerial library was messing up the
  interrupts for the I2C interface and wasn't reliable at the baud rate
  required for 10Hz.
-When using the TinyGPS++ library, it seems that the received chars for the GPS 1 and 2 modules were the same, which led me to believe
  that it wasn't behaving correctly, and I was getting no fixes. Since I
  also need to run a Kalman filter for each GPS module at 10Hz (which
  might not work at that speed on the Teensy), I switched to the NeoGPS
  library, which I'm told, requires much less system resources and is
  much faster.
-The NeoGPS library also does not return any successful fix messages due to possibly being misconfigured (I'm using the default
  configuration files)
Below is the code I'm using with the TinyGPS++ library (sans the IMU
  parts)
With this, I'm only getting stars (*), and the same number of received
  characters for both GPS 1 and 2, hence my assumption that it is
  faulty;

#include <TinyGPS++.h>

    static const uint32_t GPSBaud = 115200;

    // The TinyGPS++ object
    TinyGPSPlus gps;

    void setup()
    {
      // The serial connection to the GPS device
      #define GPS_1_Serial Serial1
      #define GPS_2_Serial Serial3
      GPS_1_Serial.begin(9600);
      GPS_1_Serial.write("$PMTK220,100*2F\r\n");
     //switch the GPS baud rate to 115200
      GPS_1_Serial.write("$PMTK251,115200*27\r\n");
     //change baud rate of serial port to 38400
      GPS_1_Serial.flush();
      delay(10);
      GPS_1_Serial.end();

      GPS_2_Serial.begin(9600);
      GPS_2_Serial.write("$PMTK220,100*2F\r\n");
     //switch the GPS baud rate to 115200
      GPS_2_Serial.write("$PMTK251,115200*27\r\n");
     //change baud rate of serial port to 38400
      GPS_2_Serial.flush();
      delay(10);
      GPS_2_Serial.end();

      Serial.begin(115200);

      while (!Serial);
      Serial.println(TinyGPSPlus::libraryVersion());
      Serial.println();
      Serial.println(F("   Fix  Date       Time     Date    Course Speed Card  Chars Sentences Checksum"));
      Serial.println(F("   Age                      Age     --- from GPS ----  RX    RX        Fail"));
      Serial.println(F("----------------------------------------------------------------------------------------------------------------------------------------"));

    }

    void loop()
    {
      static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;
    //GPS________________________________________________________GPS_1___________________________________________________________________
      GPS_1_Serial.begin(GPSBaud);
      Serial.println("Listening to GPS_1");

      printDateTime(gps.date, gps.time);

      printFloat(gps.course.deg(), gps.course.isValid(), 7, 2);
      printFloat(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
      printStr(gps.course.isValid() ? TinyGPSPlus::cardinal(gps.course.deg()) : "*** ", 6);

      printInt(gps.charsProcessed(), true, 6);
      printInt(gps.sentencesWithFix(), true, 10);
      printInt(gps.failedChecksum(), true, 9);
      Serial.println();

      if (millis() > 5000 && gps.charsProcessed() < 10)
        Serial.println(F("No GPS data received: check wiring"));
      smartDelay(100);
      GPS_1_Serial.end();
    // ---------------------------------GPS_2----------------------------

      GPS_2_Serial.begin(GPSBaud);

      Serial.println("Listening to GPS_2");

      printDateTime1(gps.date, gps.time);

      printFloat1(gps.course.deg(), gps.course.isValid(), 7, 2);
      printFloat1(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
      printStr1(gps.course.isValid() ? TinyGPSPlus::cardinal(gps.course.deg()) : "*** ", 6);

      printInt1(gps.charsProcessed(), true, 6);
      printInt1(gps.sentencesWithFix(), true, 10);
      printInt1(gps.failedChecksum(), true, 9);
      Serial.println();

      if (millis() > 5000 && gps.charsProcessed() < 10)
        Serial.println(F("No GPS data received: check wiring"));

      smartDelay1(100);
      GPS_2_Serial.end();

    }

    // This custom version of delay() ensures that the gps object
    // is being "fed".
    static void smartDelay(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (GPS_1_Serial.available())
          gps.encode(GPS_1_Serial.read());
      } while (millis() - start < ms);
    }

    static void smartDelay1(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (GPS_2_Serial.available())
          gps.encode(GPS_2_Serial.read());

      } while (millis() - start < ms);
    }

    static void printFloat(float val, bool valid, int len, int prec)
    {
      if (!valid)
      {
        while (len-- > 1)
          Serial.print('*');
        Serial.print(' ');
      }
      else
      {
        Serial.print(val, prec);
        int vi = abs((int)val);
        int flen = prec + (val < 0.0 ? 2 : 1); // . and -
        flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
        for (int i=flen; i<len; ++i)
          Serial.print(' ');
      }
      smartDelay(0);
    }

    static void printFloat1(float val, bool valid, int len, int prec)
    {
      if (!valid)
      {
        while (len-- > 1)
          Serial.print('*');
        Serial.print(' ');
      }
      else
      {
        Serial.print(val, prec);
        int vi = abs((int)val);
        int flen = prec + (val < 0.0 ? 2 : 1); // . and -
        flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
        for (int i=flen; i<len; ++i)
          Serial.print(' ');
      }
      smartDelay1(0);
    }

    static void printInt(unsigned long val, bool valid, int len)
    {
      char sz[32] = "*****************";
      if (valid)
        sprintf(sz, "%ld", val);
      sz[len] = 0;
      for (int i=strlen(sz); i<len; ++i)
        sz[i] = ' ';
      if (len > 0)
        sz[len-1] = ' ';
      Serial.print(sz);
      smartDelay(0);
    }

    static void printInt1(unsigned long val, bool valid, int len)
    {
      char sz[32] = "*****************";
      if (valid)
        sprintf(sz, "%ld", val);
      sz[len] = 0;
      for (int i=strlen(sz); i<len; ++i)
        sz[i] = ' ';
      if (len > 0)
        sz[len-1] = ' ';
      Serial.print(sz);
      smartDelay1(0);
    }

    static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
    {
      if (!d.isValid())
      {
        Serial.print(F("********** "));
      }
      else
      {
        char sz[32];
        sprintf(sz, "%02d/%02d/%02d ", d.month(), d.day(), d.year());
        Serial.print(sz);
      }

      if (!t.isValid())
      {
        Serial.print(F("******** "));
      }
      else
      {
        char sz[32];
        sprintf(sz, "%02d:%02d:%02d ", t.hour(), t.minute(), t.second());
        Serial.print(sz);
      }

      printInt(d.age(), d.isValid(), 5);
      smartDelay(0);
    }

    static void printDateTime1(TinyGPSDate &d, TinyGPSTime &t)
    {
      if (!d.isValid())
      {
        Serial.print(F("********** "));
      }
      else
      {
        char sz[32];
        sprintf(sz, "%02d/%02d/%02d ", d.month(), d.day(), d.year());
        Serial.print(sz);
      }

      if (!t.isValid())
      {
        Serial.print(F("******** "));
      }
      else
      {
        char sz[32];
        sprintf(sz, "%02d:%02d:%02d ", t.hour(), t.minute(), t.second());
        Serial.print(sz);
      }

      printInt(d.age(), d.isValid(), 5);
      smartDelay1(0);
    }

    static void printStr(const char *str, int len)
    {
      int slen = strlen(str);
      for (int i=0; i<len; ++i)
        Serial.print(i<slen ? str[i] : ' ');
      smartDelay(0);
    }

    static void printStr1(const char *str, int len)
    {
      int slen = strlen(str);
      for (int i=0; i<len; ++i)
        Serial.print(i<slen ? str[i] : ' ');
      smartDelay1(0);
    }

This is the NeoGPS library version I've attempted, which does not
  output any indication that it is working successfully;

#include <NMEAGPS.h>

static const uint32_t GPSBaud = 115200;

// NMEAGPS object
NMEAGPS gps;

void setup()
{

  // The serial connection to the GPS device
  #define GPS_1_Serial Serial1
  #define GPS_2_Serial Serial3
  GPS_1_Serial.begin(9600);
  GPS_1_Serial.write("$PMTK220,100*2F\r\n");
 //switch the GPS baud rate to 115200
  GPS_1_Serial.write("$PMTK251,115200*27\r\n");
 //change baud rate of serial port to 38400
  GPS_1_Serial.flush();
  delay(10);
  GPS_1_Serial.end();
  GPS_1_Serial.begin(GPSBaud);

  GPS_2_Serial.begin(9600);
  GPS_2_Serial.write("$PMTK220,100*2F\r\n");
 //switch the GPS baud rate to 115200
  GPS_2_Serial.write("$PMTK251,115200*27\r\n");
 //change baud rate of serial port to 38400
  GPS_2_Serial.flush();
  delay(10);
  GPS_2_Serial.end();
  GPS_2_Serial.begin(GPSBaud);

  Serial.begin(115200);

  while (!Serial);
  Serial.println();
  //Serial.println(F("  Time     Date    Course Speed Card  Chars Sentences Checksum"));
  //Serial.println(F(""));
  Serial.println(F("----------------------------------------------------------------------------------------------------------------------------------------"));

}

void loop()
{

//GPS________________________________________________________GPS_1___________________________________________________________________

  Serial.println("Listening to GPS_1");
  while (gps.available(GPS_1_Serial)) {
    gps_fix fix_1 = gps.read();
    if (fix_1.valid.location){
      Serial.println("Successful Location");
    }
    if (fix_1.valid.time) {
      Serial.println("Successful Time");

    }
  }

  Serial.println();

// ---------------------------------GPS_2----------------------------

  Serial.println("Listening to GPS_2");
  while (gps.available(GPS_2_Serial)) {
    gps_fix fix_2 = gps.read();
    if (fix_2.valid.location){
      Serial.println("Successful Location");
    }
    if (fix_2.valid.time) {
      Serial.println("Successful Time");

    }
  }

}

I'm still a beginner when it comes to programming with an Arduino, and I appreciate any assistance to get on the right track.
Thank you for reading
Yours faithfully,
Cem Huray

were you successful in running one gps module?

why are you switching the baud rate?

I was able to run both modules at 1Hz at 9600 baud, I need to change the baud rate to ensure that there is no data loss at 10Hz

You just need two instances of the parser, too:
NMEAGPS gps_1, gps_2;

       ...

//___________________GPS_1______________________

  //Serial.println("Listening to GPS_1");  <-- don't print too much!
  while (gps_1.available(GPS_1_Serial)) {
    gps_fix fix_1 = gps_1.read();
          ...

//___________________GPS_2______________________

  //Serial.println("Listening to GPS_2");  <-- don't print too much!
  while (gps_2.available(GPS_2_Serial)) {
    gps_fix fix_2 = gps_2.read();
          ...

Also answered on the Arduino forum here.

Wow, thank you so much, sorry I couldn't reply, I'm trying to smooth some stuff out, but brilliant library I must say

@C.Huray, Thanks!  If this solves your problem, click on the green triangle next to my answer to "accept" it.  Otherwise, your question lingers on, haunting us forever.... ;)

What is processing_style in NMEAGPS ? My understanding is there is a PS_POLLING style that may not work well with two GPSes and PS_INTERRUPT, that I'm not sure can handle Teensy well.
Have you tried to read directly from the Serial without any library ? When it's working, you can try to plug the library back (or parse the strings from GPS, which is quite easy).

No problem for the NeoGPS INTERRUPT processing style: just make sure the separate ISRs call the separate gps1.handle(c) or gps2.handle(c).


text:
Error using SD card module: no matching function for call to
This code is just a test code to write a file to an SD card using an SD card module. When I run the code, I get this error message and I'm not sure what to do to fix the code: no matching function for call to'SDLib::SDClass::exists(SDLib::File&)'.
#include <SD.h>
#include <SPI.h>

int cs = 10;

File myTest;

void setup()
{
  //
  char myTestName[] = "MyTest.txt";

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {

  }
  Serial.println("Initializing SD card...");
  Serial.println();

  pinMode(cs, OUTPUT);
  pinMode(SS, OUTPUT);
  if (!SD.begin(cs)) {
    Serial.println("SD did not initiliaze");
    while (1) ;
  }
  Serial.println("SD initialized.");

  if (! SD.exists(myTest)){
     myTest = SD.open(myTestName, FILE_WRITE);

     myTest.println("My 1st Line of Data");
     myTest.flush();
  }
  else{
    myTest = SD.open(myTestName, FILE_WRITE);
    myTest.println("Another Line of Data");
    myTest.flush();

  }

  Serial.println("Done Writing");

}

void loop()
{

}

The function is defined as
// Methods to determine if the requested file path exists.
boolean exists(char *filepath);

Source: https://github.com/adafruit/SD/blob/master/SD.h#L90
You call it with a File object, not the filename. You probably mixed up the variable names:
File myTest;

void setup()
{
  //
  char myTestName[] = "MyTest.txt";

  //[...]
  if (! SD.exists(myTest)){
     myTest = SD.open(myTestName, FILE_WRITE);
     myTest.println("My 1st Line of Data");
     myTest.flush();
  }
//..

Just exchange myTest for myTestName in the SD.exists() call.


text:
Reading file from SPIFFS in nodemcu using ArduinoJson
#include <ArduinoJson.h>
#include <FS.h>

/* Set these to desired credentials in runtime */
struct Config {
  String ssid = "";
  String pass = "";
  bool hFlag = false;
};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("");
  delay(1000);

  //allows serving of files from SPIFFS
  Serial.println("Mounting FS...");
  if (!SPIFFS.begin()) {
    Serial.println("Failed to mount file system");
    return;
  }

  if (readConfigFile("/LaSt.json", false)) {
    Serial.println("Config read");
  } else {
    Serial.println("Failed to read config");
  }
}

bool readConfigFile(char* fileName, bool whichFile)
{
  File configFile = SPIFFS.open(fileName, "r");
  if (!configFile) {
    Serial.println("Failed to open config file");
    return false;
  }

  size_t size = configFile.size();
  if (size > 1024) {
    Serial.println("Config file size is too large");
    return false;
  }

  // Allocate the memory pool on the stack.
  // Use arduinojson.org/assistant to compute the capacity.
  StaticJsonBuffer<256> jsonBuffer;

  // Parse the root object
  JsonObject &root = jsonBuffer.parseObject(configFile);

  if (!root.success())
    Serial.println(F("Failed to read file, using default configuration"));

  // Copy values from the JsonObject to the Config
  Config.ssid = root["ssid"];
  Config.pass = root["pass"];
  if (whichFile)
  {
    Config.hFlag = root["hFlag"];
  }

  // We don't need the file anymore
  configFile.close();

  return true;
}

Compile gives error in Copy values from the JsonObject to the Config section. Error: expected unqualified-id before '.' token.
Want to read file from SPIFFS, and store in variable to use.

Config is type. you do not have an instance of it

Your code at the top:
struct Config {
  String ssid = "";
  String pass = "";
  bool hFlag = false;
};

defines a variable "type". It's like making a new int or bool, but yours is called struct Config.
After making the type, you need to create declare an instance of it.
struct Config cfg;

Then, you refer to the one you created:
  // Copy values from the JsonObject to the Config struct named cfg
  cfg.ssid = root["ssid"];
  cfg.pass = root["pass"];
  if (whichFile)
  {
    cfg.hFlag = root["hFlag"];
  }

Note that a particular issue with ArduinoJSON and Strings is that you may get an error like:
error: ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::JsonObjectSubscript<const char*>')

There is an ArduinoJSON FAQ entry that states

Most of the time you can rely on implicit casts.
But there is one notable exception: when you convert a JsonVariant to
  a String.
For example:
String ssid = network["ssid"];
ssid = network["ssid"];

The first line will compile but the second will fail with the
  following error:
error: ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::JsonObjectSubscript<const char*>')

The solution is to remove the ambiguity with any of the following replacement:
ssid = (const char*)network["ssid"];
ssid = network["ssid"].as<const char*>();
ssid = network["ssid"].as<String>();

ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::Internals::JsonObjectSubscript<const char*>')

link1, link2

Are you  meaning to ask a new question?

No, just mentioned that in the particular case, string variable type will give the error, and the workarounds are given in the links. However, those workarounds also produce warnings.

#include FS.h
#include ESP8266WiFi.h
#include ArduinoJson.h

/* Set these to desired credentials in runtime */

  String ssid = "tttttttt";
  String pass = "ssssssss";

#define fileName "/LaSt.json"

DynamicJsonBuffer jsonBuffer;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("");
  delay(1000);

  //allows serving of files from SPIFFS
  Serial.println("Mounting FS...");
  if (SPIFFS.begin()) {

 if (SPIFFS.exists(fileName)) {

  File subscribedUsersFile = SPIFFS.open(fileName, "r");

  delay(10);

  String file_content = subscribedUsersFile.readString();

  JsonObject& users = jsonBuffer.parseObject(file_content);

           if(users.containsKey("ssid"))          {ssid=users["ssid"].as();}
           if(users.containsKey("pass"))          {pass=users["pass"].as();}

    subscribedUsersFile.close();

    users.prettyPrintTo(Serial);

  }
else  {

   // Create empty file (w+ not working as expect)

   File subscribedUsersFile = SPIFFS.open(fileName, "a+");

   JsonObject& users = jsonBuffer.createObject();

   users.set("ssid", ssid);

   users.set("pass", pass);

  users.printTo(subscribedUsersFile);

  users.printTo(Serial);

  subscribedUsersFile.close();

  Serial.println("New Config File Created...\n");

  users.prettyPrintTo(Serial);

    }

  }
}

Answer could be improved by adding a sentence or two of explanation!!  Please consider.


text:
Working on a simple door lock
this is my first project on an Arduino platform. My aim is to build up a door lock unlockable by playing a short melody on a one-octave piano keyboard. I think the idea is cool!
I'm thinking at everything, but I can't figure out how to make Arduino move something (which in my case would be the proper door lock). I thought about a little motor, but I don't know if it is or not  feasible...
To be clear, what I want to do is a simple door lock like this
(or even simpler) being moved from an Arduino program. How can I do that?

Your question is more about robotics than Arduino. I suggest you post it there: http://robotics.stackexchange.com/

if you need a lock that works w/o power or despite bugs (life safety-level) and with a key, use something like an apartment complex, https://www.amazon.com/Electric-Strike-14C-Extra-Small/dp/B00C0ZENAQ/ref=pd_lpo_60_tr_t_3 , which are pricey, but easy to self-hack. If it's for a hobby or secret compartment, half the fun is engineering something for as close to $0 as possible...

if you don't need to be able to electronically unlock it, you can use a rubber band, a push pin, a piece of iron/steel, some epoxy and one of these electro magnets to get something working. the rubber band pulls back the bolt, the electromagnet keeps it from being pulled back...

You want a solenoid.
Looks like people sell ones which are specifically made for door locks.

Oh, i didn't even know they exist. But I should install it in my door and it's not so viable. I just need something to put ON my door... By the way, thanks for the answer!

I've added a link to the generic type of solenoid, as well as the ones made to function as door locks.  That's what you'll have to do - if you want to move something in an in/out direction, a solenoid is what you want. They come in all shapes and sizes - ones to open car door locks, ones to open gas valves. You'll have to dig around and find the right one for your application, but I hope knowing what it's called will get you started.

Well, sure! I'll search about!

solenoids are unsafe because strong magnets can reach through the door to unlock by sinking the plunger. make sure it doesn't retract w/o power as well.

@dandavis That is true. Anyone could get into your bathroom simply by employing an enormous electromagnet in the other side of the door. Those bolts pictured in the question, however, are widely known to be able to withstand a force equivalent to the weight of six blue wales.


text:
DigiSpark External Oscillator
I am trying to set up a PJON SoftwareBitBang network with a bunch of DigiSparks. My setup works well with any other Arduino devices except the DigiSparks. Based on some internet searching I came to the conclusion that it's because DigiSpark doesn't have a built in oscillator.
I bough a bunch of 16Mhz Crystal Oscillators hoping the internet will help me set them up but I couldn't find any resources on how to do that
Does anyone know any resources on how to use an external oscillator on DigiSpark?
Alternatively, can anyone think of any other reason why SoftwareBitBank goesn't work with Digisparks?
Thanks,
Andi

Is "SoftwareBitBang" a library? I see no reason why bit banging shouldn't work and I think the problem probably is a different layer

SoftwareBigBang does support Attiny85/DigiSpark. It is also possible to add external xtal to Attiny85 with the trade-off of losing two precocious GPIO pins, but you can't just add the external crystal without modifying the firmware of DigiSparks. I think you should focus on why SoftwareBitBang doesn't work.

BTW, did you installed the DigistumpArduino core to your Arduino IDE which defines the pin 1 and 2 that the SoftwareBigBang is looking for to communicate with Attiny85/DigiSpark.


text:
Arduino UTFT Touch align RIGHT with margin
I am using a TFT Touch screen on an Arduino Mega, with UTFT and UTouch libraries.
When I use the code below, the text is aligning to right, all the way to the edge of the screen. Is it possible to give it a margin?
tft.print("Text", RIGHT,12)

Thank you,
Andi

tft.print("Text ", RIGHT,12)

That's interesting workaround. I realise now that I didn't think my question through, because I will also need it with integers. Is there a similar workaround I can do with those?


text:
SimpleChat BLE Example prints scrambled characters
I am trying to use the SimpleChat application to test my RedBearLab Shield.
If I send "Hello" and to to Serial.print or Serial.write the return what I see in my Serial monitor is stuff like "Fh`Fx**-H3r:AJb6# E0CbJ"
Any idea what I'm doing wrong?
Thank you,
Andi Stancu

try changing the baud rate in the serial monitor

That most definitely fixed it! Thank you! Please add it as a solution so I can mark it! Thank you!

If you are transmitting Hello and receiving Fh'Fx**-H3r:AJb6# E0CbJ, then the problem is most likely a baud rate mismatch.
The receiver is sampling the data signal 3 or 4 times faster than it should.
Start by lowering the baud rate of the serial monitor to 1/4 of the current baud rate.
If that does not produce correct data reception, then start at the lowest baud rate and work your way up.


text:
Can't get 433 RF to work
I am trying to have two Arduino's to communicate to each other via 433Mhz units. My project is a bit more complex, but I since it was notworking I reduced it to most basic form in order to exclude the possibility of other issues.
Right now I have to Arduino Mega, a received and a transmiter. I am using the RadioHead library examples, to make sure my code is not to blame.

I am using the example code:
Transmiter:
#include <RH_ASK.h>
#include <SPI.h>

RH_ASK rf_driver;

void setup()
{
    rf_driver.init();
}

void loop()
{
    const char *msg = "Hello World";
    rf_driver.send((uint8_t *)msg, strlen(msg));
    rf_driver.waitPacketSent();
    delay(1000);
}

Receiver:
#include <RH_ASK.h>
#include <SPI.h>

RH_ASK rf_driver;

void setup()
{
    rf_driver.init();
    Serial.begin(9600);
}

void loop()
{
    uint8_t buf[11];
    uint8_t buflen = sizeof(buf);
    if (rf_driver.recv(buf, &buflen))
    {
      Serial.print("Message Received: ");
      Serial.println((char*)buf);
    }
}

Other notes:

It seems the receiver works. I am using RC Switch sniffer and I can sniff other 433 remotes. But nothing coming from the sender

I already tried:

Ordering new radio modules
Variety of libraries: RadioHead, VirtualWire and a bunch of other things found online
Uploading the code with Arduino Create and with Arduino IDE

Any suggestions on that else to try to figure out where I am failing would be greatly appreciated.
Thanks.

You don't need any library to transmit text. You can simply connect the transievers to the respective UART Tx and Rx pins and have the arduinos Serial.print() to each other (it's half duplex, though). Try this to see if the used library is to blame.

If you are using the WL102-341 transmitter, it's operating voltage spec is 2.0 - 3.6VDC.

@VE7JRO that was indeed the problem. On the seller website it specifies it works with anything from 3 to 12, but I moved it from 5 to 3.3 and now it works. Thank you!


text:
handling array from post data on espwebserver
I think I have a supplement question. If irrelevant , then sorry in advance.
I have nested array in post like:  from apache web server page index.php
$_POST['colorsarray'][0] = '#ff0000';
$_POST['colorsarray'][1] = '#2d67ea';
$_POST['colorsarray'][3] = '#7cf325';
$_POST['mode'] = 'none';
$_POST['singlecolour'] = '#ff0000';
Can you suggest me how to assign this array (coloursarray) directly to another array in espwebserver. In other use cases , only the list (length) of array will increase and is not know until the variable arrives from client.
Thanks in advance.

The ability for PHP to do this is special to PHP. The PHP program parses the field names as PHP arrays if they are named thus:
<form ....>
<input name="[colorsarray][0]" value="#ff0000" />
<input name="[colorsarray][1]" value="#2d67ea" />
<input name="[colorsarray][2]" value="#000000" />
<input name="[colorsarray][3]" value="#7cf325" />
[...]
</form>

But since the ESP8266's core doesn't use PHP or understand PHP arrays, you will have to use the literal field name [colorsarray][3], parse it yourself, and determine at run-time the length of the array and how much memory is needed, etc.

Thanks for the help, So I need to take care of the length of array at runtime and have to manually parse the array data. Note: not using form data just using ajax to collect data and send typically array of hex colours.
But cannot change or resolve the array into any other convenient form, so stuck with arrays for now. I had the ultimate resolution as to use indices for the array but was here to be sure that there is not any KISS (keep it simple silly) method available.