text:
How can I switch from ArduinoOTA to ESPhome safely?
I have an ESP8266 (ESP-12F), which I flashed with ElegantOTA, a variation of ArduinoOTA with just a different interface. I never managed to flash anything else, so it's a bare OTA I flashed using a dedicated programmer. The device has not even pins for further flashing.
The ESP is already in a device that I would like to avoid opening, and I would like to avoid soldering pins and flashing locally the ESPhome firmware (which is also configured for future OTA).
I'm not sure the bootloader or whatever is used to self-flash the chip is compatible. How can I do it?
Or should I just open the ArduinoOTA webpage, upload a ESPhome firmware and go on?

if you can load a new firmware, load a new firmware. make sure it works before hand, but an image is an image.

I thought that different bootloaders use different techniques for replacing the running one. For example, one may write the new one in the second half of the flash and run it from there, but they could also write the firmware file in the second half, then copy it back to the first "already running" area. But ok, if it's compatible, I'll do it.

well i've definitely used different firmwares with different OTAs and not had a problem. It feels dirty, i'll give you that. I suppose it's possible to fail and I just got lucky, and i'm just some guy on the internet not guaranteeing your money back, but afaik, you don't really need to worry about boot-loaders on ESP8266s.

@dandavis at the end I compiled a minimal ESPhome firmware, with only OTA and wifi captive portal, and I tried to upload it (300 KB, more or less). "Space is not enough". I also tried to compile a minimal BasicOTA from the Arduino suite, and I got a binary of the same size and the same error message. I have to flash using the pins.

I compiled a minimal ESPhome firmware, with only OTA and wifi captive portal, and I tried to upload it (300 KB, more or less).
Initially I got the error "Space is not enough", but then after rebooting the ESP8266 and trying again, it worked.
So as said by dandavis, different firmwares are compatible in regard to OTA capabilities and it's possible to cross-flash.

I've found that when a flash fails with a space error, I've usually specified the wrong flash size option in Arduino (under Tools->Flash Size).  Depending on the version of Arduino you're using, try picking the one with "No SPIFFS" or FS:none that matches the size of your flash memory.  Once you make that change, recompile and reupload.


text:
Simple ESP32 MCP2515 CAN code to VP230
I have a working code that uses MCP2515 CAN module. Wanted to minimize the size of required modules, so I went with VP230 CAN transceiver and I'm having trouble relaying the same data through different libraries. All it has to do is log in with the first ''payload1'' and send voltage instruction with ''setdefaultvolt''. Any help is greatly appreciated.
MCP2515 code:
#include <mcp_can.h>
#include <mcp_can_dfs.h>
#include <SPI.h>
#include <Wire.h>

//pins:
#define CAN_INT 17                                                                         // Set INT to pin 2
MCP_CAN CAN(5);                                                                         // Set CS to pin 4 (D2)

void setup()
{
  Serial.begin(115200);
  delay(100);
  pinMode(17, INPUT);                                                                       //Setting pin 2 for /INT input

START_INIT:
  if(CAN_OK == CAN.begin(MCP_ANY, CAN_125KBPS, MCP_8MHZ))
  {
  }
  else
  {
    delay(100);
    goto START_INIT;
  }
  CAN.setMode(MCP_NORMAL);                                                        //set operation mode to normal so the MCP2515 sends acks to received data.
  unsigned char payload1[8] = {0x16, 0x50, 0x71, 0x07, 0x97, 0x089, 0x00, 0x00};  //login data with serial number
  CAN.sendMsgBuf(0x05004804, 1, 8, payload1);                                     //send login data

  unsigned char setdefaultvolt[5] = {0x29, 0x15, 0x00, 0xFE, 0x10};              //this is the command for setting the default output voltage (Last two bytes, LSB first). 16 80 is the maximum voltage of 57.6 V
  CAN.sendMsgBuf(0x05019C00, 1, 5, setdefaultvolt);                              //send setup data
}

void loop()
{
}

VP230 code:
#include <CAN_config.h>
#include <ESP32CAN.h>

CAN_device_t CAN_cfg;

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

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

  CAN_cfg.speed=CAN_SPEED_1000KBPS;
  CAN_cfg.tx_pin_id = GPIO_NUM_19;
  CAN_cfg.rx_pin_id = GPIO_NUM_23;

  CAN_frame_t my_frame;
  CAN_frame_t my_frame2;

  ESP32Can.CANInit();

  my_frame.FIR.B.FF = CAN_frame_ext;
  my_frame.MsgID = 0x05004804;
  my_frame.FIR.B.DLC = 8;

  my_frame.data = {0x16, 0x50, 0x71, 0x07, 0x97, 0x089, 0x00, 0x00};

  ESP32Can.CANWriteFrame(&my_frame);

  my_frame.FIR.B.FF = CAN_frame_ext;
  my_frame.MsgID = 0x05019C00;
  my_frame.FIR.B.DLC = 5;

  my_frame2.data = {0x29, 0x15, 0x00, 0xFE, 0x10};

  ESP32Can.CANWriteFrame(&my_frame2);

}

void loop()
{
}

Just spotted this, but if any one else finds it: You have one CAN speed set to 125kb on MCP2515 the other to 100kb on the VP230.
That's why you won't get anything!
Mark

from datasheet ...CAN controller at speeds up to 1 Mbps.
On the SN65HVD230 and SN65HVD231, pin 8 provides three different modes of operation: high-speed, slope
control, and low-power modes. The high-speed mode of operation is selected by connecting pin 8 to ground,
allowing the transmitter output transistors to switch on and off as fast as possible with no limitation on the rise
and fall slopes.

source: Stack Exchange

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

sort: votes


text:
send data from serial to client
I am using Arduino Yun to send data from serial to client, and it's partially working because I only get short data delivered, while long data (like more than 100Byte) get the most of them lost.
on the other hand when I use the softwareSerial example in the IDE to send from serial to serial it works with no data lost. I am trying to do like the example as possible with the serial to client code using client.write(mySerial.read()) but not working as expected!
what am I missing? I guess client.write doesn't hold long data or is too slow to transmit. How can I solve this or even another way to achieve my point?
I am sending the data (as a file content on one time, not in sequence- it's a must) from pc using terminal Programm sscom32e. I am receiving the data as client using netcat on the same pc (Yun and PC connected with RS232-USB and are on the same network).
#include <SoftwareSerial.h>
#include <Bridge.h>
#include <BridgeClient.h>

#define PORT 9000
// Make the client connect to the desired server and port
IPAddress addr(192, 168, 0, 100);

//not all pins on the yun are assignable as rx/tx
SoftwareSerial mySerial(10, 11); // RX, TX

// Define our client object
BridgeClient client;

int led = 4;
bool Connected;
void setup() {
 pinMode(led, OUTPUT);

 // set the data rate for the SoftwareSerial port
 mySerial.begin(9600);
 mySerial.println("Hello, world?");
 mySerial.setTimeout(20000);

 // Start Bridge
 Bridge.begin();
 //delay(1000);

 // Start Console communications and wait for port to open:
 //Console.begin();
 //delay(1000);

 //Console.println("Client connecting on port 9000");
 Connected = false;

 //delay(1000);
 //connectToClient();
 connectToClient();
}

void loop() // run over and over
{
 while (mySerial.available()) {

 client.write(mySerial.read());

 //mySerial.read();
 }

}

void connectToClient() {

 // is a connection currently active?
 if (!Connected)
 {
 // not currently connected, try to establish a connection
 client.connect(addr, PORT);
 delay(1000);

 if (client.connected())
 {
 // send something to the client
 client.println("hello server!");
 digitalWrite(led, HIGH);
 }
 else
 {
 connectToClient();
 digitalWrite(led, LOW);

 }
 }
}

Why not use hardware serial?

what do you mean by hardware serial?

The Serial class of the arduino environment (commonly used to print to serial monitor) makes use of the chips hardware serial. In this case the communication is entirely handled by the hardware, software serial kind of emulates a serial in software which is more prone to errors. As you seem to be barely able to reproduce the problem in a consistent way, this could be worth a try

because I am using an RS232-Shield to receive data

Maybe try to first buffer a full message and then sending it as complete message in one request. Currently you are sending many 1 byte requests. Can it be, that the netcat client can not receive that many requests for whatever reason

no it's not a netcat -or in general- a connection problem(cause II tried to send big data from SD and it had no problem- but this solution wasn't also good because writing to the SD from Serial had the same problem). I tried buffering it in a string, using
String content
character = myserial.read();
content.concat(character);
``` but this didn't work either to send from serial to client, although worked for serial to serial.
I tried to buffer it in char array, but char arrays are just like 250Bytes long!

I believe now that serial.read and client.write cann't work together at the same time efficiently. when client.write starts, serial.read stops and therefore data get lost. Now I am saving the serial.read in 3 arrays of each 255Byte, when they are full or I receive an end-marker I call client.write to send them and Serial stops anyway. This works but for max. 765 Byte data. I can't do more arrays to save the serial data due to the limited memory of the module, which means it's not the best solution right now. I will post the code for this later when I optimate it. the other Idea coming to my mind is to send orders to the serial to wait until client.write finishes and then continue receiving and so on. Is this possible? Is Serial that flexible? How could I communicate with Serial to wait and to continue?

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


text:
Help me get my robotic car to work?
So I recently followed a tutorial on youtube and I've assembled the car and connected all the wires.
What I've done:
Car
Now in the video, when the guy connects all the wires, the wheels constantly turn while in mine they're completely still. Is this a problem? Is it an indicator of some connection issue or something else?
For context, here is the schematic:

Add your code, and use the minimal code that should be able to spin the wheels (preferably test yourself). Also recheck all connections (the picture in the link is hard to 'analyze' ).

when the guy connects all the wires, the wheels constantly turn ... that sounds like his car is not working correctly ... the wheels should not turn until commanded to turn

The ENA/ENB (enable A/B) pins have to be at HIGH level (either hardwired or set by an mcu). There exist lots of different driver boards (mostly based on the same ICs) which sometimes don't provide this enable pin, but they are "enabled" by default. You didn't tell us which board you use, but you'll know.

I don't know your motor-driver board but here are several things to check out, based on your schematic:

The motor driver board has two enable pins. Neither of them is connected. It would make sense that these pins turn the two motors on and off.
The pin marked 12v is connected to +5v.
The linked photo of your car shows two 9v "Transistor" batteries. This kind of battery in particular is not capable of supplying much current and they most likely unable to turn the motors.

Check These:
As you have used two power source you must common ground them.
**You must check L298N motor drivers enable pins.As you have only 4 wire to motor driver from arduino.So you must give EnA and EnB pin 5v/HIGH or  You can give it (0-255) pwm value from arduino to control the speed of your motor **
If wiring is ok then you must go throw you Sketch.


text:
Which Datasheet applies to the ATmega328p?
While researching minimum-voltage requirements of Uno, I came across what appear to be two datasheets for the ATmega328P:
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf
Specifically, the power requirements (and processor speed for each power level) differ. How could I know which datasheet applies to the chip I'm using? I'm actually using an Arduino clone:

It seems the first document is only for the 328P, and the other supports more (including the 328P). I would expect the information regarding the 328P is consequent in both versions (or should be).

@MichelKeijzers: As can be seen in the photo, I am using a 328P. One of the datasheets states that the microcontroller can run at 1.8v @ 4 MHz, the other states a 2.7v minimum.

I checked the revision history and the first talks about adding automotive, but sorry, I can't explain the differences. Hopefully adds a correct answer. Upvoted since I'm curious too now.

You have ATmega328P-AU. Classic Uno with DIP socket has ATmega328P-PU. Arduino Uno SMD has Atmega328P-MU.
The automotive versions ATmega328P-15AZ and ATmega328P-15MZ have separate datasheet starting in Revision History with

Creation of the automotive version starting from industrial version
  based on the ATmega48P/88P/168P/328P datasheet 8025F-AVR-08/08.
  Temperature and voltage ranges reflecting automotive requirements.

Just to be sure: -AU does not stand for automotive? What does it stand for?

the first letter is package form. -P is "Plastic Dual Inline Package", -M is "Micro Lead Frame Package", -A is " Plastic Quad Flat Package". I only read the datasheet

Thank you. I've gone through the second datasheet again and still cannot find that information, even when searching for the phrases you mention.

@dotancohen, page 635

I see, thank you. I had no idea how to read that, I was expecting the information in another format.

I think there is an error concerning the information about supply voltages. At least it's not consistent: microchip has separate websites for ATmega328 and ATmega328p. On the site for the ATmega328p it says: "The device operates between 1.8-5.5 volts". But the datasheet they link on the exact same site says:
    "Operating voltage: 2.7V to 5.5V for ATmega328p".
This is not just confusing, but contradictory and so I think the only one who can say for sure is the manufacturer.
Actually, the specified supply voltages are determined by the manufacturer by testing at various levels, but the device might operate even below or above this range (of course, a developer has to comply with the specs). The 2.7V rating could be an old spec and in the meantime they might have found out that the device indeed runs fine even at 1.8V. Maybe, they have just missed to apply this change everywhere this rating is mentioned, but that's just a guess.


text:
SoftwareSerial interfers with TVout
I'm using an Arduino uno and a Nodemcu for making a game with the phone as a WiFi controller.
The Nodemcu is the server that receives inputs from the phone connected via WiFi and sends to the Arduino a signal via SoftwareSerial.
The Arduino reads the signal and then decides what to do and sends output to TV.
It works good but every time the nodemcu sends something, the TV signal gets distorted.
note: the code for the game is not completed
code for Nodemcu:
#include<SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid = "SpaceInvaders";
const char* password = "12345678";

IPAddress local_ip(192,168,1,1);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
SoftwareSerial SUART(4, 5); //SRX=Dpin-D2; STX-DPin-D1
ESP8266WebServer server(80);

void setup() {
  SUART.begin(115200);
  Serial.begin(115200);
  WiFi.softAP(ssid, password);
  WiFi.softAPConfig(local_ip, gateway, subnet);
  server.on("/", handle_OnConnect);
  server.on("/0", nope);
  server.on("/1", left);
  server.on("/2", right);
  server.on("/3", left_right);
  server.on("/4", shoot);
  server.on("/5", left_shoot);
  server.on("/6", right_shoot);
  server.on("/7", left_right_shoot);
  server.onNotFound(handle_NotFound);

  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}

void handle_OnConnect() {}

void nope()             {SUART.print(0); server.send(200, "text/html", " "); Serial.println(0);}
void left()             {SUART.print(1); server.send(200, "text/html", " "); Serial.println(1);}
void right()            {SUART.print(2); server.send(200, "text/html", " "); Serial.println(2);}
void left_right()       {SUART.print(3); server.send(200, "text/html", " "); Serial.println(3);}
void shoot()            {SUART.print(4); server.send(200, "text/html", " "); Serial.println(4);}
void left_shoot()       {SUART.print(5); server.send(200, "text/html", " "); Serial.println(5);}
void right_shoot()      {SUART.print(6); server.send(200, "text/html", " "); Serial.println(6);}
void left_right_shoot() {SUART.print(7); server.send(200, "text/html", " "); Serial.println(7);}

void handle_NotFound(){
  server.send(404, "text/plain", "Error: not found");
}

code for arduino (note: seems that stackexcange identifies this function as spam so i posted them here ):
#include<SoftwareSerial.h>
#include <TVout.h>
#include <fontALL.h>
SoftwareSerial SUART(2, 3); //SRX=Dpin-2; STX-DPin-3
TVout TV;
//#define debug 1
#define numberOfEnemies 15
#define maxEnemyMovement 20
#define playerDefaultY 75

int points = 0;
unsigned long int millisLastEnemyMovement = 0;
int enemyMovementDelay = 850;
int enemyMovement = 0;
bool directionIsRight = true;

struct b {
  int x;
  int y;
  bool shootable;
} bullet;

struct p {
  int x;
} player;

typedef struct {
  int x;
  int y;
  bool alive;
} Enemy;

Enemy enemyList[numberOfEnemies];

void renderEnemy(int x, int y){ //draws sprite of enemy

}

void renderPlayer(int x, int y){  //draws player sprite

}

void shoot(){
  if(bullet.shootable){
    bullet.shootable = false;
    bullet.x = player.x;
    bullet.y = 100;
  }
}

void left(){
  if(player.x > 0){
    player.x--;
  }
}

void right(){
  if(player.x < 105){
    player.x++;
  }
}

void spriteUpdate(){
  if(!bullet.shootable){
    bullet.x--;
    if(bullet.x < 0){
      bullet.x = 0;
      bullet.y = 0;
      bullet.shootable = true;
    }
    for(int i = 0; i < numberOfEnemies; i++){
      if(bullet.x > enemyList[i].x && bullet.x < enemyList[i].x + 11 && bullet.y > enemyList[i].y && bullet.y < enemyList[i].y + 8){
        bullet.shootable = true;
        enemyList[i].alive = false;
        points++;
      }
    }
  }
  if(millis() - millisLastEnemyMovement > enemyMovementDelay){
    millisLastEnemyMovement = millis();
    if(directionIsRight){
      enemyMovement++;
      for(int i = 0; i < numberOfEnemies; i++){
        enemyList[i].x++;
      }
    }else{
      enemyMovement--;
      for(int i = 0; i < numberOfEnemies; i++){
        enemyList[i].x--;
      }
    }
    if(enemyMovement == 0 || enemyMovement == maxEnemyMovement){
      directionIsRight = !directionIsRight;
    }
  }
}

void render(){
  TV.delay_frame(1);
  TV.clear_screen();
  renderPlayer(player.x, playerDefaultY);
  for(int i = 0; i < numberOfEnemies; i++){
    if(enemyList[i].alive){
      renderEnemy(enemyList[i].x, enemyList[i].y);
    }
  }

}
void setup()
{
  char x;
  Serial.begin(115200); //enable Serial Monitor
  SUART.begin(115200); //enable SUART Port
  bullet.x = 0;
  bullet.y = 0;
  bullet.shootable = true;
  for(int i = 0; i < 5; i++){
    enemyList[i] = {4+i*20, 3, true};
    enemyList[i+5] = {4+i*20, 18, true};
    enemyList[i+10] = {4+i*20, 33, true};
  }
  player.x = 50;
  TV.begin(PAL, 120, 96);
  while(true){

  }
}

void loop(){
    if (SUART.available() != 0){
      x = SUART.read();  //read char
      switch(x){
        case 'a':
          left();
          break;
        case 'b':
          right();
          break;
        case 'c':
          //left and right same time?
          break;
        case 'd':
          shoot();
          break;
        case 'e':
          left();
          shoot();
          break;
        case 'f':
          right();
          shoot();
          break;
        case 'g':
          //left and right at same time?
          shoot();
          break;
      }
    }
    spriteUpdate();
    render();
}

This is the schematic:

what is your question?

Software Serial is a pretty crummy library.  It disables interrupts while receiving for long periods of time.  That causes any other library that uses interrupts to have issues with timing.  There are a plethora of other soft serial libraries out there.  Try one of those instead.  AltSoftSerial comes to mind.

Both AltSoftwareSerial and TVout require pin 9 so i can't use them at the same time.

OK, like I said there are a large number of them.  They aren't hidden.  A quick google search should turn up several alternatives for software serial, each with it's own caveats and abilities.

It works good but every time the nodemcu sends something, the TV signal gets distorted.

That's correct. SoftwareSerial is terrible. Don't use it. When it's sending or receiving data nothing else at all can happen.
If you have to resort to SoftwareSerial then you are using the wrong hardware for your project. Maybe an ESP32 would be a better choice.

Basically you have two software hacks. Both require precise timing and neither is happy if that timing is messed with. To that end both will disable interrupts to stop things interfering. You can use one or the other, but not both.


text:
fingerprint sensor r307
am using fingerprint sensor r307 on my project and when l use connection from datasheet(My circuit connection is:
(Green) TX => Pin 0 [PWM]
(White) RX => Pin 1 [PWM]
//It doesn't respond when connected to 5V, it only heats up
(Red) VCC => 3.3v
(Black) GND => GND) the finger print is not light up and it starts to over heat but when l connect from left as ground , tx,rx and last vcc respectively the sensor lights up but it does not shown in the serial monitor it says did not find fingerprint sensor:
my code from Adafruit
#include <Adafruit_Fingerprint.h>

// On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
// uncomment this line:
 #define mySerial Serial1

// For UNO and others without hardware serial, we must use software serial...
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino  (WHITE wire)
// comment these two lines if using hardware serial
//#include <SoftwareSerial.h>
//SoftwareSerial mySerial(10, 11);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

uint8_t id;

void setup()
{
  Serial.begin(9600);
  while (!Serial);  // For Yun/Leo/Micro/Zero/...
  delay(100);
  Serial.println("\n\nAdafruit Fingerprint sensor enrollment");

  // set the data rate for the sensor serial port
  finger.begin(57600);

  if (finger.verifyPassword()) {
    Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1) { delay(1); }
  }
}

uint8_t readnumber(void) {
  uint8_t num = 0;

  while (num == 0) {
    while (! Serial.available());
    num = Serial.parseInt();
  }
  return num;
}

void loop()                     // run over and over again
{
  Serial.println("Ready to enroll a fingerprint!");
  Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");
  id = readnumber();
  if (id == 0) {// ID #0 not allowed, try again!
     return;
  }
  Serial.print("Enrolling ID #");
  Serial.println(id);

  while (!  getFingerprintEnroll() );
}

uint8_t getFingerprintEnroll() {

  int p = -1;
  Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(1);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  Serial.println("Remove finger");
  delay(2000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER) {
    p = finger.getImage();
  }
  Serial.print("ID "); Serial.println(id);
  p = -1;
  Serial.println("Place same finger again");
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.print(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(2);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  Serial.print("Creating model for #");  Serial.println(id);

  p = finger.createModel();
  if (p == FINGERPRINT_OK) {
    Serial.println("Prints matched!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_ENROLLMISMATCH) {
    Serial.println("Fingerprints did not match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  Serial.print("ID "); Serial.println(id);
  p = finger.storeModel(id);
  if (p == FINGERPRINT_OK) {
    Serial.println("Stored!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    Serial.println("Could not store in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    Serial.println("Error writing to flash");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

the I/O connector has pin numbers, not colors ... referring to wires by color has no meaning because you have not defined which pin connects to which color

What is a "fingerprint sensor r307"? What datasheet do you refer to? Your code is a mess - format it properly. We aren't psychic. No links, no answer.


text:
Sound sensor's output stucks to high values when I include a delay in the loop function
I use Waveshare's Sound Sensor module.
I use this simple code to test the module:

As you can see, the problem is that when I have a delay in the program, once the analogRead is bigger than 10 (by slightly knocking the mic with my finger), "sound" is printed, but sound sensor's output doesn't decrease back to normal values and "sound" keeps repeating.
If I don't use delay, everything works fine, but I need that delay.
*NOTE: on this test I use a STM32 nucleo development board, but I don't think that contributes to the problem.

What is a "Waveshare's Sound Sensor module"? We aren't psychic. No links, no answer.

please print the actual values ... do not use a graph

I uploaded monitor's prints

Is this your mystery device? If so, how are you wiring it? Are you trying to read the AOUT or DOUT pin?

Majenko no need for superpowers. You only need 5 seconds to google it and find all the infos in the first link that appears. If spending 5 seconds is too much time feel free to dismiss the question and save your time

Yes. Wired as instructed by the User manual. I'm reading AOUT.

@BrainTrance YOU know that the first link is the right link because YOU know what your device is. WE don't. If you are not explicit with your information then we are floundering in the dark and unable to give a good answer. Be precise in your information.

The AOUT pin of that device is no more than an amplified audio signal. It is AC coupled, and that means that it is a small signal varying around 0v. It is not suitable for feeding directly into an ADC.
The AC coupling capacitor will be being charged up by the DC offset it is there to remove, and the lack of any drain on that capacitor while the ADC is not sampling means it never discharges as it should. By sampling faster you increase the load and thus it can discharge somewhat.
To properly read that AOUT pin you need to add your own DC offset to half the VCC voltage of your Arduino board, which can be done by adding two 10k resistors. One from VCC (5v) to the analogue input, and the other from the analogue input to ground.
The signal you read will then be "idle" at around 2.5v (512 ADC reading) and vary around that as sound is picked up.
Note that you can't just sample once per second and hope: there is no provision for "did sound happen in the past second". Instead you really need to be sampling all the time.
If all you care about is if some sound above a threshold has happened then you would be better using DOUT connected to a digital input or even an interrupt pin, and using the threshold setting trim pot on the board.


text:
facing issue with while loop
I'm trying to develop one code in which I'm facing issue with while loop. Once I enter any newString it enter in while loop it count till 10 times, when (n>10)  then it is coming out from the while loop.
Facing issues in this part
while (n < 10)
  {
    while (!ret) {
      if ((time + 15) < millis()) {
        ret = dmd.stepMarquee(-1,0);
        time = millis();
      }
    }
     ret = false;
     n++;
    }

I just want when I enter any newString when loop is running it break while loop and start display newString.
Please help me out with this. Thanks for your help, greatly appreciated.
Here is my full code:
#include <SPI.h>
#include <DMD.h>
#include <TimerOne.h>
#include "SystemFont5x7.h"
#include "Arial_black_16.h"

//Fire up the DMD library as dmd
#define DISPLAYS_ACROSS 2
#define DISPLAYS_DOWN 1
DMD dmd(DISPLAYS_ACROSS, DISPLAYS_DOWN);

String inputString = "";
boolean stringComplete = false;
String commandString = "";

void ScanDMD()
{
  dmd.scanDisplayBySPI();
}

void setup()
{
   Serial.begin(9600);
   Serial.println("Arduino Start");
   Timer1.initialize( 5000 );
   Timer1.attachInterrupt( ScanDMD );
   dmd.clearScreen( true );
}

void loop() {

if(stringComplete)
{
  stringComplete = false;
  getCommand();

  if(commandString.equals("STAR"))
  {
   dmd.clearScreen( true );
  }

  else if(commandString.equals("PRSC"))
  {
    String text = getTextToPrint();
    printText(text);
  }
  inputString = "";
}

}

void getCommand()
{
  if(inputString.length()>0)
  {
     commandString = inputString.substring(1,5);
  }
}

String getTextToPrint()
{
  String value = inputString.substring(5,(inputString.length())-2);
  return value;
}

void printText(String text)
{
  char newString[256];
  int sLength = text.length();
  text.toCharArray( newString, sLength+1 );
  dmd.selectFont(System5x7);
  dmd.drawMarquee( newString , sLength , (32*DISPLAYS_ACROSS )-1 ,1);
  unsigned long time;
  boolean ret = false;
  time = millis();
  int n;
  n= 0;
  while (n < 10)
  {
    while (!ret) {
      if ((time + 15) < millis()) {
        ret = dmd.stepMarquee(-1,0);
        time = millis();
      }
    }
     ret = false;
     n++;
    }
}

void serialEvent() {
  while (Serial.available()) {            // get the new byte:
    char inChar = (char)Serial.read();    // add it to the inputString:
    inputString += inChar;                // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

what is the purpose of the while loop? ... how do you want the program to behave?

I'm sending the data to Arduino UNO via serial(Keyboard) and then UNO is to turn expected to scroll the received text on P10 DMD display.  Whenever it receive new serial data it start displaying that data into display. I want this.

scroll the received text ... you have not clearly defined the desired operation... serial characters arrive one at a time ... keep that in mind when you decide how you want the character scrolling to work

Forget using serialEvent(). It is one of the more stupid things that Arduino implemented.  It is nothing more than a function that gets called (wrapped in a check to Serial.available()) once per iteration of the main loop() function.
It is not really an "event" function at all.
To have anything happen inside your while loop you have to manually implement that thing within your while loop.  Nothing outside of the while loop (with the exception of interrupts) can affect the operation of the while loop.

So is there any possibilities to change in code?? Please help me out

There are plenty of possibilities. Personally I would ditch the while loop completely.

Now my code is working like I'm sending the data to Arduino UNO via serial(Keyboard) when it receive any serial data it scroll till 10 time and when (n>10) then will loop stop. In between this whenever I'm send any new data it is not accepting.
what exactly I want whenever I send new data to Arduino UNO via serial(Keyboard) and then UNO is to turn expected to scroll the received text on P10 DMD display at the same time.  Whenever it receive new serial data it start displaying that data into display.


text:
Receiving two values over serial port using servos
So I have a java program that picks up the mouses x and y coords on the display and I would like to send those to my arduino and then move my two servos to those locations (I have two servos ontop of each other, one for x and one for y).
The java (processing) code i have is below
void draw(){  //same as loop in arduino
  background(52, 152, 219); // background color of window (r, g, b) or (0 to 255)
  //lets give title to our window
  fill(0, 255, 0);               //text color (r, g, b)
  textFont(font);
  text("Ripple Effect Maker", 80, 30);  // ("text", x coordinate, y coordinat)
  ellipse(mouseX, mouseY, 33, 33);
  int x = mouseX;
  int y = mouseY;
  port.write(x+":"+y);
  println(x+":"+y);
  //println("y="+y);
  delay(100);
}

I don't have much arduino code because I can't seem to find a way to split the data into two seperate variables and then move the servos to their corresponding variables.
Thanks for the help!

https://majenko.co.uk/blog/reading-serial-arduino

Your problem is that you aren't providing anything to split the data on. You just send the X and y coordinates with a : between X and y. There's nothing between the y and the next X.
By changing the line
port.write(x+":"+y);

To
port.write(x+":"+y+"\n");

You then get the linefeed character to split your data on.


text:
What image formats are accepted for displays?
Sorry if there is information missing, im new to the topic.
I have an ESP32 connected to a Waveshare 7,5" RWB display, and i can display images by converting them to .xbm and including the hex code in the sketch.
So far, so good.
But heres my question: What exactly are the requirements? Because when looking at the .xbm image code, i see that its a pattern like this:
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00
But when i used a python script
import binascii
filename = 'test.png'
with open(filename, 'rb') as f:
    content = f.read()
print(binascii.hexlify(content))

to convert an image to hex code, i got this:
b'89504e470d0a1a0a0000000d4948445200000280000001800802000000b2...'(continues for thousands of characters, didnt want to paste all of that here
However, when trying to run the sketch that successfully displayed the first hex code with the second image code, i got this error(cut out the big string clutter again):
...0000000049454e44ae426082};

^

C:\Users\Administrator\Desktop\SPI_test_example\SPI_test_example.ino: In function 'void loop()':

SPI_test_example:167:21: error: 'showBitmapExample' was not declared in this scope

   showBitmapExample();

                     ^

SPI_test_example:171:51: error: 'showFont' was not declared in this scope

   showFont("FreeMonoBold9pt7b", &FreeMonoBold9pt7b);

                                                   ^

exit status 1
'showBitmapExample' was not declared in this scope

So, i would like to know - does the image code have to have exactly the format i mentioned first? This is very important for me because i want to automate the process from inputting any image to using the resulting code to feed the display.
Thanks in advance!
EDIT: As far as my understanding goes, both formats are the same data, just that the first one is displaying a white pixel as 0xFF,0xFF,0xFF and the second one as FFFFFF.

This is not a question of image format but of what format c accepts data in.
What you have is a python representation of binary data in hexadecimal encoding. That can only be used with python.
C represents hexadecimal values by prefixing them with 0x.
You will have to change your python code to output each byte individually and prefix it with 0x and separate each one with a comma. That can then be wrapped in an array structure.

This makes so much sense, i didnt expect it to be bound to programming language! Converting should be easily doable - that leaves a few questions open for me:
First, why does gimp, or rather the .xbm file, use C++ syntax (0x00)? Second, isnt one colored pixel displayed with 6 digits(000000 Black, FFFFFF White etc.) - how can i possible display the same range of colors with just 0x00?

It's all just numbers.  0xFFFFFF is the same as 0xFF, 0xFF, 0xFF.  Three bytes is all 0xFFFFFF is. That is, 0xFF red, 0xFF green and 0xFF blue.  An XBM file is a piece of C source code. Other formats aren't. If yuo save a file as XBM you get C source code.


text:
Measuring current directly with Arduino
Is it safe to measure current like this as long as measured voltage drop don't exceed 5V? I'm asking this because in almost all current sense circuits they used an opamp in their design.
Do I need a resistor between shunt resistor and ADC? Is there any noticeable current flowing to Arduino ADC that can damage it?

simulate this circuit – Schematic created using CircuitLab

Where do you connect the Arduino ground?

@EdgarBonet common ground.

You need to measure at the other side of the sense-resistor. Otherwise you'd always measure 0 Volts. The reason a lot of designs use an opamp, is so they can keep the sense-resistor as low as possible. Higher value sense-resistors will create higher voltage drops, resulting in a lower voltage supplied to the load.

@Gerben Thanks, corrected the schematic.

You should show (and connect) power source -  to Arduino GND. Normally, scematics are clearer when GND is at the bottom.

Maybe I wasn't clear enough... by “Where do you connect the Arduino ground?” I meant “Please, show the ground connection in the schematic.”

@EdgarBonet updated the schematic.

Let's imagine that you expect to have 1A of current going through your circuit.
Resistor of 0.1 Ohm will give you a voltage drop of 0.1V.
This causes two problems.
Firstly Arduino has a cheap ADC builtin. It's supposed to be easy to use, but not really precise. It has nonlinearities towards lower and higher range. You will get more precise reading when measuring voltages around 2.5V.
Secondly The precision of your measurement is cut by factor of 50. Arduino contains ADC that has resolution of 10 bits. This means that there are only 20 steps between 0V and 0.1V That's not really precise.
Solution? Use an opamp as "differential amplifier". If you multiply the voltage difference by 25 you will get 2.5V on the amplifier output when the resistor has 0.1V of drop on it. This value is much more precise when reading it by analogRead of the Arduino, and even a tiny change in voltage on the resistor will give you 25 times larger change on the amplifier output. This way it's much more precise and accurate.

I did dig into opamp "realm" and honestly a good opamp for sensing current is expensive, I was thinking to use Arduino and if i needed more accuracy i could use a 12bit ADC or increase the shunt resistor value a bit... but the question is; is it safe to connect shunt resistor directly to Arduino ADC or not.

This answer is true but not complete. You can use the internal 1.1V reference voltage for your ADC. So 0.1V would correspond to around 90 steps between it an 0V. So you can get usable but not great results with the built in approach. The diff-Amp is definitively the way to go.

@newbie I recently successfully used LM358 to boost the voltage 20 times for my battery charger feedback. They literally cost 6 cents each with free delivery from China. Just keep output in the "middle" of the voltage (2.5V)

@FilipFranik it is possible and I even purchased some LMC6482 which is way more superior to LM358 but it can't go all the way down to ground rail 0V, minimum in my case was 9mv (maximum 20mV!) which means it can't measure small voltage drops (5mV for example) on a 0.1 ohm resistor. beside you need four 1% resistors which should match two by two... it gets complicated... I want to measure current simply with Arduino.

@newbie The real power of Arduino is that you can use cheap hardware, but compensate for imprecise resistor values and hardware nonlinearities inside the software. If you want to go for precision just build the circuit, connect (expensive) ampmeter to it, and measure what ADC shows for each amperage. Then use linear interpolation algorithm to get precise values between measurements. You will get  more precision then you need this way.

There's a bad current flowing into your Arduino, if ADC voltage exceeds Vcc (5V). This undesired current can be limited by a resistor. But if there's such a high voltage across a shunt resistor, something else is wrong. You rather suffer from a too small voltage for useful measurement.
My first doubt is rather, whether it's safe for the shunt resistor.


text:
Can I power Raspberry Pi 3 via 3V3 and GND pin?
Can I power my Pi 3 using the 3v3 pin (pin 1) and GND pin (pin 6)? Also, if I want to protect the board from power surges can I just put a fuse between my power supply and the 3v3 pin?
Thanks in advance,

This is not an Arduino question BUT definitely do NOT try this!
The Foundation Hats Master has recommendations.
"It is possible to power the Pi by supplying 5V through the GPIO (sic) header pins 2,4 and GND. The acceptable input voltage range is 5V ±5%. ⋯ Implement a duplicate power safety diode ⋯ supply 5V at a minimum of 1.3A ⋯ Under no circumstances should a power source be connected to the 3.3V pins."

Thank you, I'm sorry I posted it on the wrong stackexchange forum. I didn't know there even existed a raspberry forum.


text:
Sketch works on Arduino nano but not Pro Mini
I have a simple test sketch to run for my led aquarium:
#include <IRremote.h>
#include <IRremoteInt.h>

IRsend irsend;
void setup() {

}

void loop() {

irsend.sendNEC(0xF7C03F, 32);
delay (2000);
}

I am using a 850nm Infrared LED and a 330Ohm resistor.
The connection:
Digital 3 to Resistor -> GND

On the Arduino nano it runs perfectly: the LED of my aquarium turns on and off like the sketch tells it to.
But on the Pro Mini nothing happens.
To be honest, it is my first time using the pro mini.
Maybe I forgot something???
I am using a FTDI232 (set to 5V) to flash it.
Hope someone can help me.
Kind regard
Daniel :)

Can you confirm, that the sketch really runs? You can use the Blink Sketch with a normal LED, so that you can see, if the sketch really runs, that you programmed onto the pro mini

Can you verify that the led lights up? I used the front-facing camera of my iPhone to see if my IR-led was blinking. Secondly; which pro-mini variant are you using? The 3.3V or the 5V one? Make sure you selected the correct one in the "boards" menu.

Yes, the blink sketch seems to run. The LED next to pin 9 turns on/off for 2 secs.

I think it is the 5V variant. (I measured VCC and GND and it gave me 5V).

how is that resistor connected on breadboard? in the same column?

Yes, the resistor is in the same colum. On the breadboard it is in "h" and "i" the led is in the same column in "j".

I checked with my phone, the led lights up. It is just a millisecond or so, but it lights up.

I recorded the signal, that was sent from the arduinos: pro mini: FA34C27F        nano: different signal every time it sends, nevertheless the led of my aquarium reacts to the nano signal.

the resistor in the same column does nothing. it is like it wouldn't be there


text:
Interface gps and ultrasonic sensor simultaneously
I am able to interface  gps and the ultrasonic sensor and obtain data successfully for individual interfacing with the Arduino UNO. When I combined the code for these two, I only get the data values from gps but no measurement values are obtained for the ultrasonic sensor.In the variable data, I have stored the gps data packet. I have read the solution for the same problem but none of them worked. I have attached the code below:
    #include <SoftwareSerial.h>
    #include "TinyGPS++.h"

    SoftwareSerial serial_connection(8, 9);

    TinyGPSPlus gps;
    TinyGPSCustom Trackingangle(gps, "GPRMC", 8);
    TinyGPSCustom Dir_NS (gps, "GPRMC", 4);
    TinyGPSCustom Dir_EW (gps, "GPRMC", 6);

    String data,tr,ew,ns,d1;
  int a=0;
    const int trigPin = 6;
    const int echoPin = 7;
    long duration;
    int distance;
    int buttonPin = 12;
    String s="",str_dist="",str_button="";
    int buttonPushCounter = 0;
    int buttonState = 0;
    int lastButtonState = 0;

    void setup()
    {
      pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(buttonPin, INPUT);
      Serial.begin(9600);
            serial_connection.begin(9600);
    }

    void loop()
    {
      data="";tr="";d1="";
    serial_connection.listen();
     dat_gps();
       if(data!="")
    {
    Serial.println("GPS DATA= "+data);
    ultra();
      }
   }
        void ultra()
    {
distance=0;duration=0;
         digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    //if(duration!=0)
    {
      distance= duration*0.034/2;
        Serial.print("Distance= ");
    Serial.println(String(distance));
    }
    }

    void dat_gps()
    {
     {
      while(serial_connection.available())
      {
        gps.encode(serial_connection.read());
      }

    if (Trackingangle.isUpdated())
    {
        tr=String(Trackingangle.value()); //    Serial.println(tr);
    }
    if (Dir_EW.isUpdated())
    {

     ew=String(Dir_EW.value());
    }
    if (Dir_NS.isUpdated())
    {

      ns=String(Dir_NS.value());
    }
    if(tr!="")
    { if(gps.location.isUpdated())
     {       delay(2000);
        data=String(gps.satellites.value());
       data+=",";
       if(data!="0,")
       {
        data+=String(gps.location.lat(), 6);
        data+=",";
        data+=String(gps.location.lng(), 6);
        data+=",";
           data+=String(gps.speed.mph());
              String a=String(gps.altitude.feet());
         if(a!="")
       {   data+=",";
       data+=a;
         data+=",";
          data+=String(gps.hdop.value());
         data+=",";
         data+=tr;
         data+=",";
         data+=ns;
         data+=",";
         data+=ew;
         data+="";
            }
       }}
      }
     }
    }

You need to explain your hardware setup and your code.
What type of communication do your different devices use? I2C? SPI?
What pins do they use for their interfaces?
What model of GPS and ultrasonic sensor are you using? Where can your readers find documentation and specs on those devices? What do the different commands to the devices do?
Also, you need to fix the formatting on your code. The indentation is a mess, and makes it very hard to follow the flow.

You can't.  An Arduino Uno is a a single processor.  It can do only one thing at once.  Please can you have a go at formatting your code, because its not very reader friendly.

Put Serial.println("GPS DATA= "+data); right after the call to dat_gps() and tell us what it prints.

I am using HC SR04 as ultrasonic sensor and Quectel L80 as gps. I want serial comunication on pins 8&9.

@SimSon, some values are shown as 0 as gps takes time to set. Once  its set, all the values are printed

Can anyone help?


text:
Serial communication problem with sim7600 with Arduino Mega
I am just sending the AT command to test if the serial communication works, the response I am getting is a flipped "?" or a square or rectangle symbol.
I have tested the communication using software provided by Waveshare connected through on board USB to UART.
https://www.waveshare.com/wiki/SIM7600E-H_4G_HAT
int PowerKey = 2;
char answer;

void setup()
{
 Serial3.begin(96u00);
 Serial.begin(9600);
 pinMode(PowerKey, OUTPUT);
 Serial.println("initializing");
 digitalWrite(PowerKey, HIGH);
 delay(1000);
 digitalWrite(PowerKey, LOW);
}

void loop()
{
  answer = send_at_cmd("AT\r\n");
  Serial.println(answer);
}

uint8_t send_at_cmd(const char* ATcommand)
{
  char response;
  // send test command AT
  Serial3.print(ATcommand);
  Serial.println(ATcommand);
  delay(1000);
  //Check for response from the sim7600E-H
  while(Serial3.available() != 0)
  {
    response = Serial3.read();
  }
  return response;
}

Your code sets serial 3 to 9600, but the second image sets the serial port to 115K.  I think that may be a problem, because at least one is wrong.

I have set it to 115200 but I still have the same result

You have change baud rate by at+iprex=9600 before upload your code, because sim7600 set 115200 by default then save your setting by at&w.
hope this help someone.


text:
How to convert char[12] to byte[6]
I am trying to convert a char[12] array that contains a Mac Address into a byte[6] in order to use within the Ethernet.begin method. I have tried various methods from online, but had little success to date. The char array currently contains "A4BDC334688C" and i would like a byte array containing { A4, BD, C3, etc }.
The following is extremely close to working, with the output of the following
"File Opened.
A4BDC334688C
A4
9D
C3
34
68
6C" With BD incorecctly converting to 9D, and 8C becomming 68.
#include <SPI.h>
#include <SD.h>
#include <ArduinoJson.h>

byte ByteMacAddress[6]; // RESERVED MAC ADDRESS
StaticJsonDocument<200> doc;

int ShotCount = 0;
byte buf[40];

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

  //Initialise SD Card for Config
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
  }

  // open the file for reading:
  File ConfigFile = SD.open("Config.txt");
  if (ConfigFile) {
    Serial.println("File Opened.");
  } else {
    Serial.println("error opening Config.txt");
  }

  //Deserialize Json Config in File
  delay(5);
  DeserializationError error = deserializeJson(doc, ConfigFile);
  ConfigFile.close();
  // Test if parsing succeeds.
  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.c_str());
    return;
  }

  char* SDMacAddress = doc["MacAddress"];
  Serial.println(SDMacAddress);

  char arr[12];
  strcpy(arr, SDMacAddress);

  auto getNum = [](char c){ return c > '9' ? c - 'a' + 10 : c - '0'; };
  byte *ptr = ByteMacAddress;

  for(char *idx = arr ; *idx ; ++idx, ++ptr ){
    *ptr = (getNum( *idx++ ) << 4) + getNum( *idx );
  }

  //Check converted byte values.
  for( byte b : ByteMacAddress )
    Serial.println( b, HEX );
}

void loop(){
  //Maintain DHCP Lease
  //Ethernet.maintain();

  //GetShotCount();
  delay(500);
}

Have you seen the function strtol(buf, &targetvariable, BASE) like it is used in the answer to this question? You could use it do convert each byte (2 characters) individually or even - via using a union - convert the whole string at once.

In getnum you don't consider upper case letters. Are the letters all lower case or all upper case?

usually the binary representation of MAC address is in reverse order then the hex string

@chrisl Thank you also for your answer, I really appreciate everyone who took time to help me.

Please see the comments in the code:
// SDMacAdress is zero terminated
// (it should be because you use strcp not strncp)
// char arr[12]; you need one extra byte for the zero
char arr[13];
strcpy(arr, SDMacAddress);

auto getNum = [](char c)
{
  // you forgot upercase HEX letters (A-F)
  // don't use sophisticated code
  // the best programmers produce understandable code IMHO at least ;-)
  // perhaps you copied it from the internet
  // return c > '9' ? c - 'a' + 10 : c - '0';

  if ( c >= '0' && c <= '9' ) return c - '0';
  if ( c >= 'a' && c <= 'f' ) return 10 + c - 'a';
  if ( c >= 'A' && c <= 'F' ) return 10 + c - 'A';

  return 0;
};

byte *ptr = ByteMacAddress;

for(char *idx = arr ; *idx ; ++idx, ++ptr )
{
  *ptr = (getNum( *idx++ ) << 4) + getNum( *idx );
}

Im kicking myself for that, the uppercase was the issue. And you are correct, that is copied from the internet but I had also made the same silly mistake in my attempt. Thank you very much for your time and help.

I should mention, that @chrisl had had this idea before me. I just gave you an example of how to do it. Please upvote his/her (?) comment above. I did it already. ;-)

I wish I had the rep to upvote you all, alas i am a newbie here.

It is not clear why you are trying to implement it from scratch. If your input is always properly formatted you can perform the conversion in one call to sscanf
char arr[] = "A4BDC334688C";
byte ByteMacAddress[6];

sscanf(arr, "%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx",
  &ByteMacAddress[0],
  &ByteMacAddress[1],
  &ByteMacAddress[2],
  &ByteMacAddress[3],
  &ByteMacAddress[4],
  &ByteMacAddress[5]);

Of course, you can also implement it [more elegantly] through a cycle, i.e. sscanf it one byte at a time.


text:
Send information from computer to Arduino via USB (basic clock)
I've created a small project using an Uno. I usually mess around with ESP8266 chips, because they have WiFi and are relatively easy to work with. However, this time I've decided to go right back to the Uno.
I've made a clock using a bunch of MAX7219 matrix displays (32x8 total). I want to be able to sync the time from the computer to the Arduino, no matter which PC is connected.
My thought was to create a small program, that detects the connected Uno, then sends the data over serial. However, there's probably a more clever way to do that, which requires very little programming on the PC side.
Any clues? The Arduino is connected via USB. Would love this to work on both Windows and MacOS.

no, there is no other way

you might find a terminal app that can echo the current time, but it's a one-line program anyway...

in windows, you could write a batch file


text:
How to control multiple leds independently with arduino but they share a 12v external power source
I have a project with many components.  I'd like to use 12v adapter from wall.
I have a simplified experiment to apply to the actual project.  I can't find any info on the internet after days of searching.
I want to control each of 6 leds independently with an arduino. They all have different forward voltages.  But I would like them to be powered by the same 12v external power supply.  I suspect I would use transistors, Could someone point me in the right direction to wire these up?
I can figure out the code myself.

yes. use an N-channel MOSFET and ignore it when calculating resistors. google" mosfet as a swtich". The code you need is contained in the blink example.

Thanks.  That's simple!

The basic schematic for one LED is:

simulate this circuit – Schematic created using CircuitLab
Make sure that:

R1 is the right resistance for the supply voltage, forward voltage, and desired current
M1 has a threshold low enough that the Arduino turns it fully on.

Just duplicate the circuit for each LED you want to control. The code is no different to having an LED directly attached to the Arduino.

Thanks! Very easy.  Obviously I'm a newbie.  So each led will be in parallel, right?

Not each LED, no. Each complete circuit.

Yeah, I meant circuit.  Thank you!


text:
ESP32 WebSocketsServer - stream pots data to web browser
I would like to stream pots data to a web browser using websockets.  I'm using WebSocketsServer on a Huzzah but sendTXT isn't working, but does for Connected WStype.  Is there a way to do this?   Partial code:
  // New client has connected
case WStype_CONNECTED:
{
  IPAddress ip = webSocket.remoteIP(client_num);
  Serial.printf("[%u] Connection from client: ", client_num);
  Serial.println(ip.toString());
  webSocket.sendTXT(client_num, "Server says Client is connected \r\n");
}

void loop() {
int potValue =analogRead(A4);
//Serial.println(potValue);
webSocket.loop();
}

javascript:
/*----  WEBSOCKET SERVER CONNECTION    ------- --*/
connect();

function connect()
{

var socket = new WebSocket("ws://10.0.0.1:1337");

try
{
    message('
Socket Status: '+socket.readyState);

    socket.onopen = function()
    {
    message('
Socket open Status: '+socket.readyState+' (open)');
    }
    socket.onmessage = function(msg)
    {
     message('
Received: '+msg.data);
    }
    socket.onclose = function()
    {
    message('
Socket close Status: '+socket.readyState+' (Closed)');
    }
}
catch(exception)
{
    message('
Error'+exception);
}

/* ----SEND TO SERVER -----*/

$('.fan').click(function()
{
    var idClicked = $(this).attr('id');
    console.log(idClicked);

    sendTo(idClicked);

});

function sendTo(idClicked)
{
    socket.send(idClicked);
    message('
Sent: '+idClicked)
}

function message(msg)
{
    $('#pots').html(msg+'
');
}

please show the non-working code

how do you send the text?

do you have a java script web socket client in a page running in browser?


text:
AD7476 adc and SPI
I'm trying to understand if I can use the AD7476 with Arduino and SPI:
datasheet
My rough idea is that I should put CS low, then read two bytes using SPI.transfer() twice, and then bring CS high again. Is that correct?
But looks like the AD7476 doesn't have any buffer, so I guess timing must be really precise in order to not miss any bit?
what if SPI.transfer() occurs too late after CS going low?

My rough idea is that I should put CS low, then read two bytes using SPI.transfer() twice, and then bring CS high again. Is that correct?

Yes, that is correct.

But looks like the AD7476 doesn't have any buffer, so I guess timing must be really precise in order to not miss any bit?

No. The conversion is controlled by the SPI clock.  The ADC is a successive approximation ADC.  That means for each "sample clock" a more accurate approximation of the voltage is created. In this instance that "sample clock" is the same as the "SPI clock".  Each time you send one clock pulse a new, more accurate, approximation is created.

what if SPI.transfer() occurs too late after CS going low?

Within reason, nothing untoward.
The way an SAR ADC works is it uses a DAC which is controlled by a clock to create a voltage. That voltage is halfway between 0V and "the current estimated voltage" (starting at "vref" - 5V in this case).  The voltage is compared with the "sampled" voltage (stored in a tiny capacitor). That forms one bit of the resultant value. At the next clock the DAC voltage is halved (and maybe added to the previous voltage depending on the previous comparison result) and repeated. This is the next bit of the result. It repeats with the voltage getting smaller and smaller and smaller.
Each time you clock one bit through your SPI interface it generates and compares the next voltage generating the next bit of data for you to read.
The knock-on effect of this is that there is both a maximum and a minimum frequency that you can use the SPI interface at.  Too fast and it is unable to generate the comparison voltages and do the comparison in time. Too slow and the internal capacitor loses charge through self-discharge and leakage current.  Thgis is why on page 8 of the datasheet it specifies a minimum and a maximum frequency for the SPI interface (10kHz to 20MHz).

thank you! but how can you tell if the 2 bytes you read are the actual data, or if the read occurred too late and you miss the first bits? Is the SPI library responsible of handling that, by clocking only once you start reading?

You can't "miss" any bits. You generate the bits. There's nothing to miss. If you are too slow (and you'd have to be very slow) then all you will have is reduced accuracy.

I would add, that "too slow" doesn't mean too slow between samples, but during the SPI.transfer(). As long as you don't set the SPI speed too slow, there is nothing to miss


text:
Control DC Motor with Arduino Uno WiFi Rev2 Html Slider Code
I would like to control my dc motor using the Arduino Uno WiFi Rev2 using an html range slider. Now I can control the motors speed and direction using push buttons just fine. My code is posted below of what I've done so far.
client.println("");
client.println("<input type=\"range\" class=\"class-name\" orient=\"vertical\" id=\"range\" min=\"0\" max=\"255\" step=\"0\" onchange=\"motor1(this.value)\" value=\"0\">");

This code below is the current button code. I need the below code to be used by the slider code above:
if (currentLine.endsWith("GET /MONFWD")) {
digitalWrite(MOTOR_A_ONE, HIGH);  // Establishes forward direction of Channel A
digitalWrite(MOTOR_A_TWO, HIGH);  // ENGAGE BRAKE
delay(1000);                      // DELAY BEFORE RELEASING BRAKE
digitalWrite(MOTOR_A_TWO, LOW);   // Disengage the Brake for Channel A
analogWrite(MOTOR_A_ENGAGE, 255); // Spins the motor forward on Channel A at full speed

And what is your question? You didn't ask one. Please describe, what exactly your problem is in writing the needed code.

Here's an example of slider that changes a Servo speed,
In html page code you have to add this:

  <input type="range" min="0" max="1023" value="512" class="slider" id="myRange">

Value:

In arduino you have to define handler like this:
void handle_pwm() {
 String  pwm_val = server.arg("PWMval"); // reading from slider on html pagae

 Serial.print("slider val: ");
 Serial.println(pwm_val);
int pwm_value = map(pwm_val.toInt(), 0, 1023, 0, 180);
Servo.write(pwm_value);

server.send(200,"text/plane","0"); // handling the webpage update

}

And define servo and handler in Setup() section:
void setup(void){
....
Servo.attach(MotorPin,1000,2000);
server.on("/setPWM", handle_pwm);
....
 }

I'm not using the servo.h library...I'm using a motor shield which already works with the push buttons....if I ignore the servo.write and servo .attach arguments the  code should work fine correct?

Also the above code is not compatible with the Arduino Uno WiFi Rev 2. It does not use server.on or server.arg

no difference, you can follow the above example for both motor shield and Uno WIFI board,
just replace servo.write() command with motor.setSpeed() for changing DC motor's speed in motor shield.just need to map slider value (0-1023) to your motor speed range,that is usually (0-255).
And by using libraries like WiFiNINA , you can have server.xyz arguments for Uno Wifi board so.

I am using the WiFiNINA library and there are no equivalents for server.arg and server.on except for client.read and client.println. Also no matter where I put the function handle_pwm it throws errors. The slider works fine as I did change the values there. Its getting the function to line up with the slider that its not working. I currently have 3 push buttons that work. Motor FWD, MotorREV and MotorBrake those work fine. I just need a slider to control the motor speed smoothly

the above example is originally written for Nodemcu board,It enjoys much easier libraries to parse http requests ,like ESP8266 WebServer lib including server.arg command and etc...
for Arduino Uno WiFi Rev 2,it is not seemingly as various as nodemcu,so,you should deal with the http requests with commands like client.read() , currentLine.endsWith() and equivalents like this.


text:
It is possible to revive my Arduino Leonardo (mini beetle) board?
I have this board:

It has the atmega32u4 chip.
I have updated its code several times, and used it without issues for several months. Today, while updating (using Arduino IDE) it started to throw some errors. At the end it said that the checksum didn't match, so I repeated again few more times with the same behavior until it reported "Uploaded" without errors. I used for few minutes and it was working as expected. Then, I had to do another update and the same happened (checksum didn't match). However this time I got to the point in which it was no longer detected by the OS (Ubuntu), and no LED is turning on.
Whenever I connect it to the USB port, I can only see in the logs:
usb 1-9.4: new full-speed USB device number 9 using xhci_hcd
However /dev/ttyACM0 is not longer created.
I'm trying to use avrdude to reset it, but it is reporting:
avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory
which make sense as /dev/ttyACM0 doesn't exists. So, what are my options? Is there anything I can do to make it work again?
UPDATE
I didn't realize that this board has a reset marked as "RES". Following Juraj recommendation I bridged RES and GND. The LED marked as "SDA" turns ON after I release the contact and I can read in the logs:
[1212051.679205] usb 1-9.4: USB disconnect, device number 22
[1212058.532030] usb 1-9.4: new full-speed USB device number 23 using xhci_hcd
[1212058.621972] usb 1-9.4: New USB device found, idVendor=2341, idProduct=0036
[1212058.621982] usb 1-9.4: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[1212058.621988] usb 1-9.4: Product: Arduino Leonardo
[1212058.621994] usb 1-9.4: Manufacturer: Arduino LLC
[1212058.622933] cdc_acm 1-9.4:1.0: ttyACM0: USB ACM device

Which I think its good news. However, it seems ttyACM0 becomes available for few seconds. I was able to upload the Blink example into the chip and I can confirm its working because its blinking. Still the ttyACM0 disappears after few seconds.
Output of avrdude -c avr109 -p atmega32u4 -P /dev/ttyACM0 :
Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.00s
avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: safemode: Fuses OK (E:FB, H:D8, L:FF)
avrdude done.  Thank you.

did you try double reset to activate the bootloader? did you try other USB port? try to clean the USB contacts.

I tried other USB ports and other computers as well. How do I double reset it?

wire a button between reset pin and ground and push it twice. the bootloader will handle the USB for a moment. then try to upload a small working sketch (Blink for example)

ok I will do that. I updated my question and as you can see, it seems to be working

Added blink, its working. Thanks, but ttyACM0 its being removed after few seconds... is that normal?

Its working now, after following the recommendations by chris101 in: https://discuss.littlebits.cc/t/solved-thanks-everyone-did-i-brick-my-arduino/22581/13. The trick is to use littleBits Arduino Module. @Juraj: Thank you. You point me in the right direction.

Probably you have overwritten your Bootloader.
Connect MOSI, MISO, SCK and RESET to an ISP-Programmer and flash the file
Caterina-LilyPadUSB.hex
to it.
There are lots of tutorials on the net how to use a spare arduino as an ISP-Programmer.


text:
Stepper Motor Direction via Flow Amps
I have a problem with stepper motor direction.
I want to change the direction of the stepper motor rotation, when the stepper motor shaft is stuck.
For example, when I hold the shaft of the stepper motor with my hand, the direction should change.
How can I do it?
Someone told me you should calculate the current, but I don't know how to do this?
My material components:

Arduino
stepper motor gearbox 12 V
ULN 2003A

When motors stuck their current draw increases, you can sense that increase in the current (with any current sense method you see fit) and then change the rotation of the motor.

I now this discuss but I dont now how can I do it I have no idea circuit or cod for it can  you help me more ? i need it

in Face if you have seen the air conditioner splite Opereting system stepper motor it rotats the some way for 360 Degree but when shaft stuck the direction change I want do this

If you haven't any knowledge about electronics I'm afraid you will fail in that project. You first had to learn what current is, how current is measured ( over a shunt or by heating a wire or whatever). You possibly must compute a mean value. You had to learn how to use the right ground potential and so on. And there are issues with the current that is drawn by the stepper before each step to overcome the inertia of the rotor.  But if you're only supossed to change the direction of the rotation at a define location you could use a switch at that location. That's much easier.

I now about electrinics .but now a lot .but you Idea is very nice about swiching at that location but I have no any place for it I wnat works like air conditoner

I do not know anything about the design of your device. But there different possibilities to build a switch by yourself that, might fit in your design. For instance you sense a tiny LED, or a hall sensor and a magnet.

When motors stuck their current draw increases, you can sense that increase in the current and then change the rotation of the motor. The simplest way to measure current is with using a shunt resistor, for sensing high currents, current sensors based on hall effect sensors is usually used. ACS712 is one example.
How to sense current using a shunt?
Basically we're measuring the voltage drop over a resistor (RS), but the voltage drop is too small for Arduino to measure so we need an opamp to "amplify" the input:

simulate this circuit – Schematic created using CircuitLab
The schematic above is the simplest way to measure the voltage drop at "LOW SIDE", there is differential mode and "HIGH SIDE" measurement methods.
The gain of opamp can be set with resistors and this formula:
VOUT = (1 + R2/R1) * V1
The output of opamp then can be calculated to get current using ohm's law:
I = V / R
A simple code to calculate current:
int rawAnalog;
float voltageDrop;
int resistor = 0.1;
float current;

void setup() {
  pinMode(A0, OUTPUT);
}

void loop() {
  rawAnalog = analogRead(A0); // Read A0 input
  voltageDrop = (rawAnalog * 5) / 1024; // Convert the raw value to voltage
  current = voltageDrop / resistor; // calculate the current
}

Bonus: INA219 is an easy to use high-side I2C module which can measure both current and voltage.

I good idea.can give a circuit for hall effect sensor ?the hall effect sensor must connect to uln 2003 or arduino pin for send commend

This would be a good solution if he uses a "normal" DC-Motor.  A Stepper has at least two groups of coils, each of them has its own plus and minus connection. And the current is not constant while stepping. It even gets more complicated if the stepper works with micro steps.

@PeterPaulKiefer he can measure the overall current at the power source, no need to measure group of coils...

Yes that's correct. You could measure the current the controller needs to supply the motor. But depending on the load there are high peaks. Controller IC can limit that current to protect themselves. If @Rayan_skofw had no experience which such things he/she get's easily frustrated. So I would suggest to him to use switches to check if the rotation is a a defined point and then invert the direction. Not the measuring is the problem, IMHO you can not easily distinguish between the normal stepper starts and the end condition if you only check the current.

@Rayan_skofw for ASC712 you just connect the module in series and there's a Library for it. (open the link there's a tutorial how to wire and use the ASC712).

Thanks all you guys. I want do it now what i learn here

@Rayan_skofw You're welcome, if the answer was helpful please click on that gray tik next to the answer to pick it as correct answer.

How much voltage drop would a shunt circuit like that cause? You spec'd a 100 megohm resistor, so it shouldn't be that bad. You'd need a pretty high powered resistor though.

Could you wire all the motor's coils to your current sensor through high current diodes, and just look for a peak current above some threshold?


text:
Is it possible to synchronize two SPI busses to send data out in parallel on the same clock signal?
We're working with these very odd driver chips which are sort of like shift registers except rather than latch the data at the end, the latch needs to happen over the last 'n' clock cycles in parallel with the data being shifted out.  Depending on the value of 'n', the data is 'latched' into different registers. Like I said, it's an odd protocol.
Here's an example sending six bytes of data (top row) synced to the latch (bottom row).  The latch is HIGH for the last two bits of the data as it's being shifted out.
Time-->
11001100 01010101 10011010 11001011 01001010 10010101
00000000 00000000 00000000 00000000 00000000 00000011

In this example, the latch is synced to the fifth and sixth bit of that last frame (as opposed to the 7th and 8th in the first example) which tells the chip to load this data into a different register.
Time-->
11001100 01010101 10011010 11001011 01001010 10010101
00000000 00000000 00000000 00000000 00000000 00001100

Like I said, it's an odd design, but it basically lets you shoot out data non-stop without having to pause to latch.
Because of having to 'sync' the latch with certain clock cycles in the data, we can't use the standard SPI bus and have to use normal GPIO pins, which of course are substantially slower.
BUT... if I could set up the data for a second SPI bus, then use a buffer to define where the latch is high/low accordingly, that would work.
The issue is I don't know how to, or if it's even possible to sync SPI busses together.
Only thing I can think of is to use one SPI bus as the master and another SPI bus (on the same processor) as a slave, then try to leverage the bi-directional nature of it.  But this is just a guess.
I was considering looking into DMA too, but I'm starting with SPI since I know my chip has four SPI busses on it. (Update: I'm starting to think DMA is the way to go here since I now know it is possible to sync two DMA controllers to the same clock.)

very odd driver chips ... if they do not have a part number and they have no datasheet, then don't use them

There from ST and they do have a data sheet, but that's separate from my question as I'm not asking about them. I'm specifically asking if I can somehow sync two separate pins to the same SPI clock.  If not, I'll have to give the synced-DMA route a try as I know that can be done.

i am sorry, it is difficult to visualize what you are asking ... can you draw a block diagram that describes what you are asking?

I have two buffers of data that I want to send out on two parallel pins on the same clock cycle.  Think standard SPI but with two MOSI pins. I've actually found out this is possible with DMA so I think that's the way I'm going to go, but if you can figure out how to do this via SPI, that would be cool too.

As the Wikipedia page on SPI shows (as introductory material), the SPI main device generates the clock. The SPI sub device waits for the leading edge on its CS (chip select) to start transmitting its data on the following clock edges.
So you can set up one of the senders as main device, and the other sender as sub device. Use MOSI of main as the first data output, and MISO of sub as the second data output, like this:

simulate this circuit – Schematic created using CircuitLab
You can add more SPI sub devices, if you need more synchronized outputs.


text:
Serial communication from Arduino to ESP8266 NodeMCU works, but from NodeMCU to Arduino isn't working
My circuit connection is like: (I am following this tutorial)

Code uploaded to Arduino:
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial s(5,6);

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

void loop() {
  StaticJsonBuffer<1000> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["data1"] = 100;
  root["data2"] = 200;
  if(s.available()>0){
    root.printTo(s);
  }
}

Code uploaded to NodeMCU:
#include <SoftwareSerial.h>
int D5 = 14, D6 = 12;
SoftwareSerial s(D6,D5);
#include <ArduinoJson.h>

void setup() {
  // Initialize Serial port
  Serial.begin(9600);
  s.begin(9600);
  while (!Serial) continue;
}

void loop() {
 StaticJsonBuffer<1000> jsonBuffer;
 JsonObject& root = jsonBuffer.parseObject(s);
 if (root == JsonObject::invalid())
   return;

 Serial.println("JSON received and parsed");
 root.prettyPrintTo(Serial);
 Serial.print("Data 1 ");
 Serial.println("");
 int data1=root["data1"];
 Serial.print(data1);
 Serial.print("   Data 2 ");
 int data2=root["data2"];
 Serial.print(data2);
 Serial.println("");
 Serial.println("---------------------xxxxx--------------------");
}

Arduino sends JSON data and NodeMCU parses it as expected.
--------Till this everything is fine. ---------
But my requirement is vice versa. When I create JSON object in nodeMcu and try to parse in arduino, JSON not received.
This time I wrote this code in nodeMcu:
#include <SoftwareSerial.h>
#include <ArduinoJson.h>

int D5 = 14, D6 = 12;
SoftwareSerial s(D6,D5);

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

void loop() {
 StaticJsonBuffer<1000> jsonBuffer;
 JsonObject& root = jsonBuffer.createObject();
 root["data1"] = 100;
 root["data2"] = 200;
 if(s.available()>0){
   root.printTo(s);
 }
}

And code in Arduino:
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial s(5,6);

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

void loop() {
  StaticJsonBuffer<1000> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(s);
  if (root == JsonObject::invalid())
    return;

  Serial.println("JSON received and parsed");
  Serial.print("Data 1 : ");
  int data1=root["data1"];
  Serial.println(data1);
  Serial.print("Data 2 : ");
  int data2=root["data2"];
  Serial.println(data2);
  Serial.println("---------------------xxxxx--------------------");
 }

This code doesn't work. I don't receive anything in serial monitor of arduino.
The circuit connection remains the same as before.
Anymore information should I provide ? What modification do I need?

maybe try a smaller buffer

you require a common ground connection

@jsotola, but I also tried that. Moreover, without ground connection : data comes from arduino to nodeMcu. Then why I need ground ?

@Juraj , how ? And , if data comes from arduino to  nodemcu without changing buffer, do I really need to change in case of nodeMcu to arduino ?

the 1000 bytes buffer is too large for 2kBytes RAM of Uno

@Juraj what is a allowable value ? Do I need to change SoftwareSerial.h or HardwareSerial.h ?

StaticJsonBuffer<1000> jsonBuffer

The problem may stem from Arudino boards being 5v logic pins while ESP boards are 3.3v logic pins.  3.3v high might not be enough for Arduino to see the data.


text:
Could i use a stepper motor?
i want to make a 3-axis gimbal with arduino but brush-less motors seem incredibly hard so would stepper motors work for this purpose?
if their is a way if not, is how can i connect 3 gimbal motors to one arduino board and control them seperately? (links if possible)

If I would have planned to build a arduino controlled gimbal, I would use servos which are DC motors with a feedback control system. There so many videos on youtube for example that show how to build a gimbal with servos. OK you are to lazy to find one, here is one of them. I'm nice; I know ;-) https://www.youtube.com/watch?v=UxABxSADZ6U
OK, and now switch the jokes off: You are new to this forum. The people who answer your question are glad to help you. But do not expect them to provide you with a solution for a problem if it is easy for you to check the internet and get answers.

Why should brushless motors be incredibly hard? You only need an ESC as a driver, which then can easily controlled via PWM

@PeterPaulKiefer thank you but the reason i asked for links is because ive been searching for hours without luck on finding a way to control three brushless DC motors. i looked at servos but they dont meet my needs as they seem to be not very smooth

@chrisl thanks chris so i just need to find the right ESC and ill be able to use three on my arduino board? thatll fix all my problems thanks

Ok, I was was not very nice, I'm sorry about that. You are right, Servos are not very smooth, but you did not specify your needs for smooth operation. Please see my answer.

DC Motors with a feedback line (so called PID Controller; https://en.wikipedia.org/wiki/PID_controller) would be the best way to do it. You need the motor as an actor and some sensors that sense the direction of the axis's of the gimbal. The PID controller should be very fast for smooth operation. (Perhaps an ESP32 is a better MCU for this purpose).
The PID controller uses a motion sensors.
It's good to have strong motors that do not react "nervous" on on voltage changes. You probably will have to use motors with gears. Even fast PID controller won't be able to keep your camera from turning cartwheels if a 10.000 cycles per minute racing motor gets full voltage applied.
I searched the internet for videos of such a setup but the only thing I found, are the commercial (?) gimbal "alexmos" "how to" videos. I'm with you that it is hard to build such a gimbal without much knowledge of how PIDs work. I'm also not sure if there is an arduino that's fast enough to realize a PID that gets its feedback from motion sensors and drives dc motors with this information, then get's feedbach of the motor movements (from the motion sensors) and so on.
And probably a better/stronger servo and and very fast PID setup might eventually smooth the gimbals movements.
Here is a link that might help you as a start point for PID (if you are not discouraged yet):
https://www.youtube.com/watch?v=9TTDmWiMg_Y
And even professional setups can make problems: (It's a matter of the PID parameters)
https://www.youtube.com/watch?v=UeeTXH2Qv2o

A stepper motor might work, but it is certainly not the best choice for what you try.
Instead you should use brushless motors. There are not so hard to use, as you think. Driving them directly is difficult, but no one does that. Instead just buy an ESC (Electronic Speed Control) (one for each brushless motor). That is an extra chip/board, where you need to connect a PWM signal and ground from the Arduino and the power source of the motor. Then connect the motor to the ESC and you will be able to control the brushless motor with a simple PWM signal.
For further information you can read this post in the Arduino forum, or you just google. There is plenty of information the web about ESCs.


text:
DS1820B only returns -127
ive used one DS1820B sensor in a AVR bread board circuit and it works there, now i tried attaching it to a arduino mega board with the code below and also another library below that.
currently the data pin is connected to pin 10 on the arduino board, but i also tried pin 2 as in this picture:
https://lastminuteengineers.com/wp-content/uploads/2018/12/Wiring-Multiple-DS18B20-Temperature-Sensors-With-Arduino.png
i changed: #define ONE_WIRE_BUS 10   accordingly.
So after that i put the chip back onto the bread board and it still works.
I also tried it with the 4.7k resistor on the data line as pullup....still -127.
Any ideas?
#include <SPI.h>
#include <SD.h>
/********************************************************************/
// First we include the libraries
#include <OneWire.h>
#include <DallasTemperature.h>
/********************************************************************/
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 10
/********************************************************************/
// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
/********************************************************************/
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
/********************************************************************/

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
 sensors.begin();
}

void loop() {

  Serial.print("Temperature is: ");
 Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
   // You can have more than one DS18B20 on the same bus.
   // 0 refers to the first IC on the wire
   delay(1000);

}

second code:
#include "DS18B20Events.h"

// Pin for DS18B20
#define ONE_WIRE_BUS 10

/********************************************************************/
// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Init DallasTemperature
DallasTemperature dallasTemperature(&oneWire);

//Init thermometer with index 0 (default)
DS18B20Events thermometer(0);

// the setup function runs once when you press reset or power the board
void setup() {
  Serial.begin(9600);
  DS18B20Events::setup(&dallasTemperature); // Link DS18B20Events to DallasTemperature object
  DS18B20Events::setInterval(5000); // Set min interval in milliseconds between 2 measurements. Default 10000 set in setup() method.

  // subscribe to temperature changed event
  thermometer.onChange = temperatureChanged;
}

// the loop function runs over and over again until power down or reset
void loop() {
  thermometer.loop(); // Mandatory to measure temperature and fire an event if needed

  Serial.print(thermometer.getTempC()); // Get last measured tempC if needed.
  Serial.print(" measured ");
  Serial.print((millis() - thermometer.getMillis()) / 1000);
  Serial.println(" seconds ago.");

  delay(1000);
}

void temperatureChanged(uint8_t index, float tempC)
{
  Serial.print(tempC);
  Serial.print(" new tempC at index ");
  Serial.println(index);
}

Please post a photo of your wiring (including a clear view of the stripes on your pullup resistor).

You need a photo of your ACTUAL wiring to your Arduino, not the Fritzing diagram of what your wiring should look like.

Im not sure what it was, but its working now with the second code. the first one is probably right too. Maybe i was just to cool(-127C) a few hours ago...oh no. Theres probably a stackoverflow page for that too.

you probably forgot pull up resistor

I found this page because I was having a similar problem. I was trying to attach to an ESP01. I was unable to get it to read on GPIO3, GPIO1 or GPIO0 but I was able to get it to work with GPIO2. It seems it may be quite sensitive to the pullup resistance.

127 error is a connection error, check the wiring:


text:
Controlling multiple servos as one
I want to attach multiple servos to Arduino but all them must receive same command. If it possible to connect all servos to one command pin (I don't want to use "for" in code to minimize processor time for operation)?

why do you need to have multiple servos perform identical motion?

To perform identical motion in several places (e.g. move forward)

IMHO it is possible to connect more than one server PWM control inputs to a Arduino output pin.
The Servo input is something like a comparator with an very high resistance. So the servos should not influence each other in any way, nor will the output pin be overloaded.
Because of the input capacities of the servos, there might be a limit of the count of the servos.
And if you supply the servos with power from the arduino then, there is of cause a limit.
EDIT:
It is always a good idea to use buffers in a servo control circuit, to keep a sharp square wave signal. Parasitic capacities can reshape the signal even to a sinus signal.
That might confuse the servo control unit which works well only with a square wave (i.e a PWM-Signal).

simulate this circuit – Schematic created using CircuitLab

Thanks for response. In this case should I add some kind of signal amplifier after pin?

I was very busy. Sorry about the delay. I edited the answer.


text:
Water pump control hysteresis
I'm using arduino with analog pressure sensor, temperature sensor and a relay to control water pump. The simple code I wrote works, but I want better control.
#include <OneWire.h>
#include <DallasTemperature.h>

 const int pinCidlaDS = 2;
 int pinA0 = A0;
 int teplota;
 int rele;
 float tlak = 0;  //ideal 290+-

OneWire oneWireDS(pinCidlaDS);
DallasTemperature senzoryDS(&oneWireDS);

void setup() {
 senzoryDS.begin();
 rele = 3;
 pinMode(3, OUTPUT);
 Serial.begin(9600);
}

void loop() {
 tlak = analogRead(A0);
 teplota = (senzoryDS.getTempCByIndex(0));
  if ((tlak < 285) && (teplota < 30)) {
   digitalWrite(rele, LOW);
   delay(7000);
 }
   else {
   digitalWrite(rele, HIGH);
   delay(500);
 };
 Serial.print("Tlak: ");
 Serial.println(tlak);
 Serial.print("Teplota: ");
 senzoryDS.requestTemperatures();
 Serial.print(senzoryDS.getTempCByIndex(0));
 Serial.println(" stupnu Celsia");
 teplota = (senzoryDS.getTempCByIndex(0));
 delay (200);

}

So now I'm using delay to get away from the treshold value. And I wanted to write a code that would work like:
Pressure is lower than 'x', relay ON.
Pressure rises to 'Y', relay OFF until Pressure is lower than 'x'.
What should I use? Could you please give me a example, if there is?
Thank you very much! :)

Implementing hysteresis turns out to be quite straight-forward:
float pressure = read_pressure();
if (pressure < x)
    turn_relay_on();
else if (pressure >= y)
    turn_relay_off();

In addition to this answer you can also use millis(); function instead of delay, take a look at BlinkWithoutDelay example in Arduino IDE.

@newbie, with appropriate hysteresis values you might not need any delay logic at all, using either millis() or delay(). The hysteresis range allows you to have a "dead zone" range where nothing changes. It takes time for the temperature to go from the temp/pressure "on value" to the "off value", so the pump turns on and off less frequently.

It looks like the OP's application makes its pump on /  pump off decisions based on both temperature and pressure. We need to know the values for both that should trigger the pump on, and the values that should trigger the pump to go back off again.

@DuncanC: Hysteresis on two variables is more complex. My usual approach would be to draw, in the (T, P) plane, three regions: pump on, pump off, and an hysteresis band between them. Then write a predicate on the (T, P) pair for each of pump on and pump off. Cutting out a quarter-plane (T<T1 && P<P1 and T>=T2 || P>=P2) is the simplest case, but I would not trust something with such a sharp corner to be anywhere near optimal for any application.


text:
Multiple buttons to control relays
Dears,
I have a problem that I could not solve for a while, I tried the code below but it did not work.
There will be 4 buttons controlling 4 relays but in a way that button one will turn relays 1&3 on, if button 2 is pressed only relay 2 turns on, if button 3 is pressed relays 1,2 and 3 will turn on, if button 4 is pressed it is supposed to toggle relays 1&4. one more thing: I need to be able to pass from any button to any of the others and the corresponding relays will be activated while the others will go off.
    #include <Bounce2.h>

    const int     BUTTON_COUNT = 4;
    const int16_t DEBOUNCE_DELAY = 50;
    const uint8_t buttonPins[BUTTON_COUNT] = {28, 29, 30, 31};
    const uint8_t ledPins[BUTTON_COUNT] = {34, 35, 36, 37};

    Bounce buttons[BUTTON_COUNT];
    uint8_t ledStates[BUTTON_COUNT];

    void setup() {
    for (int i = 0; i < BUTTON_COUNT; i++) {
    buttons[i].attach(buttonPins[i], INPUT);
    buttons[i].interval(DEBOUNCE_DELAY);
    pinMode(ledPins[i], OUTPUT);
    ledStates[i] = HIGH;
    digitalWrite(ledPins[i], ledStates[i]);
     }
    }

    void loop() {

// Update the debouncers.
for (int i = 0; i < BUTTON_COUNT; i++)
    buttons[i].update();

// When the first "laban" button is pressed:
if (buttons[0].rose()) {

    // Light up the first LED.
    digitalWrite(ledPins[1], LOW);
    digitalWrite(ledPins[3], LOW);

    // and turn off all the others.
    for (int i = 0; i < BUTTON_COUNT; i++) {
        ledStates[0] = HIGH;
        ledStates[2] = HIGH;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

// When the first button is released:
if (buttons[0].fell()) {

    // turn off relays.
    digitalWrite(ledPins[1], HIGH);
    digitalWrite(ledPins[3], HIGH);

}

// When the first "Soda" button is pressed:
if (buttons[1].rose()) {

    // Light up the first LED.
    digitalWrite(ledPins[2], LOW);

    // and turn off all the others.
    for (int i = 0; i < BUTTON_COUNT; i++) {
        ledStates[0] = HIGH;
        ledStates[1] = HIGH;
        ledStates[3] = HIGH;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

// When the first button is released:
if (buttons[1].fell()) {

    // turn off the first LED.
   digitalWrite(ledPins[2], HIGH);

}

// When the first "labanUP" button is pressed:
if (buttons[2].rose()) {

    // Light up the first LED.
    digitalWrite(ledPins[1], LOW);
    digitalWrite(ledPins[2], LOW);
    digitalWrite(ledPins[3], LOW);

    // and turn off all the others.
    for (int i = 0; i < BUTTON_COUNT; i++) {
        ledStates[0] = HIGH;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

// When the first button is released:
if (buttons[0].fell()) {

    // turn off the first LED.
     digitalWrite(ledPins[1], HIGH);
     digitalWrite(ledPins[2], HIGH);
     digitalWrite(ledPins[3], HIGH);
}

// When circulation button is pressed:
 if (buttons[3].rose()) {

    // Toggle its state.
    ledStates[3] = !ledStates[3];
    digitalWrite(ledPins[3], ledStates[3]);
    digitalWrite(ledPins[0], ledStates[0]);
     }
    }

Below code is an simple example of what you described, each button will turn on the relays defined for them and turn off other relays. except for button 4 which will toggle relay 1 and 4.
int relay1 = 2;
int relay2 = 3;
int relay3 = 4;
int relay4 = 5;
int sw1 = 6;
int sw2 = 7;
int sw3 = 8;
int sw4 = 9;
int sw1Status, sw2Status, sw3Status, sw4Status;
int order = 1; // default is to set all relays off.

void setup() {
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  // input pull-up, so default state of buttons is HIGH.
  pinMode(sw1, INPUT_PULLUP);
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  pinMode(sw4, INPUT_PULLUP);
}

void loop() {
  // read the buttons status
  sw1Status = digitalRead(sw1);
  sw2Status = digitalRead(sw2);
  sw3Status = digitalRead(sw3);
  sw4Status = digitalRead(sw4);

  if (sw1Status == LOW) { // if button 1 pressed
    order = 2; // go to case 2
  }
  if (sw2Status == LOW) {
    order = 3;
  }
  if (sw3Status == LOW) {
    order = 4;
  }
  if (sw4Status == LOW) { // button 4 toggle
    if (order != 5) { // if order is not equal 5 turn on relay 1 & 4
      order = 5;
    }
    else { // else go to case 1, which will turns off all relays
      order = 1;
    }
  }

  switch (order) {
    case 1: // if order equals 1
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, LOW);
      break;

    case 2: // if order equals 2
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      break;

    case 3: // if order equals 3
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, LOW);
      break;

    case 4: // if order equals 4
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      break;

    case 5: // if order equals 5
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, HIGH);
      break;

    default: // if none of above cases is valid go to case 1
      order = 1;
      break;
  }
}

Having a tidy code format and using simple coding style (if possible) will help to debug/edit/improve the code more easily.
Don't forget to de-bounce the buttons.

Thank you very much, but unfortunately, it did not work the way we were expecting. I thought it maybe my connections so I used the simulator with dc motors instead of the relays and it was the same :(  "
https://www.tinkercad.com/things/k1VCQrax95J-copy-of-arduino-simulator-or/editel?tenant=circuits?sharecode=o-fW6ONb4zlq8c6y1JUVCaG0y66HdNzOcTwLNEqftGE=  "

@medo You shouldn't connect the push buttons to the positive line, we already used the INPUT_PULLUP. remove the resistor and just connect the push button directly to the negative line.

Highly appreciated @newbie.  What do you think changes need to be made if I replace the push buttons with "TTP 223" touch sensors? any idea of changes on the code? since the sensor has 3 lines; ground, vcc and signal

@medo well sensors also have high/low output too, in case of using a sensor instead of push button you have to detect sensor status and apply it in the code: sw1Status, sw2Status .... also you should replace INPUT_PULLUP with INPUT.