text:
Serial communication by bluetooth hc-05
i am making a ultrasonic radar using stepper motor and ultrasonic sensor , and displaying the output over a software(processing 3) which looks like a radar ppi on display ...is it possible ot replace the usb cable with a bluetooth connection to send data (serial) instead of using a usb cable i want the setup to be remote ..i am using a instructable https://www.instructables.com/id/Acoustic-Radar-Display/ for coding i just need to know how to make it wireless over bluetooth ...just changing the com over processing 3 works or i need to do some changes in command mode of bluetooth

What have you tried?

radar does not use sound, it uses radio waves ... you are building a sonar

i have tried with a hc-05 without mking any changes to arduino code just power bluetooth and after loading code connect xt rx pins and just change com port over processing 3 ...i am just confused to do it with one so i tried all but not working

yes i am building a sonar kind of thing which just have a radar type display just ..its a scaled model to depict working of radar

If you use a Bluetooth Module like this, that has an SSP profile, it will show up as COM port on your windows machine.
Now if you want to use the Arduino's Hardware Serial (i.e. keep using Serial.print() but for Bluetooth) then you will connect the module like this:

Bluetooth HC06 TX to digital pin 0 (Arduino Rx)
Bluetooth HC06 RX to digital pin 1 (Arduino Tx)

But remember, you load your code using these pins too. Arduino has a "USB-to-Serial" IC on board that uses those two pins. So now two entities trying to use those same pins (U2S and BT) i.e. you will have to disconnect U2S connections:

The above image is a snippet from the Arduino schematic. One way to disconnect those connections is to remove those two resistors. But then again, next time you want to load your code, you won't be able to use USB cable anymore.
So, I will suggest you to use SoftwareSerial and choose any other two pins for Bluetooth Module and change in the code wherever you were communicating with the Processing using Serial.println(). replace that with SoftwareSerial println().

i am using a hc-05 ...bluetooth module because it can do both asa slave and master , hc-06 is a only slave type...do u want me to make my hc-05 as a slave and do this ...here dosent it should be master because it(bluetooth) is sending data  to pc(prosessing 3) ???

Your Arduino is Master, so Bluetooth should be a slave.

i a using hc 05 for the same purpose and it have SSP profile .....and i am using the hardware tx rx pins only ..i a using hc 05 for the same purpose and it have SSP profile .....and i am using the hardware tx rx pins only ..just to upload code disconnect them then reconnect then is the only change needed ...

i just wanted to know ...with just attaching the bluetooth to the project and using outgoing connection com in pc (it shows incoming and outgoing com) to which bt is connected ..is it possible to make it wireless ..for all this do i just need to connect the bluetooth at correct braud i.e.115200 in the above case and change the com port at the processing 3 as the outgoing com of bluetooth ...i just want to make the project wireless like no usb cable ..since it s a com connection i am asking can it be replaced with a bluetooth connection ...please help me i am stuck in here ...

please go through code once and see if i need some changes in the coding of project ..thank u regards..its is part of a project which i need to complete but i am not able to do it as i am new to coding and finding out the possibilities

Yes, it is possible. Just follow the connection that I mentioned in the Answer (D0, D1). In the code change the Baud Rate to 9600. Both in Arduino and Processing. HC-05 default baud rate is 9600.

i have tried but as soon as i put the TX Rx pins in hardware pins 0 and 1 ..the system stops ..i have changed the speed of HC-05 to 115200 via AT commands with 1 stop bit and 0 parity bit , AT+UART=115200,0,0...do i need to use software serials ..because the continuous "s" which r send to pc are using that connection or am i doing something wrong ...i cant use 9600 because thats too slow for the radar ... thank you for all ur help

When you connect your Bluetooth with Arduino using D0 and D1, is the USB cable from Arduino still connected to your PC?

yes it is connected ..i am like 1st running entire thing with usb and then give external power to arduino and then connect the bluetooth rx tx of HC-05 to arduino and then disconnect the usb cable..in this as soon as i connect tx rx pins to bluetooth the entire system stops  like the sweep stop over processing 3..which was running fine before this connection ..the usb is connected in this case as to get the sweep over processing 3 after this only i try to connect the rx tx and remove usb cable

Ok, the Arduino has a USB-to-Serial chip on board. And that is using D0 and D1. Without disconnecting those you won't be able to use those two pins. I think it is better to use the software serial. Choose any other two pins, connect Bluetooth there and wherever in the code you are sending something to the PC replace that with software serial.println()

I updated my answer too.

i have done changes in arduino ide as chaning all hard serials to software serials like serial.available to myserial.available(example) i changed every line with serial to myserial (myserial is my software serial)...and then connected the tx and rx of bluetooth changed the uart to 115200,0,0 for braud rate ....then paired the bluetooth with laptop saw the outgoing serial port of bluetooth (mine was com7) then changed the serial.list in processing 3 for the same (com7) port ..issues i am facing r (usb is not connected arduino is powered by a 9v battery through jack)

it shows the com port is busy ..sometimes it connects but the display displays the pings and the sweep for sometime ...like it wont work indefinitely ..not even for one complete sweep of radar ..and sometimes it just start too slow foe motor rotation ..but the biggest issue is the complete sweep thing ....to make it 360 i doubled the array at processing made additional graticules and increased the step count in arduino ide so basically i have got what i wanted but with the usb attached ...

to get it wireless i tried software serial and changes made were every serial event was chaned to software serial but its not working as desired .do i have to keep some serials as the original one and not change them to software serial ...only sending part need to be changed(azimuth direction distances ) or other things too like starting of the stepper at the click of switch and other serial.available events

do i have to create a separate port in processing or just changing the serial.list to the outgoing serial com of bluetooth is enough  (like this "Serial myBluePort;" while importing processing.serial) i am using the earlier created serial port the myPort for the same ..if i am not using it for usb wont just changing its serial.list should do the work


text:
How can I make std::cout write to Serial?
I'm using an Arduino MKR WiFi 1010, a SAMD ARM Cortex M3 board. I rely on the standard library a lot, using things like std::vector<> and std::string. I also want to use std::cout. I've managed to do this on an UNO R3 using the ArduinoSTL library, but that library neither works nor is necessary on the MKR WiFi 1010, because it has all the standard library stuff built in to the platform.
However, on MKR WiFi 1010, I cannot get std::cout to produce any output. I'm guessing its not really hooked up to anything.
I want std::cout to write to Serial (which is aliased to SerialUSB which is of type Serial_).
Is there a way of making std::cout write to the Serial stream?

Maybe try using preprocessor by creating a #define clause? It might work. Something like this, but in the other way around. It's not really "writing to serial", but it will at least look that way when you read the code.

MKR1010 is SAMD21G which is Cortex M0. but it too uses ARM implementation of stdio

http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0475m/chr1358938931411.html

The ARM gcc libraries offer a simple way to redirect standard outputs. It is enough to implement function _write(int fd, char *ptr, int len) and it will replace the default implementation used in library to direct the standard outputs to debugger semihosting. The function must be compiled as  C to match.
#include <Arduino.h>
#undef max
#undef min
#include <stdio.h>
#include <iostream>

using namespace std;

extern "C" {
int _write(int fd, char *ptr, int len) {
  (void) fd;
  return Serial.write(ptr, len);
}
}

void setup() {

  Serial.begin(115200);
  while (!Serial);

  Serial.println("START");

  printf("HERE WE ARE\r\n");

  cout << "TEST COUT\r\n";
  cerr << "TEST ERR\r\n";
}

void loop() {

}

the #undefs undefine the Arduino macros, which are in conflict with includes used in <iostream>

it took me many hours to make it work and in the end it is so simple

@TimLong, did the answer help?

Hy Thanks for sharing. It doesn't work for me. Arduion IDE 1.8.19, Mega2560 and DUE board.
iostream no found. I made some search on the net. And it seams that stl is not supported on Arduino but I found some alternatives: Silver-Fang/ArduinoSTL on Github for example

@MajorLee6695, the question was about the SAMD plaform (MKR board)

source: Stack Exchange

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

sort: votes


text:
Include guards vs #pragma once
Is there any particular reason why #pragma once doesn't seem to be used in Arduino code? Is this just because it's not a well-known feature, or is there some overriding reason to use #ifndef XXX_H/#define XXX_H/#endif?

Might be that part of the Arduino core source code is older than #pragma once. Which is by the way non-standard. It was introduced in GCC 3.4.

#pragma once is not a standard feature.

Non-standard but damn useful. Would be wise to consider adding support for it.

all #pragmas are non-standard by definition. However, I started using them in about 1986 in various C compilers and it seemed pretty ubiquitous even then. I guess I'm surprised that's not the case in the C++ world.

#pragma once operates on the absolute filename of a file. Include guards work on the content of the file.
If you have multiple copies of the same library (maybe one library has some parts of another included in it - it happens...) #pragma once would have no hope of working right.
Add to that the fact that the Arduino IDE copies some files around the place when building and '#pragma once is pretty much screwed.
Include guards work regardless. So sensible people use include guards and shun #pragma once.

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


text:
What is the correct way to externally power a MKR 1010 WiFi
I'm a little confused by the powering arrangements of the MKR 1010 WiFi. I need to power it on a breadboard from an external power supply. I will not be using a LiPo battery and I need it to work when the USB is disconnected.
Assuming there is no battery or USB connected, I think I need to apply power on the Vin pin (the pinout diagram on arduino.cc shows this as an input pin and 5V as an output pin). However, the 5V pin has a resettable fuse inline whereas Vin does not, which to me is counterintuitive.
So my questions are twofold:

What is the correct pin for supplying external power, and
What is the correct voltage to apply

https://store.arduino.cc/arduino-mkr-wifi-1010 see the FAQ section

@Juraj While that does at least in part answer the question, it might have been more in the spirit of Stack Exchange to copy that FAQ section into an answer. External links tend to rot over time and are not especially helpful.

What is the correct pin for supplying external power, and

VIN

What is the correct voltage to apply

The bq24195 can accept between 3.9V and 17V according to the datasheet. However the power LED on the board may blow if you apply more than about 12v since it only has a 330Ω resistor with it.

The polyfuse on 5V is there to protect the USB's power connection incase the user makes a mistake and short circuits it. It's more for the protection of your computer's USB port than the MKR board itself.


text:
STM32f4 Warning: The core is locked up
I built a custom board that uses a STM32F411CEU6. My problem is that tried to upload a simple blink sketch (I'm using Arduino IDE with STM32 libraries) and I get the error:
ST-LINK SN  : 57FF72067166535645342467
ST-LINK FW  : V2J37S7
Board       : --
Voltage     : 3.23V
SWD freq    : 4000 KHz
Connect mode: Under Reset

Reset mode  : Hardware reset
Device ID   : 0x431
Revision ID : Rev A

Device name : STM32F411xC/E
Flash size  : 512 KBytes (default)
Device type : MCU
Device CPU  : Cortex-M4

Memory Programming ...
Opening and parsing file: Blink.ino.bin
  File          : Blink.ino.bin
  Size          : 11256 Bytes
  Address       : 0x08000000

Erasing memory corresponding to segment 0:
Erasing internal memory sector 0
Error: failed to erase memory

Error: failed to erase memory

RUNNING Program ...
  Address:      : 0x8000000
Warning: The core is locked up
Start operation achieved successfully
the selected serial port Start operation achieved successfully
 does not exist or your board is not connected

I'm using an ST-LINK V2 USB pen that works fine. I have a Black Pill with the same STM32 to use as a control and everything works ok.
Also, when I try to check the custom board with STM32CudeProgrammer, I get the error:
  22:16:27 :   Size          : 1024 Bytes
  22:16:27 :   Address       : 0x8000000
  22:16:27 : Read progress:
  22:16:27 : Error: Data read failed

How solve the "The core is locked up" issue and upload the sketch.

Fix the problem with your board. Whatever that may be.

https://www.stm32duino.com

The solution:

Open STM32CubeProgramer and click connect
Click Option Bytes (OB) located in the left bar
Select Read Out Protection and choose AA option
Then select PCROP and uncheck the box
Click apply


text:
Arduino Nano Every I2C PORTMUX
Arduino Nano Every schematic informs us that we can use ATMega4809's pins PF03 and PF02 to communicate via I2C.
ATMega4809 manual says in page 19 that in order to use those pins as I2C we need to use PORTMUX.
I'm not really an expert and I don't understand how to do that.
Any help would be approciated.

In the Nano Every schematic, PF2 and PF3 are connected over to PA2 and PA3 respectively.  That is, Arduino pin A5 and ATMega4809 pins PF03 and PA03 are connected together by PCB traces such that there's no distinction between them, PF03 doesn't have its own header pin anywhere distinct from PA03.  They're both A5.  Likewise for Arduino pin A4 and ATMega4809 pins PF02 and PA02.
The Nano Every was designed to be compatible with the original Nano boards that used the ATMega328P.  On these boards the A5, analogRead-capable pin, is also the I2C/Wire clock signal.  Likewise,
A4, analogRead-capable pin, is also the I2C/Wire data signal.
On the ATMega4809 the I2C/Wire Master/Slave signals on PORTA routed to the A5 and A4 pins are not also analogRead-capable.  That is, they are not connected to the analog-to-digital converter in the chip as they were in the Atmega328P on the old Arduino Nano boards.
To mirror the workings of the original Nano, where A4 and A5 were both analogRead pins and I2C/Wire Master/Slave pins, they connected A4 and A5 to pairs of ATMega4809 pins.  One of these pins on PORTF is connected to make the Arduino pin analogRead-capable and the other pins on PORTA are connected to make the Arduino pin Wire/I2C Master/Slave capable.  In other words, they used two AVR pins to synthesize a single Arduino pin capable of both functions that were available on that pin on the older Nano boards.
When it comes to using PORTMUX to switch choice of I2C pins, practically speaking, you won't be able to if you're looking to get alternate pins for TWI Master.  PORTMUX lets you switch the I2C Master/Slave or just Master peripheral onto pins PC2 and PC3 instead of PA2 and PA3.  But, in the Nano Every schematic, you can see these are not connected to anything.  So if you wanted to do that, it would mean something like soldering wiring-wrap wire directly to the MCU pin, which would be difficult.  And PC2 and PC3 are the only two other ATMega4809 pins that PORTMUX will route the hardware I2C Master/Slave peripheral to.    So, practically speaking, if you want I2C any pins other than A4 and A5 on a Nano Every, it means using a software (bit-banged) implementation of I2C.
You asked (in comments) about the TWI support indicated on PF2 and PF3 in the ATMega4809 datasheet.  I think I'd either been looking at an older datasheet or maybe disregarded those pins because of how they're hardwired over to PORTA on the Nano Every.  The ATMega4809 has a "Dual TWI" mode apparently, where you can have just master mode on the pins that are normally both, and just slave mode on an alternate set of pins.  In two configurations of PORTMUX under Dual TWI, the PF2 and PF3 are where the slave-only capability of the peripheral are broken out.  With PORTC's TWI pins unconnected and PORTA's TWI pins hardwired to PORTF's TWI pins, it's unclear to me what advantage you could get out changing PORTMUX on an Arduino Nano Every.

Ok, thanks for the info. Even so, how can I force the I2C communication to use pins PF2 and PF3 instead of PA2 and PA3?

I probably wasn't clear enough in this part.  In the Nano Every schematic, you can see that those pins are hard-wired together.  That means, for example, Arduino pin A5 and ATMega4809 ports PF03 and PA03 are all the same node in the circuit connected together with copper traces.  That is the significance of having the A5/SCL label applied to all three things.

I understand that. I know that they are both connected but I'm doing some tests and I want to test an I2C communication from PF2 and PF3 pins. I think that it must be a way to swap the pins that will be used by, for example, the Wire library. That is what I'm searching for.

I get the impression that there's still something I haven't made clear.  I did go back and reword things to try to things more direct, specifically that there are only two sets of pins that can have the I2C hardware support routed to, and only one of those sets is soldered to the chip.  This is something I updated in the last paragraph.

Ok, thanks. But in that case why does the ATMega4809 datasheet informs in page 19 that PF2 and PF3 are I2C capable?

Interesting, I think I've been looking at several different editions of the datasheet.  In the one you have liked above I see (S) and (MS), which I'm guessing are "slave" and "master".  Will get back to you on it, maybe update the answer with what I find.

Let us continue this discussion in chat.


text:
Adafruit Metro Mini FTDI chip overheating
I have an Adafruit Metro Mini board that I am using. After soldering the board and accessories to a perfboard the FTDI chip is overheating, the COM port will not show up on the PC, and the 3V pin does not produce any power while the board is plugged in.
Is there a way to fix this? Have I nuked my board?

Maybe short or you reversed something

The 3.3V output of the FTDI chip might be shorted to Gnd, or overloaded by your circuit. Start by checking that.

Is there a way to fix this?

Yes. Undo whatever short circuit you have created with your soldering.

Have I nuked my board?

Possibly, possibly not. Most likely the short is making the regulator go into thermal shutdown and no lasting damage has been caused. But you can't be sure.


text:
Flow control between ESP32 and RS323 device
I'm trying to communicate an RS232 device with an ESP32 (Heltec Wifi/LoRa 32 v2) my problem is that I don't receive any response from the device, doing some research, I'm thinking that the trouble can be the flow control because I don't use these pins and the modules I've used neither have these pins. Do you know a way to, at least, solder the DB9 pins to have a sort of flow control to communicate the devices?

What kind of device are you trying to communicate with?

Also: do you use a TTL->RS232 converter?

This can only be answered by looking at the data sheet of "the RS232 device". You can emulate RTS/CTS flow control by connecting them to two unused GPIO pins and then taking care of them in your own code while sending data back and forth. Also, a real RS232 interface communicates on signal levels between 3 and 15V, so if you are not absolutely sure that "the RS232 device" answers on a signal level of less than 3.6V, you will absolutely need a level shifter. Better use a dedicated RS232 shield for that -- which is the only answer I can give from the information in the question.

You could use ESP-IDF calls to setup your UART correctly for hardware serial communication on pin 4 and 5 (and perhaps also other pins).
In the sample below, you just have to:

assign UART_CLIENT_RTS and UART_CLIENT_CTS to the pins of your need
change uart_config_t to whichever parameters are relevant for your RS232 device
set flow_ctrl to UART_HW_FLOWCTRL_RTS, UART_HW_FLOWCTRL_CTS, UART_HW_FLOWCTRL_CTS_RTS or UART_HW_FLOWCTRL_MAX

    #define BUFFER_SIZE 1024

    #define UART_CLIENT_TXD  (GPIO_NUM_4)
    #define UART_CLIENT_RXD  (GPIO_NUM_5)
    #define UART_CLIENT_RTS  (GPIO_NUM_?) // Set this
    #define UART_CLIENT_CTS  (GPIO_NUM_?) // Set this

    uart_port_t uartNum = UART_NUM_1;

    uart_config_t uart_config = { // Set this
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity    = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS
    };

    uart_param_config(uartNum, &uart_config);
    uart_set_pin(uartNum, UART_CLIENT_TXD, UART_CLIENT_RXD, UART_CLIENT_RTS, UART_CLIENT_CTS);
    uart_driver_install(uartNum, BUFFER_SIZE * 2, 0, 0, NULL, 0);

Communication can be done with the various uart_write_* and uart_read_* methods as defined in the documentation.


text:
Help printing Serial Monitor to LCD16x2
I have a motion sensor that triggers an LED and buzzer. That part works fine and it displays Motion detected in the serial monitor. I'm trying to get the LCD to print that as well but I can't get it to work. The LCD backlight turns on but that's it. At first I tried with the LCD16x2 I2C and now I'm trying with the regular LCD16x2. Here's my code:
#include <LiquidCrystal.h>

const int MOTION_SENSOR_PIN = 7;   // Arduino pin connected to the OUTPUT pin of motion sensor
const int BUZZER_PIN        = 3;   // Arduino pin connected to Buzzer's pincon
int motionStateCurrent      = LOW; // current  state of motion sensor's pin
int motionStatePrevious     = LOW; // previous state of motion sensor's pin
LiquidCrystal lcd(12, 11, 6, 5, 4, 2);

void setup() {
  Serial.begin(9600);                // initialize serial
  pinMode(MOTION_SENSOR_PIN, INPUT); // set arduino pin to input mode
  pinMode(BUZZER_PIN, OUTPUT);          // set arduino pin to output mode
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
}

void loop() {
  motionStatePrevious = motionStateCurrent;            // store old state
  motionStateCurrent  = digitalRead(MOTION_SENSOR_PIN); // read new state

  if (motionStatePrevious == LOW && motionStateCurrent == HIGH) { // pin state change: LOW -> HIGH
    Serial.println("Motion detected!");
    if (Serial.available()) {
      delay(0);
      lcd.clear();
      while (Serial.available() >0) {
         lcd.print("Motion detected!");
      }
    }
    digitalWrite(BUZZER_PIN, HIGH); // turn on
  }
  else
  if (motionStatePrevious == HIGH && motionStateCurrent == LOW) { // pin state change: HIGH -> LOW
    Serial.println("Motion stopped!");
    if (Serial.available() > 0) {
      delay(0);
      lcd.clear();
      while (Serial.available()) {
         lcd.print("Motion stopped!");
      }
    }
    digitalWrite(BUZZER_PIN, LOW);  // turn off
  }
}

start with the LCD example sketch instead of your sketch ... at this point, you do not know if the LCD module works correctly

Why are you using delay(0)? You don't need it. Also try to reset the cursor to a known position, before you print to the LCD

while (Serial.available()) is != 0 if there's something the SerialMonitor has sent. Until you do a Serial.read() inside the while. That means, it would fill your lcd with lots of "Motion stopped!" and seem blocked, then. (probably not your intention)

Yes the LCD works. Both have been used previously. @DataFiddler what do you mean with !=0? It doesn't need to have the while (Serial.available()). It was just something else I tried because I thought it might be an easier approach. Also, I didn't realize I took out setCursor(0, 0). Ill take out delay and add it again and see if it works.

!= not equal , here the same as > 0 (Be happy that it doesn't work, it would not work as intended)

Are you sending anything the Arduino on Serial?  You appear to only be writing and then checking available.  available is for seeing if something is sending TO the arduino, your sending data FROM the arduino won't change available.  IF you want the LCD to display the same as the Serial then put an lcd.print line right after the Serial.print line.  You seem to have some fundamental misunderstanding of what Serial.available() does.


text:
Arduino UNO and ESP8266-01 Wi-Fi cutting out after few seconds
I followed this tutorial: https://www.youtube.com/watch?v=2cjufbgOBYo
My serial output in Arduino editor is this:
AT
AT
AT
AT
AT
AT
AT
AT+RST
ATE0
AT+CWMODE=2
AT+CWDHCP=0,1
AT+CWSAP="RemoteXY","12345678",10,4
AT+CIPMODE=0
AT+CIPMUX=1
AT+CIPSERVER=1,6377
AT+CIPSTO=7
AT
AT
AT

The problem is the Wi-Fi is cutting out after a few seconds. I see the network pop up on my phone/on the RemoteXY app and then it disappears after a few seconds.
I have a suspicion it's something to do with the RX needing a voltage divider? But I am just following the tutorial and am new to electronics.
I also haven't wired up an LED yet (I am planning on using a mains relay instead)
All help appreciated,
Thanks.

I'll bet one of the small chips on the Uno is getting very very hot, yes?

I'm not sure, why would that be? Do you know why it's not working?

It would be getting hot because you're trying to run an ESP8266 from the 3.3V pin of the Arduino. The Arduino cannot supply enough current without the 3.3V regulator overheating. When it overheats it shuts down.

So do you know how I can rewire it? Any diagrams ?? I guess that tutorial was bad :(

Get a proper 3.3V voltage regulator that can provide at least 500mA. Run the whole thing off an external 1A (or greater) 5V power supply (phone charger).

Can I use the 5V pin from the Arduino?

You can feed your 5V supply into the 5V pin, but you shouldn't try and pull more than a few hundred mA out of it, no.

no power supply to Uno will allow more current over 3.3 V pin of Uno. the esp8266 resets if it doesn't get the current for peek draw so the regulator doesn't get hot


text:
Arduino based hour counter
I would like to make a hour counter for a particular machine.I have a problem in coding.arduino internal clock can work only till 49 days.my hour counter should calculate 150+ hours.I thought of using a condition to store a particular value and add with next value.How can I code adding values to a variable

If you make a millis() based timer, and use it like the BlinkWithoutDelay sketch does, then you shouldn't have a problem. I think the BlinkWithoutDelay sketch comes with the Arduino IDE.


text:
i am getting an error while working with esp8266
i got an error
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
An error occurred while uploading the sketch
can esp8266anyone rectify this

disconnect the esp8266 from RX/TX. it disturbs the upload

oh i got the solution for the above question
it might be because i used TX AND RX pins of the arduino. what i observed is as tx and rx pins are for serial communication pin during the process of uploading i have to leave that pins disconnected.arduino


text:
how to get live view of esp32cam at remote sever using ssh tunneling?
I have found many projects involving esp32cam, but in all projects video is being seen on local server only.For its of no use.As for a home security project user can view the video at remote location like MI robotic camera.
Also i do not want any port forwarding or tunneling service from a third party like www.nabto.com, www.ngrok.com etc.

You will need something local to the ESP32CAM that can do the SSH tunnelling. Maybe a Raspberry Pi. Everything else is just networking and routing and port forwarding. Nothing about that affects the ESP32 in any way.

If you're feeling adventurous there's an attempt to turn an ESP32 into an SSH server here, though you'd probably have to implement a whole lot more to do port forwarding.

did you post this duplicate? ... https://electronics.stackexchange.com/questions/495797/how-can-i-make-a-project-in-which-using-esp32cam-i-can-see-live-video-at-remote


text:
Read the respiration data to Arduino serial console
Currently working with ADS1292rShield library.
Is there any way to read the value of the respiration and heart rate without using the Protocentral GUI. Printing DataPacketHeader to the console just results in corrupted ASCII.
DataPacketHeader[9] = s32DaqVals[0];            // 4 bytes Respiration data
DataPacketHeader[10] = s32DaqVals[0]>>8;
DataPacketHeader[11] = s32DaqVals[0]>>16;
DataPacketHeader[12] = s32DaqVals[0]>>24;

    for(i=0; i<15; i++)
    {
      Serial.write(i);
      Serial.write(DataPacketHeader[i]);     // transmit the data over USB
    }

Here is the output below of the Arduino serial monitor, is there any way to make sense of the data or how it is converted to a readable integer on the GUI?
⸮ < 0 p s | ` r I @ @ 9     ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ < 2 $ & O ` q ` 8 0 ! > ⸮ ⸮ ⸮ ⸮ ⸮  ! 8 ! | H a @  9 $  ! ⸮ 8 B x  ⸮ ⸮ ⸮ ⸮  y a ` p  f ⸮ ⸮ ⸮ ⸮ ⸮ 1 b N p ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ " D ` ` ` p
 ! ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ 0 ⸮ ' # 3 @ O ` D B @ @ ! ⸮ ⸮ ⸮ ⸮ ⸮ 0    a F ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ " x p $ 0 ⸮

examine the four bytes as a 32 bit number

@jsotola I don't think the printout is corrupted because it is displaying valid data when the USB serial data is sent to the Protocentral GUI. I will try to group together the 4 bytes as a 32 bit integer.

the GUI is created using processing .... https://processing.org/ ... you can examine the sketch code and you can even rewrite the code for your own use

You are not printing the data, you are writing it. That is a difference. The packet format is binary, so you cannot get human readable data by writing. And jsotola is probably right. The data most likely consists of a 4 byte value.


text:
writing mqtt payload to spiffs file
I'm trying to write the payload of a MQTT message into a file in the SPIFFS file system of my esp32 board. I've tried this:
if(file.print((long)payload)) {
   Serial.println("File was written");
}else {
   Serial.println("File write failed");
}

payload is a byte* and file was opened in the setup() function like:
File file;
if(!SPIFFS.exists("/testfile")){
  file = SPIFFS.open("/testfile", "r+");
}

I always get an error when writing to it telling me that the file write failed. Is this the correct approach for what I'm trying to accomplish?

Use file.write(payload, length); for byte array. length should be the count of payload bytes, not the size of the payload array.
print and write return the count of bytes written. It is not meaningful to use the return value as boolean.

Open the file in the loop or the subroutine, but not in setup as file is then a local var to setup
In your code it should be
file = SPIFFS.open("/testfile", "a"); // a ... append

a      Open for appending (writing at end of file).  The file is
         created if it does not exist.  The stream is positioned at the
         end of the file.

r+   positions stream at the beginning of the file
and to get lines you can afterwards analyze you should use
if(file){
   file.println("Your MQTT payload");
   Serial.println("File was written");
   file.close();
} else {
    Serial.println("File write failed");
}

and do not forget to close after the operation.
EDIT
As reaction to the comments here a "clean solution" as a function:
bool writeLog(const char fileName[],  char payloadMqtt[]) {
  File logFile = SPIFFS.open(fileName, "a");
  if (!logFile)  {
        Serial.println("logFile open failed");
    return false;
  }
  else {
    //Write data to file
    Serial.println("writing Data to logFile");
    logFile.print(payloadMqtt);
    logFile.close();
    return true;
  }
}

You call it with:
writeLog("/myfilepath", payload);

and can also be used like
if (writeLog("/myfilepath", payload)) Serial.println("Log save success");
else Serial.println("Log save failure");

Hope this helps to understand the nature of SPIFFS/LittleFS/SD operations

Sorry, I put FIle file; outside the setup(), but I open it inside. And it doesn't make much sense to me to open the file inside the loop. Also, my problem is that payload is a byte array so I guess I need a casting to write that into the file

You should only open before writing and close after writing, we are on a MCU not a full scale OS. Look into the lib spiffs_api.h/cpp to see what open means for your memory (aside from unwanted errors andother probs) . If your payload is a char array you just use file.println(payload)


text:
how do i convert to assembly code (AVR assembly) from arduino
i have code in the Arduino ide for a temperature sensor that shows the temperature on three 7 segment displays, it shows the temperature to one decimal point. using an arduino uno. I am struggling to convert the below code to assembly. can someone please help?
#include <SevSeg.h>
#include "SevSeg.h" // Included the library for the 7 segment display
SevSeg sevseg;  // Created an object
const int sensor_pin = A0; // initialized A0 for LM35 sensor
float tempc;  //variable to store temperature in degree Celsius
float sensor_out;  // variable to store the output
unsigned long interval = 1000; // the time we need to wait
unsigned long previousMillis = 0; // millis() returns an unsigned long.
void setup() {
 pinMode(sensor_pin, INPUT);  // Declared the sensor pin as Input
 byte numDigits = 3;      it to 3.
 byte digitPins[] = {10, 11, 12};
 segment displays
 byte segmentPins[] = {9, 2, 3, 5, 6, 8, 7, 4};
 pins of displays
 bool resistorsOnSegments = true;
 bool updateWithDelaysIn = true;
 byte hardwareConfig = COMMON_CATHODE;   // Type of display we are using
 sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
 sevseg.setBrightness(100);
 }
 void loop() {
  sensor_out = analogRead(sensor_pin);
  tempc = (sensor_out * 500) / 1024;
  tempc = tempc - 32;
 tempc = tempc * 5;
 tempc = tempc / 9;
 delay_function();
 sevseg.refreshDisplay();
}
void delay_function() {
unsigned long currentMillis = millis();
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
sevseg.setNumber(tempc, 1);   // Sets temperature on display
previousMillis = millis();
}
}

It would be easier to just let the compiler do it for you.

Why would you want to? What are you going to do with the assembly code?

https://forum.arduino.cc/index.php?topic=50169.0

According to a comment in the code, you are using an LM35, which is calibrated in Celsius (10 mV/°C). Yet the code does what looks like a Fahrenheit to Celsius conversion, which would make sense with an LM34, but not with an LM35.

with the assembly code i am going to use it in atmel studio to upload it onto an arduino and run the program. i also want to see what it looks like and i am also learning assembly code.

@dirshanramlall You can upload the .hex file using atmel studio as well!


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

yes, if the HID has an input channel

the 'some firmware' would have to support it

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

doesn't NicoHood support Serial and HID together?


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

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

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

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


text:
Chance light intensity in a pwm pin using LDR using Arduino UNO
I am using proteus and Arduino software to simulate my circuit. What I need to do, is to have an LDR in my Arduino uno. When light intensity increases in my LDR, I need another LED which is connected to a PWM pin to react to this change in light intensity. The more light LDR detects I need my LED to get dimmer and vice versa.
I have uploaded my circuit picture. The potential probe that I have connected to LDR works fine, the more light there is, the higher voltage it has (ranged from 0 to 5v) but on the other side, my LED does not work properly. If LDR detects little light. my LED is turned on, surprisingly with no current passing the ammeter, when light intensity is less than some threshold, my LED starts blinking! again, no current passing through the ammeter! and the voltmeter always varies between 0 and 4.9 (voltmeter on my LED), it never has a value between 0 and 4.9, it seems it acts digitally, while I have used analogWrite. By the way, I mention again that I need my LED pin to have PWM.This is my code in Arduino:
void setup() {
Serial.begin(9600);
pinMode(A0,INPUT);
pinMode(10,OUTPUT);
}

void loop() {

int sensorValue = analogRead(A0);
Serial.println(sensorValue);

analogWrite(10,sensorValue/4);

delay(200);
}

By the way, I know the way I have coded, it means that LED follows the torch, and the more light intensity LDR feels, the brighter LED gets, I need it to be vice versa but I also did not know how to use it.
And finally, a minor question:
what does the  Serial.println() function do? I mean it must print it's content somewhere, but where? This feature would be useful for debugging, but I don't know how to see its printed value. I should also say that my code is a modified version of analogReadSerial example.
Thanks.

upvote for asking about the serial.print() ... it prints to the serial port ... you can view the output using the serial monitor in the arduino IDE ... you can also use any other serial terminal program such as PuTTY

@jsotola Hello.Thanks for your comment. It worked about printing issue, however I still have my main issue. I don't know how to upvote your comment, it only has a flag icon on it.

@jsotola By the way, I don't know why it only worked once. I mean it pooped up for the first time, but later times, when I tried to print it, didn't pop up :|

Welcome to the wonderful world of simulation. I'll bet if you did it with real hardware your results would be very very different.

@Majenko How is that possible? You mean it's IDE's fault and my board and code is perfectly ok?

I mean simulation is only an approximation, and Arduino simulation is notoriously bad.

It'd be better to use oscilloscope for watching PWM signal on the LED pin. It's hard to measure something even in real life if you don't have meter that supports measuring duty cycle or so.


text:
switching two relays without delay using millis
I have an Arduino-uno and two relays. Each relay has two switch on for two seconds at regular intervals.
total loop time relay 1 and relay2 is 1800 seconds.
relay 1 - 2 on,360 off,2 on,600 off,2 on,430 off,2on,402 off.
relay 2 - 12 off, 2 on, 358 off, 2 on, 606 off, 2 on, 478 off, 2 on, 338 off.
Can somebody help me on a code for this please.

Do both have a total time of 1800, then I suppose they have to be in sync. You can start by making an array or struct with the numbers. The blink without delay example runs at 1 second interval. Use that 1 second interval to check the array or struct. Have you use the 'enum' before to define numbers to actions?

When the blink without delay is used, the first second is one second after the arduino has turned on. The pinMode for relay 1 sets it off. That means after turning on the arduino or after a reset, relay 1 is off for one second. Is that okay? Assuming that a HIGH turns the relay on and a LOW output turns the relay off.

Yes, both the relays have a total time of 1800 seconds, and normally HIGH turns the relay off, and LOW turns the relay on. I tried already a few time to work with the blink without delay code (on advise), but I don't know how to code the on and off times in the code - Jerry.

What about arrays, enum and struct? are you familiar with those?

Instead of asking me all those questions, which I can only answer partly, because my little knowledge in this field. Is it not easier for someone to give me a workable sketch, so that I can try and play with it? Or is this to difficult or not possible?

this is a typical application for Blink Without Delay

// Turn leds on and off at certain times.
//
// When the digital output pin is HIGH, then the relay is off.
// When the digital output pin is LOW, then the relay is on.

enum actionEnum {
  RELAY1_ON,
  RELAY1_OFF,
  RELAY2_ON,
  RELAY2_OFF,
};

struct tableStruct {
  unsigned int time;
  actionEnum action;
} const table[] = {
  { 0, RELAY1_ON},
  { 2, RELAY1_OFF},
  { 2 + 360, RELAY1_ON},
  { 2 + 360 + 2, RELAY1_OFF},
  { 2 + 360 + 2 + 600, RELAY1_ON},
  { 2 + 360 + 2 + 600 + 2, RELAY1_OFF},
  { 2 + 360 + 2 + 600 + 2 + 430, RELAY1_ON},
  { 2 + 360 + 2 + 600 + 2 + 430 + 2, RELAY1_OFF},
  // remaining 402 for a total of 1800
  { 0, RELAY2_OFF},         // not needed, it is already off
  { 12, RELAY2_ON},
  { 12 + 2, RELAY2_OFF},
  { 12 + 2 + 358, RELAY2_ON},
  { 12 + 2 + 358 + 2, RELAY2_OFF},
  { 12 + 2 + 358 + 2 + 606, RELAY2_ON},
  { 12 + 2 + 358 + 2 + 606 + 2, RELAY2_OFF},
  { 12 + 2 + 358 + 2 + 606 + 2 + 478, RELAY2_ON},
  { 12 + 2 + 358 + 2 + 606 + 2 + 478 + 2, RELAY2_OFF},
  // remaining 338  for a total of 1800
};

const unsigned int totalTime = 1800;  // total amount of seconds for sequence
unsigned int seconds;

unsigned long previousMillis;
const unsigned long interval = 1000;  // 1000 ms is one second

const int relay1Pin = 2;
const int relay2Pin = 3;

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

  // The relay is off when the pin is high.
  // Turn output high before setting the pinMode.
  // Then the output changes from a floating pin to high,
  // and the relais will not be activated.
  digitalWrite(relay1Pin, HIGH);
  pinMode(relay1Pin, OUTPUT);
  digitalWrite(relay2Pin, HIGH);
  pinMode(relay2Pin, OUTPUT);
}

void loop() {
  // A one-second timer with millis
  if (millis() - previousMillis >= interval) {
    previousMillis += interval;

    // Scan table
    for (int i = 0; i < int(sizeof(table) / sizeof(tableStruct)); i++) {
      if (table[i].time == seconds) {
        switch (table[i].action) {
          case RELAY1_ON:
            Serial.println("Relay 1 on");
            digitalWrite(relay1Pin, LOW);  // low = relay on
            break;
          case RELAY1_OFF:
            Serial.println("Relay 1 off");
            digitalWrite(relay1Pin, HIGH);  // high = relay off
            break;
          case RELAY2_ON:
            Serial.println("Relay 2 on");
            digitalWrite(relay2Pin, LOW);   // low = relay on
            break;
          case RELAY2_OFF:
            Serial.println("Relay 2 off");
            digitalWrite(relay2Pin, HIGH);  // high = relay off
            break;
          default:
            Serial.println("Error, a bug in the sketch");
            break;
        }
      }
    }

    seconds++;
    if (seconds >= totalTime) {
      seconds = 0;
    }
  }
}

Thank you very much. I am going to try this, and I will let you know.

@Jerry I have tested it and confirmed that it is working according to the information that you gave.

Working perfect, thank you very much, Jerry.

@Jerry, I'm glad it is working for you. Do you see how it works? Any command can be put into the table. For example: "measure the temperature" or "make a beep". In the one-second-millis timer, the whole table is scanned to check if something needs to be done.


text:
Adrduino IDE doesn't show port for connected ESP32 module
When I go to select port there's no port for the connected ESP32 module. I am using Mac OS Mojave, mac mini.
The port I find is

maybe the reason is that the ESP32 module is not connected

Or maybe it uses a USB to UART chip that needs drivers installing, and you haven't installed them.

@jsotola it's connected for sure, it lights up and works with my windows.

@Majenko this is also my suspect. how do i know which driver and where to find and install them ?

Read the number on the chip. CH350G?

I see ESP32-WROOM-32D...

this one infact [https://www.amazon.fr/SeeKool-ESP-32S-d%C3%A9veloppement-Bluetooth-Ultra-Low/dp/B07DPP3BGZ/ref=sr_1_4?__mk_fr_FR=%C3%85M%C3%85%C5%BD%C3%95%C3%91&dchild=1&keywords=esp32&qid=1586468528&sr=8-4]

It's the number on the little black square chip you need. CP2102 or something is it?

It is written AMS1117, 3.3 XJS88

No, I said square, not rectangular.

oh hha unfortunately there's nothing written on it, totally black!

but we are in luck, from amazon listing i see it's CP2102!

@Majenko so what should i install? thanks

No idea, I'm not a mac user, and the way OS X is going I can see a lot of people jumping ship from OS X to something that they can work in.

@Majenko what you mean, what's wrong with OS X ?

Well, already in Catalina lots of things are failing to work (no 32-bit, increased obnoxious security, etc). And in the near future loads of drivers (kexts) will fail to work at all. My guess is that, at least for a while, the CH340G drivers will cease to work, and then be an even bigger pain to get going. Bybye cheap arduino clones on the Mac...

yes I have tried with some drivers like CH340G from other post solution but didn't work


text:
How to get 3v3 pins on Arduino Mega Sensor shield v2.0?
I am using Arduino mega and a sensor shield (picture attached below). I need to connect three different wires to 3.3 V input. Can anybody suggest how can I achieve the same? What voltage do the VCC pins of all digital and analog pins on the sensor shield have?

Is there a pin marked with 3.3 or similar? If not, you will need an external voltage regulator. If yes, you should make sure, that is can provide enough current for the sensors

They are all 5V as the Mega2560 uses 5 V logic.  However, there is a 3V3 pin at the bottom, second pin from the left, that you could use:

However, unfortunately, the pin isn't protruding above the shield, so you'll have to make an ugly solder link to the top of the pin. Either that, or remove the row of pins and replace with a female header (carefully avoiding the SD card pins):

As an aside, the Iteaduino MEGA 2560 works at 3V3 but unfortunately the Mega shield that you have won't fit it.

The Uno equivalent of your shield will fit it though:

I guess the shield would still provide 5 V from the 5 V pin of the 3.3 V Mega

I fix it solding into the board sensor shield the point where there is the pin 3.3v


text:
Is there a way to get my MacBook's date and time into Arduino IDE?
I am using a DS3231 RTC module. It requires to set the time every time it is reset. I was wondering if I could read my MacBook's time and date and feed into the module at the setup stage. Is this possible?
P.S. I do not have to use a battery.

Actually the whole point of an RTC is that it has a battery backed up clock that does NOT reset on power loss.

Yes. But due to some reason, I have a RTC without a battery backup. I had myself opened the Amazon packing today and unboxed the module. And the bottom side has no battery.

So.... attach a battery?

without the battery you don't need the RTC module. you can use the TimeLib

Please note that some of these modules have a (badly designed) charging circuit, and thus require a rechargeable coin cell (LIR2032). Or you can remove the charging resistor from the board.

What I've do with one of my clocks if create an interactive serial console, where I could type the current time, when the code saw that the RTC was reset. There is no way to get the time from the USB host without some software running on the host, or like I did, some manual serial data entry.

You can use __DATE__ and __TIME__ compiler time constants in IDE and do check inside of your setup() function if the RTC clock is zeroed then parse and set compile time values.
char cr[] = __DATE__;
char ct[] = __TIME__;

At the compile time these macros will be replaced with text constants "Apr  4 2019" and "10:35:22" respectively.

You could use softRTC library to get date/time from your system. So program flow could be get date/time from softRTC library during setup part and then use those variables in loop set your DS2321 RTC which will always be running till you poweroff.

softRTC is relying on the preprocessor. So each time you want to set the time you will have to open ArduinoIDE and compile+upload the sketch. This is not going to work in stand alone. Beside Atmel only guarantees 10.000 write cycles when uploading code.

I can't find softRTC library. how does it solve the use of DS3231 without battery?


text:
can an ISR change the value passed by pointer while the subroutine is executing?
So I am working on a project where the board plays a song on a buzzer using PWM and I want the song to stop when i press an external button
typedef enum stateType_enum{
waitPress, debouncePress, waitRelease, debounceRelease
} stateType;
volatile stateType state = waitPress;
volatile bool deviceOn = false;

int main(void){
   sei();
   while(1) {

   switch(state){
     case waitPress:
       break;
     case debouncePress:
       delayMs(100);
       state = waitRelease;
       break;
     case waitRelease:
       break;
     case debounceRelease:
       delayMs(100);
       state = waitPress;
       break;
   }

   if(deviceOn){
       triggerAlarm(&deviceOn);
   }
   _delay_ms(100);
}

ISR(PCINT0_vect){
   if(state == waitPress){
      state = debouncePress;
   }
   else if (state == waitRelease){
      deviceOn = !deviceOn;
      state = debounceRelease;
   }
}

My real question is, can I send the deviceOn as a pointer to the song?

Which arduino board do you use and which version of the arduion ide? please show a full sketch, I want to see the function triggerAlarm. Please try to explain what you want to achieve. You can send anything to the song, but that depends on what you want, which I don't understand. Can you change everything and use millis instead of delays?

Please show triggerAlarm()... why do you want to pass it if its argument is a global variable? I think there's no need for that.


text:
Can you activate the whole pixel on LCD?
I'm working on a project where I'm trying to display the level of a filled tank through ultrasonic, then displaying it on a 16x2 LCD. I'm trying to do it through the whole LCD Pixels, such that when the tank level is full, the first 5 pixels are activated (as what happens when you connect the LCD initially without having any code for it, the whole pixels are turned on, giving 16x2 white rectangles, as shown in the picture below). Is there a way to activate an entire pixel on the LCD?

You can define your own characters to display. Is that what you want?

@Majenko Nope. My issue is not to display characters. However, I want to display the white rectangles, as shown in the picture. Is there a code to activate the entire rectangle pixel?

You can define your own characters. Make a character that has all the pixels you want set.

@Majenko Oh I see. I assumed there was an easier way, since it just activates the entire rectangular pixel. Thanks for your help!

Check the datasheet for your display. It should give you the predefined characters. One might be a solid block.

that picture shows all of the pixels in the first line activated ... there are no in-between pixels

The LCD is made up from 32 characters each is 5x7 pixels in size, with a 1 pixel gap between each character.
You can never put anything in the gap between the characters, as there is just nothing there.
But what you can do is define your own characters to fit within the 5x7 pixel rectangles.
Some variants of the HD44780 have character 255 as a solid block, but not all (it depends on what language the ROM is).  If you have one that has that character you can just print it with lcd.print("\xff") or lcd.write(255).  If it doesn't it will print ÿ instead. In that case you will have to define your own character.
One benefit of defining your own characters is that you could then do partial blocks to give you a higher resolution.  Here's an example:

You can find that example and the code that goes with it here.

The LCDs like the one you picture display characters. That is all they do. You can't address the pixels in the display.
And as a point of clarification, you are talking about the 5 pixel by 7 pixel character blocks on the display as if a character is a pixel. It's not. A character block consists of 5 x 7 pixels.
Some versions may have a pre-defined solid block character, as Majenko said in their answer. You could print as many of those solid blocks as you want.
You could also define a single custom character that displays a solid block and print as many of those as you want.
As a third option (again from Majenko's excellent answer) you could define 5 different custom characters, each with a different number of columns of pixels filled in. You could then write code that displayed solid blocks for all but the last character, and then one of the 5 partly filled custom characters, and get a finer resolution of simulated bar graph.
All that said, remember, the LCD display can only display 5x7 blocks with blank space between. The LCD is built without any pixels between the characters, so there will always be blank spaces.
There are other pixel displays you could use. (I've seen OLED displays where you can control every character individually.)


text:
Mixed SHARP IR Sensor Readings
I'm using the GP2Y0A21YK Sharp IR Sensor in a ball and beam system where I'm trying to balance the ball in the center of the beam using the IR Sensor as a distance locator and a servo motor to tilt the beam. I'm using a PID Controller for the system. However, something odd happens when I apply the code. When the servo motor is disconnected, I'm getting accurate readings of the location of the ball. However, as soon as I plug in the servo motor, the distance reading is completely off and inaccurate. I've read that powering the Arduino using both the USB port and Plug will make the readings more stable. However, I've tried that and it only improved the readings by a small bit. What can be causing this problem? Since the code and the schematic would take a bit of a space, kindly let me know if they are needed and I'm happy to provide.

It is likely your power source supplies insufficient current to power both the servo and the Arduino reliably.
It is also possible that the motor in the servo is creating noise on the power rails and inducing unexpected behavior in the Arduino.  But the former is more likely.
Consider using a power source which can supply more current.  For instance, D size cell batteries can supply much more current than a small 9 volt battery.
Also consider using a separate power source for the Arduino and the motor.  Many resort to this option for such projects as you describe here.

Thank you for your reply. How do you suggest I power the motor separately? Since it's plugged to the 3.3V port on the Arduino. Would two AAA batteries do the job?

With out knowing more about the servo it is difficult to tell.  However, Alkaline Primary AAA batteries provide less current than AA sized, and those less than C sized.  The same can be said for D size. This is why I suggested the largest commonly available battery.  To address a possible and likely problem you are having.  For common servos only the controlling wire is connected to the Arduino.  The ground is common to both the Arduino and servo.  The power leads of each can be connected to one sufficiently large or two smaller power sources.  Usually these need to be the same voltage.


text:
RA-01 Lora Radio not turning off
am trying to completly turn off ra-01 radio and esp8266 and turn it on by external trigger but i have issues getting the lora radio to turn off
#include <LoRa.h>
#include <ESP8266WiFi.h>

void setup() {
  Serial.begin(115200);
  // while (!Serial);

  // disable wifi
  WiFi.mode( WIFI_OFF );
  WiFi.forceSleepBegin();

  // LoRa
  #define dio0 2
  #define ss 15
  #define rst 16
  //#define rst 32

  LoRa.setPins(ss, rst, dio0);
  LoRa.setSyncWord(0xF3);

  Serial.println("LoRa: OK");

  if (!LoRa.begin(433E6)) {
    Serial.println("LoRa: Fail!");
    while (1);
  }
  Serial.println("Sending packet: ");

  // send packet
  LoRa.beginPacket();
  LoRa.print("c");
  LoRa.endPacket();
  LoRa.end();

  // shutdown spi
  SPI.end();
  digitalWrite(dio0, HIGH);
  digitalWrite(ss, HIGH);
  digitalWrite(rst, HIGH);

  // deep sleep
  ESP.deepSleep(0);
}

void loop() {

}``

what is your question?

Turning off Lora Radio?

"but i have issues getting the lora radio to turn off" So how do you notice that you have a problem with it? Sleep current too high? Any more details available?


text:
error when trying to upload code to esp8266
Sketch uses 344,292 bytes (32%) of program storage space. Maximum is 1,044,464 bytes.
Global variables use 32,276 bytes (39%) of dynamic memory, leaving 49,644 bytes for local variables. Maximum is 81,920 bytes.
error: Failed to open COM1
error: espcomm_open failed
error: espcomm_upload_mem failed

please help me to fix this issue.

when I am trying to upload code to nodeMCU board I am getting this error message--   Sketch uses 344,292 bytes (32%) of program storage space. Maximum is 1,044,464 bytes. Global variables use 32,276 bytes (39%) of dynamic memory, leaving 49,644 bytes for local variables. Maximum is 81,920 bytes. error: Failed to open COM1 error: espcomm_open failed error: espcomm_upload_mem failed

I am sending error message coz I want solution for that.. what do u expect to send ??????????????????????????????

Try holding down the flash button when uploading the code to the board.
The ESP8266 and the ESP32 need certain buttons held down to open the COM port to upload code.


text:
error for uploading code to esp8266 module
I am getting error for uploading code to esp8266 module. I have installed cp2109 drivers also but at the time of uploading getting follwing error message:
Sketch uses 344,292 bytes (32%) of program storage space. Maximum is 1,044,464 bytes.
Global variables use 32,276 bytes (39%) of dynamic memory, leaving 49,644 bytes for local variables. Maximum is 81,920 bytes.
warning: espcomm_send_command: wrong direction/command: 0x00 0x08, expected 0x01 0x08
warning: espcomm_send_command: wrong direction/command: 0x00 0x08, expected 0x01 0x08
warning: espcomm_send_command: wrong direction/command: 0x00 0x08, expected 0x01 0x08
warning: espcomm_send_command: wrong direction/command: 0x00 0x08, expected 0x01 0x08
warning: espcomm_send_command: wrong direction/command: 0x00 0x08, expected 0x01 0x08
warning: espcomm_send_command: wrong direction/command: 0x00 0x08, expected 0x01 0x08
warning: espcomm_send_command: wrong direction/command: 0x00 0x08, expected 0x01 0x08
warning: espcomm_send_command: wrong direction/command: 0x00 0x08, expected 0x01 0x08
warning: espcomm_send_command: wrong direction/command: 0x00 0x08, expected 0x01 0x08
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed

Please help me to solve this problem

Try pressing and holing the flash button while pressing reset once. After that you will see a blink of the blue LED, release the flash button and try again.

I have done the same process of Reset and flash button blue light blink but yet not able to upload code getting this error message now:                        Sketch uses 344,292 bytes (32%) of program storage space. Maximum is 1,044,464 bytes.
Global variables use 32,276 bytes (39%) of dynamic memory, leaving 49,644 bytes for local variables. Maximum is 81,920 bytes.
error: Failed to open COM1
error: espcomm_open failed
error: espcomm_upload_mem failed

the board isn't in flash mode

Did you select the COM port properly because it is very unlikely that it is on COM port 1


text:
Error while compiling CODE
Hey guys I have run my example with esp8266 2.4.2 version now I'm getting following error while compiling- C:\Users\Shree\Desktop\FirebaseDemo_ESP8266ex\FirebaseDemo_ESP8266ex.ino:21:29: fatal error: FirebaseArduino.h: No such file or directory #include  ^ compilation terminated. exit status 1 Error compiling for board NodeMCU 1.0 (ESP-12E Module).
I'm trying to run FirebaseDemo_ESP8266 example but getting problem to compile that code. plzzz help me to solve this issue.

install the library

which libraries I need to install.?

FirebaseArduino.h?

It's strange that the missing library isn't mentioned in the error message, just an ^. Or is it a copy and paste error?

FirebaseArduino.h: No such file or directory it is mentioned in your error message

Hey guys Thank you sooo so much to all of you for helping me. Finally after installing FirebaseArduino library now I'm able to compile code without any error.


text:
Error when HX711_Arduino_Library installed
First I'm getting this error #include  no such directory. Then HX711_Arduino_Library installed. Now getting following errors:
Arduino: 1.8.9 (Windows 7), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), 4M (no SPIFFS), v2 Higher Bandwidth, Disabled, None, Only Sketch, 115200"
sketch_jul18a:34:22: error: no matching function for call to 'HX711::HX711(int, int)'HX711 scale(DOUT, CLK);
                      ^
C:\Users\My Lappy\Desktop\sketch_jul18a\sketch_jul18a.ino:34:22: note: candidates are:In file included from C:\Users\My Lappy\Desktop\sketch_jul18a\sketch_jul18a.ino:23:0:
C:\Users\MyLappy\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note: HX711::HX711()
   HX711();
   ^
C:\Users\MyLappy\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note:   candidate expects 0 arguments, 2 provided
C:\Users\MyLappy\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note: constexpr HX711::HX711(const HX711&)
 class HX711
       ^
C:\Users\MyLappy\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note:   candidate expects 1 argument, 2 provided
exit status 1
no matching function for call to 'HX711::HX711(int, int)'
Help me with this.

There are several HX711 Arduino libraries. Do you have the right one? I would guess no as the library you have installed does not have the constructor that the sketch is using. Either use the correct constructor from the installed library or install another library that has that constructor.
Cheers!

I'm Not much familiar with Arduino software. can u plz help me with easy way..?? library with constructor not getting this??

Check the file HX711_Arduino_Library\src/HX711.h and the HX711 instance in your sketch. Use the constructor that matches the library. Change: sketch_jul18a:34:22: HX711 scale(DOUT, CLK);

I have Checked the file HX711_Arduino_Library\src/HX711.h but not getting this Change: sketch_jul18a:34:22: HX711 scale(DOUT, CLK); with what I have to replace this..????

Start with the example sketch: https://github.com/bogde/HX711/blob/master/examples/HX711_basic_example/HX711_basic_example.ino

yes sir,  github.com/bogde/HX711/blob/master/examples/HX711_basic_example/ this link code running properly. getting this message Done compiling without any error. But for my code still getting same error message: no matching function for call to 'HX711::HX711(int, int)'.. Guide me for next step to solve this issue.

Please post your sketch and we will help you fix it.

Not able to post my sketch its too long.. what can I do now?

Locate the line that starts with HX711 and remove the parameters to the constructor. Add a line to the setup() the calls HX711::begin() with the pin parameters. And now you should mark the question as answered :)


text:
Looking for software allowing for Arduino-based project "mocking" / "wireframing"
I'd like to be able to import a number of components (e.g Arduinos, MPU6050s, displays, motor drivers, LEDs, etc) into an app of some sort then be able to wire those components to each other for the purpose of being able to refer to this crude schematic at a later point or to share it with others. I tried importing things into Eagle, but that seemed like an absolute overkill (if Eagle can be used for something like this, what would the best approach be?). Does software that solves that particular issue exist? Think of it like wireframing for hobby electronics projects...
Please forgive the absolute layman explanation.

Fritzing is the normal Arduino user's schematic tool.

or https://www.tinkercad.com

@Majenko Absolutely what I was after! Thank you!

tinkercad is nice because it will actually run the sketch and simulate hardware like blinking LEDs.


text:
ESP01 and Arduino - Serial port confusion
I'm trying to understand how to think about ESP01 devices and arduino connectivity
I purchased one of the USB programmers from Ebay to program the ESP01 - this works nicely, I can see the ESP doing things (I have it pinging a server sending data back and forth)
Obviously, the ESP01 has very few GPIO pins, so I'm interested in connecting to an arduino so I can combine the Arduino's IO with the Wifi on the ESP, and this is where I'm getting a little stuck. I'm assuming I have to connect the RX pin on the Uno to the TX on the ESP and the TX on the Uno to the ESP RX to set up the connection, but I'm confused as to which serial port to use on the Uno.
Specifically:

are the TX/RX pins on the arduino actually the same serial port as the USB connector - i.e if my intent is to plug the arduino into a computer to talk to it over USB, should I not then re-use the TX/RX pins to talk to the ESP
if so, should I look to software serial or something similar and use other IO pins on the arduino to connect to the ESP01

... Also, as an aside, if I get this all working, do I still need the USB programmer, or can I then program directly from the arduino?

yes and yes. and you can use the Arduino to upload to esp-01, but it is not so simple. I recommend you to upload a firmware to esp-01 with the programmer and use a corresponding library in Arduino. for example https://github.com/jandrassy/WiFiEspAT

Cool - thanks, so the first yes, is that the RX/TX pins are the same serial connection the USB port uses? (just making sure I fully understand)

yes. Atmega328p has only one UART  peripheral for hardware Serial.

It's a pity that all newbies get hooked on the artificial (and false) necessity of combine ESP01 and Arduino in a single project. A newbie should let the complexities of attaching one device to another to the future, and just start with a ESP8266 version with more GPIOs, like ESP12.

@mguima, esp8266 was developed to be used as WiFi adapter, not as standalone MCU. do you want to write sketches for CC2541 on HC-11 BLE adapter? it is a MCU too.

@juraj, this question is dumb and pointless. I didn't say anything about writing sketches for CC2541 or for HC11 - or for TMS1000, neither. But, for most of the things that a newbie could want to do, simple things like blink a LED or switch a relay, an ESP8266 is enough, and, YES, in a non-critical environment, ESP8266 can be used as a standalone CPU. A professional that would REALLY need to use Arduino and ESP8266 surely would not asking for help here in StackExchange. But, most of times, using ESP8266 as a Wifi adapter for an Arduino is just a unnecessary and complicated hype

@juraj It's NOT TRUE that "esp8266 was developed to be used as WiFi adapter, not as standalone MCU".  It seems that you said that only for disagree with what I said. Can you point to sources for this information? ESP8266 datasheet says "With the complete and self-contained Wi-Fi networking capabilities, ESP8266EX can perform either as a standalone application or as the slave to a host MCU."  If it were intented to be just a WiFi adapter, why would it have peripherals and available GPIO's?

@mguima, it doesn't say with what goal it was developed. It would be very strange to waste so many pins for boot configuration on a standalone MCU. Most of the  docs are about integration with a host MCU. There was no published SDK initially.

The Arduino UNO only has one serial port. That is pins 0/1 (RX and TX), which is mapped to the Serial object.
Those pins and that object are also used for communication with the PC through the USB connection. That means you can't easily use them for both PC communication and ESP8266 communication. It's possible, but it gets messy.
That is why many people use SoftwareSerial because that can work on any combination of pins on the Arduino that you like.

... Also, as an aside, if I get this all working, do I still need the USB programmer, or can I then program directly from the arduino?

Again, that is possible, but very messy. You could possibly get things to pass through from Serial to a SoftwareSerial instance, but it's not reliable (SoftwareSerial in general is not reliable for sustained transfers of data), and using the Arduino as a dumb UART interface would entail changing the wiring to pins 0/1 when you wanted to program.
So it's far simple to just use your USB interface for programming. Either that or set up OTA programming for the ESP8266 so you don't even have to use wires.

This is great, thanks for the guidance.


text:
Warm Atmega328p and weird power behaviour
I recently built a circuit with an atmega328p (which I have never used before standalone) and attached all the neccessary components (crystal, capacitors etc). However, when I powered it up with a regulated 5v input, I noticed the chip getting a little bit warm. Not hot, the temperature seems quite constant, and everything still works just fine. Another strange thing though, is when I connect the VCC to AVCC together as specified in the datasheet, the circuit doesn't work at all: The LCD screen just shows solid blocks at the top. When I disconnect the wire again, everything is back to normal. What went wrong? It is perfectly possible that there is a small solder bridge on my perfboard.

Please say more about your "circuit with an atmega328p", such as what is connected to the MCU and how. Running warm suggests you may be trying to supply to much current to other devices through the MCU. A schematic would help; so would  part numbers for the external devices, such as the LCD which you only mentioned in passing.

Do you have a multimeter, so you can measure the current usage? Could you post an image of your setup, or a schematic?

Current Usage at 10v (going into 5V regulator) is 0.01 milliamperes

LCD is just a generic 16x2 LCD I got on ebay, I have used it with an Arduino uno for a long time with no issues.

What kind of regulator did you use? Current input doesn't necessarily tell you about the current consumption of the board and, by itself, nothing about MCU current. In fact the regulator circuit on an Arduino board would disispate a great deal of the current drawn from a 10v supply. And 10 micro-amps? Really? Schematic please.

@JRobert  I cannot provide a schematic because I didn't make one. The atmega chip still heats up even when there is nothing connected at all. I have double checked that the crystal and ceramic capacitors are wired properly and they are. The voltage regulator is one that I salvaged from an old power supply. I provided it with 19v for about 10 minutes (which is the voltage that I will be using) and it heated up to the point that I couldn't touch it, even though the datasheet says this is well within its recommended range. The read on my bench psu said 0.01 amps.(not milliamps, my mistake)

I also tried powering it from an arduino uno board and although I can upload code and everything works properly, the chip still warms up.

I think you have to add more details about your circuit before anyone could see what's your problem, plus are you sure from that voltage regulator you salvaged? it can be a wrong value regulator, I recommend buying one or telling us it's name or number, lastly supplying a 19V to a 5V linear voltage regulator is BAD because those volts will be dissipated as heat that could rise dramatically till you couldn't touch, use lower voltage or just use a buck converter which will be ultimately better.

Sorry for late reply, I have hooked the board directly to 5V power supply and the chip draws 0.1 amps


text:
Adafruit v2.3 Motor Shield Initialization Failure
I would appreciate any help solving this as I have spent several hours trying to debug. My code seems to stop when I get to the initialization of the motor shield.

motorShield.begin();

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
#include <LiquidCrystal.h>

//CREATE LCD OBJECTm
LiquidCrystal lcd = LiquidCrystal(2, 3, 4, 5, 6, 7);

//CREATE MOTOR SHIELD OBJECT
Adafruit_MotorShield motorShield = Adafruit_MotorShield();

//SET MOTOR VALUES
Adafruit_DCMotor *frontRight = motorShield.getMotor(1);
/*Adafruit_DCMotor *rearRight = motorShield.getMotor(2);
Adafruit_DCMotor *frontLeft = motorShield.getMotor(3);
Adafruit_DCMotor *rearLeft = motorShield.getMotor(4);*/

//DEFINE SENSORS
#define centerTrigPin A2
#define centerEchoPin A3

//DEFINE SENSOR VALUES
long centerDuration; // Variable for the duration of sound wave travel
int centerDistance; // Variable for the distance measurement

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

  lcd.begin(16, 2); //Set LCD dimensions

  //motorShield.begin();

  //frontRight->setSpeed(50);
  /*rearRight->setSpeed(50);
  frontLeft->setSpeed(50);
  rearLeft->setSpeed(50);*/

  //frontRight->run(RELEASE);
  /*rearRight->run(RELEASE);
  frontLeft->run(RELEASE);
  rearLeft->run(RELEASE);*/

  pinMode(centerEchoPin, INPUT);
  pinMode(centerTrigPin, OUTPUT);
}
void loop() {
  //GET CENTER SENSOR
  digitalWrite(centerTrigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(centerTrigPin, HIGH);
  delayMicroseconds(10);
  centerDuration = pulseIn(centerEchoPin, HIGH);
  centerDistance = centerDuration * 0.034 / 2;

  if (centerDistance <= 10){
    //SERIAL OUTPUT
    Serial.print("OBJECT: ");
    Serial.print(centerDistance);
    Serial.println(" cm");

    //LCD OUTPUT
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("OBJECT");
  }else{
    //SERIAL OUTPUT
    Serial.print("DRIVE: ");
    Serial.print(centerDistance);
    Serial.println(" cm");

    //LCD OUTPUT
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("DRIVE");
  }//End Forward/Reverse Check
}//End loop

reduce your code to the minimum ... no LCD, no serial ... use an LED blink to indicate that the code is not frozen ... then add back serial so that you can send debug messages


text:
How do I make a proper long string scanner to detect specific tags in a stream of characters?
Here's my code:
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX, TX

void setup() {
    Serial.begin(9600);
    BTserial.begin(9600);
    Serial.println("Communication with HC-05 successfully started.");
}

bool is_uploading_book = false;
char c = ' ';
String recv_scanner = "";
void loop(){
    if (BTserial.available()) {
        c = BTserial.read();
        recv_scanner += c;
        if(recv_scanner.length() >= 50) {
          recv_scanner.remove(0, 1);
        }
        // I believe there's something wrong with the recv_scanner.
        if(is_uploading_book) {
          Serial.write(c);
        } else {
          if(recv_scanner.indexOf("(__BOOK_UPLOAD_START__)") >= 0) {
            is_uploading_book = true;
          }
        }
        Serial.println("\n\n" + recv_scanner + "\n\n");
    }
}

I'm sending a book (long text) in the form of characters one by one from my phone to my HC-05 module (and the Arduino).
My goal is to spot the tag "(_BOOK_UPLOAD_START_)" in the incoming characters.
Arduino allows me to receive the characters of the book one by one on each loop.
I'm storing those characters in a string called recv_scanner where I allow it's maximum size to be 50 characters and once it reaches those 50 characters, I start to remove the first character and add a new one on each loop (so it can only see 50 characters at a time because maximum String length is 200 and for my purposes, 50 is enough).
The thing is, it doesn't work properly.
When I Serial.println the recv_scanner on every loop (so I see how it progresses) it starts to look like this:
⸮qsnieq⸮cn .laslvanm.⸮⸮⸮d⸮alvuv⸮⸮urosqiam tr⸮⸮⸮

(It starts normally and then slowly progresses into this)
I have no idea what that is.
As far as my predictions go, it should show 50 characters and they should be parts of the books.
Is there something fundamental about Strings that I don't know of?
I'm doing this so I'm able to detect a tag (_BOOK_UPLOAD_END_) at the end of the book and finish uploading.
Feel free to ask my questions if something is unclear.

Another option is to not save the characters in buffer but instead check each one as they arrive to see if the character is the next in the tag sequence.
This has the advantage that you don't need a buffer to match the tag and you don't have to repeatedly search for the string in the buffer.
const char* TAG_STR="(__BOOK_UPLOAD_START__)";
int tag_pos = 0;
char c;
bool is_uploading_book = false;

void loop() {
  if (BTserial.available()) {
    c = BTserial.read();
    if (is_uploading_book) {
      //do book stuff
    } else {
      if (c == TAG_STR[tag_pos]) {
        // c matched the next character in the string
        tag_pos++;
      } else if (c == TAG_STR[0]) {
        // matched first char in the middle, restart
        tag_pos = 1;
      } else {
        // Did not match the next character so we should start over
        tag_pos = 0;
      }
      // The next character to match is the string terminator
      // so we must have matched the whole string.
      if (TAG_STR[tag_pos] == '\0') {
        is_uploading_book = true;
      }
    }
  }
}

Works perfectly!!! Thank you!

Unlikely to be an issue in this case, but the algorithm can fail for inputs like __BOOK__BOOK_UPLOAD_START__. At tag_pos 7, _ does not match U, so the algorithm returns to tag pos 1. But then B doesn't match _ and no detection is made. This problem will occur whenever the first character is repeated in the search string, and it can be avoided by comparing the search string with itself.

@Craig Sorry to bother you. Would you mind taking a look at this: https://justpaste.it/3wobv

@jpa yes that is a limit of this method.

I think your problem lies in the usage of the String class. Every time, that you concat a String variable, a new buffer for the result is allocated in the background via dynamic memory allocation. That can result in heap fragmentation, which eats up your memory pretty fast (especially on the smaller ones, like the Uno).
Instead you should use a char array as ring buffer. Let's define the buffer first and initialize it to zero:
#define BUFFER_SIZE    50
char buffer[BUFFER_SIZE] = {0};

Now we define position variables, where the valid data starts and ends in the buffer:
uint8_t buffer_start = 0;
uint8_t buffer_end = 0;

When buffer_start == buffer_end, the buffer is empty. When buffer_end is one position before buffer_start, the buffer is full. To put one character into the buffer we do the following (note, that c is the same variable, as in your code):
if( ((buffer_end + 1) % BUFFER_SIZE) == buffer_start)
{
    buffer_start = (buffer_start + 1) % BUFFER_SIZE;
}
buffer[buffer_end] = c;
buffer_end = (buffer_end+1) % BUFFER_SIZE;

What are we doing here? First we need to check, if our buffer is full. We are doing this by comparing buffer_start to the next position of your buffer_end. The calculation of the new position is where the magic happens. First we increment buffer_end by one and then we are taking the modulus with the buffer size. The modulus is the rest of an integer division. When the position is at the end of the buffer array, it will be (49 + 1) % 50, which is zero. That wraps the array end to the array end for us.
If our buffer is full, then we increment the start counter of the buffer. That means, that we are ditching one character at the start of our buffer to add one at the end (which is what you want to do). (Note, that normally with ring buffers you don't want to throw away data, so you refuse to put more data into the buffer, when it is full).
Then we store the received character into our buffer and increment buffer_end like described above.
The above principle is also called circular FIFO buffer (First In First Out), though there are missing some function to a real FIFO buffer, that you don't need here.

Now, that we have a ring buffer, which gets filled with the data, we also need to implement a function to find a string in the buffer, meaning an equivalent to the String.indexOf() method. It might look something like this:
int find_string(char str[], const char search[]){
    uint8_t start = buffer_start;
    uint8_t search_pos = 0;
    uint8_t result_pos = -1;
    while(start != buffer_end){
        if(str[start] == search[search_pos]){
            if(search_pos == 0) result_pos = start;
            search_pos++;
            if(search[search_pos] == '\0') return result_pos;
        } else {
            result_pos = -1;
            search_pos = 0;
        }
        start = (start + 1) % BUFFER_SIZE;
    }
    return -1;
}

Note, that this implementation is only roughly tested, not thoroughly.

Hello, thank you so much for the detailed answer. I'm struggling to figure out what and how to put in the find_string() function. if(find_string(?, ?)) { ... }

Could you please provide the code for my specific case because I'm not sure how to implement it properly.

First parameter is the buffer, second is the string to search for. You can use it just like the String.indexOf() method.

https://i.ibb.co/bJ3kS9v/img.png I don't think this is supposed to happen. Am I doing something wrong?

If the if(is_uploading_book) { } doesn't have the find_string checking, it works fine. The thing is, I need a find_string checking in there.

There seems to be something else wrong. Are you sure, that you have the correct baudrate configured in the HC-05?

I used Craig's solution and it works perfectly. My main problem seemed to arise when in the if (is_uploading_book) { } part I tried to again check for a second tag (UPLOAD_BOOK_END). Anyways, it works. Thank you so much for your time and attention. If you know what was going on I'm curious to hear.

Sorry, I honestly don't know what happened there. Both solutions don't use String, which is a good thing. Good that you now have your working solution

Let us continue this discussion in chat.


text:
Random without parameters
During a programming contest, I used the following line of code:
symbols[i] = random() & 0b11;

After the contest, when I looked into the Arduino reference, I found out random takes one or two parameters. Based upon that, I would expect the code not to compile. However, this code somehow worked as I expected. (Assigning a random number from 0 to 3) How come?

Simple: random() isn't an Arduino function - it's a standard C function.

Function random()
long random(void)
The random() function computes a sequence of pseudo-random integers in the range of 0 to RANDOM_MAX (as defined by the header file <stdlib.h>).
The srandom() function sets its argument seed as the seed for a new sequence of pseudo-random numbers to be returned by rand(). These sequences are repeatable by calling srandom() with the same seed value.
If no seed value is provided, the functions are automatically seeded with a value of 1.
-- AVR LIBC Manual Page

The Arduino functions themselves, actually use the random function without arguments. See source code


text:
Unable to interface using Softserial with ESP8266 and Arduino uno
I am trying to use a ESP8266 in an Arduino project, but I'm unable to get the basic Software serial interface working with it.
I have the ESP connected to a secondary 3.3v power supply. When connecting the RX and TX pins to the Uno's RX and TX, and uploading bare minimum code, I am able to interface with the module. Doing this I can connect to networks, send and receive packets, etc.
However, when connecting the ESP to any other pins and trying to implement a software serial interface, I am unable to get any response from the module. When sending it data I see the on board blue LED flash, so I think its receiving the data? I've found tons of example codes and Youtube videos that do what I'm trying to do. But following their steps I'm still not able to get any response.
I've tried using voltage divider circuits for the ESP's RX pin so its not getting 5v, but that hasn't seemed to change anything either. Any troubleshooting advice would be greatly appreciated.
One of the basic codes I've tried to get this to work:
#include <SoftwareSerial.h>

SoftwareSerial wifi(8,9);

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

  Serial.println("started!");

}

void loop(){
  if(Serial.available() > 0){
    byte b = Serial.read();
    Serial.write(b);
    wifi.write(b);
  }

  if(wifi.available() > 0){
    byte b = Serial.read();
    Serial.write(b);
  }
}

and with SoftwareSerial you wire TX to RX? and set the SoftwareSerial and the AT firmware to 9600 baud

Correct. And I've tried several different baud rates. The primary one I've been using is 115200 because that is what was working when directly interfacing with the ESP.

set the default baud rate of the AT firmware to 9600 baud and use that in Serial Monitor and with Software Serial

I'm going to get an FTDI to interface with it more reliably. I bought a lot of 4 and bricked one trying to change the baud rate through AT commands. I'm going to try to flash a new firmware on the bricked one and see where that takes me.


text:
Wroom 32 can't be recognized by Arduino 1.8.9 on a ubuntu 19.04 computer
I started by plugging my Wroom 32 into my Kubuntu desktop. I checked my /dev before and after, and found no changes. After opening Arduino IDE, I only found my other Arduino, the Arduino Due, in the port list. I already installed the ESP 32 board. What's wrong?

use lsusb and dmesg to determine what is happening ... i.e. run lsusb, plug the WROOM32 in, run lsusb again - anything new detected? run dmesg - check the output for errors regarding the new device

wroom32 has USB?

@Juraj - not the wroom32 itself. I have a "DOIT" ESP32 dev kit - the ESP32 module on it is a WROOM32 - perhaps the OP has a similar dev kit


text:
Using Servo on Timer3 on a Leonardo
I would like to use the Radiohead library and control a servo from the same Leonardo board.
Now the Radiohead library occupies timer1 and therefore cant be used together with the servo library. (It does offer to use timer2 which the Leonardo does not have.)
Are there any other Servo libraries that use timer3 or timer4 which the Leonardo has?
I have already tried:

https://github.com/nabontra/ServoTimer2  does not compile
https://www.pjrc.com/teensy/td_libs_TimerOne.html does not work (calling function blocks)

You could try manually sending the servo pulses with something like:
digitalWrite(SERVOPIN,HIGH);
delayMicroseconds(pulseWidth);
digitalWrite(SERVOPIN,LOW);

As long as the duration of the pulses is consistent, it doesn't matter if they don't occur regularly.
Downsides will be that there may be jitter if there are interrupts running, although there is the advantage that this will work on just about any pin.
If you are looking for a simple proof of concept, this may enough to test it out.

In file ServoTimers.hin standard Arduino Servo library change the timer
#elif defined(__AVR_ATmega32U4__)
#define _useTimer3
typedef enum { _timer3, _Nbr_16timers } timer16_Sequence_t;

on Windows the file ServoTimers.h is located in C:\Program Files (x86)\Arduino\libraries\Servo\src\avr

thanks, but this leads me to the compile error described here: https://forum.arduino.cc/index.php?topic=527356.0

you get that error only if you don't change the timer number to 3 as I write in the Answer

oki fixed the compile error. now the problem is that as soon as the servo is connected (pin 5) the radiohead library seems to stop working.

could it be a powering problem?

could be, i will try to run it with external power supply and not the usb.

interestingly the internal LED starts to pulsate a few seconds after i connect the servo pin. it stops that again a few seconds after disconnecting it.

I wonder if you could use this PWM version of the Servo library written for the Arduino MEGA? Looking at the code, it looks like you would have to remove the "else if (pin == 44)" and "else if (pin == 45)" blocks of code in the attach() and detach() functions in Update Servo_Hardware_PWM.cpp. Just guessing here. I haven't tried it out.
https://github.com/dadul96/Arduino-Servo-Hardware-PWM-Library

Comment from an anon user: Sorry, this won't work. I checked the datasheet for the ATMega32u4 and Timers 3 and 4 can't be used to change the state of a pin. So no, hardware servo control using the above code on a Leonardo.


text:
Applying 5v to analogWrite Pin
I am controlling a motor with an Arduino Nano, that motor is controlled by Cytron MD-10c motor controller.
i want to wire a momentary switch in parallel with the analog output PIN from the Arduino and PWM input on the MD-10c, the switch will connect the 5v output from Arduino to the PWN input on the MD-10c. Basically an override to go full power.
Is there any risk of damage with this sort of wiring with the switch?

why don't you do it properly .... use the switch as an input device to the Arduino .... then modify the software to output full power every time the switch is pressed

Not enough pins left on the arduino to accommodate this.

Mhh, if you do this, you definitely should save the PWM pin from sourcing too much current, when it goes to ground while the button is activated. I'm pretty sure, that the motor controller does not source much current, so you can simply add a current limiting resistor between button and PWM pin. Unfortunately I currently don't have an Arduino at hand to test this.

Slide switch with 3 pins should be the solution. It disconnects one pins and connects two others. So if we use pins like "(arduino) (motor) (5V)" when switch is "left" it connects (arduino) to (motor) and when it's "right" it connects (5V) to (motor) and the (arduino) is safely floating.

Yes, depending on the current that will flow.
If your PWM output pin is connected to 5V without a current limiting resistor, nothing will happen during the HIGH phases of the PWM, but you will short the input pin during the LOW phases.
According to the manual of your motor controller, you should be able to use a current limiting resistor to prevent this.
Since the ATMega328P on your Arduino Nano can sink a maximum of 40 mA, that resistor should be at least 125 Ohms. A resistor larger than 1 kOhm should work fine.
The other option would be installing a diode between your Arduino Nano and the motor controller.
This does not require the use of a current limiting resistor.
The motor controller would still work, since the minimal voltage for the pin state to be detected as HIGH is 3V (1), much lower than the ~4.3V you're left with after a diode.


text:
Is there a way to remove the 8.3 filename limitation on the SD.h library?
I need to be able to create text files on my SD card that are with names longer than 8 characters (which is what the SD.h currently limits me to). A choice would be to move to the SDFat library but before considering that option, is there a way to just remove the limit on the SD.h (because my code already implements the good-old SD.h)? What would be the best way to go about this issue?

The 8.3 "limit" is not a "limit" that can be removed. It is how FAT filesystems work.  Longer filenames are a "fudge" extension overlaid on top of that fileststem structure. To be able to use them you would need to implement that extension.
Simpler to switch to a more modern implementation.  FatFS is your friend:

LFN support, including UTF
Faster device access
More efficient
Can handle more devices than just SD cards
Can handle multiple devices at once

There is an implementation here though I don't know how good it is (I use it on chipKIT where it is bundled by default).
If you can't get FatFs then basically anything is better than the SD library to be brutally honest.

What about the SDFat library? Is it better than the FatFS? My aim is to not take too much flash memory.

I haven't used it. But as I mention - anything is better than SD.h. If you have it / can get it easily, then use it.


text:
Is there a way to make a function take an exact number of clock cycles?
Is it possible to use something like a compiler directive to pad a function with do nothing instructions so that as you add lines of code or take them away it always executes in the same amount of time?  I know there is the blink without delay style of writing a loop, but I want something a little more exact.

Please take the [tour] and read "[ask]", then come back and provide some more bits of information, at least which compiler on which system you are using. Some background why you need this would be nice, too. Oh, and please [edit] your question, don't add comments, this is not a forum. -- I don't know of any compiler that has such an option; and I know several quite different compilers. Most probably you will need to code this on assembly level by hand.

In avr-gcc you can add a single clock cycle by asm volatile ("nop"); But you cannot measure by code, how many clock cycles the controller already spent in some other ISR.

For me that sound like you are trying to shoot sparrows with canons. Why do you need the function to always execute in the same amount of time while still changing it's code? There are other exact methods to trigger the regular execution of a function (via Timers).

you could just take a time snapshot up top, and another one when your code is done, then delay or while before returning, until the duration is acceptable.

(offtopic, sorry) Sorry for the deletion of your this post. I suggest to re-ask it, but make it more clear, what you want to do. I believe you want to convert your laptop to an external SATA hard drive (possibly to an external USB), which is a very interesting problem. Funny thing is that you could actually still use your laptop, until you do not mount a single partition multiple times.

@peterh IDK which stack exchange to ask on

You can use a timer with prescaler set to 1 in combination with a counter module. Attach interrupts to the compare and the overflow events. In the corresponding ISRs you handle the counting...
I have no example for you and it might be a bit tricky how to implement the ISRs, but it's possible for sure, as long as you count a reasonable amount of clock cycles (firing an interrupt each cycle e.g. will not work as the calculations in the ISR take some time).


text:
How do I run a function every 10th time through a loop?
I currently have a function that poles all my sensors every time through it's loop, but I want to pole one of the sensors only every 10th time.  Currently there is a 10 millisecond delay at the beginning of my function.  I know I could increment a counter and use modulo, but is there a better practice for this?

Please show us the sketch you're using.

It's a thousand line program half of which is dedicated to poling the various sensors.  I just need the general solutions to doing something once for every 10 times you do something else.

You've already hit the nail on the head with the modulo.  Or there's good old count up until the variable hits 10 and set it back to zero.  Aside from that it's going to be pretty situation specific.

modulo it is then, thanks

the word is poll, not pole

decrement a counter ... if it reaches zero, then poll the sensor and reload the counter ... the microcontroller has an efficient way of checking for zero values by way of the zero flag that is set by the decrement instruction

for(int i=0; i < 9999; ++i)
{
    if(i % 10 == 0)
    {
         //my actions on i = 0, 10, 20, 30 ...
    }
}

Normally it's suboptimal to reduce the speed of loop just to be able to count them.
Apply the BlinkWithoutDelay principle instead (which is not about Blink, but about WithoutDelay)


text:
I need to happen a process between 2 given times in Arduino
In my project i have a function which i only need to execute if the current time is between given 2 times. Note that the time is fetched from RTC so its 24hr. For example if current time is 23:00,start time is 20:00 and end time is 5:00 the function must execute and not execute otherwise.
if((fromhour>=now.hour() && fromminute>=now.minute()) || (tohour>=now.hour() && tominute>=now.minute()))
{
     //Call function
}

I tried this code but not working as expected. please give a solution for this problem.

convert now.time() hh, mm, ss into three separate bytes and do the comparison that way

How to compare. I need the if statement. Can you give me the code.