text:
How to use AT+CFTRANTX command in SIM7100
I am working on a project using pro mini 8MHz/3.3v and SIM7100, I want to know how can I used AT+CFTRANTX command. I am try to read file from EFS and write to SD card via Serial port. I have get some data in SD but is junk.
My board is Arduino Pro Mini (ATMega 328) 8MHz/3.3 V datasheet (DEV-11114) and Modem is home-made board with SIM7100 module, already test board and module work with all functions without any problem. I’ve added a schematic of the board to the question.
Here is SIM7100 Schematic

Here is SD Module, Pro Mini and SIM7100 pin layout

c:\data2.txt is: A1 to F0
A1A2A3A4A5A6A7A8A9A0B1B2B3B4B5B6B7B8B9B0C1C2C3C4C5C6C7C8C9C0D1D2D3D4D5D6D7D8D9D0E1E2E3E4E5E6E7E8E9E0F1F2F3F4F5F6F7F8F9F0
Any help would be appropriated.
The code that I am using, I tried it with every possible baud rate:
#include <SPI.h>
#include <SD.h>
#include <SoftwareSerial.h>
SoftwareSerial simSerial(7, 6);
File myFile;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ;
  }

  simSerial.begin(9600);
  Serial.print("\nInitializing SD card...");

  if (!SD.begin(10)) {
    Serial.println("\nInitialization failed!");
    while (1);
  }
  Serial.println("\nInitialization done.");
  delay(8000); //For booting SIM7100
  if (SD.exists("1.TXT")) SD.remove("1.TXT");

  myFile = SD.open("1.txt", FILE_WRITE);
  if (myFile) {
    simSerial.println("AT+CFTRANTX=\"c:/data.txt\"");
    while (simSerial.available() > 0) {
      byte voc = simSerial.read();
      myFile.write(voc);
    }
    myFile.close();
    // Serial.println("\nClose done.");
  } else {
    // Serial.println("Error opening 1.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("1.txt");
  if (myFile) {
    Serial.println("1.txt:");
    while (myFile.available()) {
      Serial.print(myFile.read());
    }
    myFile.close();
    Serial.println("\nReading SD Card done.");
  } else {
    Serial.println("Error opening 1.txt");
  }

}

void loop() {

}

Here is test sketch for software & hardware serial.
SoftwareSerial mySerial(7,6); // RX, TX

void setup()
{
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.println("Hardware Serial port!");
  mySerial.begin(9600);
  mySerial.println("AT+CFTRANTX=\"c:/data.txt\"");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

Please attach a description/diagram what is attached where. And is the SD-card-reader part of a Sim7100 shield or extra. If shield which make and type. if extra partswhich parts. And how do you want to write to C:/data.txt on the PC? Make a problem statement what you want to do in logical steps

The "data.txt" coming to EFS via ftp from server, and i want to send this file to SD-card.

When having trouble in getting started with a modem, it's usually best to connect to the modem in "interactive mode", to verify that you're sending the right commands and getting the right responses.
Have you made sure that your modem/module's UART is at the right logic level to interface directly with your Pro Mini? How about the supply voltage? (Post a link to the product). If you're done with all that, then connect only the modem to the Pro Mini:
5V/3.3V -> Vcc (depending on the module's supply voltage)
D6 -> Modem TX
D7 -> Modem RX
Gnd -> Gnd

Then, upload the following to your Pro Mini:
#include <SoftwareSerial.h>

SoftwareSerial fserial(6, 7);

void setup(void)
{
    Serial.begin(57600);
    // I assume this is the default for your modem
    fserial.begin(115200);
    Serial.println("Starting.");
}

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

This should basically transfer everything you send from your Serial Monitor to the modem, and in the reverse, transfer everything the modem sends to your Serial Monitor.
After uploading the sketch, in the Serial Monitor, set the Line Ending at the bottom to Carriage Return. Then you can first send the simple AT and should receive OK from the modem, to confirm that your setup works. Then to test your file reading code, send your command AT+CFTRANTX="c:/data.txt" and see what you get.
If you can confirm this works, writing code to do this automatically should then be much clearer. Or at the very least, you'll have ruled out a whole bunch of possible problems.
(Note: the Arduino may not work reliably with 115200 baud on Software Serial. So you may want to change the modem's baud rate quickly with AT+IPREX=9600. And then modify your sketch accordingly and re-upload.)

@AliMorawej What baud rate do you see when you enter AT+IPR?? Does your command AT+CFTRANTX work from the serial monitor?

@AliMorawej What did you modify exactly? The baud rate?

@AliMorawej So you can now read the data.txt using this test sketch to send the command?

Yes, read on SIM7100 the AT command without any problem, but when I write it to SD is missed up the data, write data A1A2A3...F9F0, and get on SD something like 000000000062480198616224 change data type char and byte nothing get better ...

The Manual v1.02 of Sim7100 with all the commands can be downloaded here
Here is code to test it compiled for UNO without warnings and errors: Please test it and give feedback (read the comments to get the flow of code) Test with  the RX/TX of the Sim7100 to pins 4/5 (Software Serial and the Sim7100 to baud rate 9600):
#include <SPI.h>
#include <SD.h>

#include <SoftwareSerial.h>

#define SD_ChipSelectPin 10

SoftwareSerial simSerial(5, 6); // RX, TX to TX RX of the SIM7100 module
//#define simSerial Serial
char receiveArray[256] = {'\0'};
void readSerialPort(uint8_t);
uint8_t counter = 0;

void setup() {
   Serial.begin(57600);
    while (!Serial) {
     ;
    }
  simSerial.begin(9600); // using HW Serial on a Pro Mini
  while (!simSerial) {
    ;
  }

  simSerial.println("AT+IPR=9600"); // set sim7100 to same serial speed
  delay(1000);
  simSerial.flush();   // Flush buffer

  SD.begin(SD_ChipSelectPin);
  if (!SD.begin(SD_ChipSelectPin)) {
    //Serial.println("Error opening SD-card");
    return;
  }
  delay(1000);
  if (SD.exists("1.TXT")) SD.remove("1.TXT");
  delay(1000);
}

void loop() {

  if (counter < 3) {
    File saveFile = SD.open("1.TXT", FILE_WRITE);
    if (saveFile) {
      // This has to be the Serial the SIM7100 is attached to
      simSerial.println("AT+CFTRANTX=\"c:/data.txt\"\r");
      while (!simSerial.available()) {} // wait for data to arrive

        readSerialPort(0);

      saveFile.close();

      // Serial.println("Success creating file");
    } else {
      // Serial.println("Error creating file");
    }
    counter++;
  }
}

/* For a first test we print everything to 1.txt -
  there will be "garbagge" as the AT response in it -
  we can "clean" in a later  by using the intermediate array or the counter */
void readSerialPort(uint8_t startIndex = 0) {
  uint16_t i = 0;   // counter and we want later to filter the first X chars
  while (simSerial.available() > 0) {
    char inChar = simSerial.read();
    if (i >= startIndex) { // if we want to filter the first 16 chars it would be i>=16 (as it starts with 0)
      if (inChar == '\n') {
        receiveArray[i] = '\0'; // terminate the array
        return;
      }
      if (inChar != '\r') {
        receiveArray[i] = inChar;
        i++;
      }
    }
  }
}

The code waits now for the modem to respond

Tried the code is return blank SD Card.

I have rewiring my board and change my data file as above and test the way @ TisteAndii  guide me in code above, I got right data in Serial  with AT+CFTRANTX="c:/data.txt, but get junk like 000000000062480198616224 on SD Card. My hardware setup and wiring okay now, maybe i help again get he right format on SD Card.

Can you post the last working code in your question? Of course I'll help you

I already update codes and sample data2.txt, i have change from 1 to 100, to A1A2 up to F9F0, I was looking at how change my data format on SD, I have test with char and byte nothing change much. but I am sure wiring and SoftwareSerial (7, 6) working correct now.

use my function readSerialPort() from my answer and the according changes to the program (define char array, change loop)

I done as you said, but nothing change and my SD Crad is shows empty 1.txt.


text:
Pushbutton and switch case follow up question
PROBLEM STATEMENT:

A circuit is measuring various parameters (Temperature, Humidity,
etc.) through sensors connected to it continuously.
When a Push Button is Pressed and Hold for 2 seconds in between the Arduino should enter into Setup mode.(I have used IF loop and
millis() function to achieve this )
In Setup mode there are 6 screens which will appear one after one.
Once Arduino enters into Setup mode Switch case 0 (screen1) should appear (I have used serial monitor for the same).
Now if I press the same push button and released within a moment the next Switch case 1 (screen2) should appear.
Step 5 will be repeated till Switch case 5 (screen6).
After Switch case 5 the loop rolls over to Switch case 0 (SCREEN1) then Switch case 1, Switch case 2, so on.
If in between above Switch Case loop Push Button is Presses and Hold for 2 seconds the Switch case loop must get terminated and the
Arduino should go back to MAIN LOOP() where it is measuring the
sensor parameter.
Again if the push button is Pressed and Hold for 2 seconds in between sensing process the Arduino should enter into Setup mode.

CONSIDERATIONS:

Push Button is connected to Pin2 of Arduino (ACTIVE LOW)
The input at Pin2 is considered as interrupt so that Arduino provides service to any moment of the time.
Arduino serial monitor is used to demo the Screen1-Screen6 as output.
0.1uf Capacitor is used across the Push Button for debounce considerations. And 10K, 0.25W resistor is connected from VCC to Pin
no.2
The code for sensing parameters (Temperature, Humidity, etc.) is yet to be written.

ACHIEVEMENT:
Upto Point No. 7 of PROBLEM STATEMENT the code is working fine.
BUG:
If I press Push Button for 2 seconds in SWITCH CASE loop, Arduino is going out of the SWITCH CASE and going into MAIN LOOP() but again coming back to SWITCH CASE() loop.
It should ask again to press Push Button for 2 Seconds to enter into Setup Mode.
const int btn = 2;
const int ledPin =  13;
int selector = 0;
boolean  volatile wait = false;
const unsigned long event=2000;
unsigned long previous1=0;
unsigned long current1=0;
unsigned long sum1=0;
unsigned long previous2=0;
unsigned long current2=0;
unsigned long sum2=0;
bool buttonPress = false;
void setup()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(btn, INPUT);
attachInterrupt(digitalPinToInterrupt(btn),decoder,CHANGE);
}

void loop()
{
  if (digitalRead(btn) ==LOW && !buttonPress)
  {
    previous1 = millis();
    buttonPress = true;
  }
  else if (digitalRead(btn) == HIGH && buttonPress)
  {
    current1 = millis();
    sum1=current1-previous1;
    Serial.println(sum1);
    Serial.println("SUM1");
    if (sum1>=event)

       {  BREAK1:
          doSwitchCase();
          selector++;
          goto BREAK1;
          if (selector >6)
              {
                  selector = 0;
                  delay(500);
              }
        }
        buttonPress = false;
  }
  wait = true;
  interrupts();

}

void decoder()
{
 noInterrupts();
 wait = false;
}

void doSwitchCase()
{
  switch(selector)
  {
  case 0:
    Serial.println("SCREEN1");
    while (digitalRead(btn)!=LOW) ;
    previous2 =millis();
    while (digitalRead(btn)!=HIGH) ;
    current2=millis();
    sum2=current2-previous2;
        if(sum2>=event)
        {
         Serial.println(sum2);
         loop();
        }
    break;

  case 1:
    Serial.println("SCREEN2");
    while (digitalRead(btn)!=LOW) ;
    previous2 =millis();
    while (digitalRead(btn)!=HIGH) ;
    current2=millis();
    sum2=current2-previous2;
        if(sum2>=event)
        {
         Serial.println(sum2);
         loop();
        }
    break;

  case 2:
   Serial.println("SCREEN3");
    while (digitalRead(btn)!=LOW) ;
    previous2 =millis();
    while (digitalRead(btn)!=HIGH) ;
    current2=millis();
    sum2=current2-previous2;
        if(sum2>=event)
        {
         Serial.println(sum2);
         loop();
        }
   break;

  case 3:
   Serial.println("SCREEN4");
    while (digitalRead(btn)!=LOW) ;
    previous2 =millis();
    while (digitalRead(btn)!=HIGH) ;
    current2=millis();
    sum2=current2-previous2;
        if(sum2>=event)
        {
         Serial.println(sum2);
         loop();
        }
   break;

  case 4:
   Serial.println("SCREEN5");
    while (digitalRead(btn)!=LOW) ;
    previous2 =millis();
    while (digitalRead(btn)!=HIGH) ;
    current2=millis();
    sum2=current2-previous2;
        if(sum2>=event)
        {
         Serial.println(sum2);
         loop();
        }
   break;

  case 5:
  Serial.println("SCREEN6");
    while (digitalRead(btn)!=LOW) ;
    previous2 =millis();
    while (digitalRead(btn)!=HIGH) ;
    current2=millis();
    sum2=current2-previous2;
        if(sum2>=event)
        {
         Serial.println(sum2);
         loop();
        }
  break;
  }
}

One note before NEVER use goto in C++ its bad style and makes in an object oriented language to 99.9% no sense. To enter the switch case after a2 second press you have just to enter one statement t omy original proposal.I did not read your code as it gets unreadable the more functionality you want to add. Think about refactoring it or you will run out of luck to get help (as nobody tortues himself with caotic code of others:
const int btn = 2;
const int ledPin =  13;
int selector = 0;
const unsigned long buttonPressLong = 2000;  // 2 seconds
const unsigned long buttonPressShort = 250;  // 0.25 secondis feasable
const unsigned long buttonPressDebounce = 50;  // debouncing for too short presse Thanks Edgar Bonet
unsigned long buttonPressStart = 0;

bool buttonPress = false;
bool inMenu = false;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(btn, INPUT);
  }

void loop() {
  if (digitalRead(btn) == LOW && !buttonPress ) {
    buttonPressStart = millis();
    buttonPress = true;
  }
  // The routine is only triggered if a previous pressing took place, otherwise it's ignored
  else if (digitalRead(btn) == HIGH && buttonPress) {
    if (millis() - buttonPressStart > buttonPressLong && millis() - buttonPressStart > buttonPressDebounce && inMenu) {
      Serial.print("Long press: ");
      Serial.println(millis() - buttonPressStart);
      buttonPress = false;
      inMenu = false;
    }
    if (millis() - buttonPressStart < buttonPressLong && millis() - buttonPressStart > buttonPressDebounce && !inMenu) {    // HERE IS A CHANGE
      Serial.print("First long press ");    // HERE IS A CHANGE
      inMenu = true;
    }
    if (millis() - buttonPressStart < buttonPressShort && millis() - buttonPressStart > buttonPressDebounce && inMenu) {
      Serial.print("Short press: ");
      Serial.println(millis() - buttonPressStart);
      doSwitchStatement();
      selector++;
      if (selector > 6) {
        selector = 0;
        delay(500);
      }
      buttonPress = false;
    }
  }
  // Here you could do other stuff as it is non blocking
}
doSwitchStatement(){...}// Stays the same as yours

I just changed 1 statement (and 1 debug msg) to achieve what you want see // HERE IS A CHANGE

source: Stack Exchange

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

sort: votes


text:
ADC value changing after changing Timer1 value in program
I'm writing a code where analogRead() reads ADC value from load. After reading ADC value, if it is not in range, I need to manipulate Timer1 value. Which is also getting changed.
But, after changing the Timer value,  if the load value again gets restored, ADC doesn't show the same value again, but shows some other value.
Please refer below code:
#include <TimerOne.h>

int LED = 13;
int IN0 = 12;
int IN1 = 11;
int OUT1 = 10;
int OUT2 = 9;
int OUT3 = 8;
int OUT4 = 7;
//float A0;
//int OUT5 = 6;
const float refvolt = 5.0;
int volts = 0;
byte tempL_flag = 0;
float samples, loadval, avgacs, acsvaluef =0;
float refval = 2.0;
bool lflag=0;
unsigned long count = 0;

void setup()
{
    pinMode(IN0, INPUT);
    pinMode(IN1, INPUT);
    pinMode(OUT1, OUTPUT);
    pinMode(OUT2, OUTPUT);
    pinMode(OUT3, OUTPUT);
    pinMode(OUT4, OUTPUT);
    pinMode(LED, OUTPUT);
    pinMode(A0, INPUT);
    //digitalWrite(OUT3, LOW);
    Timer1.initialize(370000);
    Serial.begin(9600);
}

word ADC_READ(byte sample, byte tim, byte CH)
{
    word adcdata;
    word avrdata;
    word abcdata;
    byte i;

    for(i=0; i<sample; i++)
    {
        adcdata = 0;
        adcdata = analogRead(CH);
        avrdata = avrdata + adcdata;
        delay(tim);
    }
    return(avrdata/sample);
}

void flash_L()
{
    digitalWrite(LED, !digitalRead(LED));
    digitalWrite(OUT4, !digitalRead(OUT4));

    if (digitalRead(OUT4)==1)
    {
        loadval = ADC_READ(10, 10, A5);
        Serial.println(loadval);

        if(loadval < refval)
        {
            Timer1.initialize(185000);
        }
        else
        {
            tempL_flag = 1;
        }
        return;
    }
}

void loop() {

    delay(2000);

    if(digitalRead(IN0)==1)
    {
        Timer1.attachInterrupt(flash_L);
    }
    else if(digitalRead(IN0)==0)
    {
        digitalWrite(LED, LOW);
        digitalWrite(OUT4, LOW);
    }
}

how many times do you want to attach the same interrupt? It starts counitng again at attach. Put attachInterrupt in setup(). And I wouldn't read ADC in interrupt.

Only when input is read, Interrupt is generated. Yes there is ADC in interrupt , I've written a function for sampling. loadval = ADC_READ(10, 10, A5);

I don't see why would be IN0 HIGH only one loop of the loop(). And you never detach the interrupt or set it back to 370000

Let me explain. If high gets to IN0, Timer will be at 370000. Timer Interrupt will occur.  It will read ADC on load. If load is in range 370000 will continue. If not,  185000. But after load is out of range and Timer is at 185000, if load is restored, timer should be back at 370000. But even if load is restored, ADC value changes and is not same as in previous case, So I cannot jump back to 370000. Hope it is clear now.

"If high gets to IN0, Timer will be at 370000." how? "Timer Interrupt will occur" and will do what? the function is not attached to interrupt yet.

@Juraj sir, if you refer code, in setup() timer has been initialized to 370000. IN0 will be high by external switch. You can see in loop(), if IN0 is high, interrupt is attached flash_L is ISR. In ISR LED and Bulb are toggeled. If this doesn't answer your qstn. I think I'm not getting your qstn

IN0 is HIGH, the interrupt gets attached. at next 370000 micros multiple it fires  and from then it fires always again at next 370000 or 185000 microseconds

@Juraj I think I'm unable to understand what you are saying. I'm not getting your question. 370000 will only change to 185000 if load is not in range. If load is back in range after distortion, I'm not getting the same value of ADC that showed before it distorted.

do you understand that the set timer value of TimerOne is a period at which the attached function will be called repeatedly? so you want to attach the interrupt in setup() or detach it in interrupt. do you want it run repeatedly or as one shot?

@Juraj yes i do understand. That means after 370000 microseconds interuupt will be called and I need to write ISR for that. You can see in setup(), I've initialized the timer. in loop the interrupt (flash_L) has been called. after IN0 is high. yes I want to run it repeatedly every time the IN0 is high.

it will run always after next period, once attached. and it will not run 300000 after you attached it. it will run 300000 micros after you initialized the period. so the logic of your sketch doesn't make sense, because you don't understand how TimerOne library works

https://www.pjrc.com/teensy/td_libs_TimerOne.html

OP keeps talking about it getting set back to 370000 but I don't see anywhere in the code where that happens.  Once it gets set to 185000 it will always stay there no matter the load.

@Delta_G yes in code its nowhere getting back to 185000 bcz once load is restored, ADC value not getting back. So I haven't written that part of code. My main aim is to get ADC value restored then need to change timer value

@Juraj Okay thanks for your help. But doing this timer thing right will give correct ADC values? Help me in that if timer and ADC are linked likewise

@Juraj I tried your suggestion, and studies the link you shared. Then initialized timer after IN0 high and YES!! its done. Thank you soo much. :)

ADC doesn't show the same value again

You are not reading the ADC correctly, so ADC_READ() can return
anything. See the comments in the code:
word ADC_READ(byte sample, byte tim, byte CH)
{
    word adcdata;  // not needed
    word avrdata;  // not initialized
    word abcdata;  // not used
    byte i;
    for (i = 0; i < sample; i++)
    {
        adcdata = 0;  // useless
        adcdata = analogRead(CH);
        avrdata = avrdata + adcdata;
        delay(tim);
    }
    return (avrdata/sample);
}

The big issue is avrdata not being initialized. Its initial value is
whatever was left there (in the stack or some CPU registers) by the code
that ran before. The value returned by the function is then hard to
predict and depends on what the rest of the program is doing.
The other remarks I left in the comments are not that problematic,
although they are revealing of some lack of attention to detail. Same
for some badly named variables. Here is how I would implement this
function:
word ADC_READ(byte samples, byte time, byte channel)
{
    word sum = 0;
    for (int i = 0; i < samples; i++)
    {
        sum += analogRead(channel);
        delay(time);
    }
    return sum/samples;
}

Sir, I will try you suggestion. thank you

its not working sir, I tried your code. I think its having problem with timer and ADC function jumping back to 370000 from 185000

@HrishikeshDixit: I am not addressing the timer issue. I am just showing you how to correctly average ADC readings, which the program you posted doesn't do.

Sir, thanks for the suggestion, it did save variable and some lines of code. Thank you!

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


text:
How to find the time of any point on the graph on an Arduino serial plotter or Processing software?
I am plotting the graph of some sensor values on my Arduino serial plotter which looks something like this -
But what I want to do is hover over any point on the graph and display the time at that point. Is there any way to do that, if not with Arduino serial plotter, with Processing? Or any other tool is fine too. Thanks.

The Arduino Serial Plotter is not meant for this. It just directly draws, what you send. You can solve this in processing, by calculating the time from the number of the current sample (which is what you see on the x axis in your plot) via the used sampling rate.

Can I use the system time for this? I just want to find the difference between the time period of each crest or trough of the blue and red waveforms respectively. I have done it using my code but I want to verify it graphically.

What do you mean by "the system"? You want to plot the data on your PC. Processing is a tool, that is made for such situations. The difference between the plot above and what you want is just a simple factor multiplied to the x axis value: the sampling rate

why do you need system time? ... you said that you want to determine a time interval between two points

I just want to find the difference between the time period of each crest Arduino can do that for you as well

@DataFiddler >I have done it using my code but I want to verify it graphically.. I think his goal is to have a graphical useable plotter.


text:
How to generate 3 PWM signals
I have 2560 mega, and I Want to generate 3-phase PWM signal at 62.5khz, synced and shifted 120 degrees apart.
I need that for 3-phase split-coil boost converter (or even isolated flyback converter), with 3 phase transformer coupled inductor. So I dont need sine wave table like here, but actually, a direct square wave PWM output, from 3 synced digital pins, with chosen duty cycle. How can I do that?

How accurate the phase difference has to be? Is (0°, ±119.53°) good enough? If not, would a frequency of 62.745 kHz be OK? What duty cycle do you want?

@EdgarBonet  Hello. Probably, its better to stick with 2 phase or 4 phase, as it's easier to divide. Oh, and let's omit 2phase case, as it could be solved with h/w inverting (no software phase offset). All I want is a way to set up a phase offset in arduino, and question is about it. Everything other better fits as a topics for ee.se. Consider it is driving a transistors' gates, (no matter what is further), to focus only software question

If you have any timers left, I would (regardless of the number of PWM signals and if you need different PWM frequencies) just dedicate a timer to do IRQs to manage them.
The frequency of the IRQs would then depend on how accurately you want to control the duty cycle, ref. also to the comment from Edgar Bonet .

That seems to be nice solution. However, I am not very familiar with low level things of  arduino. Can you extend your answer with simple small example, please? It could be as simple as if you given 4 pins: pin[0,1,2,3], and 4 duty cycles: dc[0,1,2,3]. Frequency is fixed at 62.5khz (or 31khz, not matters), and pins must provide synced PWM signal, with given dutycycles, and phase offsets of 0, 90, 180 and 270 degrees respectively. Like for(i=0; i<4; i++) { analogWrite(pin[i], dc[i]); }, but for synced pins.  Can you give such how to sync pins, with fixed phase offsets and frequency??

Wow, hang on. Will try to write more later, but I mean that if e.g. 4 signals 90 degs apart all with 50% duty cycle, one would set a time at 8 times the frequency (not 4 since for a single 50% you need both the "LOW-to-HIGH" and "HIGH-to-LOW".Then depending on the duty cycle resolution/accuracy needs, one needs to increase the IRQ frequency (which above was the base frequency*8). Programming Arduino is like C, so operators like % (don't know the term in English, but I mean e.g. 107%100=7) come handy.


text:
My LED toggeling doesn't work the way I want
I want to do LED toggeling so I wrote this:
int led=13, button=12;

void setup()
{
    // put your setup code here, to run once:
    pinMode(led,OUTPUT);
    pinMode(button,INPUT);
}

void loop()
{
    // put your main code here, to run repeatedly:
    if(digitalRead(button)==HIGH && digitalRead(led)==LOW)
    {
        digitalWrite(led,HIGH);
    }

    if(digitalRead(button)==HIGH && digitalRead(led)==HIGH)
    {
        digitalWrite(led,LOW);
    }
}

But It doesn't work well, sometimes I need to press the button many times in order to turn on or of...and some times with just one press.
I saw this video but I didn't understand it well:
https://www.youtube.com/watch?v=aMato4olzi8&t=415s
Anyway I don't know why my way doesn't work well.

One word: bounce.

I want to do LED toggeling ... you did not explain how you want the program to function

you fail to realize that loop() repeats 10000 times per second .... you are checking if the button is being pressed, which happens over and over .... you need to wait for the transition between "not pressed" and "pressed" .... that happens only once when you press the button

nice...that helped...thnx

yes right so at the second when button is pressed it tries to make LED on and off the same second

There are a few problems with your approach.

You seem to have the button backwards.  You should wire a button so that it is between the pin and ground.  This way it should read LOW when pressed, not HIGH.  It should also have pinMode(pin, INPUT_PULLUP) instead of INPUT.  With the button wired the way you have it to read HIGH then you will need an extra resistor for each button.  With it wired the right way where it reads LOW then it needs nothing extra.
If the first if statement is true and the button is pressed and it turns on the led, what do you think are the chances that you are fast enough to get your finger off the button in the 62.5 nanoseconds it takes to get to that next if statement?   It's not going to happen, so the button is still pressed there and now the led is on so this line turns it right back off.  Only in the rare case where you happen to get your finger off the button at just the right instant will the led stay lit.  To solve this, look at the "State Change Example" that comes with the IDE.  It shows how to keep track of the last state of the button in a variable so you can act only once when the button actually changes state.
Once you get that worked out you will notice that it seems like for every time you press your button it registers tens of presses.  This is switch bounce.  That's a term you should google.  The contacts are making and breaking contact really fast in the in-between pushed and not-pushed state.  But you need to get the first two issues solved before you worry about bounce.

nice...that helped...thnx

I checked the state change example, but I didnt get why the delay for bounce is used in that specific place ? why to set lastButtonState = buttonState; since button state will anyway return to 0 when button is released , any lastButtonState was 0 anyway..so there is no change in it?

You do that so you can tell when the state changed from on loop to the next.

So the little 50ms delay is there to catch switch bounce.   Do you know what switch bounce is?  When you press a button there is a small period of time where the contacts are almost made and they sort of make and then break and then make and break over and over as they're coming closer together and almost touching.  Then once they touch all the way closed they're closed.  Same thing happens as the switch just starts to open.  So you put a little delay there so that you miss all those rapid changes.

You are right that buttonState will have a 0 when released, but it will have a 1 when pressed.  So the button is not pressed and buttonState and lastButtonState are both 0.  Then you press down the button.  When the button is read now it's HIGH, but lastButtonState is still LOW, now we've detected a change of state.  So we can take some action.  The next time through the button still reads HIGH, but lastButtonState is now also HIGH because we set it to match buttonState at the end of loop.  So nothing happens since they are the same.

And now we are reacting only to the change of state, not constantly doing something as long as the button if HIGH.  That lets us have something happen once per press.
We only react when it first gets pressed.  When you release the button it reads and gets a LOW but lastButtonState is still HIGH, so you can react once to the release if you want and then at the end of loop lastButtonState gets set to buttonState which is LOW now and once again they match.  Once again we have detected the change from HIGH to LOW.

thank you so much...yes got it

so in the example the delay to avoid bouncing is where the if condition is finished....but the bouncing happens when once pressing and once releasing the button, so  to avoid bouncing why is written only out of if and not like this if (buttonState == HIGH)  delay (50)  so it can wait the button to be stable before turning led to on ?

You’re not waiting for the button to be stable.  You’re just taking some time to not read it.  So if the button was low and is now high you know it got pressed.  You can react at that point.  You don’t need to wait until it stops bouncing to react to that.  You need to wait until it stops bouncing to react to anything else, and that’s why we take 50ms off.

Keep in mind that delay isn’t actually about debounce.  It doesn’t do that.  It’s just a hack so you don’t see the bounce.  If you only read a button once every 50 ms you’ll never see it bounce.

aha..ok.. the delay is for reading the button and not to do the digitalwrite, you said above  if the button was low and is now high you know it got pressed. You can react at that point. You don’t need to wait until it stops bouncing to react to that. but in this case the reaction isn't wrong ? because bouncing is a random series of 0 and 1 before the real 1 comes..so the Programm will react to this serie ? or not ?

It just reacts to the first HIGH that it gets.  It doesn’t matter that there is a bunch of bounce behind that.  There’s no other reason you’d be reading HIGH except someone pressed the button.

achso..yes now its clear... thank you so much


text:
Arduino Uno SD card storage
I am interested in storing accelerometer data to an SD card. Since power consumption is the main consideration of my project, it is important to do as few writes to the SD as possible, because the SD requires much current, and also takes long to be written, keeping my MCU from sleeping.

The data to be stored are about 50 bits of data at 10Hz, so I need to store 500c bits per second, or around 63 bytes per second. The arduino uno EEPROM is 1024 bytes, which could give me around 16 seconds of data stored before having to access my SD card. However I have seen that the EEPROM has limited write cycles (100000). So each byte can be written 100000 times, which gives us a total of 1000*100000=100000000 bytes to be written.As a result, with writing there 63 bytes per second, that would give me 1587301 seconds=441hours=18days of EEPROM lifetime, which is unacceptable. Is this correct?
If (1) is correct and using internal eeprom is not a possible solution, what other recommendations do you have? Is there an alternative to SD storage, that requires less power and less writing time, so that it is cheaper power-wise? The total storage should be around 200MB.

Why do you want to use EEPROM? Why not just a simple buffer array?

@chrisl It is a good idea, on what memory would the buffer array be stored, though?

The buffer would be stored in RAM. Normally EEPROM is only used, when you need persistent storage, which keeps the values over power cycles or resets. But that doesn't seem to be the case for you. Though you still need to see, how big you can make the buffer (that depends on the memory and library usage of your sketch)

Regarding 1, it's true that EEPROM has limited write cycles. Mostly it can be much more, but it's only guaranteed upto that number, so I can imagine you don't want taking the risk to be lucky.
Regarding 2, other solutions could be external SRAM, which can be much more than just 1 KB, but also adds some extra components, thus cost and more important power. When that SRAM is full (can be many KBs), you can transfer it to the SD card.
Another (added) improvement you might think of (if you did not already) is data compression (trying to store the 50 bits in less bits), but this will cost some 'computing' power.

To start with power consumption rules an Arduino UNO out so you will need some device capable of (deep) sleep mode. Devices like ESP8266 or ESP32. The table below shows the differences between each mode (information from the ESP8266 datasheet).
Item                 Modem-sleep        Light-sleep       Deep-sleep
Wi-Fi                   OFF          OFF            OFF
System clock             ON         OFF             OFF
RTC                     ON          ON              ON
CPU                     ON          Pending         OFF
Substrate current     15 mA        0.4 mA          ~20 uA
Avg. current (DTIM = 1) 16.2 mA     1.8 mA            –
Avg. current (DTIM = 3) 15.4 mA     0.9 mA            –
Avg.current (DTIM = 10) 15.2 mA     0.55 mA

These modules have around 4MB flash which yoi could use for storage of data (SPIFFS/LittleFS) so 1MB for programs and 3MB for on board storage, after that you save to SD and fill up the onboard FS again or you send the data via WLAN to an online storage or database or to a server in your network (depending on your scenario) These devices cost as much as an Arduino UNO clone (5-7$) and can be programmed with the same IDEs as Arduinos and in the same (extern C/)C++ derivate. So if power consumption is an issue look at those IoT devices

An Uno can, however, be slept at something like < 10uA, though, using LowPower. I agree that an ESP would be a better choice just because of storage and RAM, but Arduinos can sip when they need to!


text:
Generate 5VDC signal when external sensor input changes from high to low
I am new to arduino.  I have a project in which I need an arduino to generate a +5VDC  signal in response to a change of status, (high/5VDC To low/ground) from an external source.
The external source is a stand alone receiver/transmitter set which outputs +5VDC when the transmitter is out of range and ground when the transmitter is within range.
The goal is to have the arduino output +5VDC (triggering a series of events) only when the TX is within range of the RX (signal voltage is GRND vs. +5vDC).  The series of events are controlled via a stand alone event controller which is initiated by a +5VDC signal courtesy of the arduino.
I already have a RX/TX set which outputs +5VDC when the the TX is absent and GROUND when the TX is within range.  I also have the event controller.  I only need the arduino solution.
I have an arduino UNO but I am open to other option if needed.
Solution: give me +5VDC when signal voltage (from receiver) is low (ground).
If anyone could point me in the right direction it would be greatly appreciated.  This is my first arduino project so I have much to learn.
Best regards

This is literally the simplest Arduino program possible.  I can't believe you couldn't find an example of making one pin HIGH when another goes LOW.
void setup(){
  pinMode(yourInputPin, INPUT_PULLUP);
  pinMode(yourOutputPin, OUTPUT);
}

void loop(){
  if(digitalRead(yourInputPin) == LOW){
     digitalWrite(youOutputPin, HIGH);
  }
  else {
     digitalWrite(yourOutputPin, LOW);
  }
}

All you need to do is supply the appropriate pin numbers.

Why waste an Arduino on such a paltry job?  Here's a circuit that has just 3  components in it that does what you want:

simulate this circuit – Schematic created using CircuitLab
It's basically a NOT gate (you can use an actual NOT gate, like a 74HC04 if you like) where the output is the opposite of the input.  You could even remove R2 if you like - that just prevents the input floating when there's no valid signal detected.
This form of gate is called RTL - Resistor-Transistor Logic, and is one of the simplest logic gate arrangements there is.


text:
Node.js cannot recognize characters from the serial port
The following script prints everything fine, it recognizes integers from the serial port, but cannot recognize characters.  The if statement does not work with characters.  I have tried both == and === in the if statement
var SerialPort = require('serialport')
var Readline = SerialPort.parsers.Readline
var serialPort = new SerialPort('/dev/ttyAMA0', {//ttyAMA0
  baudRate: 9600
})

var parser = new Readline()
serialPort.pipe(parser)
parser.on('data', function (data) {
if(data === 'c'){/// c is not recognized
  console.log('data received: ' + data)
}

})
serialPort.on('open', function () {
  console.log('Communication is on!')
})

The Arduino code is as follows:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(12, 13); // RX, TX
int x = 0;
int y = -30000;
int z = 0;
String data;
char command = 'q';
int left = 0;
int right = 0;
int left_pwm = 0;
int right_pwm = 0;

void setup() {
  mySerial.begin(9600);     // opens serial port, sets data rate to 9600 bps
  Serial.begin(9600);
  }
void loop() {//map and compass data
if (y==30000) {
 mySerial.println('c');
 delay(5);
 mySerial.println(299);
 delay(5);
 z = -25000;
 }

 if(z==30000){
 mySerial.println('lon');
 delay(5);
  mySerial.println(529);
  delay(5);
  mySerial.println('lat');
 delay(5);
   mySerial.println(522);
          y = -30000;
    }
  y++; z++;

  if (!mySerial.available()) {
    return;
  }

  data = mySerial.readString();
   sscanf(data.c_str(), "%c%01d%01d%03d,%03d", &command, &left, &right, &left_pwm, &right_pwm);

  if (command == 'n') { // we got a navigation command
    // update the GPIO accordingly, this only happens once after a new 'n' command has been received
    Serial.print(command);
    Serial.print(left);
    Serial.print(right);
    Serial.print(left_pwm);
    Serial.print(",");
    Serial.println(right_pwm);
    }

    }////end loop

why is this command not before the if statement? console.log('data received: ' + data)

Have you tried trimming data from all white space?

@jsotola  Console Log is telling me the if statement is not working.

@chrisl   data = data.trim();  Bingo,   Thanks!

@HarryHobson, console log inside the if statement is preventing you from seeing what data is being received ... it is a poor debugging procedure

If you use the line parser in Nodejs, it does not remove all line ending characters. I think (though I currently cannot cite it), that only the 'ņ' character is removed from the string. But Serial.println() sends "\r\n" as line ending. That means, that your string is "c\r", which is not equal to "c".
By using the trim() method of the String type, you can remove all white space from start and end of the string, including line ending characters like '\r'.


text:
STM32 and SDFat - Can't create file in directory in SD
I'm using the SdFat.h library on a STM32 and I can successfully create a file in the root directory using SD.open("test.txt", FILE_WRITE); but my code fails to create SD.open("DATA/data_test.txt", FILE_WRITE); in a directory.
Here's the piece of code that successfully creates a file in the root:
String final_book_name = upload_book_name + ".txt";
if (SD.exists(final_book_name.c_str())) {
  SD.remove(final_book_name.c_str());
}
tft.println(final_book_name); // This successfully prints "test.txt"
book_file = SD.open(final_book_name, FILE_WRITE);
if (SD.exists(final_book_name.c_str())) {
  tft.print("Created file");
} else {
  tft.print("Failed to create/replace\nfile!");
}

and here's the piece of the code that fails to create a file in a directory:
if (!SD.exists(DATA_DIR)) {
  SD.mkdir(DATA_DIR);
}
String final_book_name = upload_book_name + ".txt";
String book_data_path = DATA_DIR;
book_data_path += "/data_" + final_book_name;
if (SD.exists(book_data_path.c_str())) {
  SD.remove(book_data_path.c_str());
}
tft.println(book_data_path); // This successfully prints "DATA/data_test.txt"
File book_data_file = SD.open(book_data_path, FILE_WRITE);
if (SD.exists(book_data_path.c_str())) {
  book_data_file.print(upload_book_font);
  book_data_file.print("|");
  book_data_file.print("0");
  book_data_file.close();
} else{
  tft.print("Failed to create/replace\ndata file!");
  if (SD.exists(final_book_name.c_str())) {
    SD.remove(final_book_name.c_str());
  }
}

Try it with /DATA/test.txt I remember SD library uses the classic 8.3 filenames and data_test.txt is invalid

@DataFiddler I'm using SdFat.h with Long Names (which allows names up to 255 characters)

I found the issue. I'm not creating the directory folder properly. When I checked the SD card from another device, the DATA folder was invalid, and creating it manually works. I'll look for a solution and post an update.
UPDATE: https://forum.arduino.cc/index.php?topic=421131.0 I'll try this tomorrow but it'll probably fix the issue.

As you have given no variable for DATA_DIR
String book_data_path = DATA_DIR;
book_data_path += "/data_" + final_book_name;

so your resulting path looks like
DATA_DIR + "/data_" + final_book_name

IF DATA_DIR = "/" then it would be "/" + "/data_" + final_book_name
As tip do not use the string class but char arrays
definition
 const char[] DATA_DIR = "/books";
 char book_data_path [128] = {'\0'};
 char final_book_name [13] =  {'\0'}; // IF no LFN support is used its 8.3 !!!
 const char upload_book_name[] = "my_book";
 strcpy (final_book_name, upload_book_name);
 strcat (final_book_name, ".txt");
 Serial.println(final_book_name);

If you want long filr namesupport us SDFat library or enable LFB withSD lib (whichneeds about 35% ,ore memory as SDfat (when using long file names).
EDITAs you are using SDFat and I do not know which version/fork there is abug with writing to subdirectories. Please check the following:
To check run the SdFat\examples\DirectoryFunctions and watch your serial monitor for the results
SdFile.cpp. At line 782 and 1452, you have (in my version):
if (block <= m_vol->cacheBlockNumber()
  && block < (m_vol->cacheBlockNumber() + nb)) {

The working code has:
if (m_vol->cacheBlockNumber() <= block
  && block < (m_vol->cacheBlockNumber() + nBlock)) {

If you have the upper version change it and it should work
EDIT 2 Work around for buggy SDFat lib
Here is a workaround code
const char DATA_DIR [] = "data";
char final_book_name[128] ={'\0'};
char book_data_path [256] ={'\0'};

if (!SD.exists(DATA_DIR)) {
  SD.mkdir(DATA_DIR);
  SD.chdir(DATA_DIR);
}

strcpy (final_book_name, upload_book_name);
 strcat (final_book_name, ".txt";
String book_data_path = DATA_DIR;

strcpy(book_data_path, "data_");
strcat(book_data_path, final_book_name);

if (SD.exists(book_data_path)) {
  SD.remove(book_data_path);
}
SD.mkdir(book_data_path);
SD.chdir(book_data_path);

tft.println(DATA_DIR);
tft.println(book_data_path); // This successfully prints "DATA/data_test.txt"
File book_data_file = SD.open(final_book_name, FILE_WRITE);
if (SD.exists(final_book_name)) {
  book_data_file.print(upload_book_font);
  book_data_file.print("|");
  book_data_file.print("0");
  book_data_file.close();
} else{
  tft.print("Failed to create/replace\ndata file!");
  if (SD.exists(final_book_name)) {
    SD.remove(final_book_name);
  }
}

DATA_DIR is "DATA". I don't see the solution in your answer. I will make my Strings to characters, that's a good idea but what about my main issue here?

Sorry, it's still unclear to me what I should do. I'm using STM32, not an Arduino and I don't have a Serial Monitor. I will try downloading a newer SdFat version.

I downloaded the newest version of SdFat from here: https://github.com/greiman/SdFat and ran it, but it still fails to create a file in a subdirectory

I could try to do SD.chdir(DATA_DIR); but I'm not sure how that works exactly and if even that's the problem. I don't think SD.chdir(DATA_DIR); is necessary

I tried with SD.chdir(DATA_DIR); (as far as I know how to use it) but it failed. (it created the file in the root, not in the dir)

Use my EDIT 2 leave it for the moment as it is

"As you do not want to fix your obviously buggy SD.lib" I've never said that. How do I fix it, I don't have serial monitor?

Sorry for my cynism. But you reveal info step by step which should be in you question from the beginning.On the stm32you will have to rewrite the progfor your Tft. So have you tested the work around.On an STM32 the lib isknown to give problems

I have no idea what you're talking about. Thanks for trying to help me out. I will look at the code you posted and I'll try to implement some parts of it tomorrow. Thanks for the help.


text:
Turn RGB blinker via serial
I have a BLUno bluetooth arduino based on uno.
the logic kind of works, I am connecting ok to the phone, getting and sending messages via blue tooth
but with the serial data, Im having problems using it, and with the logic.
I want to have the option to turn ON/OFF some RGB LEDs, the problem is that the state is sometimes erratic.
here the code
int redLED = 2;
int greenLED = 4;
int blueLED = 3;

static bool redRunning;
static bool greenRunning;
static bool blueRunning;
static bool freq = 34;

void setup() {
  Serial.begin(115200);               //initial the Serial
  Serial.write("started");

  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(blueLED, OUTPUT);

  digitalWrite(redLED, HIGH);
  digitalWrite(greenLED, HIGH);
  digitalWrite(blueLED, HIGH);

  redRunning = false;
  greenRunning = false;
  blueRunning = false;
  freq = false;
}

void loop()
{

  if (Serial.available() > 0)
  f{
String s = Serial.readStringUntil('\n');

//    String s = Serial.readStringUntil("#");   // Until CR (Carriage Return)
//    s.replace("#", "");
    Serial.println("s:" + s);

if (s == "red_ON")
{
  redRunning = true;
}

if (s == "red_OFF")
{
  redRunning = false;

}  if (s == "green_ON")
{
  greenRunning = true;

}  if (s == "green_OFF")
{
  greenRunning = false;

}  if (s == "blue_ON")
{
  blueRunning = true;

}  if (s == "blue_OFF")
{
  blueRunning = false;

}

 }

 //

  if (redRunning) {
//    Serial.println("redRunning");

digitalWrite(redLED, LOW);
delay(125);
digitalWrite(redLED, HIGH);
delay(125);
  }

  if (greenRunning) {
//    Serial.println("greenRunning");

digitalWrite(greenLED, LOW);
delay(125);
digitalWrite(greenLED, HIGH);
delay(125);
  }

  if (blueRunning) {
    //    Serial.println("blueRunning");

    digitalWrite(blueLED, LOW);
    delay(125);
      digitalWrite(blueLED, HIGH);
    delay(125);
  }

  if (!redRunning && !greenRunning && !blueRunning) {
    digitalWrite(redLED, HIGH);
    digitalWrite(greenLED, HIGH);
    digitalWrite(blueLED, HIGH);
  }

   }

So what is the proper way to handle state? so the LED stay blinking? but also can turn off all LEDs
also if I can turn LEDs combined, at the moment, I'm turning on one, then the other,
All these problems come from not understanding how to handle state internally, and manage changes that come via serial.

use blueRunning = HIGH;  to store the LED state directly .... then set all three colors at the same time withhout using an if statement ... digitalWrite(blueLED, blueRunning); delay(125); digitalWrite(blueLED, LOW);

@jsotola what a great way to do it! thanks! please make it an answer

I think you are handling the state quite well, but if you spend some time to some other topics, I'm sure you get it working:

Instead of delay's everywhere, use just one at the end, and make sure you handle all state before that delay. This means that you set all your states the way you want, that single delay gives a much easier sketch to analyze.
Split your sketch in separate parts (within the loop function):

Read serial input
Adjust states according to your serial input
Adjust states according to time (for blinking purposes)
Set the GPIO pins for the LEDs based on that state
Delay
Regarding the states, you use now 3 'running' states, one for each color, this is good. Probably it's easier to keep these variables attached to the serial input (so if you get "green_ON", greenRunning is always true, else false. So you don't need to always set them to false in the beginning of the loop function, just once during declaration or within setup.

Than you make another (global) variable that defines if (any) LED is in HIGH state (if it WOULD be running) of LOW. This variable you change every 125 ms (or whatever speed you like). You can flip this variable every 125 ms (ledsOn = !ledsOn).
So you get something like (# = pseudo code), for red only, rest is similar:
in global:
bool redRunning = false;
bool ledsOn = false;

in loop:
// Read serial input
# Read input

// Set states
# if serial data Red On is received
   redRunning = true;
# if serial data Red Off is received
   redRunning = false;

ledsOn = !ledsOn;

// Set LEDs
digitalWrite(redLED, redRunning && ledsOn ? HIGH : LOW);

// Delay
delay(125);

Here is some untested code that uses a non-blocking timer to flash the leds.

uint8_t redLED   = 2;
uint8_t greenLED = 4;
uint8_t blueLED  = 3;

static uint8_t redRunning   = HIGH;   // leds off at start
static uint8_t greenRunning = HIGH;
static uint8_t blueRunning  = HIGH;

// static bool freq = 34;             // not sure what this is

void setup() {
  Serial.begin(115200);               // initialize the Serial
  Serial.write("started");

  pinMode(redLED,   OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(blueLED,  OUTPUT);

  digitalWrite(redLED,   HIGH);       // leds off
  digitalWrite(greenLED, HIGH);
  digitalWrite(blueLED,  HIGH);

//freq     = false;
  tick     = false;                   // time interval signal
  ledState = false;                   // state of led display

  static uint32_t ledTicker = millis();
}

void loop() {

  if (millis() - ledTicker >= 125) {             // Once every 125 ms
    ledTicker = millis();
    tick = true;                                 // set the tick flag
    ledState = !ledState;                        // changes state at every tick
  }

  if (Serial.available() > 0) {
    String s = Serial.readStringUntil('\n');

//  String s = Serial.readStringUntil("#");      // Until CR (Carriage Return)
//  s.replace("#", "");
    Serial.println("s:" + s);

    if (s == "red_ON"   )  redRunning   = LOW ;  // sometimes, this format is easier to read
    if (s == "red_OFF"  )  redRunning   = HIGH;

    if (s == "green_ON" )  greenRunning = LOW ;
    if (s == "green_OFF")  greenRunning = HIGH;

    if (s == "blue_ON"  )  blueRunning  = LOW ;
    if (s == "blue_OFF" )  blueRunning  = HIGH;
  }

  //
  if (tick) {                                    // 125 ms passed, so update the leds
    tick = false;                                // reset tick so that leds change only once every tick

    if (ledState) {                              // state of leds at this tick
      digitalWrite(redLED  , redRunning  );
      digitalWrite(greenLED, greenRunning);
      digitalWrite(blueLED , blueRunning );
    }
    else {                                       // all off this time around
      digitalWrite(redLED  , HIGH);
      digitalWrite(greenLED, HIGH);
      digitalWrite(blueLED , HIGH);
    }
  }
}


text:
Problem communicating with GSM module which is a Fona 3G from adafruit
My issue is fairly simple to describe but I have no idea what the problem could be. So I got my FONA 3G and immediately after taking it out of the box, I connected the battery and I wired up my FTDI board (aka USB to serial converter), and then I plugged it into my USB port to try and establish communication. I just tried the most basic at command AT(using PuTTy). You're supposed to get an OK in response but the FONA doesn't appear to even notice that I'm trying to talk to it. I type AT and press enter and nothing happens at all.
The issue is most certainly not my FTDI board, I'm very experienced communicating with wifi modules and other GSM modules using PuTTy. So please don't be concerned with the setup. That's 100 percent definitely not the problem.
I was able to send AT commands after plugging the module into my laptop directly using the module's USB input, but there is still some issue with its UART. I haven't been able to send or receive any communications directly from RX and TX. It wont respond to any programs I load up onto my arduino. Its like the UART is asleep.
If you have experience with FONA 3G, please speak up and tell me what steps you took to get the UART to respond. What should the status indicator look like before its ready to receive commands? Any knowledge you have about the FONA3G module would be helpful.
As a side note, the FONA3G has a chip number. It is SIM5320a. I don't know if that helps. Most people know it as FONA 3G.

If your Fona3G is not even reacting to Putty AT commands, you set everything up  perfectly there is only one possibility left. Power supply not sufficient or DOA -in that case let it replace by the seller or go to a repair store if its a used one

It's been my experience that when a poster is 100% sure that the problem doesn't lie in one particular area, about 50% of the time we end up finding the problem in that area.  Mostly because the OP has probably looked at everything else, but isn't looking where they're sure the problem isn't.  Look even experts make dumb mistakes and miswire something sometimes.  I surely doesn't hurt you at all to show that part.  It's amazing what another set of eyes can catch sometimes.  Smart folks get the details out when they want help.  It's foolish to hide things in a case like this.

Okay I realize thats a common thing. But I have never had issues like this with other devices. I'm experienced in working with the UART. Some devices need to be reset before they'll respond to AT commands. I was wondering if someone who has used this module before knows what the trick is to get it to respond. That's all.

All right. Thanks to those of you who posted comments. It turned out to be an issue with the baud rate! Its always the simple stuff. Adafruit said this thing has auto baud meaning you can use any baud rate but they are wrong. It requires 115200 to work properly. Also I'd like to point out that there was nothing wrong with my setup. Sometimes you should trust the person when they say their setup is 100 percent fine.


text:
UNO SPI slave read from UNO SPI Master beginTransaction
For a project I am trying to understand SPI.
The final project I will use this in, is for reading the SPI from a car radio.
That Radio writes to address 0x80 of a DDRAM LCD display. MY intent is to read for a write to this address and if the bits are correct replace waht is being written.
IE Radio says write the letter E to 0x80, using a mega2560 read this and then interject a different letter then write to the radio screen. So the radio is a master with the Mega and LCD as daisy chained slaves.
I'm using the base code from for writing to the screen. This was written to fully replac ethe radio so i'm trying to mimic the radio using an UNO as Master and the screen using a Uno as a slave.
I've got the demo working from circuits4you.com
I'm trying to modify it to use the same STI settings as seen in the base radio replacement code i'll be modifying for my final project. I know this code writes correctly to the screen. The problem is that the code uses SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3)); as its designed to replace the radio functions.
I'm trying to get that line to work on the 2 UNO's im bench testing with so I can make the mega a slave in the final project.
SPI MASTER Code

void setup (void) {
   Serial.begin(9600); //set baud rate to 115200 for usart
   digitalWrite(SS, HIGH); // disable Slave Select
   SPI.begin ();

}

void loop (void) {
    SPI.beginTransaction(SPISettings(9600, MSBFIRST, SPI_MODE3));

   char c;
   digitalWrite(SS, LOW); // enable Slave Select
   // send test string
   for (const char * p = "Hello, world!\r" ; c = *p; p++)
   {
      SPI.transfer (c);
      Serial.println(c);
   }
   digitalWrite(SS, HIGH); // disable Slave Select
   delay(2000);
   SPI.endTransaction();
}

The problem seems to arise from the SPI.attachInterrupt() not being compatible with the SPI.beginTransaction is this correct and is there a way around it?
SPI SLAVE Code
include <SPI.h>
char buff [50];
volatile byte indx;
volatile boolean process;

void setup (void) {
   Serial.begin (9600);
   pinMode(MISO, OUTPUT); // have to send on master in so it set as output
   SPCR |= _BV(SPE); // turn on SPI in slave mode
   indx = 0; // buffer empty
   process = false;
   SPI.attachInterrupt(); // turn on interrupt

}

ISR (SPI_STC_vect) // SPI interrupt routine
{
   byte c = SPDR; // read byte from SPI Data Register
   if (indx < sizeof buff) {
      buff [indx++] = c; // save data in the next index in the array buff
      if (c == '\r') //check for the end of the word
      process = true;
   }
}

void loop (void) {

   if (process) {
      process = false; //reset the process
      Serial.println (buff); //print the array on serial monitor
      indx= 0; //reset button to zero
   }

}

Please show your modification (use and position) of SPI.setDataMode() in your code above.

Okay so I have got this working now. It seems that it was the Slave not understanding the data mode. I found the SPI.setDataMode() it is listed as Do not use in the reference guide on Arduino.com but its worked spot on for me.


text:
Why is function mentioned in global declaration?
I came accross this code for writing data into EEPROM in arduino. Why is void printTemp();, void clearEEPROM(); and void writeTemp(); functions are mentioned in global declaration? How will this help?
#include <EEPROM.h>

#define SAMPLE_TIME 2000  //The time between each EEPROM write function call in ms

int tempPin = 0;      //the ADC pin
int printPin = 2;     //the print button pin
int erasePin = 4;    //the erase button pin

int address = 0;      //EEPROM address counter

unsigned long timer;

float conv_coeff = 0.0;   //coefficient for converting from 0-1024 to 0-5 range

void printTemp();
void clearEEPROM();
void writeTemp();

void setup(){
  Serial.begin(115200);     //start the serial connection as always
  conv_coeff = 5.0/1024.0;  //find the coefficient to do the conversion
  timer = millis();         //millis() returns the time since program start in ms
}

void loop(){
  if(millis()-timer > SAMPLE_TIME)  //check if it's time to do a temp sensor sample
  {
    writeTemp();
    timer = millis();
  }

  if(!digitalRead(printPin))  //check if print button is pressed
  {
    printTemp();
    delay(500);
  }

  if(!digitalRead(erasePin)) //check if erase button is pressed
  {
    clearEEPROM();
    delay(500);
  }

  delay(1);
}

void printTemp()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    byte value = EEPROM.read(i);                //read EEPROM data at address i
    if(value != 0)                              //skip "empty" addresses
    {
      float temp = value*conv_coeff;            //convert ADC values to temperature
      temp = (temp - 0.5)*100;                  //take care of the offset

      Serial.println(temp);
    }
  }
}

void clearEEPROM()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    if(EEPROM.read(i) != 0)                     //skip already "empty" addresses
    {
      EEPROM.write(i, 0);                       //write 0 to address i
    }
  }
  Serial.println("EEPROM erased");
  address = 0;                                  //reset address counter
}

void writeTemp()
{
  byte value = analogRead(tempPin);     //read sensor value

  EEPROM.write(address, value);         //write value to current address counter address

  Serial.print("Sensor value stored at address ");
  Serial.println(address);

  address++;                      //increment address counter
  if(address == EEPROM.length())  //check if address counter has reached the end of EEPROM
  {
    address = 0;              //if yes: reset address counter
  }
}

Those are called function prototypes.  They mean "These functions exist somewhere else".  That "somewhere else" could be later on in the same file, or a different file entirely.
Usually these kind of things are provided by header (.h) files, or are automatically created (for functions in the INO file) by the IDE and hidden from you, so you never really see them. But if you're not using the IDE then you need to have them so your code (which is parsed linearly) knows that these functions exist before the parser comes across them.

Thanks! is it recommened to write it in the code? Even when using IDE?

It's a good habit to get into for when you graduate and start programming properly ;)

@Majenko, ouch. We all have to learn sometime!

@DuncanC All I'm saying is that many Arduino users are students, and when you graduate and get a job certain standards will be expected of you ;)

Originally, C (from which C++ inherited the bulk of its syntax) was compiled by a single-pass compiler: the compiler only got one look at the code.
A multi-pass compiler could look over the code and collect function definitions in one pass, then in a later pass, compile the code that calls those functions, or detect errors in those calls, if there are any.
A single pass compiler couldn't do that so it needs either the function or its prototype to appear before any code that uses calls it, for the compiler to have that same information when it needs it.
The prototype provides the function's name, the number and types of its arguments, and the type of value it returns, which is what the compiler needs to confirm and compile a function call or to issue a diagnostic message if the call doesn't match the prototype.


text:
Is there a test framework for Arduinos?
I'm working on big Arduino project that involves lots proprietary libraries. Ergo, we need test scripts to ensure each library works. Is there a testing framework for Arduino similar to CPPUnit, JUnit, Cunit, etc.? It should preferable also have the ability to simulate an Arduino.
EDIT: By "Arduino Simulator" I only want something that allows observation of local variables, global variables, the different register values (at a minimum the INPUT/OUTPUT status of the pins, what is being inputted or outputted), and fake inputs into the various pins. This way, only the Arduino itself needs to be simulated, not the external hardware components like LEDs, buttons, real time clocks, motors etc.

afaik there is not such thing ... for some libraries I created my own 'stubs', with some smarter than others to test my specific application.

You could simulate an Arduino, sure, but that will be of little to no value. You need to simulate the entire system, including external stimuli. And that system is unique to you - so who would write a simulator for that...?

Yes ... I mimiced the use of a DMX library to show all the to-be-connected lights to be shown on a PC instead as sets of pixels turning on and off ... so in your case you might have to stub it in such a way that is appropriate for you.
A good start is to write all libraries NOT related directly to the Arduino or hardware and test them on a PC and when working correct, copy them to the Arduino project.

In the PlatformIO there was some --target test, but I haven't investigate how it's meant to be used or so...

Why don't you use any common C++ unit testing framework, and provide a simulated/faked/mocked-up version of the Arduino libraries? After all, you don't have direct hardware access with them.

@thebusybee because the Arduino IDE uses a custom C++ compiler that does not have most of the C++ libraries available in other C++ compilers (e.g. g++). This includes CPPUnit and object oriented error handling (try, catch, throw statements and error objects). While the assert library is available, it's not ideal. Also, most of our libraries do have direct hardware access.

I don't mean to run the tests on the Arduino. Use your PC. You want to test your code, not the compiler. -- So you want not only the application tested, but mainly the libraries that use direct hardware access. Well, that has nothing in common with Arduino.

It should preferable also have the ability to simulate an Arduino.

As said in the comments, only simulating the Arduino is mostly not enough, because you would also need to simulate all the connected components. Just simulating the Arduino is a rather hard task. You can find Arduino simulators, but they always only support a rather small collection of additional hardware (mostly things like switches, LEDs, buzzers, ...). I guess the proprietary libraries, that you use, are for connecting to some extra devices (maybe are also proprietary), which will be rather complex. These devices will most likely not be supported by any of the Arduino simulators.
Also: Arduino is a beginner and fast prototyping platform. The ones, that do professional things like designing a product (which are mostly the ones, that need such test suites), will fastly move away from the Arduino platform to program an abstraction layer lower directly on the AVR platform. So why would those people need a test suite for Arduino?
Simulating electronic circuits can be really difficult, so you won't see a program, that can handle all of your circuit, including the complex parts like sensors with communication interface. That means, that you can only test your circuit and the corresponding code (which interacts with the circuit) in the real hardware. Some IDEs (like PlatformIO) might give you the possibility, to write test sketches, but you would still need to upload them to the real hardware and observe the results yourself.
Code, that is independent from the Arduino hardware, could be unit tested on the PC, but that is mostly not the case, since Arduino/microcontrollers are so hardware near. Of course, you could write mocking code for the Arduino parts, but that is often even more tedious, than just using the hardware.

As no real Arduino testing framework exists, you are down to writing own testsketches and using a good IDE (not the Arduino IDE) to organize them.


text:
Unreliable EspSoftwareSerial Bluetooth transmission for longer read/writes on ESP8266
I have a project which runs on an ESP8266 and one functionality is to do nothing else but to read what comes in from a HC-05 Bluetooth adapter via SoftwareSerial and outputs the read data to the HardwareSerial TX pin. Vice versa, the same is done with what kind of data comes in via HardwareSerial's RX pin and is output to the HC-05 via SoftwareSerial. I use this cheap serial-to-bluetooth adapter, to flash a device where the stock adapter would cost me 100$ or more.
On the surface, the code still runs fine, as most of the time no errors occur. But after some handshake data is transmitted and the flashing begins with larger blocks of data (100+ bytes), the device I'm talking to quits the communication. I can't really figure out why because I don't have access to its internals, but when I flash the ESP8266 with a binary of my software that is about a year old, the communication is much more stable and most of the flash procedures work fine.
I have checked my code and it is basically the same as a year ago, except for the SoftwareSerial constructor and the .begin statement which changed a while ago. But other than that, there is nothing much I can see.
Of course it could be changes inside the EspSoftwareSerial library or even the framework. I was using 2.3.3 until a while ago, but I can't recall which version of EspSoftwareSerial I used a year ago. I tried 2.3.3 for the framework and 5.0.4 for EspSoftwareSerial via configuration in platformio.ini, but to no avail.
Is there anything known about changes in behaviour in EspSoftwareSerial or in relation to the framework that I shoudl consider?
Here's the relevant code:
void handle_bluetooth() {

//  SoftwareSerial BtSerial(2, 0, false, 256);
  SoftwareSerial BtSerial;

  if (!webServer.authenticate(http_user, http_pass)) {
    return webServer.requestAuthentication();
  }

  unsigned long timeout = millis();
  uint16_t idx = 0;
  uint8_t bt_read = 0;
  uint8_t bt_write = 0;
  uint16_t crc_result = 0;
  boolean need_flash = false;
  boolean fw_poll = false;
  boolean fw_memory = false;
  uint8_t model_no = webServer.arg(0).toInt();

  String message = "";
  if (model_no > 0) {
    message.concat(F("Emulating model no. "));
    message.concat((String)model_no);
  }
  webServer.send(200, "text/html", message);

//  BtSerial.begin(38400);
  BtSerial.begin(38400, SWSERIAL_8N1, 2, 0, false, 256);

  telnetClient.println(F("Starting Bluetooth mode..."));
  while (timeout + 300000 > millis()) {

    while (BtSerial.available() > 0) {
      bt_read = BtSerial.read();
      if (bt_read == 0x02 || idx > sizeof(rx_msg)) {
        idx = 0;
      }

      telnetClient.print(to_hex(bt_read));
      telnetClient.print(F(" "));
      rx_msg[idx] = bt_read;
      if (bt_read == 0x03) {
        telnetClient.println();
        crc_result = decodeMsg(idx+1);

        if (rx_msg[3] == 0x27 && model_no > 0) {
          fw_poll = true;
          fw_memory = false;
          telnetClient.println(F("FW request detected."));
        }
        if (rx_msg[3] == 0x25 && rx_msg[4]+rx_msg[5]+rx_msg[7] == 0 && (rx_msg[6] == 4 || rx_msg[6] == 4)) {
          fw_poll = true;
          fw_memory = true;
          telnetClient.println(F("FW memory request detected."));
        }

        if (rx_msg[3] == 0x64) {
          telnetClient.println(F("BT-Address detected:"));
          for (int x=4; x<10; x++) {
            if (CMD[x]!=rx_msg[x]) {
              need_flash = true;
              CMD[x] = rx_msg[x];
            }
            telnetClient.print(to_hex(CMD[x]));
            telnetClient.print(F(" "));
          }
          telnetClient.println();
        }
      }
      Serial.write(bt_read);
      idx++;
      timeout = millis();
      yield();
    }

    while (Serial.available() > 0) {
      BtSerial.write(bt_write);
      if (bt_write == 0x03) {
        telnetClient.println();
      }
      yield();
    }
  }
  telnetClient.println(F("Exiting Bluetooth..."));
  BtSerial.flush();
  BtSerial.end();
  Serial.begin(38400);
  while (Serial.read() >= 0) {    // flush the receive buffer
    yield();
  };
}

uint16_t decodeMsg(uint16_t idx) {
  uint16_t counter = 0;
  uint16_t i = 0;
  while (i < idx) {
    if (rx_msg[i] == 0x1B) {
      rx_msg[counter] = rx_msg[i + 1];
      rx_msg[counter] = rx_msg[counter] - 0x20;
      i++;
    } else {
      rx_msg[counter] = rx_msg[i];
    }
    i++;
    counter++;
  }
  if (crc8(rx_msg, counter - 2, 1) != rx_msg[counter - 2]) {
    telnetClient.print(F("CRC error in message received: "));
    telnetClient.print(to_hex(crc8(rx_msg, counter - 2, 1)));
    telnetClient.print(F("/"));
    telnetClient.print(to_hex(rx_msg[counter - 2]));
    telnetClient.print(F("/"));
    telnetClient.println(to_hex(counter));
    return 0;
  } else {
    return counter;
  }
}


text:
Arduino Nano IoT 33 Char Array size constraints
I would like to save data that I am receiving from API calls in a char array. The problem is that the data is around 80 kB, and my Arduino IoT 33 only has 32 kB of memory.
It will save data in a char array up to 25000 bytes, but when I go to 30000 bytes or above the Arduino freezes. When I copy-paste the entire data to a char array without specifying the size it works fine, but when receiving data over the API in chunks of 10 kB it won't save the entire 80 kB. Is there a way around this?

why do you want to store all that data? process it right away.

well, it is basically a hexadecimal array to update an E-Ink Display. I need all of it at the same time.

then use a SD card or save it to flash memory (if it is not to many writes)

well, my Arduino has a CPU Flash Memory of 256KB can use that somehow?

you can, but it has only 10000 writes

wait so what do you mean by 1000 writes? Can't I save 80kb in CPU flash?

you can but flash memories have limited count of write-erase cycles

I will be updating my display probably 5 to 6 times a day. That should be enough right?

I will try that. Thanks a lot :)

what do you mean by hexadecimal array? ... are you storing text, not bytes?

You can use the flash memory of the SAMD21 MCU used on the Nano 33 IoT, if you don't write too often. Flash memories have a limited count of write-erase cycles. It is guarantied for 10000 writes.
For Arduino SAMD boards like the Nano 33 IoT you can use the FlashStorage library. The library is in the Library Manager.


text:
NodeMCU v2 with MH-Z19B CO2 sensor UART read problem
I'm trying to read data from MH-Z19B sensor to NodeMCU v2 board with a simple circuit like this.

Some key points, which could be not that obvious from picture:
 - sensor has separate power supply of 4 AAs, providing ~5,5V
 - sensor's TX connected to GPIO15 (TX D2) of NodeMCU
 - sensor's RX connected to GPIO13 (RX D2) of NodeMCU
And here is my sketch:
const byte readCommand[] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79}; // according to datasheet
unsigned char response[9];

void setup() {
  // according to datasheet, sensor uses 9600 baud, 8 databits and 1 stopbit
  // with parity NONE, which I believe corresponds to default config SERIAL_8N1
  Serial.begin(9600);
}

void loop() {

    //  ... check if it is time to measure

    Serial.swap(); // switch to sensor

    Serial.write(readCommand, sizeof(readCommand));

    memset(response, 0, sizeof(response));

    int attempts = 5;
    int available = Serial.available();
    while(available < sizeof(response) && attempts > 0) {
        delay(100);
        attempts--;
        available = Serial.available();
    }

    Serial.readBytes(response, sizeof(response));

    Serial.swap(); // switch back to console

    // print out the response in hex
    for (int i = 0; i < sizeof(response); i++) {
      Serial.print(String(response[i], HEX));
      Serial.print("   ");
    }

    // ...process the response according to protocol
}

The Problem
For some reason after sending command to serial I get an answer exactly the same as command is although the structure of answer expected to be different. Of course datasheet says nothing about situations like this.
Expectation
ff 86 .. .. 0 0 0 0 CRC

Reality (same bytes I sent as a command)
ff   1   86   0   0   0   0   0   79

Other notes:
 - I got exactly the same when tried to use SoftwareSerial with D1 & D2 pins
 - connecting TX to RX respectively on both sensor and MCU results in reading failure
 - I tried to pull everything while available from serial, there are only my expected 9 bytes
 - my soldering skills are far from ideal, but I'm pretty sure tx/rx on the sensor are connected properly
I'm new to all this stuff, so it is completely possible that there is ridiculously silly, but crucial mistake, so would appreciate any help on this. And I understand that sensor also has additional interfaces to obtain the value, but as I mentioned I'm a newbie and wanted to familiarize myself with UART as this is something new for me.
UPD 1:
I didn't use level conversion for sensor output as datasheet says:

Assuming this I thought that sensor provides logical level conversion itself. Did I get it wrong?
UPD 2:
I got back to proper TX - RX connection just to check out what is going on exactly to describe that "reading failure" problem with more details. It seems that Serial.available() returns 0 after I send command so this loop gets stopped after 5 attempts:
while(available < sizeof(response) && attempts > 0)

It has to be RX to TX with UART. That it results in reading failure is another problem. What exactly do you mean by "reading failure"?

You don't step down the TX voltage of the sensor from 5V to 3.3V for the NodeMCU. That is risky, as you might destroy the RX pin of the NodeMCU

@chrisl thank you for your comments, I updated my question with some details regarding that reading failure case and my assumptions I took from datasheet which made me think I don't need 3,3 level conversion.

It says in your description that you have the Rx connected to Rx and the Tx connected to Tx.  That's backwards.  What one transmits the other needs to receive.  When you have a conversation with someone, do you talk into their mouth and listen to their ears?  You should have Rx-Tx and Tx-Rx.
You also need to be sure that it is OK to feed a 5V Tx into that Rx pin.  On some ESP8266 boards it is and on most it isn't.  If you don't have one of the boards that specifically has circuitry built in to handle 5V inputs then you will fry your NodeMCU

Thank you for your answer. I added a screenshot from sensor's datasheet which says that it provides UART 3,3 so I thought that level conversion was made on sensor's side. Did I get it wrong?

If it does give 3V3 then you're safe.  It appeared from your question that it was 5V.


text:
How compile an Arduino program for a desktop PC
I have an arduino program that only does serial communications with a little bit of math, and I am writing another one to communicate with it on a second arduino.  For testing purposes I was hoping I could run the serial only program on my desktop.  I know it is possible to run on a raspberry pi but I have never done that.  Can I do something similar on windows?  If not, can anybody recommend the easiest way to do this with a regular C++ program that would require very little editing? Here is a copy of my code if it's helpful.  It basically increments a variable up and down between 0 and 100.
int pos = 60;
bool flag=0;
int dly=50;
int vel=0;

const int buttonPin =  12;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);

Serial.begin(115200);
}

void loop() {
    dly=50;
    buttonState = digitalRead(buttonPin);
    if (buttonState==0)dly=12;
    Serial.print(vel); //speed
    Serial.print(",");
    Serial.println(pos); //position
    delay(dly);
    if (pos==30)flag=1;
    if (flag==1) pos+=1;
    if (pos==100)flag=0;
    if (flag==0) pos-=1;
    vel=1000/dly;
    if (flag==0) vel*=-1;

}

try processing ... https://processing.org/ .... look for example sketches that do serial comm ...

I'm familiar with processing.  The goal for me is to just have one program that I can run in two places.  Otherwise I can just use python or another Arduino.

If you want to run the Arduino sketch on your desktop, you just have to
implement the Arduino core library for your PC.
It may not be as bad as it sounds. If your program makes only minimal
use of the Arduino core, you may implement only the parts you really
need. For example, this partial implementation is enough to run your
program:
#include <cstdint>
#include <iostream>
#include <unistd.h>  // for usleep()

using std::cout;
using std::endl;

#define INPUT_PULLUP 2

void pinMode(uint8_t, uint8_t) {}

uint8_t digitalRead(uint8_t) { return 0; }

void delay(int t) { usleep(t * 1000UL); }

struct {
    void begin(int) {}
    template<typename T> void print(T x) { cout << x; }
    template<typename T> void println(T x) { cout << x << endl; }
} Serial;

int main()
{
    void setup();
    void loop();
    setup();
    for (;;) loop();
}

I tested this on Linux, by simply appending your program right below
this. If you are using Windows, you will have to replace the usleep()
function with the appropriate Windows call (and <unistd.h> with the
appropriate header). The serial stream goes to the standard output. You
may redirect it to the USB serial port if you wish (trivial to do in
Linux, I assume it should be doable on Windows). You may also want to
replace digitalRead() with something that simulates a more realistic
user interaction.
Keep in mind that the sizes of the basic data types can be different on
the Arduino and on the PC. On an AVR-based Arduinos, int and pointers
are 16 bits while long is 32 bits. This is an “IP16” data model. An
ARM-based Arduino would typically be ILP32, whereas a 64-bit PC is LP64,
unless it runs Windows, in which case it's LLP64. This can make a
difference, especially if some of your calculations are prone to
overflow with the smaller data models.

Edit: I recently stumbled upon NCORE, a native core for
Arduino. It may be a good fit for what you are trying to do.
From the page description:

The native core allows you to compile and run Arduino sketches on the
  PC, generally with no modification. It provides native versions of
  standard Arduino functions, and a command-line interpreter to give
  inputs to your sketch that would normally come from the hardware
  itself.

This might be the way to go about it.  I'm just curious why all this is required for a desktop, but I can run an ino file on a raspberry pi without it.

@bobmcgrath: I guess someone has already implemented a quite complete Arduino-compatible core for the Raspberry... WiringPi maybe?

It depends on what exactly you wanna test. I guess you want to run the "Serial & math only" sketch on the PC, while communicating over Serial (via USB) with the other real Arduino. It can be done, but you would have to change quite a lot. The Serial libraries for a PC are different than for an Arduino. Also you cannot simply compile Arduino code for a PC, they are totally different devices.
Mostly the Serial code is better tested with the real hardware, by checking, what actually is send. You can do this by connecting to the Arduino over Serial/USB with a corresponding program (Arduino Serial Monitor, Putty, ...), so that you can test the functionality by hand. Or write a simple test sketch for the second Arduino.
For testing the math part, you could relatively easy write a so called unit test on the PC. A unit test tests a confined code part without or only with few dependencies. Most math is the same on Arduino and PC (as long as you use variables of the same size and type). So you could put all the math code into a function, which does not contain Arduino specific code, like Serial code. Just the math. Then you can copy that function into the source code of a C++ PC programm and use it, to test the math function unit without involving the Arduino.
A further option would be using an Arduino Simulator. But keep in mind, that these simulators can never be as good as the real hardware and you can see differences in the behavior of simulated and real Arduinos. Though it should work, as long as your program is simple and does not rely on too much outer hardware or events. Your current program is simple enough, so that a simulator should be able to work with it.
All in all: Testing your code outside of the real Arduino mostly only makes sense, when you have a complex program, that does not involve Arduino specific code, which would need the hardware to work. If your project is not very complex, you are mostly better off with testing directly with the real hardware.

There is also arduino_ci, a framework for running unit tests against an Arduino library (maybe also sketch) on your computer. It contains mock implementations of most Arduino functions and some libraries, and gives the unittest control of things like Serial buffers and I/O pin values.
For your example, you could maybe write a unittest that just use stdin/stdout as a serial port and then connect two of these programs together, or maybe you could generalize your communication code a bit into an object and then instantiate that twice.


text:
Rechargeable USB "AA" Batteries. Has anyone used them?
I have a cosplay project where I'm creating a "Megaman" aka Rockman type of arm cannon (it's actually based on DC's Cyborg). Anyhoo, I've been weighing options like using 3xAA alks or 4xAA nicd (or otherwise 1.2V)--inclcuding various combinations of less or more cells with a voltage regulator; boost up or step down as appropriate.
there are 4 lighted segments (15 leds of WS2812B x 4). I also of course have to power the Arduino Nano as well. I'm flexible on led brightness so I'm just going to tune it [code it] to whatever looks adequate for my purpose. I am aware of the 50ma draw of these units at full brightness
My original plan was to just keep it easy (read lazy) and use 3 AA alks per 2 segments, and another 3 so the nano can have it's own supply. So 9 cells in total (without any additional regulation). Before you judge me--weight, volume, and especially area are definitely big factors in my decision.
So that's a long way to get to my actual question. Has anyone used these new types of USB rechargeable batteries? They seem to have the best of both worlds with the power of an alkaline but the consistency and sustainability of a NiMH /NiCD as they have internal regulators that produce a steady 1.5v (until they don't--which I'm more than cool with)
Short of having a properly regulated 5v power supply, are these a good option if I want to be slightly more responsible than throwing in whatever other AAs I have lying around? They definitely check the box on my space/mass requirements. I'm sure they do fine with most consumer electronics, but as far as arduino and any other custom/hobby 4.5-5v applications how reliable are these? Even if you haven't used them before I'd be curious of your thoughts. I'm a novice at best when it comes to elec engineering.
Yes, they are expensive. Thanks all!
examples:
https://www.amazon.com/Rechargeable-Batteries-Quick-Charge-Integrated-Protection/dp/B07F27PK2M/ref=sr_1_5?crid=1RTQUCZYG4KBM&dchild=1&keywords=usb+aa+batteries+1.5v&qid=1588280164&sprefix=usb+aa%2Caps%2C242&sr=8-5
https://www.amazon.com/Blackube-Rechargeable-Batteries-Lithium-1500mAh/dp/B07D9K2H9H/ref=sr_1_11?dchild=1&keywords=usb+aa+batteries+1.5v&qid=1588282813&sr=8-11

1500mAh is considerably less than what you'd get from a normal NiMH. And for the price of them you could get a pack of normal NiMH and a proper charger.

I think you can get a good LiIon or LiPo battery and a fitting charger/voltage regulator module for less than that. And it could output directly 5V, so you wouldn't loose more power with an extra voltage regulator. Or are you somehow bind to using AA sized batteries?

@chrisl I'm not necessarily stuck on AA, but I'm mounting them on the outer circumference of a 3" PVC pipe, aligned with the direction of the pipe openings. Imagine a small ammo bandolier around your forearm with nine 20ga shells surrounding...That's kind of what I'm thinking. So larger flatter batteries are going to have a weird footprint for my purpose. Mounting 9 or so individual AA battery holders seemed like a good way to make this look clean. The section of pipe is also on a spinning bearing, so the batteries have to be distributed somewhat evenly. A single large battery won't work.

If you want to fit it into PVC pipe, why not consider 18650 Li-ion rechargeable, it gives you anywhere from 2000 to 3500mAh with a single compact battery with 3.7v output. You could either add a boost converter or use 2 batteries feed into Vin of Nano.

@hcheung I like this. I'm actually thinking I would do two in a series and pop in a 5v reg since I'll be saving space with 2 cells instead of 3 or 4. Also an expensive option but other than that it's a good fit.

I use for this purpose the eneloop (2800 mAh) Keep up the mAh for 85-90% of the full load. Advantage same circuit as for batteries, quickly exchangeable, can be loaded with a normal loader and reliable with changing temperatures (used them from -5C to +40C). Disad: cost a bit more than a normal NiMh (four for around 10$)

Those "batteries" are actually a 3.7V¹ ~750mAh Lithium rechargeable cell with a 1.5V switching regulator and 5V charge circuit built in.
In about the same space as one of those, if you throw away the charge circuit and switching regulator, you can get a single 18650 Lithium rechargeable cell at 3.7V¹ (nominal) and three times the capacity. Two of those plus a small 5V switching regulator² would give you more power capacity and longer run time in a smaller space than the equivalent voltage of these strange "batteries".

¹ Nominal
² Use a good one with a Li-Ion battery protection circuit and maybe a built in 2S charger too for convenience

Thanks for the context on the USB AA cells! Taking your advice on the 18650's.


text:
Subscribing to Bluefruit LE Friend with ArduinoBLE not working
I've been using an Arduino Nano 33 BLE to communicate with my PC over the BlueFruit LE Friend's UART characteristic. Using the default ArduinoBLE library, I'm able to connect to the BlueFruit from the Nano 33 as a central device, and write to the BlueFruit and have it show up in a serial terminal. I can get the Nano 33 to read from the Bluefruit as well, by sending a Characteristic.read() request and a subsequent Charcterisitc.readValue() command. Subscribing to the rx characterisitic on the Nano 33 does NOT work, however, even though the Bluefruit's info page says that the rx characterisitc (address 0x0003) is capable of Notify. I need to be able to subscribe, so that I can use the characteristic.valueUpdated() function to know when new data is available. Here is the relevant code:
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}

// discover peripheral attributes
Serial.println("Discovering attributes ...");
displayNum('A');
if (peripheral.discoverAttributes()) {
  Serial.println("Attributes discovered");
  displayNum(-1);
} else {
  Serial.println("Attribute discovery failed!");
  peripheral.disconnect();
  displayError('A');
  return;
}

// retrieve the TX characteristic
BLECharacteristic txCharacteristic = peripheral.characteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
BLECharacteristic rxCharacteristic = peripheral.characteristic("6e400003-b5a3-f393-e0a9-e50e24dcca9e");

// make sure BlueFruit UART characteristics have been loaded properly are of
// proper format
if (!txCharacteristic) {
  Serial.println("Peripheral does not have TX characteristic!");
  peripheral.disconnect();
  return;
} else if (!txCharacteristic.canWrite()) {
  Serial.println("Peripheral does not have a writable TX characteristic!");
  peripheral.disconnect();
  return;
}
if (!rxCharacteristic) {
  Serial.println("Peripheral does not have RX characteristic!");
  peripheral.disconnect();
  return;
} else if (!rxCharacteristic.canSubscribe()) {
  Serial.println("rxCharacteristic is not subscribable!");
  peripheral.disconnect();
  return;
} else if (!rxCharacteristic.subscribe()) {
  Serial.println("rxCharacteristic subscription failed!");
  peripheral.disconnect();
  return;
}

What's strange is that Characteristic.canSubscribe() method returns true, and it is only when I actually try to subscribe that my error message is triggered. This code is also basically taken directly from the ArduinoBLE SensorTag example, so I'm not sure if this is an issue with the Arduino library or the Bluefruit, so any input would be appreciated.

As an update, I'm able to get notifications through the BlueFruit Connect app, which makes me think that the issue has something more to do with the Arduino library.


text:
Arduino Turn on a led with the PCA9865
I am using the PCA9865 to light a led
My circuit
Arduino to PCA9865
A5 > SLC A4 > SDA 5V > 5V GND > GND and
5 volts from a battery

My code:
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

// called this way, it uses the default address 0x40
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

void setup()
{
  pwm.begin();
  pwm.setPWMFreq(60);  //~60 Hz updates
}

void loop()
{
  int pin = 0;
  pwm.setPWM(pin, 4096, 0);
}

the led does not light

add a current limiting resistor in series with the LED. could you light the LED with Uno directly? set higher freequency

really? you wired it to 4 and 5 instead of A4 and A5?

As written in the comments check resistor/led AND make sure you get power/GND to the terminal on the PCA board as this is needed for powering servos/leds/motors hanging on the board. I use about 10 on my layout and they are fantastic for powering all kind of appliancies. I patched the lib but in your case this is overkill. Instead of
void setPWM(uint8_t num, uint16_t on, uint16_t off);

you could also try
void setPin(uint8_t num, uint16_t val, bool invert=false);

but that is not the problem here
EDIT
Thanks for the foto now its clear why not. You have to connect A4 (UNO SCA) -  SCA (PCA9865)  AND A5 (UNO SCL) - SCL (PCA9865) see diagram:

I added a photo of my circuit


text:
Backup an ATMEGA16
I have an ATMEGA16 lying around that was in an old robot I'd bought. It was in a socket, so I pulled it out and was thinking of using this page to use it with Arduino IDE. Is there a way for me to backup the chip's current state, so as to be able to restore it if I mess up?
I don't have an SPI programmer with me, but I do have a Arduino Uno available at hand

Comments are not for extended discussion; this conversation has been moved to chat.

A detailed how to is here its for the ATMega16 but check connections with the circuit diagram.

Use this command for backup of flash
 avrdude -c avrisp2 -p m16 -P /dev/ttyUSB0 -b 115200 -U flash:r:Old_flash_backup_file.hex:h

Backup EEPROM (just in case there is something stored there)
avrdude -c avrisp2 -p m16 -P /dev/ttyUSB0 -b 115200 -U eeprom:r:eeprom_backup_file.hex:h

and this for writing the new bootloader / backup back
 avrdude -c avrisp2 -p m16 -P /dev/ttyUSB0 -b 115200 -U flash:w:New_BootLoader.hex:i -v

and this for EEPROM writing back
avrdude -c avrisp2 -p m16 -P /dev/ttyUSB0 -b 115200 -U eeprom:w:new_eeprom_file.hex:h

As your avr-dude outputis
lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

there seems to be no lock on the chip. As you are on LINUX when reading youhave tospecify the format :h hex when reading

Comments are not for extended discussion; this conversation has been moved to chat.