text:
Problems lighting LEDs on receiving Arduino given a char array from sending Arduino in Tinkercad
The gist of the problem is that I'm trying to have an Arduino with a breadboard that has 5 buttons and 4 LEDs each led is linked with a button and the fifth button "sends" the lights that were switched on with a char array to the receiving Arduino, in this Arduino, this Arduino algo has a breadboard with 4 LEDs of the same color and with the char array I try to switch the same LEDs that were switched on in the first Arduino, my problem is when I send the char array and receive it in the second Arduino and try to run a function that runs through the array and find which points in the char array are different than 0 and turn on a led it never turns any LEDs, I know the logic is right but I don't understand why it doesn't work.

This is the design I am working with in tinkercad and will also link the project if you wish to run it on there, I assume that the problem is from tinkercad and not the code though I may be horribly wrong.
This is the sender sketch
#include <SoftwareSerial.h>

#define rxPin 9
#define txPin 8

// Iniciamos los pins de los 4 leds de sender y reciver
const int ledRed = 13;
const int ledBlue = 12;
const int ledGreen = 11;
const int ledWhite = 10;

// iniciamos los pins de los 5 botones
const int pushbuttonRed = 7;
const int pushbuttonBlue = 6;
const int pushbuttonGreen = 5;
const int pushbuttonWhite = 4;
const int pushbuttonEnviar = 3;

// Declaramos el estado de los 4 leds de sender y reciver
int ledStateRed = 0;
int ledStateBlue = 0;
int ledStateGreen = 0;
int ledStateWhite = 0;

char c;
char leds[7] = {'H','0','0','0','0','F','\0'};

//String cadena_final = "";
SoftwareSerial receiver =  SoftwareSerial(rxPin, txPin);

void setup() {
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  Serial.begin(9600);
  receiver.begin(9600);
  pinMode(ledRed, OUTPUT);
  pinMode(ledBlue, OUTPUT);
  pinMode(ledGreen, OUTPUT);
  pinMode(ledWhite, OUTPUT);
  pinMode(pushbuttonRed, INPUT);
  pinMode(pushbuttonBlue, INPUT);
  pinMode(pushbuttonGreen, INPUT);
  pinMode(pushbuttonWhite, INPUT);
  pinMode(pushbuttonEnviar, INPUT);
}

void loop() {

    // Boton Rojo
    if(digitalRead(pushbuttonRed) == 1) {
      digitalWrite(ledRed, HIGH);
      ledStateRed += 1;
      leds[1] = '1';
      if(ledStateRed % 2 == 0){
        digitalWrite(ledRed, LOW);
        leds[1] = '0';
        ledStateRed = 0;
      }
      delay(100);
    }

    // Boton Azul
    if(digitalRead(pushbuttonBlue) == 1) {
      digitalWrite(ledBlue, HIGH);
      ledStateBlue += 1;
      leds[2] = '1';
      if(ledStateBlue % 2 == 0){
        digitalWrite(ledBlue, LOW);
        ledStateBlue = 0;
        leds[2] = '0';
      }
      delay(100);
    }

    // Boton Verde
    if(digitalRead(pushbuttonGreen) == 1) {
      digitalWrite(ledGreen, HIGH);
      ledStateGreen += 1;
      leds[3] = '1';
      if(ledStateGreen % 2 == 0){
        digitalWrite(ledGreen, LOW);
        ledStateGreen = 0;
        leds[3] = '0';
      }
      delay(100);
    }

    // Boton Blanco
    if(digitalRead(pushbuttonWhite) == 1) {
      digitalWrite(ledWhite, HIGH);
      ledStateWhite += 1;
      leds[4] = '1';
      if(ledStateWhite % 2 == 0){
        digitalWrite(ledWhite, LOW);
        ledStateWhite = 0;
        leds[4] = '0';
      }
      delay(100);
    }

    // Boton Enviar
    if(digitalRead(pushbuttonEnviar) == 1) {
      // Reinicio los leds de sender para enviar otro mensaje
      ledStateWhite = 0;
      ledStateGreen = 0;
      ledStateBlue = 0;
      ledStateRed  = 0;
      digitalWrite(ledWhite, LOW);
      digitalWrite(ledRed, LOW);
      digitalWrite(ledBlue, LOW);
      digitalWrite(ledGreen, LOW);
      delay(100);
      Serial.write(leds,7);
      leds[1] = '0';
      leds[2] = '0';
      leds[3] = '0';
      leds[4] = '0';
    }
}

void printArray(char A[]){
    int i = 0;
    for(i=0;i<6;i++){
        Serial.print(A[i]);
    }
}

This is the receiver sketch
#include <SoftwareSerial.h>

#define rxPin 9
#define txPin 8

char leds2[7] = {'\0'};

// Iniciamos los pins de los 4 leds
const int Red = 4;
const int Blue = 5;
const int Green = 6;
const int White = 7;

// Creamos el boton que limpia pantalla
const int buttonClear = 10;

char c;
String recData;

SoftwareSerial receiver =  SoftwareSerial(rxPin, txPin);

void setup() {
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  receiver.begin(9600);
  pinMode(Red, OUTPUT);
  pinMode(Blue, OUTPUT);
  pinMode(Green, OUTPUT);
  pinMode(White, OUTPUT);

  Serial.begin(9600);
}

void loop() {
    int i=0;

    if (receiver.available()) {

      delay(100); //allows all serial sent to be received together
      while(receiver.available() && i<6) {
        leds2[i] = receiver.read();   // starts with i=0
        delay(100);
        i++;
      }
      leds2[i]='\0';
      //digitalWrite(Red,HIGH);
    }
    if(i>0) {
      lightLeds(leds2);
    }
}

void lightLeds(char A[]){
    int i;

    for(i=0;i<6;i++){
        if(A[1]=='1' || A[1]==1) digitalWrite(Red, HIGH);
        if(A[2]=='1' || A[2]==1) digitalWrite(Blue, HIGH);
        if(A[3]=='1' || A[3]==1) digitalWrite(Green, HIGH);
        if(A[4]=='1' || A[4]==1) digitalWrite(White, HIGH);
    }
}

void printArray(char A[]){
    int i = 0;
    for(i;i<6;i++){
        Serial.print(A[i]);
    }
}

Your "working logic" is quite unlogic:
In sender you define a char array:
char leds[6] = {'H','0','0','0','0','F'};
which should be
 char leds[7] = {'H','0','0','0','0','F','\0'}; // terminate the array

Here each '0' represents a led as can be seen in subroutine Boton Enviar
Instead of assigning a state to each position 0/1 so leds[2]='1' would be e.g. led blue ON you write a number to it (example walk through for blue):
if(digitalRead(pushbuttonBlue) == 1) {
      digitalWrite(ledBlue, HIGH);
      ledStateBlue += 1;
      leds[2] = '5';  // Here should be leds[2] = '1';
      if(ledStateBlue % 2 == 0){
        digitalWrite(ledBlue, LOW);
        ledStateBlue = 0;
        leds[2] = '0';

so if blue and and you send (if using the terminator)
 leds[] = {'H','5','0','0','0','F'.'\0'};

On the receiver side the following happens:
   while(receiver.available() && i<6) {
        leds2[i++] = receiver.read();   // starts with i=1
        delay(100);
      }
      leds2[i++]='\0';
      digitalWrite(Red,HIGH);
    }
    if(i>0) {
      lightLeds(leds2);

so your led2 looks like
 {XX,'H','5','0','0','0','F'} //XX is undefined garbage might be '\0' so the array ends here

Solution define array as follows:
char leds2[7] ={'\0'};
.....
   while(receiver.available() && i<6) {
        leds2[i] = receiver.read();   // starts with i=0
        delay(100);
        i++;
      }
      leds2[i]='\0';
      // digitalWrite(Red,HIGH); // USE builtin led not one of the used as "end marker"
    }
    if(i>0) {
      lightLeds(leds2)

The light logic should go for the space a value is and not the value:
void lightLeds(char A[]){
    int i;

    for(i=0;i<6;i++){
        if(A[2]=='1' || A[2]==1) digitalWrite(Blue, HIGH);
        if(A[2]=='0' || A[2]==0) digitalWrite(Blue, LOW);
       ....
    }
}

To get the mix of different logics apart place both progs in an editor (eg. notepad++) side by side and look for differences in the logic. There is more than one error in the programs, fix them as proposed and it wll work (Read the comments in my code for further details).
EDIT
The OP had still problems with his code. I tookthe example and let it run hardware based on two UNOs, it worked but SoftwareSerial is very bad. No problem on the hardware with AltSoftSerial.h. In TinkerCAD no chance, the moment I switched to HW-Serial it worked like a charm, so here is the refined code for SENDER:
// Time variables
unsigned long startTime = 0;
unsigned long intervalTime = 1000; // send once a second

// Iniciamos los pins de los 4 leds de sender y reciver
const int ledRed = 13;
const int ledBlue = 12;
const int ledGreen = 11;
const int ledWhite = 10;

// iniciamos los pins de los 5 botones
const int pushbuttonRed = 7;
const int pushbuttonBlue = 6;
const int pushbuttonGreen = 5;
const int pushbuttonWhite = 4;
const int pushbuttonEnviar = 3;

// Declaramos el estado de los 4 leds de sender y reciver
int ledStateRed = 0;
int ledStateBlue = 0;
int ledStateGreen = 0;
int ledStateWhite = 0;

char c;
char leds[7] = {'H', '0', '0', '0', '0', 'F', '\0'};

//String cadena_final = "";
SoftwareSerial sender =  SoftwareSerial(rxPin, txPin);

void setup() {
  pinMode(ledRed, OUTPUT);
  pinMode(ledBlue, OUTPUT);
  pinMode(ledGreen, OUTPUT);
  pinMode(ledWhite, OUTPUT);
  pinMode(pushbuttonRed, INPUT);
  pinMode(pushbuttonBlue, INPUT);
  pinMode(pushbuttonGreen, INPUT);
  pinMode(pushbuttonWhite, INPUT);
  pinMode(pushbuttonEnviar, INPUT);
  sender.begin(19200);
  DEBUG_INTERFACE.begin(9600);
  DEBUG_INTERFACE.println("DEBUG ON");
}

void loop() {

  // Boton Rojo
  if (digitalRead(pushbuttonRed) == 1) {
    digitalWrite(ledRed, HIGH);
    ledStateRed += 1;
    leds[1] = '1';
    if (ledStateRed % 2 == 0) {
      digitalWrite(ledRed, LOW);
      leds[1] = '0';
      ledStateRed = 0;
    }
  }

  // Boton Azul
  if (digitalRead(pushbuttonBlue) == 1) {
    digitalWrite(ledBlue, HIGH);
    ledStateBlue += 1;
    leds[2] = '1';
    if (ledStateBlue % 2 == 0) {
      digitalWrite(ledBlue, LOW);
      ledStateBlue = 0;
      leds[2] = '0';
    }
  }

  // Boton Verde
  if (digitalRead(pushbuttonGreen) == 1) {
    digitalWrite(ledGreen, HIGH);
    ledStateGreen += 1;
    leds[3] = '1';
    if (ledStateGreen % 2 == 0) {
      digitalWrite(ledGreen, LOW);
      ledStateGreen = 0;
      leds[3] = '0';
    }
  }

  // Boton Blanco
  if (digitalRead(pushbuttonWhite) == 1) {
    digitalWrite(ledWhite, HIGH);
    ledStateWhite += 1;
    leds[4] = '1';
    if (ledStateWhite % 2 == 0) {
      digitalWrite(ledWhite, LOW);
      ledStateWhite = 0;
      leds[4] = '0';
    }
  }

  // Boton Enviar
  if (digitalRead(pushbuttonEnviar) == 1) switchAll();

    if (millis() - startTime > intervalTime) {
    DEBUG_INTERFACE.println(leds);
    sender.println(leds);
    startTime = millis();
  }
}

void switchAll() {
  // Reinicio los leds de sender para enviar otro mensaje
  ledStateWhite = 0;
  ledStateGreen = 0;
  ledStateBlue = 0;
  ledStateRed  = 0;
  digitalWrite(ledWhite, LOW);
  digitalWrite(ledRed, LOW);
  digitalWrite(ledBlue, LOW);
  digitalWrite(ledGreen, LOW);
  DEBUG_INTERFACE.println(leds);
  leds[1] = '0';
  leds[2] = '0';
  leds[3] = '0';
  leds[4] = '0';
}

and the code for RECEIVER:
// Iniciamos los pins de los 4 leds
const int Red = 4;
const int Blue = 5;
const int Green = 6;
const int White = 7;

// Creamos el boton que limpia pantalla
const int buttonClear = 10;

char rc;
const int maxChar = 6;
static byte charCount = 0;
char leds2[7] = {'\0'};
bool newData = false;

#define DEBUG_INTERFACE Serial
#define receiver Serial

void setup() {
  receiver.begin(9600);
  pinMode(Red, OUTPUT);
  pinMode(Blue, OUTPUT);
  pinMode(Green, OUTPUT);
  pinMode(White, OUTPUT);

  DEBUG_INTERFACE.begin(9600);
  DEBUG_INTERFACE.println("DEBUG ON");
}

void loop() {
  receiveStartEndMarkers();
  if (newData) {
    DEBUG_INTERFACE.print(" LED Array received: ");
    DEBUG_INTERFACE.println(leds2);
    lightLeds(leds2);
    newData = false;
  }
}

void lightLeds(char A[]) {
  for (int i = 0; i < 6; i++) {
    if (A[1] == '1' || A[1] == 1) digitalWrite(Red, HIGH);
    if (A[2] == '1' || A[2] == 1) digitalWrite(Blue, HIGH);
    if (A[3] == '1' || A[3] == 1) digitalWrite(Green, HIGH);
    if (A[4] == '1' || A[4] == 1) digitalWrite(White, HIGH);
    if (A[1] == '0' || A[1] == 0) digitalWrite(Red, LOW);
    if (A[2] == '0' || A[2] == 0) digitalWrite(Blue, LOW);
    if (A[3] == '0' || A[3] == 0) digitalWrite(Green, LOW);
    if (A[4] == '0' || A[4] == 0) digitalWrite(White, LOW);
  }
  DEBUG_INTERFACE.print(A); DEBUG_INTERFACE.println(" Leds switched");
}

void receiveStartEndMarkers() {
  static boolean recvInProgress = false;
  char startMarker = 'H';
  char endMarker = 'F';

  if (receiver.available() > 0) {
    rc = receiver.read();
    //DEBUG_INTERFACE.print(rc);
    if (recvInProgress) {
      if (rc != endMarker) {
        leds2[charCount] = rc;
        charCount++;
        if (charCount > maxChar) {
          charCount = maxChar;
        }
      }
      else {
        leds2[charCount] = rc;
        charCount++;
        leds2[charCount] = '\0'; // terminate the string
        recvInProgress = false;
        charCount = 0;
        newData = true;
      }
    }
    else if (rc == startMarker) {
      recvInProgress = true;
      leds2[charCount] = rc;
      charCount++;
    }
  }
}

Working code looks like this - change to HW-Serial 0(RX), 1(TX) to 1(TX), 0(RX):

So as a result DO NOT USE SoftwareSerial.h in TinkerCAD - its not working at the moment, use HW serial for communication examples or you will get crazy if working code suddenly outputs garbagge. When using real hardware use AltSoftSerial (full duplex mode). If you plan to use your design with real hardware use resistors for the LEDs (search for resistor calculator LED) as different colored leds need different resistor values.

I've added all of the suggested changes, still the problem persists, the lights from the second arduino will not light up. Also i cannot find a continuation in the comments as you suggest in the end of your post.

There, the code has been edited

Sure, here is the tinkercad link: https://www.tinkercad.com/things/37CXjQkn6Bi-copy-of-4-buttons-4-leds/editel?sharecode=dSsvqDLMEfnYp7htfceDF2-BnIh1-h0FegRC5zt1KdQ

Riddle solved see my edit above example under your link is fully working now-have fun and if ok mark as solved Thanks

I'm sorry, it seems that both receiver and sender are the same code.

Codebreaker, it's not working for me. The LEDs on the second Arduino are not lighting up and the second Arduino is never receiving the LED array or atleast the message is never displaying.

Code fixed (c&p error). You have of course to use HW Serial so connect 0(RX), 1(TX) from one Uno to 1(TX), 0(RX) to the other and delete the sw serial cables I tested for an hour it works 100%

Yes, it works. Thank you so much.


text:
eps32 bad adc even with external adc (ADS1115)
Im trying to read an analog value with my esp32 and send it over wifi to another esp32. The wifi part works flawless, however when i try to read an analog value form the esp32 its not useable. It jumps around +-100 on range 0-2000. Now i tried to use an external adc, because i heard that some have problems using the internal one with wifi. However i connected it via pins 21 and 22 (SDA Scl) and i have the same problem.
Internet couldnt help me at all, i hope you guys can.
Br
Felix

Are you running the external ADC from the ESP32's power?

What kind of analog value are you trying to read?

The esp has two internal adcs, of which one does not work with wifi. But the other one is supposed to work and I haven't had any problems so far. Please say something more about your setup. Breadboards can cause problems when wifi is active.

Ok so muiltiple things caused a bad analogread. Im trying to read a voltage level from 0-3,3v. Only pin 33 Worked and there i had a bit better readings. However still unusable. After i connected the esp32 to an external power supply the value was much better and more usable. Then i implemented some code wich is calcualating an average from 500values. This helped a lot and now im on +-1 on range 0-1000. I still dont know why the external adc didnt work well. I also ran it from external power. Same problem. Best Rg Felix

source: Stack Exchange

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

sort: votes


text:
Terminal read-only serial monitor without blocking serial port for sketch upload
I would like to have all serial output from Arduino (nano) dumped to the terminal in Linux, without blocking the serial port for uploading new sketch version (for quick debugging loop), when using Arduino-Makefile:
[Errno 16] could not open port /dev/ttyUSB0: [Errno 16] Device or resource busy: '/dev/ttyUSB0'

Is there something made for that already? I did read about 10 related questions here and elsewhere (using screen, socat and others) but none of them deals with the question how to not block the port.
I might eventually code something in Python, which will disconnect when  signalled and reconnect again after a few seconds (I use custom Makefile for the upload) and I imagine Arduino's IDE serial monitor does something similar.
Other pointers on how to solve the issue are appreciated!

(using screen, socat and others) but none of them deals with the question how to not block the port.

Other pointers on how to solve the issue are appreciated!

I say:

Virtually all hardware problems can be solved with software. But, sometimes, the $50000 software problem can be solved with the $2 hardware solution.

This is one of those cases. Buy a CP2102 6-pin serial UART USB adapter for < $2 on Ebay, or for < $10 on Amazon, to provide a second serial interface to the same Arduino (both connected to the same hardware UART built in to the Arduino's ATmega328 mcu). Let the main USB serial interface handle code uploads to the Arduino. Let this 2nd, external UART handle READ-ONLY from the Arduino!
Plug it in:
Arduino     CP2102 USB 6-pin UART
-------     ---------------------
Tx          Rx
GND         GND

Done. Do NOT plug in the CP2102 Tx to anything.
Now, use picocom (one of my favorites), screen, or my crude datalogging Python serial terminal I wrote here (eRCaGuy_PyTerm), or a 2nd instance of the Arduino IDE with the Serial Monitor, or any other serial terminal for that matter, to read from the CP2102 while the Arduino's built-in USB adapter does code uploading.
Two serial interfaces to the same pins on the Arduino: one does Tx/Rx to/from the Arduino, while the other does only Rx to read from the Arduino.
I use a 2nd UART like this all the time as a trick to allow me to read the data from the Arduino into one Serial Monitor in one instance of the Arduino IDE so I can see the numbers, and I use the external CP2101 USB adapter to read the same exact data from the Arduino into the Serial Plotter of another instance of the Arduino IDE so I can see the live, plotted graphs!
It's amazing how well this works. Quick hack. Easy solution.

Note: to you use my eRCaGuy_PyTerm Python serial terminal, first set all your serial parameters inside the user_config.py file, then run python3 serial_terminal.py to run the program. It is a 2-way serial terminal, with datalogging. It works quite well. I really should improve its readme and post some examples someday.

Cool!! In fact I have a few of those adapters around, it will be a $0 solution :)

You can write your own python script that prints received serial output. By using try/except in a loop you can "pause" your serial monitor while uploading is in progress.
I did the same a while ago using pyserial on linux. I'd like to share it, but at the moment I have no access to my other machine. I can post it later if you want.

Please post it, that would be awesome! I did not try yet but reconnecting while upload is in progress will make it fail; can you handle that or is there simply a fixed time to wait after failure?

@eudoxos k, I'll look for the code. You can't access the port with two processes at the same time, but you can catch the exception

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


text:
Need debug Software that can be used with Arduino IDE
Background: I have made a standalone Arduino board using Atmega328PB.  I have written code for a clock which lights LEDs based on the time.  After a day or so it locks up.  Sometimes it reboots.
I would like to get debug software that will tell me where in the code it is locking up or crashing.
It could be a memory issue - stack and heap crashing(?).
Compiler tells me sketch is using 62% of 32256 bytes storage space. Global variables use 34% of dynamic memory leaving 1332 bytes for local variables of 2048 bytes total.
Question:  Is there relatively cheap ( < $100) debugging software that is not very complex I could use to solve this issue?

serial.print() instructions placed in the program and serial monitor

did you use String?

@jsotola actually that's not really debugging (but afaik the only way on an Arduino)

Atmel Studio and a real hardware debugger. It's hardware you need, not software. Also remove String from your code.

I am not using String in my code.

What hardware would I use with Atmel Studio?

@MichelKeijzers, it is a sad state of affairs with debugging the arduino .... i have been using an array of integers ... various points in the program increment one of the integers ... a button press dumps the array to serial ... it avoids time delays due to multiple serial.print() statements within the program

you could use the watchdog interrupt to print some information about the state of the MCU and then let the watchdog reset the MCU

I did read about the watchdog interrupt.  Do you know of a good link I could learn about it and how to print the state of the MCU?

https://github.com/per1234/WatchdogLog

Thanks Juraj!  I will study that.

@jsotola that's approximately the same as I also did some debugging (except for the button which is a good idea). But also the lack of memory makes this hard to 'store' some data (as lack of SRAM is already an issue without this way of 'debugging'). Testing all non-Arduino related code via a separate PC program/unit tests is also a good idea, but of course you cannot test Arduino specific code this way.

If you suspect there is a memory leak, you may want to Serial.println the freeMemory in your loop.

@hcheung I will try printing free Memory.  I did not know of the MemoryFree Lib.  I just let it run for 14 hours with serial prints throughout and it went into a strange mode.  It went to a function from Loop and just kept going through the function like it was in a while loop.  Then every 7 seconds it would randomly go back to loop and go to a few other functions, and in one function went through if and else statements like they were both true, then back in the first function as if a while loop again....then repeat.  I reset the board and runs fine. Lets see what FreeMemory tells me.


text:
Arduino PS2X module not working with controller
I have been trying to use the PS2X module to try to use my PS1 remote with my arduino (I am guessing that PS1 controllers will work because they are virtually the same ). The problem is that I don't want to download the module from the original website because it is not secure (it had HTTP instead of HTTPS) and the download file could contain viruses. Instead I got it off the arduino website. I have wired my controller correctly and have triple checked that all the wires are in the right positions and they seem to be. I then used the arduino example program given by the safely downloaded file. I complied it onto my arduino and I got the following message in the serial "No controller found, check wiring, see readme.txt to enable debug. visit www.billporter.info for troubleshooting tips
Unknown Controller type." I then looked into the text file to debug it and it told me to uncomment 2 of the lines which is what I did. I then ran the example program file again like how the readme file told me to, and I still get the same errors.
link github:https://github.com/madsci1016/Arduino-PS2X
link to the main: http://www.billporter.info/2011/03/27/arduino-playstation-2-controller-library-troubleshooting-guide/
wiring:

how I have wired it:

@jsotola it LITERALLY means "the same"

Which example in which library? Please provide a link, if possible for the github site of the library. Also show your wiring

@chrisl shown above

You still didn't include the link. Do you mean this library?

yes I do mean that one sorry


text:
sim800l gsm module reboot command
i have a project to control a relay by sms and call by arduino and sim800L gsm modem
and i need to modify the code below to by adding command to reboot or reset the modem ever hour
i mean delete all sms and call history and reboot the modem because the modem is always on for long time and the modem after few days of operation becomes not responsive
any one can help me and solve the problem

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11);  // (Rx,Tx  > Tx,Rx)

char incomingByte;
String inputString;
int relay = 4; // Output for Relay Control
int LEDG = 8;
int buzzer = 5;
int LED = 6;
int buttonPin = 2;
int buttonState = 0;
void setup()
{
      pinMode(relay, OUTPUT);
      pinMode(buzzer, OUTPUT);
      pinMode(LED , OUTPUT);
        pinMode(LEDG , OUTPUT);
      pinMode(buttonPin, INPUT);
      digitalWrite(relay, LOW); // Initial state of the relay
       digitalWrite(buzzer, LOW);
        digitalWrite(LED, LOW);
        digitalWrite(LEDG, LOW);

      Serial.begin(9600);
      mySerial.begin(9600);

     while(!mySerial.available()){
        mySerial.println("AT");
        delay(1000);
        Serial.println("Connecting...");
        }
      Serial.println("Connected!");
      delay(30000);

      mySerial.println("AT+CMGF=1");  //Set SMS to Text Mode

      delay(1000);

      mySerial.println("AT+CNMI=1,2,0,0,0");  //Procedure to handle newly arrived messages(command name in text: new message indications to TE)
      delay(1000);
      mySerial.println("AT+CMGL=\"REC UNREAD\""); // Read Unread Messages
      delay(1000);
       mySerial.println("AT+CLIP=1");
        delay(1000);
      digitalWrite( LEDG , HIGH);
     }

void loop()
{

 m:
  if(mySerial.available()> 0){
      delay(100);

    inputString = mySerial.readString();
    Serial.println(inputString);

     if(inputString.indexOf("0000000") > 0)
      {
             mySerial.println("ATH");
             delay(250);
            digitalWrite(relay, HIGH);
            delay(250);
            digitalWrite( buzzer , HIGH);
            delay(250);
            digitalWrite( LED , HIGH);
            delay(300);
            digitalWrite( relay , LOW);

            while(1){
               inputString = mySerial.readString();
                    Serial.println(inputString);
                  if (inputString.indexOf("00000000")>0 && inputString.indexOf("OFF") > -1){

                     digitalWrite( buzzer , LOW);
                     digitalWrite( LED , LOW);
                     goto m;
                  }
            buttonState = digitalRead(buttonPin);
           if (buttonState == HIGH) {
                    digitalWrite( buzzer , LOW);
                     digitalWrite( LED , LOW);
                   goto m ;
                   }
                   }

          }

    if(inputString.indexOf("000000") >0 && inputString.indexOf("1") > -1 )
      {

            digitalWrite(relay, HIGH);
            delay(250);
            digitalWrite( buzzer , HIGH);
            delay(250);
            digitalWrite( LED , HIGH);
            delay(300);
            digitalWrite( relay , LOW);
               while(1){
                   inputString = mySerial.readString();
                    Serial.println(inputString);
                  if (inputString.indexOf("00000000")>0 && inputString.indexOf("OFF") > -1){

                     digitalWrite( buzzer , LOW);
                     digitalWrite( LED , LOW);
                     goto m;
                  }

           buttonState = digitalRead(buttonPin);
           if (buttonState == HIGH) {
                    digitalWrite( buzzer , LOW);
                      digitalWrite( LED , LOW);

                       goto m;
                   }

                   }

          }

  }
}


text:
activate a relay with two esp8266 -12e pins
I have an esp8266-12e that I want to activate the reset side of a latching relay.  The problem is that the 12e only puts out 12mA/pin and the relay needs more than that.  I am using a transistor on the set side from a rf antenna signal.  I only have one 3.3v power source.  Is there a way to have two pins go HIGH at the exact same time and be connected to the reset side of the relay so there is enough current?  Would this work, would it hurt anything, and how would I write the code for it and how would I wire it up?
I have tried the code where one pin is written HIGH right after the other like this
digitalWrite (5,HIGH);
digital Write (6,HIGH);

but I think pin 5 goes of before pin 6.
Any way to get them to go off at the same time?
Thanks for the help

No that's not a good idea.  You need to use a transistor to switch the relay.  You can drive the relay from an output pin.

I think you will need a transistor. On separate question that you asked, you can turn two digital pins on at the same time through port manipulation.

get power from power supply. use a pin to switch the power over a transistor

@hcheung Port manipulation like that isn't available on the ESP8266 where all the hardware interaction is performed through an SDK and the internal port -> pin arrangements aren't known (if they even exist).  Better is to use the tri-state functionality of the pins if you must do it at all.

That is not a good idea.
Isolating the relay from the IO pin is not just about the current limit of an IO pin, it's also about preventing back-EMF spikes from the relay coil(s) from damaging the delicate internals of the chip.
Instead you must at least use a transistor and a back-EMF protecting diode.
However - if you did want to theoretically have two pins safely controlled to provide double the current (though I stress again, do not do this for driving a relay), it is possible.
But it's not straight forward.
It's not possible on the ESP8266 to use port manipulation to make two pins change state at the same time. However it is possible to go via a third state that makes it safe.
Note: this will only be "safe" for IO pins that do not do strange things at bootup, and many of the pins on the ESP8266 do strange things.
IO pins actually have three states, not two:

High
Low
High Impedance

The latter is the state the pin is in when in INPUT mode. And we can use that to our advantage.
When in High Impedance mode it's like the pin is disconnected.  So we could:

Make sure both pins are in INPUT mode
Switch one pin to OUTPUT and set it to the desired state
Switch it back to INPUT mode (keeping the desired state latched)
Switch the other pin to OUTPUT and set it to the desired state
Set the first pin back to OUTPUT mode again.

This can be slightly compressed as we don't really need to set both pins to INPUT at the start, only one.  So here's some code that might do it:
void digitalDoubleWrite(int pina, int pinb, bool level) {
    pinMode(pina, INPUT);
    pinMode(pinb, OUTPUT);
    digitalWrite(pinb, level);
    pinMode(pinb, INPUT);
    pinMode(pina, OUTPUT);
    digitalWrite(pina, level);
    pinMode(pinb, OUTPUT);
}

You might ask why we'd want to switch to OUTPUT just to latch a level into the pin. Well, that's because of a quirk of the Arduino API. A historical artefact that is lingering in there to this day:

digitalWrite() on a pin set to INPUT mode was used to turn the internal pullup resistor on and off

It's actually how the AVR's IO ports control the pullup resistors internally, and that has most often been copied in software for other chips to maintain backward compatibility with old code. So as a result we have to switch to OUTPUT mode so that the API code knows that we mean to set the output latch state and not the pullup resistor state.

Thank you for your answers.  They are all very valuable.  I will make this one as the answer as it provides the most information for anyone wishing to get information.


text:
How to use DO pin on ldr module?
I have ldr module with 4 pins
 1. Vin
 2. Gnd
 3. AO
 4. DO
I want to know how can i take advantage of DO suppose i want to turn on lcd display when light falls on the ldr sensor!

I have noticed when light falls on ldr sensor the Green  led with DO written next to it lights up.

I bet if you look where you bought that little board from they have some sort of instructions on how to use it.  They usually do.

I bought it long time back i dont even remember now :(

it is digital out ... do some experimenting

So go look online for a similar one.  Check and see if it has some numbers or something on it that you can google.  Be smart about this.

what is the problem? wire and code it as button

The DO pin gives a Digital Output that is HIGH when the light falling on the LDR is above a threshold, and LOW when it's below a threshold. Just connect it to a digital input pin and read that pin with digitalRead().
You can change the threshold by adjusting the small blue trimpot.

fwiw, this is problematic because the LDR can get "accustomed" to a light level and change responsiveness, so the threshold adjustment won't always keep the same objective light level (lux) setting as a trigger level, but it should be enough for "is it light or dark". It would be better done in software, so you can work around such fatigue and surging values from the LDR with debouching, self-calibration via computed averages, and actually seen high/low values as a min/max.

@dandavis, for that there is AO (analog output). but why would one buy a module for LDR and one resistor.


text:
Timer Accuracy Always off by 1uS
I am using the ATMega32u4 to generate a pulse at 1 kHz. I am using Timer 3, which is a 16-bit timer and using a prescaler of 1, so I have a 0.0625uS resolution. The good news is that this is working, I can control the frequency and pulse length of the square wave. The issue is that I noticed the pulse always seems to be 1uS off.
If I set a period of 1000uS, and a pulse of 500uS, the oscilloscope shows a period of 1001uS and a pulse of 501uS.
If I set a period of 100uS, and pulse of 10uS, the oscilloscope shows a period of 101uS, and a pulse of 11uS.

If the Timer had an error percentage, then both the period and pulse should be off by the same percentage, but there are always off by the same 1uS length. I assume I am doing something wrong, so I have posted my code below.
const int pin1 = 4;

void setup() {
  //Set pin to output
  pinMode(pin1, OUTPUT);

  // Reset Timer 3 Control Register to 0
  TCCR3A = 0;

  // Set prescaler to 1
  TCCR3B &= ~(1 << CS32); //0
  TCCR3B &= ~(1 << CS31); //0
  TCCR3B |= (1 << CS30);  //1

  //Reset Timer 3 and set compare value
  TCNT3 = 0;

  // Enable Timer 3 compare interrupt A and B
  TIMSK3 |= (1 << OCIE3B);
  TIMSK3 |= (1 << OCIE3A);

  //Enable global interrupts
  sei();

  //Set Refresh Rate
  OCR3A = 1000;
  OCR3B = 100 / 0.0625;
}

void loop() {
  delay(100);
}

ISR(TIMER3_COMPA_vect) {
  PORTD &= ~_BV(pin1); //LOW
  OCR3A = 160;
}

ISR(TIMER3_COMPB_vect) {
  TCNT3 = 0;
  PORTD |= _BV(pin1); //HIGH
}

Why doing a division with a float in 100 / 0.0625 instead of simply 1600?

@hcheung I just do this to make it easy to change. I will say "1600" when I lock down a frequency I want to use. Right now I am just testing, and it still works.

The thing is floating point calculation take time, your question is about timing.... Of course the compiler might optimised it for you during the compilation, but that's an assumption.

@hcheung, the floating-point operation is only in the setup, so it should only be crunching that number once and then putting it in the register. If I do change it to "1600", there is no change to the timing.

oh yes, you are right.

Not only that, but the compiler probably optimizes it to just a constant value, so there’s no crunching numbers at all (at least not by the ATMega).

The problem is here:
ISR(TIMER3_COMPB_vect) {
  TCNT3 = 0;
  ...

If you want to get anything that vaguely looks like accurate timings,
you should never reset the timer. The MCU needs time to process an
interrupt: it has to save the program counter to the stack, load the
address of the interrupt vector, execute it (it's typically a jump),
save all the registers it needs to the stack, and only then can it start
executing the code you wrote in the ISR. From your experiment, it looks
like all this process takes about 1 µs. But don't take this delay
for granted: from time to time the interrupt will fire while the MCU is
processing another interrupt, and this will increase the latency.
You have two options:

Update the compare registers in order to program the next interrupts
some time in the future. In this case, the COMPB ISR would do
OCR3A = OCR3B + 160; OCR3B += 1600;. Do not worry about the
overflows: they do the Right Thing.
Let the timer reset itself to zero: it will then do so without
loosing a single cycle. See the CTC and fast PWM modes of the timer.

For your specific use case, PWM seems like the obvious choice. Not only
will the timer handle the resetting itself, it can also generate the
output signal without requiring you to write any ISR. Beware that in
this case the period of the signal is whatever you load in corresponding
compare register plus one, and the duration of the pulse is another
compare register plus one.
As a side note:
  // Reset Timer 3 Control Register to 0
  TCCR3A = 0;

I would also reset TCCR3B. The Arduino core configures both registers
for it's own purposes, so it would be safer to clear them both.


text:
PC8563 Arduino interface
i am trying to interface pc8563 with arduino uno . I have small doubt related to RTC slave address reading
RTC datasheet says page no 14
where device slave address is A2 for write and Read A3
i would like to know how A2 /A3
Example code from website device id mentioned as 0X51
My question how to config exact slave address ??
#include "Wire.h"
#define PCF8563address 0x51

byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
String days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

byte bcdToDec(byte value)
{
  return ((value / 16) * 10 + value % 16);
}

byte decToBcd(byte value){
  return (value / 10 * 16 + value % 10);
}

void setPCF8563()
// this sets the time and date to the PCF8563
{
  Wire.beginTransmission(PCF8563address);
  Wire.write(0x02);
  Wire.write(decToBcd(second));
  Wire.write(decToBcd(minute));
  Wire.write(decToBcd(hour));
  Wire.write(decToBcd(dayOfMonth));
  Wire.write(decToBcd(dayOfWeek));
  Wire.write(decToBcd(month));
  Wire.write(decToBcd(year));
  Wire.endTransmission();
}

void readPCF8563()
// this gets the time and date from the PCF8563
{
  Wire.beginTransmission(PCF8563address);
  Wire.write(0x02);
  Wire.endTransmission();
  Wire.requestFrom(PCF8563address, 7);
  second     = bcdToDec(Wire.read() & B01111111); // remove VL error bit
  minute     = bcdToDec(Wire.read() & B01111111); // remove unwanted bits from MSB
  hour       = bcdToDec(Wire.read() & B00111111);
  dayOfMonth = bcdToDec(Wire.read() & B00111111);
  dayOfWeek  = bcdToDec(Wire.read() & B00000111);
  month      = bcdToDec(Wire.read() & B00011111);  // remove century bit, 1999 is over
  year       = bcdToDec(Wire.read());
}

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  // change the following to set your initial time
  second = 0;
  minute = 28;
  hour = 9;
  dayOfWeek = 2;
  dayOfMonth = 13;
  month = 8;
  year = 13;
  // comment out the next line and upload again to set and keep the time from resetting every reset
  setPCF8563();
}

void loop()
{
  readPCF8563();
  Serial.print(days[dayOfWeek]);
  Serial.print(" ");
  Serial.print(dayOfMonth, DEC);
  Serial.print("/");
  Serial.print(month, DEC);
  Serial.print("/20");
  Serial.print(year, DEC);
  Serial.print(" - ");
  Serial.print(hour, DEC);
  Serial.print(":");
  if (minute < 10)
  {
    Serial.print("0");
  }
  Serial.print(minute, DEC);
  Serial.print(":");
  if (second < 10)
  {
    Serial.print("0");
  }
  Serial.println(second, DEC);
  delay(1000);
}

RTC datasheet

so, which one works? A2 or 51?

the two are actually the same address .... A2 is an 8 bit number .... 51 is a 7 bit number ... bit 0 is used to specify read or write .... write down A2 as a binary number ... you'll see that 51 is the top 7 bits

Normal I2C addresses are 7-bit long. On the first frame of an I2C
transaction, the master sends an 8-bit byte containing the address of
the slave followed by a bit specifying whether this is a read or a write
operation. Some people tend to call “address” the whole 8-bit frame,
which causes confusion. Because of this, we end up having three flavors
of I2C addresses:

the 7-bit address, which is the real device address
the 8-bit “write address”, which is the address followed by a 0
meaning “write operation”
the 8-bit “read address”, which is the address followed by a 1
meaning “read operation”

For your RTC, the 3 addresses are the following, in hex and binary:
7-bit = 0x51 = 0b1010001
write = 0xA2 = 0b10100010
read  = 0xA3 = 0b10100011

The Arduino Wire library expects the 7-bit address.


text:
HID communication between Arduino Uno and computer
I used some firmware I found online to turn the UNO into an emulated HID device. The Arduino is no longer connected to a Serial COM port so I can't send serial data from my computer to the device. Is there a way that the Arduino can receive data from the computer in order to drive a function while in the HID emulated state?

yes, if the HID has an input channel

the 'some firmware' would have to support it

You could use a second USB on the PC and use Hardware Serial to transmit commands. (Either via a second Arduino or a FTDI adapter) But be aware that at least the firmware I use and the controller programs are very sensitive to being disturbed in the loop. So you should have a good understanding of timers, interupts and non blocking code.

doesn't NicoHood support Serial and HID together?


text:
Wire.endTransmission() hangs, but only, if wire.begin(); is called with an address (MKR WiFi 1010)
This code runs without issues, scoped and seen from serial output:
#include <Wire.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Wire.begin();
  Wire.onReceive(receiveEvent);

  while (!Serial);
}

void loop()
{
  Serial.println("1");
  Wire.beginTransmission(8);
  Serial.println("2");
  Wire.write(0x1);
  Serial.println("3");
  delay(100);
  Wire.endTransmission();
  delay(100);
  Serial.println("4");
  delay(500);
}

void receiveEvent(int howmany)
{
  delay(100);
}

This one hangs on Wire.endtransmission():
#include <Wire.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Wire.begin(10);
  Wire.onReceive(receiveEvent);

  while (!Serial);
}

void loop()
{
  Serial.println("1");
  Wire.beginTransmission(8);
  Serial.println("2");
  Wire.write(0x1);
  Serial.println("3");
  delay(100);
  Wire.endTransmission();
  delay(100);
  Serial.println("4");
  delay(500);
}

void receiveEvent(int howmany)
{
  delay(100);
}

The problem starts as soon as I assign an address in Wire.begin(). As I understand, a slave is also allowed to send data and temporarily becoming a master when addressing another device.

Is there another master on the bus, that would require the mkr to also be a slave?

Yes and no, I have three devices, master mkr, two trinket m0 slaves. I want to push data from the slaves to the master immediately when they receive said data. The way it is setup, data collision from the slaves is impossible as the master alterantely enables the sensors on the slaves (this is why I need it to be a master for coordination) but I also want to receive the data as soon as it arrives and not poll for it as I fear that might mess up my interrupts on the slaves.

While the wire library supports multi-master for AVR, it doesn't for ATSAMD.
Temporary promotion to master is disabled when given a slave address, so the program will hang on wire.endTransmission().

I want to push data from the slaves to the master immediately when they receive said data.

So that means, that each slaves becomes master directly after it has received data from the MKR. This is still a multi-master setup, even while you are avoiding collisions through a fixed protocol. The Wire library does not support multi-master.
But I also don't understand, why you would need this. Your protocol does this: The MKR sends data to a slave (triggering it and maybe also sending some commands). Then the slave should send data back to the master. Then the transmission ends. This is normally done in I2C with just one master. The master does a master write (via Wire.endTransmission() and sends some command data to the slave. The slave will prepare the data, that the master requested, in it's buffer. Then the master will start a master read (via Wire.requestFrom()) which reads the data from the slave.
So you don't need a multi-master setup for this. It does exactly, what you described, but with only one master.

I found out the Wire library actually does support multi-master, but not on the ATSAMD

I have no way to predict when the slave will receive it's data, so other than polling the slave continuously I won't know when the data arrived at the slave.

In your original plan, you wanted to prevent collisions by essentially polling the slaves (writing data to them, so that they answer them selfs with a master transmission). If that is not an option anymore, you should think about a different communication interface, that better supports multi master scenarios


text:
5 arrays or one matrix?
I am working on a project where i need to store as fast I can following :
1 - Acceleration on X
2 - Acceleration on Y
3 - Acceleration on Z
4 - timestamp
5 - A value from some other sensor
Because I need to get these as fast as I can I am thinking to not do any calculation while acquire values and just store them for 30 -60 seconds and then when the "test" is complete to compute calculations.
My question is if will be better to create 5 arrays and put these values there or create a matrix and store values there.
I need these values to be stored like they are "connected"
e.g. on reading 1 i get 5 values and put them on array[0] , then on reading 1 and so on
Also an important thing to mention, this will run on a esp32.
Thank you

The time needed to store these values in RAM will most likely be completely dwarfed by the time needed to read the values from the sensors.

Thanks a lot, I think you are right

I fully agree with Edgar Bonet.
My opinion is keeping a 'matrix' is better, or actually one array (of structs), where each array elements stores all information for one measurement (which is stored inside one struct). This has some benefits:

Data of one measurement is consecutive in memory, so you can easily transfer it (to some external memory or sending it). It's exact one struct (and you can use sizeof(struct_item) to know how many bytes you have to transfer.
It's good practice in general to keep information together, creating 5 always-equal length arrays seems strange.
If for some reason you want to make a single array dynamic or change it to a ring buffer for example, you can easily add/remove items (instead of dynamically changing 5 arrays).
Locality of change (see comments of Kwasmich/DuncanC)

There is also one benefit about having separate arrays (where each array stores one type of information, like an acceleration or timestamp: when you have a function (especially in another class) that only needs one of them, you can specifically send that array (or pointer/reference), so the other information is hidden from that function.

You are right but now rise another question: If i put all in one array then value[x] should contain all - probably i need concatenate them somehow accX,accY...so i will have a string array

You know there are religious fights going on abaout AoS vs. SoA (Arrays of Struct versus Structure of Arrays). It is mostly about data locality which does not apply to MCUs because of the lack of caches.

@David the idea is to make an array of structs where you put in the values.

@Kwasmich I didn't know those fights are so hard/religious. However, I can mention something about it in my answer (so I'm going to adapt).

For modern CPUs or GPU farms, locality of reference can make a huge improvement in cache coherence, and thus a huge speed improvement. That would suggest an array of structs, where all the values for a single calculation were grouped together. However, as Kwasmich says, that doesn't apply to MCUs like Arduinos.

@DuncanC  Ok, so another (good) reason to have an array of structs. On the other hand, suppose you need to perform an algorithm on a single type (let's say timestamp), than it would be opposite, but in most cases I assume the info of one measurements belongs more together than the information of one  type (axis, time stamp).


text:
Vin & VU pins of NodeMCU V3
Can we use the vin pin of the lolin v3 nodeMCU as a 5V supply. If yes, i checked mine with a multimeter. At max, it gives a voltage of 2V. Is my pin blown out? Also, can use the VU pin as a 5V supply? Will using it cause any problems to my laptop's USB port? Can somebody help me out?
I need 5V to drive a relay using the v3

In addition to the voltage, you need to think about how much current you’ll need.  That’s the bigger driver of whether or not you can use  pin as a source.

no, but you can use the same pin on an Amica nodemcu (which all seem to use a cp2102 instead of ch340), that's connected to 5v on the usb through a diode that handles about 400ma safely. for this reason alone (powering 5v periphreals while running from usb power), i never buy the the larger lolin boards, except accidentally when listings are deceptive.

So the Vin of V3 doesn't support 5V output?

On the NodeMCU “v3” (and only on the v3) there’s a pin called VU (Vusb) that is connected to the +5V on the USB bus of the NodeMCU socket. This pin can be used to feed external components when it’s connected to USB, within the limits of the USB power supply it’s connected to.
The Vin pin (which is available on all NodeMCUs (and not just the v3) is a +5V power input which can be used to power the NodeMCU if it is not connected to USB. It can not be used as an output and it needs a stabilized supply.

The previous versions do give 5V from the Vin pin. I've driven sensors using them. The V3 also has been used for the same. I was informed by my employer.

Strictly speaking, the Vin pin is less than 5v because it steps down to about 4.76V because of a Schottky diode (see circuit diagram)

The VU is useful for example to power 5 V relay modules, which at 3.3V, usually work but are slower and less reliable.

Oh my god. Where is this info mentioned? I was about to return my LEDS/controller thinking they are defective or something. Then I saw this answer!


text:
With the press of a button, I need to play an intro sound file, then one of 50 other sounds in order, each time a button is pressed
I need to play an intro file and one of 50 different files after it in order each time the switch is pressed, with a short delay between the intro and next file.
For example let's say the intro is called "intro.wav," and each of the 50 other sound files are just named 01.wav-50.wav.
The logic would be:
TRIGGER
PLAY intro.wav
250ms DELAY
PLAY 01.wav
END

TRIGGER
PLAY intro.wav
250ms DELAY
PLAY 02.wav
END

TRIGGER
PLAY intro.wav
250ms DELAY
PLAY 03.wav
END

and so on, until all 50 files are played, then start over.
The messages are going to be a curated group of words. I'm not sure what the intro will be yet, but it will just be something like:
intro.wav = "The word of the day is"
01.wav = "help"
02.wav = "climb"
03.wav = "think"
I'm looking for some guidance on where to start with this, if an Arduino product would be suitable, and if so, which one.  I've worked with the Adafruit Audio FX Sound Board before, and that can almost do what I need it to do, but not by itself. It looks like I'll need an Arduino of some kind to accomplish this, so I went ahead ordered an Uno.
I'm not married to the idea of having the intro and word files separate either. If I need to create all 50 files to contain the intro and the word, that would be fine, as long as each one is triggered sequentially.
In that scenario, 01.wav could be "The word of the day is ... help" and the button would basically be the "next track" command.  I don't really have a problem with doing that because I'm all about keeping things simple and I don't think I'd run out of space, but I think it would be less time consuming to just dump all the individual word files onto the card.
The important thing is that the track(s) would play once, then stop, and when the button is pressed again, the next one plays.

That's simple.  Look at any basic Arduino example for how to read your button.  Then you just need an if statement that says if the button is pressed then play a sound.  An array of file names or if they're really sequentially numbered then you can probably create the file names on the fly.  They're just char array strings.  What part of this is holding you up?  You've done a great job of describing what you want to do but not what your problem is.  This isn't a free code writing service.  If you were hoping someone would just tell you what to do next you're in the wrong place.

@delta_g Yeesh. Guess I’m just a big dummy and I should give up since this is so simple and I couldn’t figure it out instantly! ¯\(ツ)/¯  This is my first foray into the Arduino world and was kinda hoping someone else had a similar project so as not to reinvent the wheel because yes it does seem like an easy thing to do, and in my 2 hour search I didn’t find any solutions.  I’m sure I’ll figure it out once I have a device I can work with.

Try forum.arduino.cc   That more for the non-specific, just tell me how to do it kind of questions.

@AdamDallas, you are not a dummy, you are a beginner arduino programmer ... try out some of the example sketches that are included with the Arduino IDE ... break your programming task into small pieces ... start with the button ... write code that toggles an LED ... add code that increments a number ... add code that inserts the number into a text string to produce a file name such as "4.wav" ... find code on the internet that plays wav files from the SD card ... pass the file name to that code

You will find all the code and thelibrary you need on the Adafruit learn center.
For such a project I would use a DF-robot (clone) MP3 player (~4$), an Uno, a speaker and an SD card. The library for the player includes examples to get you started and the sound project you plan is possible even with low programming skills. Look at the example codes provided and start to program.

Thanks for the input!  I just saw this, but I happened to order the microSD MP3 player the day I posted the question so I'm glad I'm on the right track. I will be testing as a standalone device today, but it does look like I'll probably need some code.  I was just reading through the sample code from DFRobot and it definitely looks like this is feasible.  Just hoping I can do this with the cheaper Arduino stuff and not have to use a Pi.


text:
Swap two arrays (using pointers, not copy)
I've got two arrays, defined as:
uint8_t array1[10];
uint8_t array2[10];

I'd like to swap the arrays (actually the pointers to each array) using code like this:
uint8_t *tmp = array1;
array1 = array2;
array2 = tmp;

However, I keep getting errors like:
invalid array assignment

for the last two lines. I don't recall this being such a problem in traditional C++. I've tried all sorts of casting to no avail. Is there something I'm missing?
I can get the code to run properly if I switch the declarations for the arrays to use new and have them just be more-or-less pointers rather than arrays, but I'd rather not have to do that:
uint8_t *array1 = new uint8_t[10];
uint8_t *array2 = new uint8_t[10];

Code is running on an ARM-based SAMD51 (Cortex M4 processor).
Thanks for any tips!

Figured it out. Though using new works, I wanted to keep the buffers out of the heap. The following declarations work with the swap code:
uint8_t a1[10];
uint8_t a2[10];
uint8_t *array1 = a1;
uint8_t *array2 = a2;

uint8_t *tmp = array1;
array1 = array2;
array2 = tmp;


text:
Is there a way to both read and write on the rising edge of the SPI Clock?
Im trying to use sipo and piso shift registers simultaneously with ESP32 using SPI. However the sipo(SN74AHC) reads data on the rising edge of clock and the piso(SN74HC165) outputs data on the rising edge of the clock. Using the arduino SPI library, there is not a spi mode that can accomidate this. As a result, I am losing a bit from either device no matter what I do.
Is there something I can do to get both read and write at the rising edge or will I be forced to read and then write, changing the spi mode in between?

Have you experimented with this?  You should still be ok with Mode 1 or 2.  You output on the rising edge and sample on the falling edge.  The PISO won't change the data bit until the next rising edge, so it will still be good to read when the clock falls.


text:
Need help with using pulseInLong to time a sensor
I have a setup consisting of a magnet suspended above a sensor coil. It acts as a pendulum and creates a ~ 4 mV signal when it swings over the coil - this goes through two stages of an LM358 to generate a 5V signal. The signal is very messy with lots of 'ringing'
This signal is fed into pin A0 of an Arduino Uno. I used MegunoLink.h and Filter.h which is an exponential filter library then applied constrain and map, finally converting to a clean 0 - 400 (units?) square wave of about 1 second with a varying duty cycle. This is the information I want as it tells me that the magnet is homing in on the sensor (the duty cycle increases as it gets close).
But when I apply pulseInLong I only get a string of zeros on the serial monitor.
What am I doing wrong?
Here is the sketch:
//  Coding by Jeremy 130520
//  further development for ricochet module
//https://www.megunolink.com/documentation/arduino-libraries/exponential-filter/
//https://www.google.com/search?q=how+to+use+arduino+pulsein

#include "MegunoLink.h"
#include "Filter.h"
// Create a new exponential filter with a weight of 5 and an initial value of 0.
ExponentialFilter<long> ADCFilter(5, 0);

int coilPin = 8;
int analogIn = A0;
unsigned long pulseLength;
unsigned long signal_1;

void setup()
{
  pinMode(coilPin, OUTPUT);
  pinMode(analogIn,INPUT);
  Serial.begin(9600);
  }

void loop()
{
 int RawValue = analogRead(analogIn);
  ADCFilter.Filter(RawValue);
 signal_1 =(ADCFilter.Current());
 signal_1 = constrain(signal_1,80, 200);
 signal_1 = map(signal_1, 80, 200,0,400);
 if (signal_1 >= 200) {signal_1 = 400; digitalWrite(coilPin, HIGH);}
 if (signal_1 < 200) {signal_1 = 0; digitalWrite(coilPin, LOW);}

 Serial.println(signal_1); //using the plotter

//pulseLength = pulseInLong(coilPin, HIGH);
 //Serial.println(pulseLength);
 delay(10);
}

You cannot use pulseInLong() because it is a blocking function. It
waits until the input rises, then waits until it falls again, and only
then it returns a value. While it's waiting, the rest of the program
cannot run. This means you will not be able to actually generate the
signal you are trying to time.
The easiest solution is to time things yourself with micros(). You
have to implement an edge detector, i.e. some logic that remembers the
previous state of the signal and notices when it changes:
static bool is_high;  // is the input currently HIGH?
static uint32_t time_of_rise;  // when did it rise?

if (!is_high && signal_1 >= 200) {  // rising edge
    time_of_rise = micros();
    is_high = true;
} else if (is_high && signal_1 < 200) {  // falling edge
    uint32_t pulse_width = micros() - time_of_rise;
    is_high = false;
    Serial.println(pulse_width);
}

Thanks Edgar that looks good - I shall try it tomorrow and get back to you

That worked very well. Clearly showing when the magnet gets close to the sensor coil allowing me to take some other action at that point.


text:
How do I set a variable so that after a condition is met the loop ignores input?
I have a analog inputs to my Uno that I am cleaning up and using to keep a digital pin high until the output drops to zero. At this point I want to stop reading that input because it may come back up after being low for a short time.
Is there any way to set a variable that can be triggered by that first zero that prevents the loop from sending the digital pin high from then on?
Like a latch of some sort, or could I use an interrupt somehow?

Sure. Just set a variable to some value. And use if to compare that value.

You may call that variable a "flag" which is set once your input == 0 and read before settings the output to high.

You've already described what you need to do.  Just set a boolean variable.  It really couldn't be easier.
boolean runThisPart = true;

void loop() {

  if(runThisPart) {
     // this part only runs if runThisPart is true
     //  if something happens and you don't want
     //  to run this part anymore then
     if(some-condition){
        runThisPart = false;
     }
  }
  //  The rest of your code can also set runThisPart
  //  to true or false to turn that section on or off.
}


text:
Is it possible to count rising edges of a 4 MHz clock on an Arduino Due and trigger an interrupt like all 4'000'000 edges?
I am struggling with my Arduino Due and the Timer Counter functionallity. The following is what I am trying to achieve:
I want to execute a function to a specific point of time or more precisley after a specific amount of rising edges given by an external clock signal with a frequency of approx. 4 MHz. Thus I read the Atmel Datasheet, Section 36, Timer Counter. My approach was to trigger an interrupt every rising edge and increment a counter variable until I reached the desired amount of rising edges and call my function then. I can confirm that I am in fact counting rising edges with my current approach but I am reading way too slow. Is there any kind of register or hardware counter which automates the counting process. Like I set the register to a specific value and wait for an overflow, execute my function and reset the register? From my web research I found that this is possible on the Uno and Mega but I could not find anything for the Due and to be honest I am a bit overwhelmed by the Atmel Datasheet. Why not just use an Arduino Due or Mega then? I need the 3.3 Volts of the Due and from what I found the Uno and Mega are 5 V devices.
This is my code:

// define capture channels
#define CAPTURE_TC TC0
#define CAPTURE_CHANNEL 0
#define CAPTURE_IRQn TC0_IRQn
#define CAPTURE_Handler TC0_Handler
#define CAPTURE_ID ID_TC0
#define CAPTURE_PIN 2
#define CAPTURE_CLOCK_SELECTION TC_CMR_TCCLKS_TIMER_CLOCK3

// clock divisors corresponding to CAPTURE_CLOCK_SELECTION
static const uint32_t divisors[5] = { 2, 8, 32, 128, 0};

volatile uint32_t captured_pulses = 0;
volatile uint32_t captured_ra = 0;
volatile uint32_t captured_rb = 0;
volatile float frequency, duty_cycle, active_time;

/*
* Function:  setup
* ------------------------------------------------------------------------------
* Setup code. Will be executed once.
*/
void setup() {

  // init serial connection
  Serial.begin(115200);
  Serial.print("Initializing...");

  // configure the PIO pin as peripheral
  const PinDescription *config = &g_APinDescription[CAPTURE_PIN];
  PIO_Configure(config->pPort, config->ulPinType, config->ulPin, config->ulPinConfiguration);

  // enable timer peripheral clock
  pmc_enable_periph_clk(CAPTURE_ID);

  // configure the timer
  TC_Configure(CAPTURE_TC, CAPTURE_CHANNEL,
    CAPTURE_CLOCK_SELECTION   // Clock Selection
    | TC_CMR_LDRA_RISING      // RA Loading: rising edge of TIOA
    | TC_CMR_LDRB_FALLING     // RB Loading: falling edge of TIOA
    | TC_CMR_ABETRG           // External Trigger: TIOA
    | TC_CMR_ETRGEDG_FALLING  // External Trigger Edge: Falling edge
 );

  // configure TC interrupts
  NVIC_DisableIRQ(CAPTURE_IRQn);
  NVIC_ClearPendingIRQ(CAPTURE_IRQn);
  NVIC_SetPriority(CAPTURE_IRQn, 0);
  NVIC_EnableIRQ(CAPTURE_IRQn);

  // enable interrupts
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_IER = TC_IER_LDRBS;

  // start timer counter
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_CCR = TC_CCR_CLKEN | TC_CCR_SWTRG;

  Serial.println("ready!");

} // setup

/*
* Function:  loop
* ------------------------------------------------------------------------------
* Loop code. Will be executed repeatedly after setup completed.
*/
void loop() {

 // Serial.print("Captured rising edges: "); Serial.println(captured_ra);
} // loop

/*
* Function:  CAPTURE_Handler
* ------------------------------------------------------------------------------
*
*/
void CAPTURE_Handler() {
 if ((TC_GetStatus(CAPTURE_TC, CAPTURE_CHANNEL) & TC_SR_LDRBS) == TC_SR_LDRBS) {
   captured_pulses++;
   // captured_ra = CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RA;
   // captured_rb = CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RB;

   if (captured_pulses == 4164303) {
    captured_pulses = 0;
    // specific_function_call();
   }
 }
} // CAPTURE_Handler

Thanks for your time, any help is grealty appreciated.

Atmel Datasheet, Section 36, Timer Counter. My approach was to trigger an interrupt every Are you sure you did read it? The timer is called "Timer Counter" because literally it has an internal... counter... so that you do not need to do something every input.

@KamilCuk As I said I was overwhelmed by it. I guess Section 36.7.2 is the relevant part for me but I usually do scientifc computing, I'm pretty new to all this hardware stuff which is why I am asking for help.

Sure. Aim for the RC compare part, set the the compare counter to that 4164303 and just trigger the interrupt once every 4164303 cycles. Also you could divide input clock by some value.

Thanks for the input, gonna try it.

If I may ask, for what application you need it for ? Btw any microcontroller datasheet is painful to read

@Weldriv  Datasheets are a pain to read, but that's the minimum you need to do to use the devices effectively.  And don't forget to read the erratas.  There are always noce surprises there that may save you a couple of weeks of tries and failures.

First of all excuse my inactivity but as you know it's crazy times right now. However I finally figured it out, it's for sure not the most elegant solution but it meets my requirements. Thanks for your help @KamilCuk.
Here is my code if anyone may ever have the same problem as I did. External signal goes on Digital Pin 2. Works fine with a 4.2 MHz external clock.

// define capture channels
#define CAPTURE_TC TC0
#define CAPTURE_CHANNEL 0
#define CAPTURE_IRQn TC0_IRQn
#define CAPTURE_Handler TC0_Handler
#define CAPTURE_ID ID_TC0
#define CAPTURE_PIN 2
#define CAPTURE_CLOCK_SELECTION TC_CMR_TCCLKS_TIMER_CLOCK3

/*
* Function:  setup
* ------------------------------------------------------------------------------
* Setup code. Will be executed once.
*/
void setup() {

  // init serial connection
  Serial.begin(115200);
  Serial.print("Initializing...");

  // configure the PIO pin as peripheral
  const PinDescription *config = &g_APinDescription[CAPTURE_PIN];
  PIO_Configure(config->pPort, config->ulPinType, config->ulPin, config->ulPinConfiguration);

  // enable timer peripheral clock
  pmc_enable_periph_clk(CAPTURE_ID);

  // configure the timer
  TC_Configure(CAPTURE_TC, CAPTURE_CHANNEL,
    CAPTURE_CLOCK_SELECTION   // Clock Selection
    | TC_CMR_LDRA_RISING      // RA Loading: rising edge of TIOA
    | TC_CMR_ABETRG           // External Trigger: TIOA
    | TC_CMR_CPCTRG           // RC Compare
  );

  // configure TC interrupts
  NVIC_DisableIRQ(CAPTURE_IRQn);
  NVIC_ClearPendingIRQ(CAPTURE_IRQn);
  NVIC_SetPriority(CAPTURE_IRQn, 0);

  // enable interrupts and start counter
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_IER = TC_IER_CPCS;                  // enable RC Compare Interrupt
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_CCR = TC_CCR_CLKEN | TC_CCR_SWTRG;  // the datasheet said I need this
  NVIC_EnableIRQ(CAPTURE_IRQn);                                                  // enable interrupts

  // set the trigger value for RC_Compare
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RC = 4164303;

  Serial.println("ready!");

} // setup

/*
* Function:  loop
* ------------------------------------------------------------------------------
* Main code. Will be executed repeatedly.
*/
void loop() {

} // loop

/*
* Function:  CAPTURE_Handler respectively TC0_Handler
* ------------------------------------------------------------------------------
* Timer capture trigger. Will be executed if TC0_RA == TC0_RC
*/
void CAPTURE_Handler() {
  // reset status register
  TC_GetStatus(CAPTURE_TC, CAPTURE_CHANNEL);

  // do something
  Serial.println("Trigger");
  // function_call()
}


text:
How to power 6 servo motors using battery to create a robotic arm?
I am trying to create a robotic arm. The problem is that I could not run all 6 servo motors -3 MG966r servo motors and 3 MG90S servo motors - simultaneously, using 12V and 3A AC to DC adaptor. Last time I tried, My arduino uno is totally broken. If you can, Could you provide the schematics for the circuit? or Is there any methods to solve this problem?. Also Is it a better idea to use servo motor shield?

the arduino and motor power are not related ... aruino provides control, not power

For this task you should use an extra power supply not running trough the Arduino. For this kind of setup I use PCA9865 16-channel servo dirver board cost around 5$, needs two pins only and can run all servos (strong 5V power supply provided => Amperage) simultaniously. For a max of 8 servos a 5V/2-2.5A power supply (wall wart) should be sufficient.
See this example circuit for how to connect:

The PCA9865 library has examples how to drive servos via program. As this board is an I/O board you could also attach joystick(s) or buttons to it to save pins on your board.


text:
Bluetooth Module 4.0 BLE
I'm trying to read data sent from my phone to arduino via HM-10 Bluetooth Module. I downloaded the app, I paired the module to phone but I can't read data.
If I just upload a blank sketch to arduino and open Serial Monitor, if I sent "1" from phone, it appears on the monitor, it's ok. But if I write Serial.begin(9600) in setup loop then noting happens and I can't see anymore the data from phone and Serial.read() is useless. Can you help me?
This don't work:
char incomingValue = 0;
int doorPin = 13;
void setup() {
  Serial.begin(9600);
  pinMode(doorPin, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    incomingValue = Serial.read();
    Serial.print("\n");
    if (incomingValue == '1') {
      digitalWrite(doorPin, HIGH);
    } else {
      digitalWrite(doorPin, LOW);
    }
  }
}

And with this I cand see to the Serial Monitor what I'm sending from phone but I can't read the character.
char incomingValue = 0;
int doorPin = 13;
void setup() {
 // Serial.begin(9600);
  pinMode(doorPin, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    incomingValue = Serial.read();
    Serial.print("\n");
    if (incomingValue == '1') {
      digitalWrite(doorPin, HIGH);
    } else {
      digitalWrite(doorPin, LOW);
    }
  }
}

Have you connected HM-10 RX to Arduino RX and HM-10 TX to Arduino TX? If yes, try to swap these two, vonnecting RX to TX and vice versa

I swapped thep and now I can't even connect my phone to the module.

I managed to reconnect the module to phone but with HM-10 RX to Arduino RX and HM-10 TX to Arduino TX, vice versa doesn't work.

how is the module connected to the arduino? ... you do not have any code that talks to the BT module ... it appears that you connected to pins D0 and D1, which makes the module connected directly to the serial converter chip ... the data you are seeing on the serial monitor is not passing through the arduino sketch

My module's pins are connected like this:

VCC -> 5V arduino
GND -> GND arduino
RX -> Digital Pin 0 (RX)
-TX -> Digital Pin 1 (TX). How can I make the data pass through the arduino sketch?

I tried this code but still no success: https://create.arduino.cc/projecthub/electropeak/getting-started-with-hc-05-bluetooth-module-arduino-e0ca81

Which one did you try from there? I have seen 3 different codes there

use software serial ... https://www.arduino.cc/en/Tutorial/SoftwareSerialExample


text:
How to use USB-in on an arduino?
I'm trying to use an arduino as a controller adapter. How would I get USB-in to get the signal from a usb video game controller?

Google for arduino USB host shield

Depends on which Arduino you have.  You’ll probably need a USB host shield to read from the controller and you’ll want one of the 32u4 based boards if you want the PC to recognize your Arduino as a joystick.

@Delta_G The project is to convert a usb controller into a gamecube controller signal. Would a 32u4 based board still be optimal for that?

You’ll have to explain to me what that means.  This is intended to plug into a GameCube and control that?  That may be a tougher but to crack.

Yes, that is my intention. I know it will be tough to crack, but I'm sure it's possible, as I've seen people make GameCube controllers out of Arduinos.

why 32u4? it can emulate a HID device, not read it.

Maybe better to use a Leonardo as it has a "real USB". So you can "fool" the video game controler and let it belive it's connected to a PC.

It makes actually no sense to plug an USB-Controller via an Arduino to a PC. The direct way and using an autofire/macro /custom key programmer app is more efficient.

The Arduino UNO (with 32u4) can either replace an USB controller as demostrated in NicoHood HID library or
additionally act as an interface for controller with strange vendor specific plugs demostrated in UNOJOY and you can build your own Controller/interface out of nearly every old non usb controller by cutting the hardware specific plug (e.g. old Xbox) and attach to an UNO who acts as "interface" to the PC. Another example is a C64-Joystick to the PC
The other option for using an Arduino is interfacing with "old video game systems" . For some there are already more or less succesfull projects. When connecting the USB controller via an USB shield you have normally a high lag time due to the USB shield library, so the better approach is to cut the USB plug and directly interface with the Arduino.

Project with USB Host-shield:

C64 - with USB Joysticks

Project old Joystick to USB-PC:

NES controller to PC USB

Project Arduino as controller for NES/SNES:

UNO to NES/SNES

Info on the pinout/protocol cn be found in this page

Pretty much anything is more efficient on a PC, compared to arduino. There can still be many valid reasons for using/building arduino projects.


text:
Why can the Xbox360 not detect the Arduino Leonardo as keyboard?
Arduino Leonardo as keyboard in the computer works! But not with the Xbox360.
The Teensy works perfectly on the PC but how to emulate a keyboard device for the Xbox360.
I know the Xbox360 has security IC, but a simple USB keyboard works!
What is the diference ?
How i can emulate an usb keyboard for the Xbox360?

It probably needs the "Boot Keyboard" protocol, which the Leonardo doesn't provide.

I very new to hid devices, i will find out about that

does leonardo work as a keyboard at boot time in BIOS?

i don't remember, i guess no, but i will try later!

@jsotola, it doesn't work as boot keyboard with Arduino Keyboard library. this library can emulate boot keyboard on Leonardo: https://github.com/NicoHood/HID

Like Juraj and Majenko said. Arduino Keyboard library does emulate "Boot Keyboard".
I use NicoHood HID library and now it works.


text:
Program is executing but AT commands not showing in serial monitor
My purpose was to send SMS using GSM SIM800L coreboard  and Arduino UNO. Here is the code

    #include <SoftwareSerial.h>

//Create a software serial object to communicate with SIM800L
SoftwareSerial mySerial(3, 2); //SIM800L Tx & Rx is connected to Arduino #3 & #2

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(115200);

  //Begin serial communication with Arduino and SIM800L
  mySerial.begin(115200);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Once the handshake test is successful, it will back to OK
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CMGS=\"+ZZxxxxxxxxx\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("TEST"); //text content
  updateSerial();
  mySerial.write(26);
}

void loop()
{
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

And here is the serial monitor output
 22:31:19.430 -> Initializing...

However, when I run the code, I get the text message to my mobile phone, but I can't see any AT commands in the serial monitor. It only outputs "Initializing..." .
All the connections and baud rates are okay, checked a thousand times. Has connected 2A, 4.4v power supply to the GSM coreboard and shorten the wires, and sho No bad soldering joints. GSM module red led flash per 3 seconds. And again, I'm getting the text message to my phone. So that means the problem is with the Arduino serial monitor or code, not in the hardware. I need to see AT commands because I need to put more commands through the serial monitor, I tried typing and click send, But it's not showing anything. Any assistance you can provide would be greatly appreciated.

have tried a lower baud rate? ... that is one of the first things to try when debugging serial comm

Yes, I have tried many baud rates, 4800, 9600, also higher baud rates


text:
Splitting a string in arduino from computer
I am having an issue splitting an incoming string from a computer program to arduino.
The incoming format is as follows:
123.456,987.654 \r\n
The comma separates the two values.
code is this(edit to add code most likely too many variables):
char c;
String com;
String targetstr;
String actualstr;
bool newdata = true;
float target =1;
float actual = 5;
float diff;
int pwm = 0;
float firstup = 2.75;
float firstdown = 2.25;
float intensifier = 5;
unsigned long lasttime = 0;
unsigned long currenttime = 0;
int watchdog = 1000;

void setup() {
  // put your setup code here, to run once:
Serial.begin(19200);
dac.begin(0x60);
}

void loop() {
  // put your main code here, to run repeatedly:
currenttime = millis();

while(Serial.available()>0&&newdata == true){
  c = Serial.read();
// switched to '\r' from '\n' for testing.
  if(c == 0x0D){}

  if(c ==0x0A){
  targetstr = getValue(com,0x2C,0);
  //targetstr = com.substring(0,com.indexOf(0x2C));
  target = targetstr.toFloat();
  actualstr = getValue(com,0x2C,1);
  //actualstr = com.substring(com.indexOf(0x2C)+1);
  actual = actualstr.toFloat();
  com = "";//reset string
  diff = actual - target;
  newdata = false; //reset flag
  lasttime = currenttime;
  //Serial.print("Diff = ");
  //Serial.println(diff);
  Serial.print("Tgt ");
  Serial.print(targetstr);
  Serial.print(" Act ");
  Serial.println(actualstr);
  }
  else{
    com += c;
  }

The getValue is an example that I found on stack exchange
String getValue(String data, char separator, int index)
{
    int found = 0;
    int strIndex[] = { 0, -1 };
    int maxIndex = data.length() - 1;

    for (int i = 0; i <= maxIndex && found <= index; i++) {
        if (data.charAt(i) == separator || i == maxIndex) {
            found++;
            strIndex[0] = strIndex[1] + 1;
            strIndex[1] = (i == maxIndex) ? i+1 : i;
        }
    }
    return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

So I have attempted two different ways to make this work. If I use the arduino serial monitor the code executes perfectly, but if I use the computer program it will not split the values.
In a serial monitor this is the sent code to the arduino via serial monitor(hex and ascii)
31 32 33 2E 34 35 36 2C 34 35 36 2E 31 32 33 0A   123.456,456.123.
and this is the arduino response
54 67 74 20 31 32 33 2E 34 35 36 20 41 63 74 20 34 35 36 2E 31 32 33 0D 0A                         Tgt 123.456 Act 456.123..
And this is code sent from the computer program to arduino:
31 36 31 2E 39 35 32 2C 31 35 30 2E 38 30 30 0D 0A    161.952,150.800..
arduino response:
54 67 74 20 2E 39 35 32 2C 31 35 30 2E 38 30 30 0D 20 41 63 74 20 0D 0A                   Tgt 161.952,150.800. Act ..
I am not sure of the reason of not splitting, I have tried ascii and hex in the code for the comma, as well as two methods of actually splitting.
What are some other things I can try?

Show the rest of the code.  Are you trying to do all of this with the String class?  This would be simpler with the data in a char array.  If c was a pointer to the char you're on then you could use atof on that and get a float, then find the comma and use atof again.  You're about to ask me for an example or something and that's not really possible without knowing what else you got going on here.

I was trying to minimize the code but keep it relevant. c is a char that gets wrapped into a string 'com'.. here is everything else in that part of the code.

Why would you "wrap" a char array into a String?  Just use the char array.

One problem that you have is that you start trying to extract the string while you are still reading it in.  I'm not sure how that works at all...  Is there an end marker to this packet?  Could you read to 7 char after the comma or something?  Either way, you need to read in the whole string before you start trying to convert it.  You can't convert what you haven't received yet.  If c==Ox0A where you start trying to convert that string, the actual first digit is still sitting in the buffer waiting to be read.

I tested your sketch with the data sent by your PC program, and it works as expected. Note, however, that since the string you send ends with \r\n, and you read up to the \n, the response of the Arduino ends in \r\r\n. You may want to replace if (c == 0x0A) by if (c == '\r' || c == '\n'). Note also that you can write ',', '\r' and '\n' instead of 0x2C, 0x0D and 0x0A respectively, and that would make the code easier to understand.

The reason I had them in hex was to test.. originally I had it as '\n' and ','  the \n at the end is the end marker

Do you have the code for the PC app? Did you write it? If so, what language was it written in?

I cannot comment on the pc app... I can sure ask though... im curious as to why it would matter