text:
SI5351 Breakout 153,600Hz Square Wave Signal
I'm trying to generate a consistent 153,600Hz square wave signal with 50% duty cycle from a Adafruit SI5351 3.3-5v breakout board for use as a fixed synchronous serial clock reference, but the closest frequency I get from it is 142,857Hz which is too far off the target.
Originally, I followed this article (my device looks exactly like the one in the pictures) from Adafruit to no avail. I tried using the Adafruit library and the mentioned ClockBuilder software, but the article makes no mention of how to apply the values returned from the software into code, and messing with the values myself didn't help either.
So, I then moved on to using this library from etherkit. It's has a lot simpler interface, and was easy for me to get at least something being output.
Here is my current code using the etherkit library running on my Arduino Mega. It seems to only output 142,857Hz, even though I specified my target frequency of 153,600Hz.
//Arduino Mega
#include "si5351.h"
#include "Wire.h"

Si5351 si5351;

void setup()
{
    Serial.begin(9600);

    if (!si5351.init(SI5351_CRYSTAL_LOAD_8PF, 0, 0))
    {
      Serial.print("Cannot communicate with SI5351.");
    }
    else
    {
      si5351.drive_strength(SI5351_CLK0, SI5351_DRIVE_8MA);
      si5351.output_enable(SI5351_CLK0, 1);
      si5351.set_freq(153600ULL * 100ULL, SI5351_CLK0);
    }
}

void loop(){}

But here is where it gets odd: I can set the frequency argument of set_freq to anything under 120000ULL * 100ULL and the output will be spot on, but anything above that amount will "snap" back to 142,857Hz, up to 190000ULL * 100ULL.
The other thing I got working against me is that I don't have access to a oscilloscope to more accurately measure it's output. My current solution is a Arduino UNO acting as a frequency measuring tool, running the following code:
//Arduino Uno
#define pin_MeasureThis A0

volatile unsigned long on_time;
volatile unsigned long off_time;

float lfreq;
float freq;
char freq_str[12];
char msg[32];

void setup()
{
  pinMode(pin_MeasureThis, INPUT);
  Serial.begin(9600);
}

void loop()
{
  on_time = pulseIn(pin_MeasureThis, HIGH);
  off_time = pulseIn(pin_MeasureThis, LOW);
  freq = 1000000 / (on_time + off_time);

  if (freq >= 0 && freq < 999999)
  {
      dtostrf(freq, 8, 0, freq_str);
  }

  if (freq != lfreq)
  {
    lfreq = freq;

    sprintf(msg, "%sHz", freq_str);
    Serial.println(msg);
  }
}

I tested my measuring code by comparing it's measurement against visible frequencies with a LED and it performed perfectly. I do understand that probably doesn't scale well for higher frequencies, but I really have no better way right now.
Here is a sample of the exact serial output I get back from my Arduino UNO measuring the CLK0 output of the SI5351 breakout board:
  ...
  142857Hz
  125000Hz
  142857Hz
  125000Hz
  ...

Any advice on how to get to a steady 153,600Hz signal would be much appreciated. Thanks.


text:
Nested For Loop Controlling speed
I have a servo motor That I am trying to determine the delay speed in between pulses with a nested for loop. This issue is instead of running together like 0,0 1,1 2,2 its actually going up like 0,0 0,1 0,2. SO the first for loop i will only go up once all of the x for loop goes to its max 255.
What I want it to do is go up together until x reaches 255 and then it will stabilize there as I will countering to climb.
If any know anything about nested for loop I would appreciated (please only add valuable comment or help to this. I don't need pointless or dumb comments (talking about  jsotola and all he did was criticized my question)
 for (int i=0; i<500; i++)
  {
      for( int x=0; x<255; x++){

    digitalWrite(DIR,LOW);
    digitalWrite(PUL,HIGH);
    Serial.print("i = ");
    Serial.println(i);
    Serial.print("x = ");
    Serial.println(x);
    delayMicroseconds(x);
    digitalWrite(PUL,LOW);
    delayMicroseconds(x);
  }}

These are nested loops:
for (int i = 0; i < 500; i++) {
    for (int x = 0; x < 255; x++) {
        do_something_with(i, x);
    }
}

“Nested loops” means you have a loop within a loop: within each
iteration of the outer loop you get a full run of the inner loop. The
sequence of (i, x) pairs is:
(0, 0), (0, 1), (0, 2), ... (0, 254)
(1, 0), (1, 1), (1, 2), ... (1, 254)
...
(499, 0), (499, 1), ...     (499, 254)

What I want it to do is go up together until x reaches 255 and then it
  will stabilize there as I will countering to climb.

This sentence is not very clear. I assume you mean that you want the
following sequence of (i, x) pairs:
(0, 0), (1, 1), (2, 2), ... (255, 255),
(256, 255), (257, 255), ... (499, 255)

If this is what you want, you can more easily achieve it with a single
loop:
for (int i = 0; i < 500; i++) {
    int x = min(i, 255);
    do_something_with(i, x);
}

Thank you! I appreciate your help!
This worked.

source: Stack Exchange

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

sort: votes


text:
L293D to change the direction current and amplify it - Temperature-Stabilizer
I have a question about my project. I'm going to make a temperature-stabilizer. To make this, I think I should use a TEC with a H-bridge and a LM35. First of all, I tried to make a H-bridge by myself, I have only used four NPN transistors and It didn't go well. Then I bought L293D motor driver - not the module one, tried it and it works well. But as datasheet says, it's output current is max 600mA. But this current doesn't make TEC work efficiently. So that, I need to amplify the current. But I don't want to buy high amp motor drivers, hardwares are to expensive in my city. Of course I'll if there's no another way.
Arduino will be used to get temperature values from LM35 and give the H-bridge voltage, control the current direction when necessary. I learned how to use transistors to amplify but if I'll change the direction, it won't work. But I don't know how to make this circuit.
The algorithm that I thought using is this:

The scheme that I thought using in this:

What should I do to solve my problem? Thank you for all.
Resources:

My Tec1-12706 Datasheet:
http://www.thermonamic.com/TEC1-12706-English.pdf
LM35 Datasheet - (I have LP package):
https://www.ti.com/lit/ds/symlink/lm35.pdf
L293D Datasheet: https://www.ti.com/lit/ds/symlink/l293.pdf
The transistor method to amplify:
https://www.youtube.com/watch?v=WZD9RZoMhVE

Amplifying the current is basically what the LM293D is doing. You need a more powerful H-bridge. There's not really any way around that.

Use LM298 which provide up to 2A.

I am interested on this as I have the same issue. What about using a FET or MOSFET to amplify the current that the LM293D provides?

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


text:
How to use attachInterrupt() in ATtiny85 with Arduino IDE?
It's possible use external interrupts/attachInterrupt() with the ATtiny85 when I program with Arduino IDE?
If is possible, how many inputs (for external interrupts) the ATtiny85 have and which are they?
Someone have an example code?

The ATTINY 85 doesn't have external interrupts.  You'll have to use pin change interrupts instead.

Except... PB2 has INT0...

Darnit.  I just looked at the spec sheet and didn't see one listed.

Pin PB2 is the only pin that has a real external interrupt.  This is INT0.
Whether you can use attachInterrupt(0, ...) or not is entirely down to whether it is implemented in the core that you are using.


text:
Receiving multiple Values from android via Bluetooth
my question is, how can I receive 3 integer values in Arduino, which I send from my android phone. I send all 3 values at the same time and I also need to read them in about the same time.
I hope you can help me.

If there are no other constraints, send them as a text with delimiters and a  terminating character.
e.g. something like "123;45;678\n"
On the arduino, either manually check for those delimiters and convert the digits to a number on the fly, or use strtok  and atoi after reading the whole line.


text:
Can't get keypad to use Keyboard.write on an Arduino Uno
I've tried to use Keypad.h and Keyboard.h libraries to get my Arduino to use my Keypad for Keyboard input.
I'll start with working keypad code (which is pretty easy but it's my first post so I want to make it as neat as possible).
Working keypad
#include <Keypad.h>

const byte Rows = 4;
const byte Cols = 4;

char hexaKeys[Rows][Cols] = {
  {'1', '2', '3', 'A' },
  {'4', '5', '6', 'B' },
  {'7', '8', '9', 'C' },
  {'*', '0', '#', 'D' },
};

byte rowPins[Rows] = {9,8,7,6};
byte colPins[Cols] = {5,4,3,2};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins
, Rows, Cols);

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

void loop() {
char customKey = customKeypad.getKey();
  if (customKey){
    Serial.println(customKey);
  }
}

At this point, using Serial Monitor, I can see that all keys are being read and printed out no problem.
Then, I tried adding the Keyboard.h library to get it to act as an keyboard input
Not Working Keyboard Input
#include <Keypad.h>
//#include <Keyboard.h>
const byte Rows = 4;
const byte Cols = 4;

char hexaKeys[Rows][Cols] = {
  {'1', '2', '3', 'A' },
  {'4', '5', '6', 'B' },
  {'7', '8', '9', 'C' },
  {'*', '0', '#', 'D' },
};

byte rowPins[Rows] = {9,8,7,6};
byte colPins[Cols] = {5,4,3,2};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins
, Rows, Cols);

void setup() {
  Serial.begin(9600);
 // Keyboard.begin();
}

void loop() {
char customKey = customKeypad.getKey();
  if (customKey){
    Serial.write(customKey);
    //Keyboard.write(customKey);
  }
}

The commented out sections are where I've added changes.
The problems I've encountered:
 - Can't include Keyboard.h on regular Arduino Uno. I've read that changing board type to Arduino Leonardo helps, and it does, but then the Serial Monitor is greyed out and doesn't read keypad input.
 Using following code I get following error message ( I'm still 'using' Leonardo board since Keyboard.h doesn't want to work with Uno)
#include <Keypad.h>
#include <Keyboard.h>
const byte Rows = 4;
const byte Cols = 4;

char hexaKeys[Rows][Cols] = {
  {'1', '2', '3', 'A' },
  {'4', '5', '6', 'B' },
  {'7', '8', '9', 'C' },
  {'*', '0', '#', 'D' },
};

byte rowPins[Rows] = {9,8,7,6};
byte colPins[Cols] = {5,4,3,2};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins
, Rows, Cols);

void setup() {
  Serial.begin(9600);
 Keyboard.begin();
}

void loop() {
char customKey = customKeypad.getKey();
  if (customKey){
    Keyboard.write(customKey);
  }
}

processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77)
    at processing.app.SketchController.upload(SketchController.java:732)
    at processing.app.SketchController.exportApplet(SketchController.java:703)
    at processing.app.Editor$UploadHandler.run(Editor.java:2047)
    at java.lang.Thread.run(Thread.java:748)
Caused by: processing.app.SerialException: Error touching serial port 'COM7'.
    at processing.app.Serial.touchForCDCReset(Serial.java:107)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - COM7; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.touchForCDCReset(Serial.java:101)
    ... 6 more
An error occurred while uploading the sketch
Exception in thread "Thread-28" java.util.ConcurrentModificationException
    at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966)
    at java.util.LinkedList$ListItr.next(LinkedList.java:888)
    at processing.app.packages.LibraryList.getByName(LibraryList.java:61)
    at cc.arduino.contributions.libraries.LibrariesIndexer.addToInstalledLibraries(LibrariesIndexer.java:130)
    at cc.arduino.contributions.libraries.LibrariesIndexer.scanLibrary(LibrariesIndexer.java:229)
    at cc.arduino.contributions.libraries.LibrariesIndexer.scanInstalledLibraries(LibrariesIndexer.java:201)
    at cc.arduino.contributions.libraries.LibrariesIndexer.rescanLibraries(LibrariesIndexer.java:161)
    at cc.arduino.contributions.libraries.LibrariesIndexer.setLibrariesFolders(LibrariesIndexer.java:120)
    at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:677)
    at processing.app.Base.onBoardOrPortChange(Base.java:1336)
    at processing.app.Editor$UploadHandler.run(Editor.java:2083)
    at java.lang.Thread.run(Thread.java:748)

if you have a "genuine" UNO, then check this out https://github.com/NicoHood/HoodLoader2

The UNO can't be a Keyboard. It doesn't have a real USB connection. It has a serial connection that passes through a UART to USB converter.
You cannot use the UNO as a keyboard.
Instead you need one of the boards that has a real USB connection, such as the Arduino Leonardo or any of the other ATMega32U4-based boards.

Thanks for that clarification!  Would Arduino Mega 2560 work?

No. That doesn't use the ATMega32U4 either. Arduino Micro or Leonardo

if the UNO uses a ATMega16U4 as a USB to serial converter, then it is doable .... you would have to reprogram the ATMega16U4


text:
ESP8266, I am trying to establish a SoftAP and I cant seem to get the WiFilocalIP function to give me my IP
I am just trying to establish a server and it seems that I can't get the serial monitor to read the local IP of my device and my Client can't establish a connection to update the sensor value. when I run the monitor I get this:
IP Address: (IP unset)
here is my code:
    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>

    /// Config parameters for Access Point
    char * ssid_ap = "This Little Buddy";
    char * password_ap = "guessing";
    IPAddress local_ip(192,168,4,4);
    IPAddress gateway(192,168,4,1);
    IPAddress subnet(255,255,255,0);

    //Setup Server Object
    ESP8266WebServer server;

    //Sensors and what not here
    float sensor_value = 0.0;

    void setup() {
        //identify and start WiFi
      WiFi.mode(WIFI_AP);
      WiFi.softAPConfig(local_ip, gateway, subnet);
      WiFi.softAP(ssid_ap, password_ap);
      //sanity check
      Serial.begin(115200);
      Serial.println();
      Serial.print("IP Address: "); Serial.println(WiFi.localIP());
      //Configure the server's routes
      server.on("/", handleIndex); //using top root path for last sensor value
      server.on("/update", handleUpdate); //use this to update sensor value
      server.begin();
    }

    void loop() {
      // put your main code here, to run repeatedly:
    server.handleClient();
    }

    void handleIndex(){
      server.send(200, "text/plain", String(sensor_value));//need to refresh page to get information
    }

    void handleUpdate(){
      //value is passed by an URL argument
      sensor_value = server.arg("value").toFloat();
      Serial.println(sensor_value);
      server.send(200,"text/plain", "Updated");
    }

You should be using WiFi.softAPIP(); to get the AP IP address.

Ya I know this but I am still not getting a reponse from my client. this line isnt becoming true on the client.
Serial.println("Response: ");
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);

Have you tried just running the WiFiAccessPoint example?

Comment // WiFi.mode(WIFI_AP); You dont need it with softAP

The WiFi.localIP() is a function of the STA. To print the IP address of the SoftAP, use WiFi.softAPIP().

this is the answer to the question, code and output in the question. if you want to ask why the client can't connect, ask with the code and output of the client


text:
Arduino Timer 1 Library manipulate Timer value
I'm using Timer1 library for generation of pulse.
But in my code, at some places i need to change the timer values.
Can anyone suggest the ways to do it.
In below code in place of 370000, I need to change the value after getting some inputs in conditional loops.
Ex. if (x==1) Timer value should be 370000 else 185000.
#include <TimerOne.h>

int count = 0;
int LED = 13;

void setup() {
 pinMode(LED, OUTPUT);
 Timer1.initialize(370000);
 Serial.begin(9600);
}

void loop() {
 Serial.print("Count Value: ");
 Serial.println(count++);
}

When you look into TimerOne.h, which is the header file for the TimerOne library, you can see at line 55 the method
void setPeriod(unsigned long microseconds)

which can be used to set the period of the timer at any time in your program. The method TimerOne.initialize() also calls this method to set the timer period.

Just use a variable...
unsigned long val = 0;

void setup(){
  if(something){
    val = 370000;
  }
  else {
    val = 185000;
  }
  Timer1.initialize(val);
}

Calling the initialize method multiple times feels wrong. In some libraries this can have some weird side effects. In the case of Timer1 if you call detachInterrupt and then change the period using initialize, instead of setPeriod, the interrupts will start again, and you ISR will get called. Though I admit that's a bit of an edge case.

Who said to call it multiple times?  It's only called once in setup.  Is there more to this than was in the question?  I thought we were coming up with a way to alter the 370000 number.  Question should be more specific.  If this answer is a downvote for answering exactly what the question said then I'm downvoting the question for being vague.

@Delta_G - You can call the initialize function twice per minute with different values if you like. I've built a clock that does just that, and has been running for over a year with no issues. https://arduino.stackexchange.com/a/68627/37523 +1 for your answer.

I still say the question didn't ask to do it over and over.  The question just asked how to do it once in setup.

@Delta_G - The question is not the greatest, but it does say ...at some places i need to change the timer values. I still like your answer :)

While it does say that, I figured that was a language issue as the code posted shows nothing in loop and only shows the one Timer1 function being called.  If that's not the code the OP needed help with then why is that the code that was posted?

@Delta_G that's right I didn't post the full code here. Let me clarify. I'm blinking LED/Bulbs with arduino. On time of that will be 370ms and same off time. After current/load sensing, if load is in range, I need to start timer with 370000. If not, timer should count 185000. So here is my question, that once I initialize timer to 370000 in setup, is it possible to change that value later in code. Because i badly need to change the timer value. Hope this clarify the things and doesn't sound stupid enough to down vote the question.

@Delta_G Also let me add something to question that, once I start blinking LED/Bulbs with timer say 370ms. After starting timer, in ON timer I'm checking load/current by polling. If load not appropriate, I've to change value from 370000 to 185000 while timer is still going on with 370000.

This would all be simpler without the timer library if that's all you need to do.  Just use millis for the timing.


text:
Send data to Programmable Power supply from Arduino by RS232
I have a programmable power supply, which has serial communication port. If I send a string "VSET1:11.00" then power supply will be set to 11.00V.
But, I need to write a program which will increase the voltage of power supply by 0.10V
For ex from 0V to 11.00V in incrementing steps of 0.10V.
Also, power supply needs a fixed data frame format like Parity bit, Data bits, stop bit.
So, how to create a data frame structure and send from arduino.
Do I need to use Software Serial library?
PS. I'm new to arduino, so may sound foolish.

That sounds like the same PSU that I have. Mine's badged as TENMA though I have seen what looks like the same one badged by other people...

One thing I really find annoying with this PSU is that as soon as you send anything over the serial port it completely locks out the front panel for a while.

Yes that's right. It is TENMA power supply.

First you will need a TTL to RS-232 adaptor. These are most commonly known as the "MAX232" and is available as a little module.
This will convert the 0-5V TTL signal the Arudino produces into the ±10V signal that RS-232 uses. There's plenty of tutorials online about how to use them.
Then you need to generate the signal. Yes, for the Arduino UNO the SoftwareSerial library is what you want.  Again there's plenty of tutorials on using it.
To actually send the instructions it may be something like:
#include <SoftwareSerial.h>

SoftwareSerial PSU(10, 11); // RX, TX

void setup() {
    PSU.begin(9600);
}

void loop() {
    for (int i = 0; i < 11000; i += 100) { // I'm working in millivolts here.
        PSU.print("VSET1:");
        PSU.println(i / 1000.0, 2); // Convert millivolts into volts with 2 DP
        delay(10); // 10ms delay
    }
}

I haven't tested it, but that should give you 0-11v rising at 0.1v per 10ms.

Thanks Sir, I will try the same.


text:
Bluetooth module HC05 does not react to bluetooth signal from smartphone
I try to switch off two leds with a hc05 module by sending the signal from my phone.
I know there are a lot of examples on the internet and I tried some of them, but they dont work either. I use a Elegoo Uno R3 and the "Serial Bluetooth Terminal" on my phone. When I try to send a 1 to the HC05 (slave) from my phone it just gives the 1 back, but does not seem to save it in the variable state.
I dont know if the two software serials can be a problem? But when I delete the the Software Serial it still does not work.
Here is my code:
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

SoftwareSerial Bluetooth(8,9); // RX, TX
SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;

void printDetail(uint8_t type, int value);
char state;
void setup()
{
  pinMode(7,OUTPUT);  //LED1
  pinMode(6,OUTPUT);  //LED2
  Bluetooth.begin(9600);
  mySoftwareSerial.begin(9600);
  Serial.begin(9600);

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true){
      delay(0); // Code to compatible with ESP8266 watch dog.
    }
  }
  Serial.println(F("DFPlayer Mini online."));

  myDFPlayer.volume(30);  //Set volume value. From 0 to 30
}
void loop()
{
  digitalWrite(7,HIGH);
  digitalWrite(6,HIGH);
  static unsigned long timer = millis();
  static unsigned long zeit = 0;

mySoftwareSerial.listen();
  if (millis() - timer > 900000) {
    timer = millis();
    myDFPlayer.next();  //Play next mp3 every 10 minutes
    zeit = millis();
    while(millis()-zeit < 10000){
      digitalWrite(7, !digitalRead(7));  // toggle state
      delay(50);
      digitalWrite(6, !digitalRead(6));
      delay (100);
    }
  }
Bluetooth.listen();
state = Bluetooth.read();
if (state == '1'){
   digitalWrite(6,LOW);
   delay(5000);
  }
}

Your help would be much appreciated.
Best wishes,
CR

You tried to read bluetooth byte right after Bluetooth.listen(), which is probably why you don't receive anything. Instead wait for byte to be available using "while (Bluetooth.available() == 0);"

Thanks for your answer, Fahad, but it still does not work. It appears that the condition Bluetooth.available() == 0 is always right...so it does not get a signal? I can, however, send something from the HC-05 to the phone.

Let's work with a simple example and just test the Bluetooth. Get rid of everything, except Bluetooth SoftwareSerial. If there is one SoftwareSerial you won't even need listen(). In the loop() just check if Bluetooth.available() is greater than zero or not. If is greater, read() and print().

Also listen() clears the SoftwareSerial buffer. Both of your SfotwareSerial uses the same buffer. So if you received anything before calling listen(), it is gone now.

I did that, but the available() is never greater than zero.

When I do: if(Bluetooth.available() ==0) {Bluetooth.write("something")}, it works, but not for read(). SO there is some kind of connection, but the available returns 0. Btw, (I dont know if this means anything) if I write something in the bluetooth terminal on my phone, the same thing comes back (from the hc05?). Like, if I write 1, it returns a 1.

Can you post your new code? Also, provide the link for bluetooth terminal. I have one HC-05. I can test on my end.

#include "Arduino.h"
#include "SoftwareSerial.h"
SoftwareSerial Bluetooth(8,9); // RX, TX
char state;
void setup()
{
pinMode(3,OUTPUT);  //LED
Serial.begin(9600);
Bluetooth.begin(9600);
}
void loop(){
digitalWrite(3,HIGH);
if(Bluetooth.available()){
state = Bluetooth.read();
Serial.println(state);
if (state == '1'){
digitalWrite(3,LOW);
delay(5000);
}
}
}

https://play.google.com/store/apps/details?id=de.kai_morich.serial_bluetooth_terminal&hl=de

It worked as expected. So you might have different issues. If you can, edit your question, and add a connection, how did you connected your module with Arduino. Also, provide a link of the exact module you are using.

I dont know why, but it works now. Fahad, thank you very much for your effort :)


text:
Serial Moniror, '\r' and Realterm
I'm wanting the results from each of the 6 ultrasound modules to print on their respected line after new results have been generated instead of spitting out a continuous flow (see attached image). I've downloaded Realterm and got the results to show on there as I've read that the serial monitor can't do that but I don't know where to put the '\r' syntax within my script as I have multiple serial.prints to display the data I need.
Here is a section for 1 of the ultrasound modules, they are just repeated for the differing modules.
Thanks in advance for any help!

  //Object Ahead Distance.
  long duration1, distance1;
  digitalWrite(trigPin1, HIGH);
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

   delay(500);
   if (distance1 >= 40){
    Serial.print("Nothing Ahead, Okay");
    Serial.print(distance1);
    Serial.println("cm");}
   else if (distance1 <= 39 || distance1 >= 29){
    Serial.print("Vehicle Ahead, Slow ");
    Serial.print(distance1);
    Serial.println("cm");}```

\r returns the cursor to the start of the current line. You can't use it to go back up to previous lines.
Instead you need to learn ANSI escape sequences to move the cursor around.
For example Serial.print("\e[2J"); will clear the entire screen. Serial.print("\e[1;1H"); will move the cursor to the top left corner of the screen (the coordinates are \e[{Y};{X}H by the way).
You can also add colour and all sorts of other nice things, none of which the Arduino IDE's "Serial Monitor" can do.
You can find a good reference of ANSI escape codes here.

Thank you, Serial.print("\e[1;1H"); worked a treat


text:
Script works on Mega but not Uno
I'm struggling to get a script to work on an Uno that I've had working on a Mega.The script was made for an Uno and I've used all the same pin numbers as the orignal (Original project).
I just bought the Uno and something doesnt seem right about how Arduino's IDE responds to it as opposed to the Mega (see the pics I've attached). They are both copies but Arduino seems to retreive more info on the Mega.
I've installed the driver from wch.hn and it appears in the device manager as being installed okay. The 'Blink' example seems to work fine on the Uno but stops when I disconnect the USB and use external power.
The script uploads to the Uno fine and recognises the controller as per the error message section but the wheels of the model don't turn. The script I've used was made for an Uno and as I said the script worked fine on the Mega this morning and I've changed it back since not being able to get it to work and it's still okay on the Mega.
Any help is much appreciated.
P/S - I should add that the RX LED is blinking every half second when I'm using external power.
#include <PS2X_lib.h>       //for v1.6 PS2 Library

#define PS2_DAT        12
#define PS2_CMD        11
#define PS2_SEL        10
#define PS2_CLK        9

#define leftm1     3
#define leftm2     4
#define rightm1    5
#define rightm2    6
#define left_EN    2
#define right_EN   7

  //analog values read from PS2 joysticks
int LX = 0;
int LY = 0;
int RX = 0;
int RY = 0;

//#define pressures   true
#define pressures   false
#define rumble      true
//#define rumble      false

PS2X ps2x; // create PS2 Controller Class

int error = 0;
byte type = 0;
byte vibrate = 0;

void setup() {

  Serial.begin(9600);

  pinMode(leftm1,  OUTPUT);
  pinMode(leftm2,  OUTPUT);
  pinMode(rightm1, OUTPUT);
  pinMode(rightm2, OUTPUT);
  pinMode(left_EN, OUTPUT);
  pinMode(right_EN, OUTPUT);

  digitalWrite(left_EN, LOW);
  digitalWrite(right_EN, LOW);

  delay(300);  //added delay to give wireless ps2 module some time to startup, before configuring it

  //setup pins and settings: GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error
  error = ps2x.config_gamepad(PS2_CLK, PS2_CMD, PS2_SEL, PS2_DAT, pressures, rumble);

  if (error == 0) {
    Serial.print("Found Controller, configured successful ");
  }
  else if (error == 1)
    Serial.print("No controller found, check wiring. ");

  else if (error == 2)
    Serial.print("Controller found but not accepting commands. ");

  else if (error == 3)
    Serial.print("Controller refusing to enter Pressures mode, may not support it. ");
}

void loop() {
  ps2x.read_gamepad(false, vibrate); //read controller and set large motor to spin at 'vibrate' speed

  if (ps2x.Button(PSB_L1))
  {
    LY = ps2x.Analog(PSS_LY);                     //receive values from p22 joystick
    LX = ps2x.Analog(PSS_LX);
  }
  if (ps2x.Button(PSB_R1))
  {
    RY = ps2x.Analog(PSS_RY);
    RX = ps2x.Analog(PSS_RX);
  }

  if (LY > 200 || RY > 200)                       //check if the joystick pushed up side
  {
    REV();
  }
  if (LY < 100 || RY < 100)
  {
    forward();
  }
  if (LX < 100 || RX < 100)
  {
    left();
  }
  if (LX > 200 || RX > 200)
  {
    right();
  }
  if(LX == 128 && LY == 128 && RX == 128 && RY == 128)
  {
    waithere();
  }

LY = LX = 128;         //return to default vlaues
RY = RX = 128;         //return to default values
}

void forward()
{
  //Serial.print("forward");
  digitalWrite(left_EN, HIGH);
  digitalWrite(right_EN, HIGH);

  digitalWrite(leftm1, HIGH);
  digitalWrite(leftm2, LOW);
  digitalWrite(rightm1, HIGH);
  digitalWrite(rightm2, LOW);

}
void REV()
{
  //Serial.print("rev");
  digitalWrite(left_EN, HIGH);
  digitalWrite(right_EN, HIGH);

  digitalWrite(leftm1, LOW);
  digitalWrite(leftm2, HIGH);
  digitalWrite(rightm1, LOW);
  digitalWrite(rightm2, HIGH);
}
void left()
{
  //Serial.print("left");
  digitalWrite(left_EN, LOW);
  digitalWrite(right_EN, HIGH);

  digitalWrite(leftm1, LOW);
  digitalWrite(leftm2, LOW);
  digitalWrite(rightm1, HIGH);
  digitalWrite(rightm2, LOW);

}
void right()
{
  //Serial.print("right");
  digitalWrite(left_EN, HIGH);
  digitalWrite(right_EN, LOW);

  digitalWrite(rightm1, LOW);
  digitalWrite(rightm2, LOW);
  digitalWrite(leftm1, HIGH);
  digitalWrite(leftm2, LOW);
}
void waithere()
{
  //Serial.print("stop");
  digitalWrite(left_EN, LOW);
  digitalWrite(right_EN, LOW);
  digitalWrite(rightm1, LOW);
  digitalWrite(rightm2, LOW);
  digitalWrite(leftm1, LOW);
  digitalWrite(leftm2, LOW);
}

Are you program the Arduino through ISP (since you are using "ArduinoISP" as programmer option)? When I want to  upload via USB, I use the option "AVRISP mkII".

Also: When you try the blink sketch with external power supply (which doesn't work as of your description), how exactly are you connecting what type of power supply with which voltage?

@chrisl, for USB upload the selected programmer is ignored

@chrisl I'm uploading the blink example via usb then unplugging the cable and leaving the board powered by 4x AA batterys (6v).

How are you supplying the voltage to the board.  6V is too much to go into the 5V pin and not quite enough for VIN.


text:
Slow refresh rate of 1.8 TFT display
I have 1.8 TFT display for Arduino Nano and it changes color very slow. When I try to change the color of the whole screen I see how it changes color line by line. I use "Adafruit GFX graphics core" and "Adafruit ST7735" libraries to change colors.
Question: Slow refresh rate of 1.8 TFT display is due to limited computation capability of Arduino or 1.8 TFT display itself or library used?

Well, it's 16012818 bits (maybe *24, if it's not packed). With 1MHz SPI clock that means about 2.7Hz refresh rate (but without anything else like setting pixel address and so).

@KIIV most small TFTs run in 16-bit mode. That's (16*(160128)) + (118) bits (+11 for the setup of a drawing window), or 327768 bits. At 1MHz clock that's about 3fps.

The ST7735 TFT uses SPI to communicate. That can never be particularly fast.
At 160x128 pixels with 16-bit colour depth that gives you 327680 bits that you need to transfer just for the colour data.  On top of that you have 88 bits to set up a drawing window (11 bytes of "set X coordinate and width" [5 bytes], "set Y coordinate and height" [5 bytes] and "start drawing" [1 byte]).
That's a total of 327768 bits that you need to transfer.
Now the transferring of that data is at the mercy of the SPI clock speed. How fast that can go depends on what the ST7735 can work at and the quality of your wiring (if it's a shield you can almost discount the wiring).  Assuming you can operate at the maximum 8MHz that the Arduino can run SPI at (which is probable) then you get:
8,000,000
---------   =  24.4 frames per second
 327768

That is the absolute maximum theoretical speed, and doesn't take into account any work done by the Arduino to actually send the data. The SPI library is completely blocking in its operation and each pixel has to be sent separately as one blocking transaction. So you can expect about half that rate in reality, if not less, while it loops around and sends each pixel, then blocks waiting for the pixel to be sent.
And of course that's assuming running at the maximum speed. In reality that probably isn't happening. Libraries that use SPI often choose the "lowest common denominator" for their SPI speed (if they actively choose a speed at all) so that the library "just works" in the majority of cases. So the speed the library is running at will most likely be considerably lower than the actual maximum speed you could run at.
For example, if it runs at 1MHz instead of 8MHz then you will get about 3 frames per second (which is more like what you are describing).
So examine your chosen library and see what it does in the way of configuring the SPI speed. If it doesn't do anything then consider adding code to increase the speed. If it does then consider increasing the speed it operates at (see the SPI library reference for more details).
TBH, though, a small Arduino is seldom a good choice to control a TFT screen. At the bare minimum you really need a chip with far more memory so you can draw graphics "off-screen" in a framebuffer, and then use DMA to transfer that off-screen buffer to the TFT screen over a 16-bit parallel connection at high speed while leaving the CPU free to do other jobs.  Or even better a microcontroller with a built-in TFT controller to directly generate the correct drive signals for a TFT panel and store the whole screen image in internal RAM.

Given you use the last library versions and have the cables right - it is hard to guess without your code.
So to check if it your code load one or two of the library examles and see if it works there.Another option is to set SPI speed the set with begin(freq) is not working, because its wrong see more in this issue.If the problem still exists come back with wiring and code used. The nano is not the best choice with TFTs but runs decently.


text:
Regarding Strings and assignments
I have this code which works :
String ErrorMsg;
.......
if(!UploadPacketError)
{
    ErrorMsg="OK";
}
else
{
   ErrorMsg="NOK";
}

String creates a dynamically allocated array which I want to avoid. I would prefer something like :
unsigned char ErrorMsg[5];
......
if(!UploadPacketError)
    {
        strcpy(ErroMsg,"OK",3); // +1 for the Null Termination ?
    }
    else
    {
       strcpy(ErroMsg,"NOK",4); // +1 for the Null Termination ?
    }

i.e. is there a way to dynamically assign a value to a fixed size character array ?
Cheers
Thomas

Almost.
First it's char not unsigned char:
char ErrorMsg[5];`

Second you don't specify a size with strcpy:
strcpy(ErrorMsg, "OK");

There is a variant of strcpy called strncpy which copies at most n characters:
strncpy(ErrorMsg, "OK", 5);

That is used to prevent buffer overruns. But when working with string literals like that it's pretty pointless.

Thanks Majenko. Is there a way to do do something like : String flashhtml = "Programming" + ErrorMsg + " Programming Over " ;   Something similar to concatenating multiple fixed strings and variable strings ? I know there are other ways to do this , but i was looking for the simplest possibility.

Into a suitably sized char buffer? Yes.  strcpy replaces the string content from the start. strcat concatenates more content on to the end.  strcpy(buffer, "
Programming

"); strcat(buffer, ErrorMsg); strcat(buffer, " Programming Over "); ...

Terrific , Majenko,exactly what I was looking for !

@EmbSysDev I have a small blog post about replacing String with C strings. https://majenko.co.uk/blog/evils-arduino-strings

Very nice blog indeed. Arduino is a wonderful tool;but it does seem to help you mess up bigtime. I guess like everyhing else, one learns by first messing up

@majenko Sorry to be questioning but wouldn't strncpy(ErrorMsg, "OK", 5); write the terminator out of bounds, shouldn't it be strncpy(ErrorMsg, "OK", 4); for a char[5] ? As I normally do it like strncpy(ErrorMsg, "OK", strlen (ErrorMsg)-1) to be on the safe side

No. The 5 includes the terminator if there is one within the first 5 bytes. But even then, it will only do 3 bytes anyway since it stops on the NULL before it reaches the limit of 5.

Yes clear with the example of "ok" but if I do "first" wouldn't that write out of bounds -since that could be a problem for general usage of strncpy Thanks for your time

No, you just won't get a null terminator.

http://www.cplusplus.com/reference/cstring/strncpy/

Also recomending the fixed char approach but for completeness there is a possibility to "get away with String class" IF you ONLY use fixed AND predefined Strings to build dynamicly variable messages:
bool first = true;

String A = F("My first ");
String B = F("My second ");
String C = F("answer");
if (first) serial.println(A+C);
else serial.println(B+C);

Read more on the F-macro here. Conclusion:

Large blocks of text to a file system (like SPIFFS, LittleFS, SD)
dynamic texts to large enough fixed char arrays and
short messages (consisting of fixed parts) can be created with the F-Macro

Assigning strings A, B and C will allocate heap and copy the data into it wasting RAM. Adding the strings will concatenate them in memory and return the result wasting more RAM. There is never a good reason (or even a good way) to use String.

@Majenko: for people with a casual amateur interest in programming, efficiency and performance aren't likely to be driving factors compared to code simplicity and readability. For large projects every bit counts, but using direct port access or cstrings won't improve the perceived performance of a simple 4x20 LCD digital thermometer project, and could very well be harder for the "programmer" to customize than one using digitalWrite(), literals, operators, and String methods. Sometimes "getting away with ___" means "yes, i can mod this" vs "idk what this even means"; have mercy on the noobs.

@dandavis I said "good" reason. That is not a good reason. It is a reason, but not good. It's not about efficiency, or performance. It's about someone writing some seemingly simple code and then turning up here some time later saying "My Arduino crashes randomly after a few hours and I can't work out why". And of course they used String. And the heap fragmented, and overflowed.


text:
Using millis() in unsynchronized manner
I am assuming millis() is a Timer ISR function.
If so :
When using millis() as mentioned in Arduino Reference :
unsigned long currentMillis = millis();
What would happen if the ISR asynchronously changes the value being read in a function. I mean if I have read one byte into currentMillis, but millis had changed the value before the remaining 7 bytes are read.
Cheers and TIA

Embedded systems developer? look into the source code of millis() before asking

I am assuming millis() is a Timer ISR function.

It is a function that retrieves a value that is updated by and ISR.

What would happen if the ISR asynchronously changes the value being
read in a function.

Cannot happen: the value is read with interrupts disabled.
See for example, in the AVR core:
// disable interrupts while we read timer0_millis or we might get an
// inconsistent value (e.g. in the middle of a write to timer0_millis)
cli();
m = timer0_millis;
SREG = oldSREG;

I mean if I have read one byte into currentMillis, but millis had
changed the value before the remaining 7 bytes are read.

An unsigned long is only 4 bytes. That is, until someone comes with a
64-bit Arduino platform.

Sure, a 64 bit Arduino with 2k of RAM :-)

@Edgar Bonet ,Just as an aside ( I am actually writing a millis() like function for another uC ) : Is it valid,  to say , use a lock bit to prevent read while timer is updating the variable , instead of  disabling the interrupt? Thanks much !

@EmbSysDev: There is no need to “prevent read while timer is updating the variable”: the ISR is not interruptible, so nothing can read the variable while it is being updated. You need to prevent the update while the main program is reading it.

@EdgarBonet: cli() disables all interrupts, so too many calls to millis() would affect all interrupt based events.Would it not be sufficient to only disable TIM0 ? In the function they don't seem to be enabling the interrupts again, is it being done elsewhere(otherwise no interrupt would be enabled).Would make sense to enable the interrupts again before exiting millis() ? Thanks for your time !

@EmbSysDev: You may indeed disable selectively TIM0, although that would take a few more cycles than cli(). This critical section is very short, so globally disabling interrupts is fine here. Re “they don't seem to be enabling the interrupts again”: that's what SREG = oldSREG; does: re-enable interrupts, but only if they were initially enabled when the function was called.


text:
Is there a method of figuring out whether or not my stepper drivers are dead?
I'm working on a project that involves stepper motors, and I'm mainly using DRV8825 stepper drivers. At the moment, it seems like only one of my drivers actually gives the motors any current. The others usually return 0s when I measure their VREFs. One returns a value but still can't pull the motors. After checking all of my DRV8825s and finding only two returned VREFs, I checked my A4988s and none of them gave anything (aside from power supply voltage when measuring different pins). Is there a way I can figure out whether my stepper drivers are actually fried? I have a suspicion that maybe the potentiometers on the drivers are thrown off or there's some other issue I can't place. I'm happy to give more information if that can help to figure out what's going on here. Thank you!

Most surefire way to tell if your drivers work is to wire them up CORRECTLY and try them out.  You should not be frying them if you have the correct setup (including current limit) for your conditions.  That said, conditions include your heat sink install and the environmental temperature.
The usual gotchas:

Note that DRV8825 and A4988s may have different pin locations so be sure to orient them correctly (check their EN pin location) if using a shield.
Also note that the gains from the voltage to the current limits will be different for the different model #s.  Be sure to use an appropriately sized screw driver and attach the meter to the screw driver as you turn to adjust the current limit.


text:
How to put together an HKT30 optical rotary encoder?
I'm working on a project involving stepper motors. It is important for this project to track the position of these motors, so I decided to buy an optical rotary encoder, specifically an HKT30(HKT3005-C03G-1000B-5E) pictured here. I've found it difficult to find resources on how to put this together. I've found datasheets, like this one, but it does not seem to be made up of the same components I have. I think I've basically gotten the gist of how one puts this together from google images, but I would like to be pointed in the way of an explicit resource in case I damage my parts.
Additionally, I was hoping for an explanation on the 5 wires (red, green, black, white, and gray), their purpose and how to set one up on a board.
If any clarification or images are needed, I would be happy to provide.
Thank you!

It's not hard...

The sensor screws into the screw holes.
The disc slots into the gap in the sensor
The case clips on the outside

As to what the wires are, only the datasheet / manual / manufacturer can tell you that. Maybe if you trace them on the sensor board you can work out what is what.

About that, the disc isn't a tight fit into the sensor. Is that supposed to be the case?

Of course. It has to be able to spin, doesn't it...


text:
ESPTool 3-run stub fail error
I'm trying to program my NodeMCU ESP8266 ESP-12E module with AT commands. However, whenever I try and flash to my ESP8266 using ESPTool, I get a 3-run stub fail error. Can anyone tell me why I get this error and how to fix it?
I have my suspicions that it might be the fact that I haven't pulled any of the pins, but I've been told that GPIO0, GPIO2, GPIO15, and CH_PD are all already pulled to the proper positions by default. If that may be the reason behind this error, could someone explain to me how exactly I should pull the pins, whether it be with a circuit or through code?
If it helps, I'm trying to follow along with this resource.
The only thing the ESP is connected to is the computer with USB.

Just wanted to update and let anyone who had a similar issue learn how I solved the problem.
My baud rate was set to 1152000 rather than 115200. Setting it to 115200 solved my problem.


text:
Two-Wire Interface (TWI) Frequency and SMBus Compatibility
Have I understood the ATmega328P datasheet correctly regarding the TWI clock frequency?
From §21.5.2 Bit Rate Generator Unit, the TWI clock frequency is calculated as follows:

Then solving for TWBR:

However, §8.12.2 CLKPR – Clock Prescale Register mentions that the CPU frequency is prescaled by CLKPR. So should the equation be:

And solving for TWBR:

Is the following code a correct implementation of the equations?
void SetFrequency(uint32_t twi_freq)
{
    if (smbus)
    {
        // SMBus clock frequency is 10 kHz to 100 kHz.
        if (twi_freq > 100000u)
        {
            twi_freq = 100000u;
        }
        else if twi_freq < 10000u)
        {
            twi_freq = 10000u;
        }
    }
    else if (twi_freq > 400000u)
    {
        // Up to 400 kHz data transfer speed.
        // §21.1 Features
        twi_freq = 400000u;
    }

    // TWI prescaler of 1.
    // Table 21-8. TWI Bit Rate Prescaler
    // TWPS1 = 0, TWPS0 = 0
    TWSR &= B11111100;

    // Achievable maximum TWI frequency with current CPU frequency, CLK prescaler and minimum TWBR with TWI prescaler of 1.
    // Rounded down to nearest integer.
    const uint32_t TWI_FREQ_MAX = F_CPU / ( ( 1 << CLKPR ) * ( 16 + 2 * 0x00 * 1 ) );

    // Achievable minimum TWI frequency with current CPU frequency, CLK prescaler and maximum TWBR with TWI prescaler of 1.
    // Rounded up to nearest integer.
    const uint32_t DIVISOR = ( ( 1 << CLKPR  ) * ( 16 + 2 * 0xFF * 1 ) );
    const uint32_t TWI_FREQ_MIN = (F_CPU + (DIVISOR - 1)) / DIVISOR;

    if (twi_freq > TWI_FREQ_MAX)
    {
        twi_freq = TWI_FREQ_MAX;
    }
    else if (twi_freq < TWI_FREQ_MIN)
    {
        twi_freq = TWI_FREQ_MIN;
    }

    // TWI bit rate.
    // §21.5.2 Bit Rate Generator Unit
    // §8.12.2 CLKPR – Clock Prescale Register
    byte bit_rate = (F_CPU / (1 << CLKPR) / twi_freq - 16) / 2

    TWBR = bit_rate;

    // Check.
    const uint32_t twi_freq = F_CPU / ( ( 1 << CLKPR ) * ( 16 + 2 * TWBR * 1 ) );
}

Note that smbus is a flag set elsewhere (global or class member) to indicate SMBus mode.

Just to confirm, in case anyone else is wondering, the second pair of equations in my question are the correct ones which take the CPU clock prescaler (CLKPR) into account.
TWI clock frequency:

And solving for TWBR:


text:
Arduino MQTT Library sending disconnect packets even though it is not called
I am trying to connect to AWS IoT through the Arduino Portenta H7 and I am following this blog (https://create.arduino.cc/projecthub/Arduino_Genuino/securely-connecting-an-arduino-mkr-wifi-1010-to-aws-iot-core-a9f365).
When I run the code, it shows that there was an error connecting to the MQTT broker (Error code: -2)...but when I check the Cloudwatch logs, it shows a successful connection and a client initiated disconnection. I am not sure why it disconnects as my code does not initiate disconnection.
Here is the code:
void connectMQTT() {
  Serial.print("Attempting to MQTT broker: ");
  Serial.print(broker);
  Serial.println(" ");

  while (!mqttClient.connect(broker, 8443)) {
    // failed, retry
    Serial.print(mqttClient.connectError());
    Serial.print("\t");
    delay(5000);
  }
  Serial.println();

  Serial.println("You're connected to the MQTT broker");
  Serial.println();

  // subscribe to a topic
  mqttClient.subscribe("arduino/incoming");
}

Did you correctly set up the certificate?

Yes...because the Cloudwatch logs show that the device connected and even subscribed


text:
Whats the best way to keep an Arduino in a waterproof junction box and prevent overheating?
I am trying to make an automatic garden gate unlock that runs on a timer. I plan on running an arduino uno 24/7 with a software timer that activates a motor to release a bolt lock. I am going to fit all the electronics and extension cord into a waterproof junction box. Will this cause over heating? Is there a need for some kind of waterproof cooling system? Has anyone ever built outdoor electronics and ran into this problem?

Arduinos don't generate that much heat - except maybe the 5V regulator. Use an efficient switching regulator instead of relying on the 5V regulator on board and there will be little to no heat.

If you do need to actively cool something then use a metal enclosure and thermally connect that component to the casing.

I wouldn't worry all that much about the Arduino itself, but, depending on what you use, the power supply and especially the motor driver may generate some heat. It won't be on often, or for very long, though. Somebody somewhere could do the math given your exact set-up; speaking for myself, I would just try it and experiment.

@Majenko good point I'll look into that.

@ocrdu no the motors won't be on often likely twice a day for a couple of seconds, but the arduino will be running always but not performing any tasks until the time

I'd be more worried about the sun heating the box, than the Arduino board.

You also might consider using sleep mode.

I can't remember where I found it, but one person I saw had actually just protected the battery and battery charger and left the Arduino Nano out in the elements. He said they are so robust they just work regardless of the elements, and as soon as they dry out from the rain they just start working again. He said he had been doing it for years and had many Nanos just living out in the wild outside of enclosures and doing fine. This leads me to believe that enclosing cheap Arduino Nano-based projects perfectly is less important than I once thought.

The linear regulator on an Arduino works by converting excess voltage to heat. If you power it with 12V and draw a full amp from it it will turn (12-5)*1a or 7 watts of power to heat, and quickly overheat even if it's not in a box.
If you power it from 6.5V and only draw 300mA from it, it will turn (6.5-5)*.3, or a little under half-a-watt. While the Arduino is idling it will probably only draw 50mA, so less than 1/10th of a watt of heat.
For infrequent, short bursts of a few seconds you can probably get away with drawing 500mA of power without overheating.
Or skip the internal regulator and use a buck style voltage regulator. Those generate a LOT less heat.
Edit:
For a project I did recently, I used an external 5V regulated supply for everything. I cut a USB cable and soldered the red and black (+5V and ground) to the 5V supply, and plugged that into the Arudino's USB connector. That feeds 5V into the Arduino.

I normally use a SEPIC converter and low RDSon MOSFETs. I usually set the output of the converter to about 8 volts. I am assuming the motor is powered by another power supply not the one on the Arduino. I typically use the plastic Euro boxes without any problems. Keep it out of the sun and you will be OK.

"I usually set the output of the converter to about 8 volts." Wait, what? You then feed the converter into the VIN and still drive the Arduino's voltage regulator? Why not set your converter to 5V and use it's output to power the Arduino directly?

If you use a converter to generate 8 volts and feed that into the Arduino's VIN, you'll still turn 2V to heat.

Sorry, you'd convert THREE volts (and whatever current is drawn through the Arduino's regulator) to heat.

Using the Vin adds additional filtering and stability and it is free. I do not like inductive loads or lines leaving the enclosure to be on the same power supply as the microprocessor, they are great antennas. That is a lot less heat with an 8V feed then with a 12V feed. The proper choice of MOSFETS will have a big impact on the heat. Most of my designs do not use heat sinks, Low RDSon FETs cost more but are generally much cheaper for me then installing heat sinks.

The simplest selection is Aluminum water proof box.
You can make it yourself, using aluminum U profiles,
and mount arduino heat generator parts on the internal surface of the box.


text:
Send JSON body with SIM900 board
I'm trying to send JSON, but i'm not able to set Content-Type header.
Other commands are successful:
[23:49:41:856] AT+SAPBR=3,1,"CONTYPE","GPRS"␍␊
[23:49:41:899] ␍␊
[23:49:41:899] OK␍␊
[23:49:52:327] AT+SAPBR=3,1,"APN","internet"␍␊
[23:49:52:367] ␍␊
[23:49:52:367] OK␍␊
[23:49:59:585] AT+CSQ␍␊
[23:49:59:594] ␍␊
[23:49:59:610] +CSQ: 18,0␍␊
[23:49:59:610] ␍␊
[23:49:59:621] OK␍␊
[23:50:07:449] AT+SAPBR=1,1␍␊
[23:50:08:501] ␍␊
[23:50:08:512] OK␍␊
[23:50:13:900] AT+SAPBR=2,1␍␊
[23:50:13:928] ␍␊
[23:50:13:928] +SAPBR: 1,1,"127.0.0.1"␍␊
[23:50:13:955] ␍␊
[23:50:13:955] OK␍␊
[23:50:21:261] AT+HTTPINIT␍␊
[23:50:21:291] ␍␊
[23:50:21:291] OK␍␊
[23:50:40:284] AT+HTTPPARA="CID",1␍␊
[23:50:40:320] ␍␊
[23:50:40:320] OK␍␊
[23:50:47:652] AT+HTTPPARA="URL","http://127.0.0.1:5000/data"␍␊
[23:50:47:713] ␍␊
[23:50:47:713] OK␍␊
[23:50:54:359] AT+HTTPPARA="CONTENT","application/json"␍␊
[23:50:54:414] ␍␊
[23:50:54:414] +CME ERROR: operation not allowed␍␊
[23:51:06:576] AT+HTTPDATA=38,10000␍␊
[23:51:06:612] ␍␊
[23:51:06:612] DOWNLOAD␍␊
[23:51:12:034] ␍␊
[23:51:12:050] OK␍␊
[23:51:19:386] AT+HTTPACTION=1␍␊
[23:51:19:414] ␍␊
[23:51:19:414] OK␍␊
[23:51:27:747] ␍␊
[23:51:27:758] +HTTPACTION:1,500,290␍␊
[23:51:35:599] AT+HTTPREAD␍␊
[23:51:35:628] ␍␊
[23:51:35:628] +HTTPREAD:290␍␊
[23:51:35:635] <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">␊
[23:51:35:692] <title>500 Internal Server Error</title>␊
[23:51:35:735]
Internal Server Error
␊
[23:51:35:766]
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
␊
[23:51:35:935] ␍␊
[23:51:35:935] OK␍␊

ip addresses aren't real.
My server received invalid request (with JSON body, but without special header), and replied 500 Internal Server Error.
Revision: 1137B08SIM900M64_ST_DTMF_JD_MMS

127.0.0.1?! How do you expect to get there?

I wrote ip addresses aren't real.. I don't want to share my public ip.

Sorry, missed that bit. I'm viewing on my phone at the moment.

You need firmware version B10 to use the content Param. You have B08.

@Majenko, thank for your reply. At the moment I'm trying to upgrade to 1137B15SIM900M64_ST through pl-2303hx adapter, but my attempts are unsuccessful.

It's not something I have ever tried (I have never used a SIM900), so I can't help with that sorry.

Thanks for @Majenko.
I solved problem by upgrade firmware to 1137B15SIM900M64_ST.


text:
Run function concurrent to server.available()
I have a Arduino UNO WiFi Rev2 board that runs WiFiServer serving as a web server. The server listens and accepts clients using server.available(). I also want a loop that controls a servo in concurrent of the server.
I looked at ArduinoThread and tried to implement my web server with it.
class WebServer : public Thread
{
private:
    // Some method definition omitted
    WiFiServer server;
    void accept_and_process();

public:
    void run() override;
}

void WebServer::accept_and_process()
{
    Serial.println("Waiting for client");
    // listen for incoming clients
    WiFiClient client = server.available();
    // Process client
}

void WebServer::run()
{
    this->accept_and_process();
    this->runned();
}

But the code does not run in parallel with code in void loop() it only ran code inside loop function and does not accept client as expected
This is the code I ran the server with
void setup()
{
    Serial.begin(9600);
    WebServer webserver = WebServer();;

    webserver.setInterval(100);
    webserver.run();
}

void loop()
{
    Serial.println("Hello");
    delay(1000);
}

How would I run the server concurrent to another function.

There is no “parallel” on a single core arduino.  All you need to do is program both things in a non blocking fashion.  Don’t use delay or while loops waiting on things and you can do both things so fast it seems like they are parallel.  There are tons of tutorials on non blocking code.  Or post some actual compilable code here and maybe someone can help you see how.

@Delta_G thanks for the suggestion, I moved server.available() into void loop() to unblock the execution. I'm still experimenting with it but now everything should work as expected.

I never expected server.available() to be non-blocking because I assume it's basically socket.accept() in other languages which for most of the time, is blocking.

No.  server.available doesn’t wait for anything.  It just immediately returns whether or not there is a connection available.  If there’s not then it returns false and moves on.  Don’t assume.  There’s a great adage about what happens when you assume things.  Look it up if you don’t know it.

@Delta_G hey do you mind posting your comments as answer so I can accept it?

There is no “parallel” on a single core arduino. All you need to do is program both things in a non blocking fashion. Don’t use delay or while loops waiting on things and you can do both things so fast it seems like they are parallel. Put a call to server.available() in loop and then if it returns an invalid client object then the rest of the loop runs.  If it returns a valid client object then you can quickly do what you need with the server and then get back to everything else.
As noted in the comments, server.available is not blocking.  It doesn't wait for anything to come, it simply returns whether there is a connection available or not.


text:
ESP8266-01 Upload Sketch Problem Arduino UNO
My problem is actually in two stages.
I am very new to arduino uno and 8266-01. I have read many documents and watched videos for nearly 2 weeks, but I cannot even run the simplest "blink" example.
First of all, I installed the compatible software with an esp download tool as follows according to 6014h. And it seems okay.

After triple check, my wires and connections where they have to .
Rx->Rx  Tx->Tx  CH-3.3v GPI0 grounded Ground->Ground  and also 8266-01 VCC connected to Arduino 5v with 3.3v regulator and connected with capacitor, to debug voltage i check with voltmeter.
Problem is:
When I try to upload simple Blink example below imag.  My IDE gives a very different output from the videos I watched. I could not understand the reason for this.
the IDE outputs on the all of videos that i watched, are while uploading

This kind of upload starts when it says upload and when it's finished, the program runs.
BUT!In my case my  IDE is acts like that and nothing happens end of the upload.

My 8266 generic settings are as follows.

Led out pin in the blink example is 2 and GPI1 is connected to led to blink after all this explanation, where i missed up ?
Why i am taking different uploading process and code is not working?

Set flash mode to DOUT instead of QIO? You get different output because the videos you have seen are out of date and use an old uploading tool (esptool.exe) rather than the current one (esptool.py) or maybe the OTA tool (espota.py).

I set the flah mode to DOUT. I uploaded sketch again and hard resetting via rst pin is occured again and not blinking or any other serial AT commands not working. I think i catch somethings but i dont know. Why my code is not running or how I run the code after uploaded ?

you deleted the AT firmware with sketch upload

@Juraj how I run sketch ? is there any other connection mode for running mode ?

buy a development board for Arduino sketches on esp8266. something like Wemos D1 mini. it has USB and controls the flashing mode and reset of the esp8266. with esp-01 you must manually handle io 0 and reset for every upload. I wire buttons to esp-01 for frequent flashing. Then for flashing I hold the button for io 0 and click the button for reset. then I release the io 0 button.

My general advice these days: forget ESP8266 - use the ESP32. It's so much more capable.

Do you know whether you have an ESP-01 or ESP-01S? Visually, ESP-01 has two LEDs near the PCB antenna, a Blue LED connects to Tx line (GPIO1) and a Red LED as a power indicator. ESP-01S however only has one Blue LED and it is connected to GPIO2 instead. Based on your Arduino Menu, you are selecting GPIO2 as LED pin which only works for ESP-01S. If you have an ESP-01, you need to change "Builtin Led" to "1". See my blog for more explanation.


text:
Sparkfun OBDII - Arduino Uno Stuck at 832RPM-13Kmh
I'm working on a hobby project with Sparkfun OBDII UART + Arduino Uno + 16x2 LCD Screen, i'm trying to read my car's RPM-Speed-Coolant Temprature-Oxy Sensor on runtime.
Product Page
Wired OBDII to Arduino as:
OBD TX -> ARDUINO RX
OBD RX-> ARDUINO TX
OBD GND -> ARDUINO GND
As far as i understand OBDII board does all the job and it's just communicating with arduino through serial, they provided an example here : Hookup Guide
I don't have sparkfun serial lcd, so i've changed codes according to my lcd as follow;
#include <SoftwareSerial.h>
#include "DFRobot_RGBLCD.h"
const int colorR = 255;
const int colorG = 0;
const int colorB = 0;
DFRobot_RGBLCD lcd(16,2);  //16 characters and 2 lines of show
char rxData[20];
char rxIndex=0;
int vehicleSpeed=0;
int vehicleRPM=0;
void setup()
{
lcd.init();
lcd.setRGB(colorR, colorG, colorB);
Serial.begin(9600);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Hiz: ");
lcd.setCursor(0,1);
lcd.print("Devir: ");
delay(1500);
Serial.println("ATZ");
delay(2000);
Serial.flush();
}

void loop()
{
Serial.println("010D");
getResponse();
getResponse();
vehicleSpeed = strtol(&rxData[6],0,16);
lcd.setCursor(4,0);
lcd.print(vehicleSpeed);
lcd.print(" km/h");
delay(100);
Serial.flush();
Serial.println("010C");
getResponse();
getResponse();
vehicleRPM = ((strtol(&rxData[6],0,16)*256)+strtol(&rxData[9],0,16))/4;
lcd.setCursor(6,1);
lcd.print(vehicleRPM);
delay(100);
}
void getResponse(void){
  char inChar=0;
  while(inChar != '\r'){
    if(Serial.available() > 0){
      if(Serial.peek() == '\r'){
        inChar=Serial.read();
        rxData[rxIndex]='\0';
        rxIndex=0;
      }
      else{
        inChar = Serial.read();
        rxData[rxIndex++]=inChar;
      }
    }
  }
}

with above code i believe arduino receives last rpm and speed record before i shut down the engine which is 832RPM - 13 Kmh (at this point i'm not sure if arduino receive speed value correctly because when i shut down the engine i was parked the car and speed was 0kmh), in normal case when i start the car rpm and speed value should have changed but even after started the car the value stands still,it's not changing.
I bought waveshare's USB FTDI(TTL) adapter to figure it out is this board communicate with car or pc properly, connected usb ttl as;
OBD TX -> TTL RX
OBD RX-> TTL TX
OBD GND -> TTL GND
connected to OBDII port of my car, opened tera term, connected to COM20 (ttl defined as com20 on the pc) and run below commands as suggested in their manual;
ATZ -- resetted card successfully
ATRV -- returned 12.4 V as it should be, which is my battery voltage
ATSP0 -- auto find and select car's protocol it returned OK
010C -- RPM of the car it returned 41 0C 00 00 (engine wasn't started)
010C -- RPM of the car it returned 41 0C 10 F4 (engine started--idle RPM arround 1.000 rpm)
010D -- speed of the car it returned 41 00 00
010D -- speed of the car it returned 41 00 00 both value is the same because the car is not moving :)

According to above outcome the board is fine and communicating with car or pc or arduino without any problem.
But when i try with arduino when i connect the board to my car and turn my ignition to battery mode it reads rpm as 832 and speed as 13 and don't update those values even i start the engine.
What am i doing wrong?

after 1 week of try i finally solved it :)
As you guys know UNO has 1 i/o serial port, and Sparkfun's OBDII board doesn't work on same i/o serial port (at least i couldn't be able to), with uno when you send a command through serial to obd board you need to wait minimum 3 seconds to send another command or car's can-bus thinks that you canceled the first command returns STOPPED error, but with MEGA it works perfectly because mega has 3 i/o serial ports. You simply define Serial(TX)-Serial1(RX) and it works perfectly with 75ms delay.
Here is the working code.
//Set up ring buffer
char rxData[20];
char rxIndex = 0;
int rpmstored = 0;

    void setup()
    {
      Serial.begin(9600); // prints to serial monitor
      Serial1.begin(9600); //Hardware serial connection to the obdii uart
      OBD_init(); //initiates obd link
      delay(3000);
    }

    void loop()
{
rpmstored = getRPM();
//int mph = (int)((getSPEED() * 10000L + 5) / 16090); //convert to mph
//  Serial.print (mph);
Serial.print("S:");
Serial.print (getSPEED());
Serial.print (",");
Serial.print("R:");
Serial.println (getRPM());
//Serial.print (",");
//Serial.print("W:");
//Serial.print (getWATERTEMP());
//Serial.print (",");
//Serial.print("O:");
//Serial.print (getOILTEMP());
//Serial.print (",");
//Serial.print("F:");
//Serial.print (getFUEL());
//Serial.print (",");
//Serial.print("V:");
//Serial.println (getVOLT());
delay(100);
Serial.flush();
    }

    void OBD_init(void)
    {
      //Wait for a little while before sending the reset command to the OBD-II-UART
      delay(2000);
      //Reset the OBD-II-UART
      Serial1.print("ATZ\r");
      //Wait for a bit before starting to send commands after the reset.
      delay(2);
      OBD_read();
      Serial1.print("ATE0\r");
      OBD_read();
      //Serial1.flush();
    }

    int getRPM(void)
    {
      //Query the OBD-II-UART for the Vehicle rpm
      Serial1.flush();
      Serial1.print("010C\r");
      OBD_read();

      return ((strtol(&rxData[6], 0, 16) * 256) + strtol(&rxData[9], 0, 16)) / 4;
    }

    int getSPEED(void)
    {
      //Query the OBD-II-UART for the vehicle speed
      Serial1.flush();
      Serial1.print("010D\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16);
    }

    int getOILTEMP(void)
    {
      //Query the OBD-II-UART for the vehicle speed
      Serial1.flush();
      Serial1.print("015C\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16);
    }

    int getFUEL(void)
    {
      //Query the OBD-II-UART for the vehicle speed
      Serial1.flush();
      Serial1.print("012F\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16);
    }

    int getVOLT(void)
    {
      //Query the OBD-II-UART for the vehicle speed
      Serial1.flush();
      Serial1.print("0142\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16);
    }

    int getWATERTEMP(void)
    {
      //Query the OBD-II-UART for the Engine Coolant Temp
      Serial1.flush();
      Serial1.print("0105\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16) - 40;
    }

    void OBD_read(void)
    {
      char c;
      do {
        if (Serial1.available() > 0)
        {
          c = Serial1.read();
          if ((c != '>') && (c != '\r') && (c != '\n')) //Keep these out of our buffer
          {
            rxData[rxIndex++] = c; //Add whatever we receive to the buffer
          }
        }
      } while (c != '>'); //The ELM327 ends its response with this char so when we get it we exit out.
      rxData[rxIndex++] = '\0';//Converts the array into a string
      rxIndex = 0; //Set this to 0 so next time we call the read we get a "clean buffer"

    }

I only need RPM & Speed that's why i comnented out other parameters but tested all and works perfectly.


text:
Arduino-controlled Pet Door Lock
Have a problem: new house but it gets super-windy and the doggy doors' magnets are too weak and blow open. Can't use bigger magnets because the doggies are too small.
So I thought I'd reinforce the pet-doors with a latch.
Next problem: the dogs are too dumb to learn wait for the doors to open. So the release mechanism must be rapid.
My plan was:
Arduino - uno or beetle/leonardo
motion sensor or ultrasonic sensors x2 (one inside and one outside) -> arduino -> relay ->wall power supply -> electromagnet release (normally on)

only the electromagnet gets super hot, so may not be best. Do servos or solenoids open fast? as in < 1s

Anyone have any suggestions on a  better way?? THanks so much!

Solenoids are probably your best bet. Get a spring loaded one with a chamfered actuator designed for door locks. https://www.amazon.co.uk/Solenoid-Electromagnetic-Electric-Cabinet-Intelligent/dp/B07GSV92YJ


text:
PCA on ESP32 - libraries and recommendations?
it would seem that this would be a commonly sought-after topic, however I cannot find straightforward libraries for this and it's taking too long, so please allow me the question:
Is there a good library for Arduino/ESP32 to run principal component analysis (PCA) on a 3D matrix? Any links etc welcome, EigenArduino is the 'only' library I could find but it's not exactly straight forward (no example code etc). I want to extract the first component of some data sized 3x3000.
Thanks

this looks like example code https://eigen.tuxfamily.org/dox/GettingStarted.html#title1


text:
MAX30100 not working
I am unable to get the MAX30100 sensor to work
It keeps throwing the following error:
16:06:32.936 -> Initializing...
16:06:32.936 -> MAX30105 was not found. Please check wiring/power.

I am using the Sparkfun library Example sketch "Example5_HeartRate"
As far as I understand the breakout board for the MAX30100 is a bit buggy -
By which I mean the internal pullup resistors are connected to 1.8V for some reason instead of 5V
I have used MAX30100 before and had faced the same issue. However, after scouring the internet for hours  I found this helpful article: https://reedpaper.wordpress.com/2018/08/22/pulse-oximeter-max30100-max30102-how-to-fix-wrong-board/
I want to use another MAX30100 sensor and have followed the above article again and have done the said changes to my sensor which resulted in the board being detected at address 0x57 when I run the i2c scanner. However, unlike the previous time, the Example sketch did not run as expected.
I even tried this solution:
https://github.com/oxullo/Arduino-MAX30100/issues/51#issuecomment-391193292
But kept receiving the same error message.
The pin connections are:
ARDUINO -> MAX30100/MAX300102
3V3     ->    VIN
SDA (A4)->    SDA\
SCL (A5)->    SCL
GND     ->    GND
I need help asap.
Thank you in advance!
I hope the links mentioned are helpful for someone else.

This video might help you, in this video, an Indian guy explained the issue in detail with the help of the max30100 sensor schematic diagram, and solved it in two ways.
https://youtu.be/ZqdmA4NAqb0

It would be good for you to summarize the important point from the video in case the video disappears in the future.

Check out this link. I guess it will work I had the same MAX30100 module what i did was removed those 4.7k resistors mounted through hole resistors on breadboard and pull-uped them using 5V and it was working fine for me

I had similar trouble with a cheap board (RCWL-0531). Used the same “How to fix wrong board” fix you mentioned (pictured). Which worked ... sort of ... Achieved terrible sensing stability (both HR and O2). I read the comments in the sample code about Uno boards (which I had started out on) having insufficient capacity to handle the full sample data, so migrated to ESP32. Still not great.  Gave up and bought a Sparkfun MAX30105, still connected to an ESP32 and OLED display. Immediately a different experience, much higher quality but I don't know why. I have some "still to-do" ideas to investigate the MAX30102_by_RF library and also to use a more capable processor (e.g., Due) to see if the signal processing capability can be cranked up. Hope this helps - you're not alone.


text:
Get more PCINT capable pins on Mega 2560
I'm building kinda "ball game" for a total of 6 players based on these per-player specs:

1 stepper motor with 4 pins
2 end stops (start & finish) per motor
1 finish LED
3 holes to score, resulting in slow, medium or fast motor movement

Additionally, there's a "master reset" to move all motors back to their starting end stops.
Because of my initial assumption, 54 pins would be enough, I didn't realize actually requiring 60 pins (24 for motors, 12 for end stops, 6 for LED, 18 for holes). I'm also neither an expert at microelectronics nor C programming language, but my understanding of the Mega's pins is that I need 12 + 18 PCINT capable pins (end stops + holes) while only 16 pins are available.
So far, the only information I could find suggests buying an Arduino Shield to resolve this by providing additional 16 PCINT pins. But being connected via I2C, I suspect delays resulting in unequal treatment of player scores.
How to get at least 30 PCINT capable pins, treated equally by Arduino? In case there's no need for the PCINT requirement, which pins can be used as an alternative?

If you write good code you won’t need an interrupt for any of that.  Do you think that switch can make and break in less than a millisecond?  For comparison blinking your eyes takes about 200ms.  Don’t use delay for timing and you won’t need any interrupt for this.

If you want more PCINT you can do it yourself outside the chip. Just AND or OR (depending on if you want active LOW or HIGH) multiple signals together and feed the result into a single interrupt pin in addition to each signal into its own digital pin, then when the single interrupt occurs poll the other digital pins to see which changed.

@Delta_G How to? The current code within Arduino's loop() actually does use delay between setting e. g. the steppers to allow for kinda "cooldown". It's not that I want 1 ms response time, it's more in terms of "chance equality" between all players.

@Majenko So, you're suggesting me to, e. g. combine all 6 PCINT inputs into 1 and upon the interrupt, poll all 6 to find the right one? What about player #2 hitting the same hole (on his table, not player #1's table)? Wouldn't that be swallowed in vain then?

I wouldn't know. I have no idea what holes you're talking about, nor how a player "hits" them.

@Majenko It's kinda table game where a player needs to throw a ball into 1 out of 3 holes to then let his avatar move forward until any player reaches the finish line.

And...? You still haven't explained your concern in a way that is meaningful to someone that has no clue how your game is intended to work.

@Majenko I'm thinking of this: P1 throws ball into hole A, PCINT for all 6 players's A-hole (no pun intended), or in case all 3 types of holes, i. e. A, B & C, are tied together onto 1 PCINT, their triggering prevents detection of any other player's hit of hole A, B or C at their lane.

I think you missed the bit where I mentioned "in addition to each signal into its own digital pin" (I even had it in italic...). One interrupt fires. That interrupt then looks at other pins to see what is active. Of course the incoming signals have to last long enough for the polling to see them. If they are very very brief then you may want to latch them, maybe with an S-R latch, which is then reset by the MCU when it's been read.

I did read it, it's just that your creating the exact "why can't you see, it's so simple" mood that prevented me from even writing the OP in the first place. I'm a .NET dev in my day job, so working with (from my POV and not meant to be rude in any way) low-level stuff isn't as accessible as I hoped for in order to help my friend (for whom I write/wrote the code as he neither speaks English nor is able to write code). I just want this board to recognize inputs, but I'm near zero with knowledge what (extension) board/chip/etc. I need to buy & put where, get its lib from where & compile.

If you’re that newbie then why are you messing with advanced concepts like interrupts?   Get some experience with the basics first.  Like I said before none of this should require interrupts.  Just don’t use delay for timing.  If you want the code to do nothing then let the loop function run doing nothing.  But you don’t need any interrupt.

Beause I understand the concept of interrupts which is why they're not an advanced concept to me. Getting a LED on/off was as simple as moving stepper motors - but then there's a gap which I blame lack of official docs for as they rather created the new name "shields" instead of giving useful examples. That put aside, I don't understand how you read my words as "loop function shall do nothing in between". Again, please explain how am I supposed to get notified of a changed input without a) a PCINT or b) polling all such inputs every now and then. Maybe you can show an (abstract) code example?

The Atmega2560 has a total of 24 pins associated to the PinChange interrupt. You cannot change that. It is an internal property of the microcontroller.
As you already have seen yourself, you need to use extra chips to extent the available IO pins. There are different options to consider:

IO-Port-Expanders (available for I2C or SPI) (for example the PCF8574. Don't know, if that is the best, just the port expander, that I also used myself)
Shift-In (for inputs) or Shift-Out (for outputs) registers (often used are the 74HC595 (Shift-out register) and the 75HC165 (Shift-In register). I often used this tutorial as reference)

As you don't want to poll these chips all the time, I suggest, that you use one, which provides an additional interrupt pin. That pin will change its value, when one of the input changes. You could then connect this pin to one of the interrupt pins of the Atmega2560. When the interrupt triggers, you can read the states of the input pins.

But being connected via I2C, I suspect delays resulting in unequal treatment of player scores.

Indeed that wouldn't be good. So you should divide the pins up by their purpose, not by their association to a player. For example all end stop inputs, or all outputs for the stepper motors. Then you need to access, what timing requirements each group has. Then you can take the group with the lowest requirements and check, if and which chip would be able to handle the data fast enough. For example the "finish LED". You didn't specify, what exactly it does, but I guess, that it is not really time critical. So you could handle all finish LEDs via a single shift-out register.
Or take the inputs for the holes: I guess here you have some sensor, that triggers, when a ball passes it. Check how long the sensor get's triggered. Most likely (depending on the type of sensor) this depends on the speed of the ball. Take a speed, that you want to consider maximum (for example the pitching speed of a good baseball player, as these are really high), and calculate, how long the resulting pulse will be. The chip, that you choose, might be fast enough for this. So you could handle all ball hole inputs over extra chips (meaning chips providing extra input chips, like a Shift-In register or a port expander).

In case there's no need for the PCINT requirement, which pins can be used as an alternative?

Every pin capable of digital IO. That's nearly every pin on the Arduino Mega. Though that means, that you cannot use interrupts for them and you have to poll then constantly. That might be ok for you. It really depends on your exact timing requirements.

I thought polling was a "avoid where possible"-area?!

Yes and no. First you asked for the possibility of using other pins, so I mentioned that above. Though doing that means using no PinChange interrupt. Generally polling is bad, when

you spend too much time on it, leaving no time for other functions of the code, or
if the events, that you are polling, are too short for your polling code.

That can happen in the cases, that

you use blocking code to poll (like waiting with a while loop for a button press), which blocks all other functions from executing.
your code needs a long enough event to register it (for example the signal from your hole sensors might be very short. If your polling interval is bigger than that, you will loose some events)

If you stay inside of the confinements and use non-blocking code, there is nothing bad with polling.
Let's take the often used Bounce2 library for Arduino. It helps you with reading buttons and handles the debouncing for you. It does not use any interrupts. You are expected to call Bounce.update() often enough to catch all button presses, which is typically a few ms at max. But since the Arduino Mega runs on 16MHz, it is capable of way faster speeds than the few ms. Calling Bounce.update() often enough is easy, when you don't write code, that stays a long time to execute. So no delays, except for maybe very short ones. Instead you can use the coding style of the BlinkWithoutDelay example, that comes with the Arduino IDE. It uses the millis() function as a time base to check repeatedly, if it is time to do something, and only do so, if it really is time for it. Much like you are baking a pizza by putting it into the oven and then regularly watch at your clock, if it is time to get the pizza out of the oven. You don't want to sit in front of the oven waiting for pizza. The analog of doing that is writing blocking code with delay().
So all in all about polling vs interrupts: It depends on your requirements. Fast response times or short events often need interrupts, though you need to cope with limited usable pin numbers and different interrupts (which is a bit more complex to code). Polling - when done right - can give you big freedom and rather easy handling, while saving interrupt sources for more important functions. Though it poses bigger limits on response times and the duration of events. Also it depends strictly on the rest of your code.

Note, that in the above, terms like "time critical", "fast response times" and such are more meant for the region of a low number of microseconds. Timings in the millisecond range can easily be done by using the mentioned non-blocking coding style (either with millis(), or for greater resolution and accuracy at low numbers of milliseconds micros()). The principle is always the same and there are tons of tutorials about it on the web and even many questions and answers on this site. So you can google for this, to get a more detailed tutorial.

Sorry, my obligations prevented a sooner reply.. As I've got zero knowledge about I2C/SPI beyond their basic working, can you please recommand such an IO expander and/or a shift-in/-out register with such an additional interrupt pin? Regarding the "finish LED", the winning player's LED shines after his avatar crosses the finish line (and all 6 LED together upon reset-button press) - so yes, not time-critical at all. :) Yes, hole inputs work via sensor triggers. But I don't get what you mean by "extra chips" :( And regarding polling: I thought polling was a "avoid where possible"-area?!

@Yoda I added more information to my answer, including examples for possible parts (IO expander, Shift-in register, Shift-out register) and a section about polling vs interrupts. With "extra chips" I meant chips like the above, to get more IO pins.

thanks for your help, time and especially your useful explanations! I'll go for polling then, trying millis() & micros() first & falling back to 75HC165/74HC595 or PCF8574 if that doesn't work out. Again, thanks a lot for your valuable help!


text:
which kind of data are store If i terminate the call in sim800?
I'm working in SIM800 for DTMF based project.
I want to know which kind of data are stored in the buffer during termination of call in SIM800.
How to find if call was disconnected in SIM800?
Also please suggest some AT-COMMAND tester software and DTMF codes for my reference.


text:
Help me for interfacing Arduino with AMTP32M VOICE IC
i'm trying to get control an Aplus chip aMTP32M (stores audio samples) with Arduino . this amtp32m ic provide CPU SERIAL MODE its come with DATA and CLOCK pin.i try Spi mode with Amtp32m ic but its not working.
Please help me for this.
Link for  for DATASHEET of AMTP32M IC -http://www.aplusinc.com.tw/proimages/Mtp%20Vioce%20Ic/aMTP32M/aMTP32M/Datasheet/aMTPxxM-Datasheet_V1.1_20141216.pdf

Finely i try the below code for serial mode. it's worked perfectly...
type def union
  {
unsigned char BYTE;
struct
{
    unsigned        BIT0:1;
    unsigned        BIT1:1;
    unsigned        BIT2:1;
    unsigned        BIT3:1;
    unsigned        BIT4:1;
    unsigned        BIT5:1;
    unsigned        BIT6:1;
    unsigned        BIT7:1;
};
}ByteToBit;

void Play(unsigned char Val)
{
  ByteToBit SectionNo;

  SectionNo.BYTE = Val;

CLOCK = 1;
DATA  = 0;
CLOCK = 0;

DATA  = SectionNo.BIT0;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT1;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT2;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT3;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT4;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT5;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT6;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT7;
CLOCK = 1;
CLOCK = 0;

DATA  = 0;
CLOCK = 1;
DATA  = 1;

return ;
}

 void main(void)
 {
    unsigned char SectionNo;

CLOCK = 1;
DATA  = 1;

SectionNo = 0x00;
while(1)
{
    Play(SectionNo);
    Delay_1mS();        // Wait for BUSY set up time...
    while(BUSY);        // Voice playing...
    SectionNo++;
}

return ;
}

according to this :

it's more similar to I2C than SPI. anyway, it's just 2 wire custom serial interface. you can use any 2 GPIOs for this purpose.
for sending a byte, you have to:

initialize 2 GPIOS (CLK_IO and DAT_IO) to output, high.
set DAT_IO low
wait at least 1us (according to datasheet ver 1.1, page 18) then set CLK_IO low.
place the D0 bit value on the DAT_IO
toggle the CLK_IO (set it high, wait at leas 1us, set it low)
do steps 4 and 5 for all the remaining bits.
at the end set CLK_IO high
wait for at least 1us and set the DAT_IO high.

thank you for your replay.i will try your suggestions.

According to datasheet page 25, it would be much easier to use the Parallel mode than the Serial mode.

hcheung..Yes parallel mode is much easier .but it's give only 32 sections for audio storage. in serial mode  it give 255 sections for audio storage.


text:
avrdude: stk500v2_ReceiveMessage(): timeout error for bluetooth arduino
I am trying to link the Bluetooth module to my arduino UNO in order to wirelessly program a robot. The only issue that I am having is that the bluetooth module does not seem to pick up the arduino.
Here is how the bluetooth module is wired up to my arduino:

The bluetooth module is paired to my PC via a bluetooth dongle. I know that the bluetooth module is working on port COM7. The LED then on the bluetooth module blinks quickly. After this I set the port to the correct port that the bluetooth module uses:

One thing that I found strange was that the name of the arduino board does not come up just like when I use a USB to upload the program.
When I open up the serial monitor the LED on the bluetooth module begins to blink more slowly possibly indicating it is connected. I afterwards try to send an AT command via the serial monitor to the arduino by typing in AT to the serial input at the top of the serial monitor and hitting enter and nothing happens. I then tried to send 3 different pieces of code separately to the arduino one at a time:
First code sample:
void setup() {

 Serial.begin(9600);

while (!Serial) {
   ; // wait for serial port to connect. Needed for native USB port only
 }

 Serial.println("ASCII Table ~ Character Map");
}

int thisByte = 33;

void loop() {

 Serial.write(thisByte);

 Serial.print(", dec: ");
 Serial.print(thisByte);

 Serial.print(", hex: ");
 Serial.print(thisByte, HEX);

 Serial.print(", oct: ");
 Serial.print(thisByte, OCT);

 Serial.print(", bin: ");
 Serial.println(thisByte, BIN);

 if (thisByte == 126) {
   while (true) {
     continue;
   }
 }
 thisByte++;

}

Second code sample:
#include <SoftwareSerial.h>
SoftwareSerial BTSerial (2,3);
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Enter AT Commands");
  BTSerial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(BTSerial.available()){
    Serial.write(BTSerial.read());
  }
  if(Serial.available()){
    BTSerial.write(Serial.read());
  }
}

Third code sample:
char inputByte;
void setup() {
 Serial.begin(9600);
 pinMode(13,OUTPUT);

}

void loop() {
while(Serial.available()>0){
  inputByte= Serial.read();
  Serial.println(inputByte);
  if (inputByte=='Z'){
  digitalWrite(13,HIGH);
  }
  else if (inputByte=='z'){
  digitalWrite(13,LOW);
  }
  }
}

(The following situation occurs for all 3 samples of code I copied from online). When I set the port to COM7 and then click upload to the board, the IDE says "Uploading" and the LED begins to blink more slowly just like as I was mentioning before with the serial monitor. After a while eventually the following error messages came up:
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

I looked online for answers. The internet suggested to use a larger baud rate so I switched it from 9600 to 57600 and also at the same time switch from Newline to Both NL and CR. Still nothing happened and I got the following error message. One final suggestion I saw on the internet was to put a resistor divider/voltage divider across the RX pin (I haven't done this as I don't see how this could make a difference, I could be wrong about it though and it could make the whole difference).

You have no method to reboot the Arduino into the bootloader. You can't just slap a bluetooth interface on and hope it works. You need to have some way of triggering a reset like the USB interface does through the DTR signal.

Also you have to manually configure the HC05's baud rate to match the baud rate of the bootloader (115200 baud IIRC) which you can only do through its serial interface pins.

@Majenko Only problem is that I am not that experienced...

Then you need to read, read, read. Read how the HC-05 works. If there's something you don't understand then read up about that aspect. Keep reading until you understand it all.

@Majenko Is there a way I could use the reset pin on the arduino to solve the problem?

If you can come up with some way of remotely toggling it through the bluetooth connection, yes. Or tap the reset button at the right moment, but I guess that kind of negates the whole point of the bluetooth...

One thing that I found strange was that the name of the arduino board does not come up ... why should it? ... the name comes from the USB driver

@jsotola To be fair I was thinking that.

I am not sure how comfortable you are with soldering, but checkout this video where somebody showed how to reset the Arduino from the Bluetooth module: https://youtu.be/6GD3aNFrJ9I?t=401

The Bluetooth range is small so the robot can't be far from the computer for upload.

To solve the reset for the Bluetooth you could add a reset button on the robot and use it while avrdude attempts to upload the sketch. Baud rate on HC-05 must be set to 115200 baud.

As an alternative you could have USB connector on the robot. You can use a short USB extension cable as internal cable from the USB connector of the Arduino to the outer shell of the robot.


text:
'class Adafruit_SPIDevice' has no member named 'endTransaction'
So what I have done is followed all of the instructions in the following link:
https://learn.adafruit.com/adafruit-pygamer/setup
and have managed to get all the way up to https://learn.adafruit.com/adafruit-pygamer/arduino-libraries.
the board not has its own serial COM port and does work with a very basic blink example program which does not include any libraries at all. Shown on https://learn.adafruit.com/adafruit-pygamer/using-with-arduino-ide.
The next problem occuring is that now another error message is coming up within the code which I am not too sure it is trying to say:
Arduino\libraries\Adafruit_EPD\src\Adafruit_EPD.cpp: In member function 'void Adafruit_EPD::csHigh()':
and
libraries\Adafruit_EPD\src\Adafruit_EPD.cpp:649:12: error: 'class Adafruit_SPIDevice' has no member named 'endTransaction'.
Here is the github for the library I am using (its called adafruit arcada library), https://github.com/adafruit/Adafruit_Arcada.
Here is the code that I am trying to run using the adafruit_arcada library. I have checked it is installed in the right place in the arduino/library folder on the computer system.
Here is my code I am trying to run:
#include "Adafruit_Arcada.h"
Adafruit_Arcada arcada;

void setup(void) {
  Serial.begin(9600);
  Serial.print("Hello! Arcada TFT Test");

  // Start TFT and fill black
  if (!arcada.arcadaBegin()) {
    Serial.print("Failed to begin");
    while (1) delay(10);
  }
  arcada.displayBegin();

  // Turn on backlight
  arcada.setBacklight(255);
}

void loop() {
  arcada.display->fillScreen(ARCADA_RED);
#if defined(ADAFRUIT_MONSTER_M4SK_EXPRESS)
  arcada.display2->fillScreen(ARCADA_RED);
#endif

  delay(100);

  arcada.display->fillScreen(ARCADA_GREEN);
#if defined(ADAFRUIT_MONSTER_M4SK_EXPRESS)
  arcada.display2->fillScreen(ARCADA_GREEN);
#endif

  delay(100);

  arcada.display->fillScreen(ARCADA_BLUE);
#if defined(ADAFRUIT_MONSTER_M4SK_EXPRESS)
  arcada.display2->fillScreen(ARCADA_BLUE);
#endif

  delay(100);

  arcada.display->fillScreen(ARCADA_BLACK);
#if defined(ADAFRUIT_MONSTER_M4SK_EXPRESS)
  arcada.display2->fillScreen(ARCADA_BLACK);
#endif

  delay(100);
}

However, something is telling me that something is either out of date or I might have potentially installed something wrong because in the guide that was sent there is 5 examples within the adafruit arcada library. But with the one I have installed, there is lots of examples. The guide itself was not updated too long ago (6th November 2020). The arcada library I have installed is the one installed from the library manger and the version of the library is 2.5.0 and the one on the tutorial on https://learn.adafruit.com/adafruit-pygamer/arduino-libraries seems to be saying the library is version 1.0.0. Perhaps the library is too update on my computer to date compared to the one in the guide which potentially might be more out of date than the one I have on my computer.

The line in your error message seems to be referring to a library for "Adafruit E-paper displays".  Did I miss something in your question that should have clued me into why an e-paper display plays a role in this?

Well... I am not too sure if the screen is a E-paper display.

But I did look at the adafruit EPD driver and it seemed to be out of date so I updated it.

The display used on the board is described as "1.8" 160x128 Color TFT", "TFT" being an LCD technology.  Mostly I was wondering if you'd added anything or if there was a mini-display or battery indicator something of that sort that would account for it.  EPD library is mentioned as a dependency of Arcada, for what reason I don't know.  It'll be a while before I get a deeper look into it.

Don't worry I have solved it, all that I did was update the EPD driver and that was it.

Post what you did as an answer to your own question.


text:
Is there a way to convert between arduino and raspberry pi pins
I have a robot that I have brought that is designed for raspberry pi (it comes with a raspberry pi HAT), and I am terrible at using my raspberry pi. So I was thinking what if there is some sort of way that I could use the digital pins on the arduino and the pins on the GPIO pins on the raspberry pi.
My idea is currently this (I actually have not tried it out yet just in case something goes wrong):

Connect an arduino digital pin to the bottom of one of the female
pins on the raspberry pi HAT (which would be typically used on a
raspberry pi rather than an arduino)

Would this be possible?

of course it is possibke ... use dupont jumpers with male connector at one end and a female connector at the other end

The Pi is 3.3V, Depending on what is on that "hat" you may need 5V <-> 3.3V logic level conversion.

@jsotola So could it be possible to connect digital pin 10 (just a random one for example), to GPIO pin 26 on the raspberry pi HAT and then use this digital input going through GPIO pin 26 on the raspberry pi somehow to control a motor?

@Majenko That makes thing a whole lot more difficult, would is simply be just most reasonable to supply the raspberry pi HAT with 3.3V?

@DigitalRookie4 No, you're thinking backwards. The "simplest" option would be to use a 3.3V Arduino.

@Majenko So you are meaning supplying the raspberry pi HAT with 3.3V from the arduino's 3.3V pin?

No. You either (depending of course on what is actually on that "hat" - RTFDS...) need to convert the Arduino's 5V GPIO signals to 3.3V or use an Arduino that runs at 3.3V so that it already outputs 3.3V GPIO signals.