text:
Search for a certain combination of strings in serial and read the following characters until another set character stops the search
I have the following serial message that I'm receiving from an ESP32 running GRBL:
<Idle|MPos:158.500,0.000,0.000|FS:0,0|Pn:H|Ov:100,100,100|SD:0.21,/instruction.nc>

I want to check the value after SD: which in this case would be 0.21.
It is a value that represents the percentage of a file being read, so values between 100.00 and 0.00 are being sent.
My guess is to look for the SD: in the string and then read all characters until the , but I can't really find a way to realize that.
I found the startsWith() and the substring()function that are able to look for a set of characters in a string, but it seems like they can only check a set amount of characters which in this case doesn't work as 0.00 is 4 characters and 100.00 is 6 characters.
Any help is much appreciated!!

I'd split the string on | then for each substring split it on :. You then have key/value pairs that are easy to compare and work with. Use a C string not a String object and strtok_r and strcmp to do the job with minimal memory outlay. I'll write a proper answer later, I'm on my phone at the moment.

@Majenko thanks for the super quick reply! I 'll give it a try as far as I can!

Firstly you should really be working with a C string (char *) instead of a String object, otherwise you will be massively fragmenting your heap with the string manipulations to come.
Once you have your data in a C string (char array) you can use strtok_r to split the string on the | character, then for each substring further split it on the :.  You need the _r variant of strtok to make it "re-entrant" so you can have two tokenizations at once nested.
For example (untested):
char *data = "<Idle|MPos:158.500,0.000,0.000|FS:0,0|Pn:H|Ov:100,100,100|SD:0.21,/instruction.nc>";
char *pair; // Pointer to a K/V pair
char *pairptr = data; // Pointer for outer strtok

// Split the string on the first |
pair = strtok_r(data, "|", &pairptr);

// While we have a K/V pair
while (pair) {
    char *kvptr = pair;
    // Split the substring into two parts on the colon
    char *key = strtok_r(pair, ":", &kvptr);
    char *val = strtok_r(NULL, ":", &kvptr);
    if (val) { // If we split the data correctly:
        if (strcmp(key, "SD") == 0) { // If the key is "SD" then
            Serial.print("SD data: ");
            Serial.println(val);
        }
    }
    // Get the next string portion
    pair = strtok_r(NULL, "|", &pairptr);
}

Once you have your val you can further split that down on commas in the same way as it's been split on the colon.


text:
How many FPS I can theoretically get for streaming frame from OV7670 with this setup?
Setup:
OV7670 -> STM32F103... --USART--> ESP01 --UDP--> Gateway --> Internet --> Server

I want to achieve a real-time streaming experience.
Here is my analysis:

According to the OV7670 datasheet, the camera supports 30 FPS for a 640×480 image.

Based on the ESP8266 (ESP01) datasheet and using the built-in firmware with AT commands, I can enable transparent mode for UART-WIFI passthrough with UDP. This means any incoming data from the MCU through UART will be directly forwarded to the server through UDP.

The datasheet also states that the AT commands can adjust the baud rate up to a maximum of 115200×40 baud. If one baud is represented by 9 bits (including 1 stop bit), then the theoretical bit rate is 41.472 Mb/s. For safety, use 115200×39 baud rate which the theoretical bit rate is 4.4928 Mb/s.

Since I’m using UDP as the transport protocol, I need to limit the UDP buffer size. Inspired by YouTube video streams that also use UDP, I found 1357 bytes to be an effective packet size when I Analyzed this with Wireshark.

If I configure the OV7670 in RGB555 (15-bit) format, then 1 pixel = 16 bits = 2 bytes, leaving 1 unused bit as the most significant bit (MSB) of the first byte.

To maximize the unused 1 bit, I plan to use it as a flag to indicate the beginning of a frame. If set to zero, the pixel is not the start of a new frame; if set to one, it indicates the start of a new frame.

Using this bytestream, the MCU's task as a frame buffer (I prefer say byte buffer) is to simply forward per 1357 bytes from the camera (including setting the frame indicator flag) to USART through DMA for faster since it's direct memory access. The MCU waits for the buffer to fill (up to 1357 bytes) before sending it to the ESP8266.

The server will reconstruct this bytestream into image frames, given that it understands the custom protocol.

Each frame would require 320×240×2 160×120×2 bytes for QVGA QCIF, or 1.2288  0.3072 Mbit per frame. Therefore, 30 FPS = 36.864 Mb/s 15 FPS = 4.608 Mb/s, which comfortably fits within the ESP8266's USART-WIFI UDP passthrough capability of 4.4928 Mb/s.

Is there anything I missed with my setup/calculation? Assume the network is reliable and UDP packet loss is tolerable (handled by server).

If you are looking for performance, why don't replace STM32 host -> ESP8266 modem approach with an ESP32-S3? ESP8266 is a single-core, and UART is very slow...

@hcheung cost effectiveness, I saw market use esp8266+stm32f103+ov7670 is cheaper than esp32-cam directly.

@hcheung Can you give me the reason why did you say UART is very slow?

You are hilariously overestimating the ESP8266's performance and capabilities. It has to do a great deal of processing to parse AT commands, to decode text into binary data, to copy the data being sent multiple times and to run the network stack. And you're not going to run its serial port at "115200×40 baud", whatever that means. 1 baud is not "represented by 9 bits including the stop bit"; in this case 1 baud means 1 bit. Your estimates are way out of whack with reality. And @hcheung says UART is very slow because it is very slow. ESP8266 is the wrong choice for what you want.

@romkey I updated my calculation, is it still hilariously?

What if I'm using 8-bit GPIO on esp12 (esp8266), and then forward to UDP after 1357 bytes buffered.

@MuhammadIkhwanPerwira 115200bps is bits per second, that is 115200 / 10 bits (8 bits + 1 start bit + 1 stop bit) = 11520 bytes per second, whatever streaming rate you are going to have, the serial port is going to be the bottleneck.

@hcheung Host sends per 1357 bytes. Leaving many 115200-1357 bytes space.

@hcheung So, the bottleneck comes from processing power? general CPU or network interface inside esp8266?

Why don't you give it a try? Otherwise this is just a self-fulfilling prophecy.

Good idea, but I think I will follow your suggestion to use esp32 (chip only). It turns out that development board is indeed expensive, but cheap for chip only.

Quote from esp32 docs

Because UART is used for communication between ESP-AT and the host MCU by default, and the baud rate is 115200. On the hardware, the baud rate upper limit is 5 Mbps. Therefore, if the throughput is expected to be less than 5 Mbps, the user can use the default UART as the communication medium with the host MCU, and the following optimization methods can be carried out.

In another word, since the incoming stream is 4Mbps, then just use 115200 baud rate.
But, it was about esp32, perhaps it's similar to esp8266.
Also, consider about transmission interval AT+TRANSINTVL that talking about interval between UDP packet size. I need to set it to 0, which means once the data arrive from host (MCU), just forward to internet.
Also disable AT+SYSMSGFILTER=0 https://docs.espressif.com/projects/esp-at/en/latest/esp32/AT_Command_Set/Basic_AT_Commands.html#cmd-sysmsgfilter

Hi, The throughput we tested with AT UART-WiFi passthrough mode is as below:
TCP Throughput: AT TCP passthrough Tx 303 Kbps; Rx 302Kbps @ baudrate 420000
UDP Throughput: AT UDP passthrough Tx 250 Kbps; Rx 250 Kbps @ baudrate 420000

Source: https://bbs.espressif.com/viewtopic.php?t=2187

How does a 4 Mbps stream translate to a baud rate of 115200? That is not in the text you quoted.

source: Stack Exchange

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

sort: votes


text:
Where do avrdude parameters get defined in the Arduino IDE?
I am interested in learning how the Arduino IDE handles parameters in order to correctly upload hex files with avrdude.
I found this in boards.txt:
uno.name=Arduino/Genuino Uno

uno.vid.0=0x2341
uno.pid.0=0x0043
uno.vid.1=0x2341
uno.pid.1=0x0001
uno.vid.2=0x2A03
uno.pid.2=0x0043
uno.vid.3=0x2341
uno.pid.3=0x0243

uno.upload.tool=avrdude
uno.upload.protocol=arduino
uno.upload.maximum_size=32256
uno.upload.maximum_data_size=2048
uno.upload.speed=115200

uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0x05
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex

uno.build.mcu=atmega328p
uno.build.f_cpu=16000000L
uno.build.board=AVR_UNO
uno.build.core=arduino
uno.build.variant=standard

There is this in platform.txt:
# AVR Uploader/Programmers tools
# ------------------------------

tools.avrdude.path={runtime.tools.avrdude.path}
tools.avrdude.cmd.path={path}/bin/avrdude
tools.avrdude.config.path={path}/etc/avrdude.conf

tools.avrdude.upload.params.verbose=-v
tools.avrdude.upload.params.quiet=-q -q
tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.program.params.verbose=-v
tools.avrdude.program.params.quiet=-q -q
tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.erase.params.verbose=-v
tools.avrdude.erase.params.quiet=-q -q
tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Ulock:w:{bootloader.unlock_bits}:m -Uefuse:w:{bootloader.extended_fuses}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

tools.avrdude.bootloader.params.verbose=-v
tools.avrdude.bootloader.params.quiet=-q -q
tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.platform.path}/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m

This line is particularly interesting:
tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

It seems like these variables are corresponding:
{cmd.path} --> tools.avrdude.cmd.path
{config.path} --> tools.avrdude.config.path
{upload.verbose} --> tools.avrdude.upload.params.verbose
{build.mcu} --> uno.build.mcu
{upload.protocol} --> uno.upload.protocol
{serial.port} --> ?
{upload.speed} --> uno.upload.speed
{build.path} --> ?
{build.project_name} --> ?

It seems these are likely used in the Java code for the IDE. There are obviously a few I am unsure of. I would guess these are considered user inputs in the IDE. Though I am by no means a Java or JavaScript programmer.
Where are these variables explicitly defined in the Arduino library? (e.g. {runtime.tools.avrdude.path}, {path}, {cmd.path} ....) Or how do they get defined by IDE?

where can I find,
Boards.txt
Platform.txt
programmers.txt file. I use - Mac Mojave 10.14.6
Arduino iDE - 1.8.12 When I run the data logger code (to save in SD card) I am getting /Users/placidafernando/Library/Caches/Homebrew Error. I reinstalled Brew and Avrdude. I. see it has installed under when I look via Terminal. Cannot see from MAC apple man /Users/myUserID/Library/Caches/Homebrew But my sketch and Arduino is in /Documents libraries Following message is due to IDE or Arduino-CLI unable to fine the avrdude.tar file in the current directory? I am npt a big mac user. How can I set the path

@ShaunChristianFernando you should probably just ask your own question.

There are 3(or 4) places that you need to look at to know how to upload.
There is the boards.txt file and the platform.txt file.
You can consider a platform.txt file line
tools.avrdude.path={runtime.tools.avrdude.path}

as (in linux in windows replace ${xx} by %xx%)
set tools.avrdude.path ${runtime.tools.avrdude.path}

and the board.txt for the selected board like
uno.bootloader.tool=avrdude

as
set bootloader.tool avrdude

The arduino ide uses the following string to know the upload command environment variable
tools.${bootloader.tool}.upload.pattern

This way it knows the command to upload is
"{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

{cmd.path} is hardcoded as tools.${bootloader.tool}.cmd.path which equals {path}/bin/avrdude
where {path} is to be understood as tools.${bootloader.tool}.path wich equals {runtime.tools.avrdude.path}.
{runtime.tools.avrdude.path} is defined by the boardsmanager based n the json file and the location where the boardsmanager extracted the download.
So that makes 3 files: boards.txt, platform.txt and json file and some hard coding.
A 4th file comes into play when you use the "other upload commands". These are located in the programmers.txt file.
IMHO Arduino IDE core team did not opt for the simplest solution to define these things. They also change the way they work from time to time.
If you use a makefile know that a lot of people have done this already so it may be a good idea to "reuse other peoples work" instead of "reinventing the wheel". It is not so easy or straightforward.
Note I know all these things because I implemented the Arduino eclipse IDE. As far as I know none of this is documented.

The Arduino library is about what runs on the target, while the "IDE" (not sure if it can still be called IDE, as now they try to do also command line) is about everything else.
But my impression is that if you are ready to ask these sort of question, you could consider dropping the IDE and moving to a more standard Makefile approach. Or Maybe Eclipse, where you still have the IDE, but you can define everything in a more standard way.
The Arduino approach is good to get people with little experienced started, but after a while one started to feel its limitations.

I've used a makefile approach. So I am now interested in finding out how and where the parameters that get sent to avrdude are defined. More specifically the variables involved in tools.avrdude.upload.pattern.

Not sure I understand you. Do you want to know how to invoke avrdude by replicating what the IDE does?

I want to know how to choose the parameters that need to be sent to the avrdude program for a given board type. I have found where the flags are settools.avrdude.upload.pattern. I am unsure of how they are set. Please see the block in my post with arrows signifying "corresponding". All the variables prefixed with uno, I understand where those values come from (boards.txt). But the variables prefixed with tools and the ? marks, I am unsure of where those are defined. I would like to know where those are defined.

Ok, my bad, I should have asked an open question. Next try: what are you trying to achieve with this? Why do you want to know this?

I want to know this because I want wrap the Arduino C library for use with Python. I want to know this because it is part of the design for how the wrapper would work, i.e. the upload process.

I'm a bit confused. The Arduino C library, AFAIK, is something that is compiled for the target (AVR mostly). Then there is a java (afaik) implementation of the IDE, which relies on various tools, like avr-gcc and avrdude. If you want to use them, why not just executing them from python? As you must have seen, they work even from Makefile.

I understand I could execute from Python but I want to wrap the Arduino library. I want to be able to write in Python, not just compile from it, e.g. Blink.py not Blink.cpp.

I have done my share of python bindings for C libaries, but they always rely on having a python interpreter running on the target. That is simply not possible on a basic AVR like the 328p. The closest you might get is with https://wiki.python.org/moin/PyMite but it seems abandoned. Or go for a targeted implementation like https://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers/posts/1198333. Of course you might achieve python-like syntax wit lots of work on the parser/compiler, but that's a different story.

I am looking to use Cython to convert Arduino.h into an Arduino.so, so I can then import Arduino in a Python script. For now, I think it I will then output a cpp from the Python script, which will then compile and upload via an upload command.

Let us continue this discussion in chat.

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

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


text:
Serial Communication, Arduino and Rpi , C library
I am currently working on a project on serial communication between RPi and Arduino. This is the code that I am using from RPi side, it's in C:
int main()
{
   //-------------------------
   //----- SETUP USART 0 -----
   //-------------------------
   //At bootup, pins 8 and 10 are already set to UART0_TXD, UART0_RXD (ie the alt0 function) respectively
   int Arduino= -1;

   //OPEN THE UART
   //The flags (defined in fcntl.h):
   //   Access modes (use 1 of these):
   //       O_RDONLY - Open for reading only.
   //       O_RDWR - Open for reading and writing.
   //       O_WRONLY - Open for writing only.
   //
   //   O_NDELAY / O_NONBLOCK (same function) - Enables nonblocking mode. When set read requests on the file can return immediately with a failure status
   //                                           if there is no input immediately available (instead of blocking). Likewise, write requests can also return
   //                                           immediately with a failure status if the output can't be written immediately.
   //
   //   O_NOCTTY - When set and path identifies a terminal device, open() shall not cause the terminal device to become the controlling terminal for the process.
   Arduino = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);           //Open in non blocking read/write mode
   if (Arduino == -1)
   {
       //ERROR - CAN'T OPEN SERIAL PORT
       printf("Error - Unable to open UART.  Ensure it is not in use by another application\n");
   }

   //CONFIGURE THE UART
   //The flags (defined in /usr/include/termios.h - see http://pubs.opengroup.org/onlinepubs/007908799/xsh/termios.h.html):
   //   Baud rate:- B1200, B2400, B4800, B9600, B19200, B38400, B57600, B115200, B230400, B460800, B500000, B576000, B921600, B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, B4000000
   //   CSIZE:- CS5, CS6, CS7, CS8
   //   CLOCAL - Ignore modem status lines
   //   CREAD - Enable receiver
   //   IGNPAR = Ignore characters with parity errors
   //   ICRNL - Map CR to NL on input (Use for ASCII comms where you want to auto correct end of line characters - don't use for bianry comms!)
   //   PARENB - Parity enable
   //   PARODD - Odd parity (else even)
   struct termios options;
   tcgetattr(Arduino, &options);
   options.c_cflag = B9600 | CS8 | CLOCAL | CREAD;      //<Set baud rate
   options.c_iflag = IGNPAR;
   options.c_oflag = 0;
   options.c_lflag = 0;
   tcflush(Arduino, TCIFLUSH);
   tcsetattr(Arduino, TCSANOW, &options);

   //----- TX BYTES -----
   unsigned char tx_buffer[20];
   unsigned char *p_tx_buffer;
   int Angle=-20;
   int Speed=100;

   int Botschaft=Fusion(Crypt(Angle),Crypt(Speed));

   p_tx_buffer = &tx_buffer[0];
   *p_tx_buffer++ = Decompositer(Botschaft,1)+'0';
   *p_tx_buffer++ = Decompositer(Botschaft,2)+'0';
   *p_tx_buffer++ = Decompositer(Botschaft,3)+'0';
   *p_tx_buffer++ = Decompositer(Botschaft,4)+'0';
   *p_tx_buffer++ = Decompositer(Botschaft,5)+'0';
   *p_tx_buffer++ = Decompositer(Botschaft,6)+'0';

   if (Arduino != -1)
   {
      int count = write(Arduino, &tx_buffer[0], (p_tx_buffer - &tx_buffer[0]));     //Filestream, bytes to write, number of bytes to write
      if (count < 0)
      {
        printf("UART TX error\n");
      }
   }

//----- CHECK FOR ANY RX BYTES -----
   if (Arduino != -1)
   {
      // Read up to 255 characters from the port if they are there
      unsigned char rx_buffer[256];
      int rx_length = read(Arduino, (void*)rx_buffer, 255);     //Filestream, buffer to store in, number of bytes to read (max)
      if (rx_length < 0)
      {
        //An error occured (will occur if there are no bytes)
      }
      else if (rx_length == 0)
      {
        //No data waiting
      }
      else
      {
        //Bytes received
        rx_buffer[rx_length] = '\0';
        printf("%i bytes read : %s\n", rx_length, rx_buffer);
      }
   }

   //----- CLOSE THE UART -----
   close(Arduino);
}

int Fusion(int Angle, int Speed)
{
   int msg;
   msg=Angle*1000+Speed;
   return msg;
}

int Decompositer(int Num,int Place)
{
   int Result[5];

   Result[0]=Num/100000;
   Result[1]=(Num-Result[0]*100000)/10000;
   Result[2]=(Num-Result[0]*100000-Result[1]*10000)/1000;
   Result[3]=(Num-Result[0]*100000-Result[1]*10000-Result[2]*1000)/100;
   Result[4]=(Num-Result[0]*100000-Result[1]*10000-Result[2]*1000-Result[3]*100)/10;
   Result[5]=(Num-Result[0]*100000-Result[1]*10000-Result[2]*1000-Result[3]*100-Result[4]*10);
   return Result[Place-1];
}

int Crypt(int Value)
{
   int result;
   result = Value + 100;
   return result;
}

And this is my code from the Arduino side:
void setup()
{
    Serial.begin(9600);
    Serial2.begin(9600);
}

void loop(){
    if (Serial2.available())
    {
        int inByte = Serial2.read();
        Serial.write(inByte);
    }
    if (Serial.available())
    {
        int inByte = Serial.read();
        Serial2.write(inByte);
    }
}

My purpose is to send a 6 digit number to my Arduino side, and be able to read them and then separate them into 2 different numbers...
The problem is I see only the first 2 digits and the rest are weird characters like 1‚þ.
I really appreciate your help.

Do you know just what it is your Pi program is actually sending out?

I guess, Characters ? by the way I tried to set a higher baude rate and for some reason it works , I dont know why :/

Was that 115200 baud perchance?

Yes exactly! Is there something wrong with it?

I have come across suituations where changing the baud rate fails miserably. Closing the port, re-opening it and setting the baud then works. It's like it only applies the baud change when the port closes. 115200 is the default baud rate the port is already on.

But do you think it might create a problem in the future?  Or should I change something in my code?

Later on I will post some other serial code that I use. I am not at my desk at the moment.

Here is how I use the serial port on Pi-like devices: https://github.com/majenkotech/SerialPort

Or you could just use one of the existing libraries on the Pi which work. Incidentally I don't know what the embedded code (with its own scroll bar) is supposed to show - it is unreadable.

This overriding problem here seems to be that you've mixed serial communication code with data coding code, without really verifying that either works by itself.  Split them apart and test your serial implementation with nice, human readable strings.  Separately test your encoding code to or from the terminal or a hex dump utility, depending on what it is you want it to be doing.

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


text:
Arduino for Wi-Fi hotspot?
I want to create a Wi-Fi hotspot and redirect all connections to a custom login page.
I would like to know if the Arduino Yún is a good choice in this case?

Better use a regular router and flash DD-WRT or OpenWRT to it (check the supported router list on their websites). Next use something like NoCatSplash, to create a captive portal with login.
Arduino's just are not fast enough for this. Arduino Yuns are typically more expensive.

Did you know that operating system the Yun runs is OpenWRT?  It's no slower or faster than most home routers since it uses the very same chip that many of them do.

Thank's ! I have also read Raspberry PI could be a good choice ?

Mikrotik has some really nice routers / switches that will be able to do what you want for a very reasonable price and fairly good performances.

Raspberry + SD card + power adapter + usb-wifi module. So more expensive than a typical router. Also since both wifi and ethernet go over usb on the Pi, the maximum speed is reduced.

Here is a project where I make a Yun into a hotspot and even have it act like a captive portal so users can control things though the Yun...
http://wp.josh.com/2014/05/01/a-platform-for-casual-encounters-with-interactive-technology/
Even though it does work, I can not recommend using the Yun for something like this unless you have no other choice. It is just not a good platform and you end up wasting huge amounts of time on unnecessary problems.
Much better to use something like a BeagleBone or Raspberry PI to handle to Wifi stuff. You can then connect these to a normal Arduino if necessary to deal with your hardware.

So how to have a hotspot (like mikrotik)
and also control hardware using raspberry pi? What is the server I can use? @bigjosh


text:
Motor Shield Enable and Input Pins

Hello,
I am new to the Arduino UNO board and am trying to make a dc motor run using the MATLAB software. The motor is connected to the motor shield board in a similar way shown in the picture below (taken from another question asked here). It runs use the IDE software with the motor shield library but I would like it to run it on MATLAB. I am not able to find out what enable pin, input A and input B for any of the motors. Any help would be greatly appreciated.
The working code from Arduino IDE examples:
// Adafruit Motor shield library
// copyright Adafruit Industries LLC, 2009
// this code is public domain, enjoy!

#include <AFMotor.h>

AF_DCMotor motor(4);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor test!");

  // turn on motor
  motor.setSpeed(200);

  motor.run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  motor.run(FORWARD);
  for (i=0; i<255; i++) {
    motor.setSpeed(i);
    delay(10);
 }

  for (i=255; i!=0; i--) {
    motor.setSpeed(i);
    delay(10);
 }

  Serial.print("tock");

  motor.run(BACKWARD);
  for (i=0; i<255; i++) {
    motor.setSpeed(i);
    delay(10);
 }

  for (i=255; i!=0; i--) {
    motor.setSpeed(i);
    delay(10);
 }

  Serial.print("tech");
  motor.run(RELEASE);
  delay(1000);
}

please copy the working code and paste it into your question

Thank you for having a look at this issue. I pasted the working code to the question.

you almost had the code formatting correct ... the code delimiter is ```

the motor shield uses a shift register to control the motors ... the arduino GPIO pins are not connected directly to the motor driver


text:
Equivalent libary of RTCZero for Arduino UNO
I am a beginner to Ardunino UNO
This is my first program to light up an LED strip
#include <Adafruit_NeoPixel.h>

#include <RTCZero.h>

#define PIN            6
#define NUMPIXELS      60 // Define the total number of pixels in your strip
#define BRIGHTNESS     50 // Adjust the brightness (0-255)

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
RTCZero rtc;

void setup() {
  strip.begin(); // Intializes the neo pixel library for use
  strip.show();  // Initialize all pixels to 'off'

  rtc.begin();
// Intialzes the real time clock , the rtc is defined previuosly ,the dot access the the memebr in this case begin () , which is a method , method is used to perform an action , they belong to a class and defines how an object behaves

  // Set the initial time at the time of the project
  rtc.setHours(12);
  rtc.setMinutes(0);
  rtc.setSeconds(0);
}

void loop() {

  int currentHour = rtc.getHours(); // Get the current hour from the real time clock
  uint32_t color;

  // Set color based on the time of the day
  if (currentHour >= 6 && currentHour < 16) {
    // Yellow during 6 am to 4 pm

    color = strip.Color(255, 255, 0);
  } else if (currentHour >= 16 && currentHour < 20) {
    // Orange during 4 pm to 8 pm

    color = strip.Color(255, 165, 0);
  } else {
    // Blue during 8 pm to 6 am

    color = strip.Color(0, 0, 255);
  }

  // Set the color for all pixels
  fillStrip(color);

  // Optional: Adjust brightness
  strip.setBrightness(BRIGHTNESS);

  // Update the NeoPixel strip
  strip.show();

  // Delay to avoid updating the colors too frequently
  delay(60000); // Delay for 1 minute (adjust as needed)
}

// Uses for loop to itrate the color for all the pixels in the led strip
void fillStrip(uint32_t color) {
  for (int i = 0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, color);
  }
}

Unable to compile the program due to the below error.
How do I find an equivalent function for Arduino UNO ??
WARNING: library RTCZero claims to run on samd architecture(s) and may be incompatible with your current board which runs on avr architecture(s).

The RTCZero library is meant to control the RTC peripheral embedded in some Arduinos. The Uno does not have an embedded RTC, so there can be no equivalent.

There is no built in RTC on a normal Arduino UNO.  If you want to do the same thing on an UNO you can either add an external RTC module like the DS3231 or the DS1307.  There are libraries in the library manager for those devices that will work with your UNO.  You can then find the functions that perform the same job as the ones in your code and replace them.
If your UNO is the new UNO-R4, then yes those do have an RTC and there is a library in the core for it, but the RTC on those boards is terribly inaccurate due to the lack of an accurate clock source to drive it.  So even in that case I'd still recommend an external RTC.


text:
I2C conflict with 2 Arduinos
I am having some trouble connecting my 2 Arduino Nanos with I2C. I have this configuration:

SLAVE RECEIVER Nano with DS1037 and LCD 16x02 on I2C.
MASTER SENDER Nano.

After some time the Slave receiver prints on LCD random chars. If I delete the line including library RTCLIB.h everything is working except the clock. Thanks for your help :D
Slave receiver code:

#include <Wire.h> // include la libreria
#include <LiquidCrystal_I2C.h>
#include "RTClib.h"

LiquidCrystal_I2C lcd(0x3E, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
RTC_DS1307 RTC; // orologio

static int anno;
static int giorno;
static int mese;
static int ora;
static int secondo;
static int oldSecondo;
static int minuto;
static int oldMinuto;
static int annoGrezzo;

//------------------------------------------------------------
// si ripete la union esattamente come nel master
union Scomp_float {
  // si utilizza union x float
  float temp;
  char byte_s[4];
} S_float;

//------------------------------------------------------------
// si ripete la union esattamente come nel master
union Scomp_long {
  // si utilizza union x long
  long int mioL;
  char byte_sL[4];
} S_long;

//------------------------------------------------------------
//------------- byte temporanei
byte f0 = 0;   // contengono i byte ricevuti
byte f1 = 0;
byte f2 = 0;
byte f3 = 0;
byte a1 = 0;
//-------------------------------------------------------------
//  qui si introdurranno i dati ricomposti dopo la trasmissione
long int masterLong = 0;
float masterFloat = 0;
int masterInt = 0;
//--------------------------------------------------------------

void setup() {
  Wire.begin(80);                // join i2c bus with address #4
  Wire.onReceive(receiveEvent); // register event
  lcd.begin(16, 2);
  Serial.begin(9600);           // start serial for output
  //-----------orologio-----------
  RTC.begin();
  // Check to see if the RTC is keeping time.  If it is, load the time from your computer.
  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // This will reflect the time that your sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
  //-----------fine orologio-----------
}

void loop() {
  //------------------------------------------------------------
  //   si stampano i dati ricevuti e ricomposti
  //------------------------------------------------------------
  Serial.println(masterInt);
  Serial.println(masterLong);
  Serial.println(masterFloat);
  DateTime now = RTC.now();
  annoGrezzo = now.year();
  anno = ( annoGrezzo % 100);
  mese = now.month();
  giorno = now.day();
  ora = now.hour();
  minuto = now.minute();
  lcd.setCursor(0, 0);
  lcd.print(masterInt);
  lcd.setCursor(0, 1);
  lcd.print(giorno);
  lcd.print(" ");
  lcd.print(mese);
  lcd.print(" ");
  lcd.print(anno);
  lcd.print("  ");
  lcd.print(ora);
  lcd.print(":");
  lcd.print(minuto);
  delay (1000);
  lcd.clear();
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  if (howMany == 2) {
    // se in arrivo due dati
    f0 = Wire.read(); // si leggono i byte
    f1 = Wire.read();
    masterInt =  ((f1 << 8) | f0); // si ricompone l'intero
  }

  if (howMany == 4) {
    // se in arrivo 4 dati è un float
    f0 = Wire.read();  // si leggono i byte
    f1 = Wire.read();
    f2 = Wire.read();
    f3 = Wire.read();
    S_float.byte_s[0] = f0; // si ricompone il float
    S_float.byte_s[1] = f1;
    S_float.byte_s[2] = f2;
    S_float.byte_s[3] = f3;
    masterFloat = S_float.temp;
  }

  if (howMany == 5) {
    // se in arrivo 5 dati è un long
    f0 = Wire.read();  // si leggono i byte
    f1 = Wire.read();
    f2 = Wire.read();
    f3 = Wire.read();
    a1 = Wire.read();
    S_long.byte_sL[0] = f0;  // si ricompone  il long
    S_long.byte_sL[1] = f1;
    S_long.byte_sL[2] = f2;
    S_long.byte_sL[3] = f3;
    masterLong = S_long.mioL;
  }
}

Master sender code:
#include <Wire.h> // si include la libreria
//---------------------------------------------------------
union Scomp_float {
 // si utilizza union x float
  float temp;
  char byte_s[4];
} S_float;
//---------------------------------------------------------
union Scomp_long {
 // si utilizza union x long
  long int mioL;
  char byte_sL[4];
} S_long;
//----------------------------------------------------------
// questi sono i dati che si vogliono trasmettere

long int mioLong = 1234567801;
float mioFlo = 123456.29;
//----------------------------------------------------------
byte a1 = 0; // conterrà i primo byte dell'int
byte a2 = 0; // conterrà il secondo byte dell'int
byte f0 = 0; // contengono i byte del float e del long
byte f1 = 0;
byte f2 = 0;
byte f3 = 0;
void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

void loop() {
  int mioInt = random(30000);
 //-----------------------------------------------------
 // trasmissione di un intero ( 2 byte)
 //-----------------------------------------------------
  a1 = byte(mioInt); // si scompone l'intero in 2 byte
  a2 = byte( mioInt >> 8);
  Wire.beginTransmission(80); // inzia trasmissione allo slave

  Wire.write(a1); //  invia un byte
  Wire.write(a2); //  invia il secondo byte
  Wire.endTransmission(); // stop transmitting
 //------------------------------------------------------
  delay (2000);
 //------------------------------------------------------
 // trasmissione intero lungo 4 byte
 //------------------------------------------------------
  S_long.mioL = mioLong; // si scompone in 4 byte
  f0 = S_long.byte_sL[0];
  f1 = S_long.byte_sL[1];
  f2 = S_long.byte_sL[2];
  f3 = S_long.byte_sL[3];
  a1 = 1; // si trasmette questo byte solo per segnalare allo slave
 // che stiamo trasmettendo un long
 // una volta scomposto si trasmettono i 4 byte
  Wire.beginTransmission(80); // trasmette allo slave
  Wire.write(f0); // invia un byte
  Wire.write(f1); //
  Wire.write(f2); //
  Wire.write(f3); //  invia un byte
  Wire.write(a1);
  Wire.endTransmission(); // fine trasmissione
 //-------------------------------------------------------
  delay (2000);
 //------------------------------------------------------
 //   trasmissione di un float 4 byte
 //------------------------------------------------------
  S_float.temp = mioFlo; // si scompone in 4 byte
  f0 = S_float.byte_s[0];
  f1 = S_float.byte_s[1];
  f2 = S_float.byte_s[2];
  f3 = S_float.byte_s[3];
 // una volta scomposto si trasmettono i 4 byte
  Wire.beginTransmission(80); // trasmette allo slave
  Wire.write(f0); // invia un byte
  Wire.write(f1); //
  Wire.write(f2); //
  Wire.write(f3); //  invia un byte
  Wire.endTransmission(); // fine trasmissione
 //-------------------------------------------------------
  delay (3000);
}
//------ end master ----------------------------------

AFAIK you can't control the I2C if you are a slave. Slaves only respond to the master's requests, but can't start a communication (for instance to an LCD). If you want your slave to control the LCD screen, then make another I2C bus where the slave is the master, or make the master control the LCD directly. Or connect the master and the slave through another bus (SPI, serial, ...) and make the slave the new master...

can help me to convert this to Master reader/Slave receiver i try without result... tnks for help

i partially resolve the problem with this:
MASTER RECEIVER code:
#include <Wire.h> // include la libreria
#include <LiquidCrystal_I2C.h>
#include "RTClib.h"

LiquidCrystal_I2C lcd(0x3E, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
RTC_DS1307 RTC; // orologio

static int anno;
static int giorno;
static int mese;
static int ora;
static int secondo;
static int oldSecondo;
static int minuto;
static int oldMinuto;
static int annoGrezzo;
char t[10] = {};
char v[10] = {};

void setup()
{
  Wire.begin();                // join i2c bus with address #4
  lcd.begin(16, 2);
  Serial.begin(9600);           // start serial for output

  //-----------orologio-----------

  RTC.begin();
  // Check to see if the RTC is keeping time.  If it is, load the time from your computer.
  if (! RTC.isrunning())
  {
    Serial.println("RTC is NOT running!");
    // This will reflect the time that your sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
  //-----------fine orologio-----------

}

void loop()
{
  //------------------------------------------------------------
  //   si stampano i dati ricevuti e ricomposti
  //------------------------------------------------------------
  Wire.requestFrom(8, 3);
  int i = 0;
  while (Wire.available()) {
    t[i] = Wire.read(); // every character that arrives it put in order in the empty array "t"
    i = i + 1;
  }
  Wire.requestFrom(8, 3);
  i=0;
  while (Wire.available()) {
    v[i] = Wire.read(); // every character that arrives it put in order in the empty array "v"
    i = i + 1;
  }
  Serial.println(t);
  DateTime now = RTC.now();
  annoGrezzo = now.year();
  anno = ( annoGrezzo % 100);
  mese = now.month();
  giorno = now.day();
  ora = now.hour();
  minuto = now.minute();
  lcd.setCursor(0, 0);
  lcd.print(t);
  lcd.setCursor(5,0)
  lcd.print(v);
  lcd.setCursor(0, 1);
  lcd.print(giorno);
  lcd.print(" ");
  lcd.print(mese);
  lcd.print(" ");
  lcd.print(anno);
  lcd.print("  ");
  lcd.print(ora);
  lcd.print(":");
  lcd.print(minuto);

  delay (1000);
  lcd.clear();
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()

SLAVE SENDER code:
#include <Wire.h> // si include la libreria
//---------------------------------------------------------

char t[10];
char v[10];

void setup()
{
  Wire.begin(8); // join i2c bus (address optional for master)
   Wire.onRequest(requestEvent);
}

void loop()
{
 int mioInt = random(30000);
 int mioInt2 = 1234;
  dtostrf(mioInt, 3, 2, t); //convers the float or integer to a string. (floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, empty array);
  dtostrf(mioInt2, 3, 2, v);
//------------------------------------------------------
delay (500);
}
void requestEvent() {
  Wire.write(t);
  Wire.write(v);
}
//------ end slave    ----------------------------------

now my problem is the second variable T im unable to receive it on Master. Thanks for help

Only the Master is now the Master and the RTC, the I2C display and the Slave Nano are all Slaves. That is good, there will be no more collisions on the I2C bus. You have to know what kind of data you want to transmit. A zero terminated string is not the best option. You could send two integers at once or a struct with values. It is easier to send a single data package. In the Slave, the requestEvent() is run from an interrupt. Therefor the variabeles that you send must be made 'volatile' and the if they are used in the loop() the interrupts have to be turned off temporarily in the loop().

how? im a little bit confused, with one no problem its the second the problem.. i understand how it work with one. thanks for reply

For example with "int x[2];". Transmit them with "Wire.write((char *)x, 4);". In the Master, request 4 bytes, use also a "int x[2];" and you could use "Wire.readBytes((char *)x, 4);" to read the data into the integers. The problem you have is not the second one, it is the way you use the two strings. Therefor a single package will be better.

If this solved your problem please accept your own answer, other Stack Exchange considers the question not answered appropriately.


text:
I2C wire.h send 2 variables
I am trying to send 2 variables with wire.h. I tried with  this code:
MASTER RECEIVER:

#include <Wire.h> // include la libreria
#include <LiquidCrystal_I2C.h>
#include "RTClib.h"

LiquidCrystal_I2C lcd(0x3E, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
RTC_DS1307 RTC; // orologio

static int anno;
static int giorno;
static int mese;
static int ora;
static int secondo;
static int oldSecondo;
static int minuto;
static int oldMinuto;
static int annoGrezzo;
char t[10] = {};
char v[10] = {};

void setup() {
  Wire.begin(); // join i2c bus with address #4
  lcd.begin(16, 2);
  Serial.begin(9600); // start serial for output
  //-----------orologio-----------
  RTC.begin();
  // Check to see if the RTC is keeping time. If it is, load the time from your computer.
  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // This will reflect the time that your sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
  //-----------fine orologio-----------
}

void loop() {
  //------------------------------------------------------------
  //   si stampano i dati ricevuti e ricomposti
  //------------------------------------------------------------
  Wire.requestFrom(8, 6);
  int i = 0;
  while (Wire.available()) {
    Serial.println(i);
    t[i] = Wire.read();
    // every character that arrives it put in order in the empty array "t"
    i = i + 1;
  }
  Serial.println(t);
  DateTime now = RTC.now();
  annoGrezzo = now.year();
  anno = (annoGrezzo % 100);
  mese = now.month();
  giorno = now.day();
  ora = now.hour();
  minuto = now.minute();
  lcd.setCursor(0, 0);
  lcd.print(t);
  lcd.setCursor(5,0);
  lcd.print(v);
  lcd.setCursor(0, 1);
  lcd.print(giorno);
  lcd.print(" ");
  lcd.print(mese);
  lcd.print(" ");
  lcd.print(anno);
  lcd.print("  ");
  lcd.print(ora);
  lcd.print(":");
  lcd.print(minuto);
  delay (1000);
  lcd.clear();
}

SLAVE SENDER
#include <Wire.h> // si include la libreria
//---------------------------------------------------------
char t[10];
char v[10];

void setup() {
  Wire.begin(8);
  // join i2c bus (address optional for master)
  Wire.onRequest(requestEvent);
}

void loop() {
  int mioInt = random(30000);
  int mioInt2 = 1234;
  dtostrf(mioInt, 3, 2, t);
  //convers the float or integer to a string. (floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, empty array);
  dtostrf(mioInt2, 3, 2, v);
  //------------------------------------------------------
  delay (500);
}

void requestEvent() {
  Wire.write(t);
  Wire.write(v);
}

I'm unable to receive v in my master receiver. Thanks for your help.

I don't have the library to hand, but I think reading requires you to request a certain number of bytes from an I2C address.  You don't appear to be doing that.  Suggest you look more closely at a working I2C library and see how they do it.

You're requesting 6 bytes when you should be requesting 20, if I understand it correctly, and there is no code in the Master to write to v.

I2C is 8-bit data bus, where address can be 7 bit or 10 bit, you can't send more than 8 bit at a time, if you want to send data more than 8 bit you will be sending them like this, for example let you need to send 16 bit data then you send 8 bit LSB first and then 8 bit MSB or vice versa as per your configuration.
Secondly I had noticed you code and noticed many errors, the major one is that you hadn't followed the rules of I2C protocol in your code. I am here attached a link for sample program of arduino i2c slave and master. Go through it you will get your answer.


text:
Trying to measure distance using an ultrasound sensor
I am relatively New to Arduino and need your help. Actually i made a code and the problem is that the ultrasound sensor doesn't work at all. It isn't displaying the distance between the object and and the sensor. Can you help me please!
Here is my code:
note: the code has some motor cotrol commands
int enableBridgePin = 10;
int forwardPin = 11;
int backWardPin = 9;
int tickPin = 2;
const int trig = 5;
const int echo = 6;

int dt;
int distance;

float rotationSpeed[50];

void setup() {
  pinMode(enableBridgePin, OUTPUT);
  pinMode(forwardPin, OUTPUT);
  pinMode(backWardPin, OUTPUT);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);

  digitalWrite(forwardPin, LOW);
  digitalWrite(backWardPin, LOW);

  interrupts();
  digitalWrite(enableBridgePin, HIGH);
}

void loop() {
  analogWrite(enableBridgePin,255);

  digitalWrite(forwardPin, HIGH);
  digitalWrite(backWardPin, LOW);

  distancefonction(dt, distance);
  if(distance>5){
   detachInterrupt(digitalPinToInterrupt(tickPin));
   digitalWrite(forwardPin, LOW);
   }

}

int distancefonction(int dt, int distance)
{
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  dt = pulseIn(echo, HIGH);
  distance = 0.034/2*dt;
  Serial.println(distance );}

reduce the sketch to minimum to measure and print the distance and then test it.

You have declared int distance outside of any method. That means it's available from all methods. Some people call it a global variable.
However, you have a method int distancefonction(int dt, int distance) which receives int distance as a parameter. This results in an ambiguity: if you refer to distance within the method like
distance = 0.034/2*dt;

should this now refer to the parameter distance or the global variable distance?
The answer is: you can't decide. The C/C++ standard has decided for you and the answer is: the parameter will take precedence and thus hide the global variable. This thing is also called "shadowing".
What does it actually mean?

The global variable distance has an undefined value at the start of the program. Let's assume the value is 0.
distancefonction() is called, passing distance as a parameter. This will create a copy of the value 0 on the stack.
the function will calculate the distance and update the variable on the stack.
The Serial.println() statement within the function accesses the variable on the stack and will print the correct distance.
Once the function is complete, the code in loop() will access the global variable distance, which still has the old value, because only a copy has been updated.

What is the solution?
Of course there are several solutions.

The simplest fix is probably to remove the parameter int distance from distancefonction. Thus the function will not receive a copy and instead operate on the global variable.
Another solution is to let distancefonction return the actual distance. The method signature already indicates that you wanted to return a value: the intfrom int distancefunction(...) says that. At the moment, the function does not return anything. You could write return distance; at the end. This approach could eliminate the global variable completely.

"Some people call it a global variable." because if it is on the top of the project's main ino file, the it has global scope

thanks a lot for your help it worked! i actually returned the distance from the function.


text:
Xiao ESP32-C6 in CircuitPython
So I recently bought two Xiao ESP32-C6 from SeeedStudio; they work with Arduino code out of the box. Now I want to flash the CircuitPython bootloader from here https://circuitpython.org/board/espressif_esp32c6_devkitm_1_n4/ to see if it works.
The "canonical" way of entering the ESP32 in flashing mode (at least the ESP32-S2 I own) to change its bootloader is to press and hold the BOOT and then press RESET. This procedure does not work in the Xiao ESP32-C6, the board just resets (I was expecting Windows to show it as a mass storage device). How to make it work?

EDIT: as of today (08/22/2024) there is official support from Adafruit for Xiao ESP32-C6 CircuitPython: https://circuitpython.org/board/seeed_xiao_esp32c6/ .
I made it work, flashed the CircuitPython firmware to the ESP32-C6. Turns out you have to use the "Flash download tool" from Espressif https://www.esp32.com/viewtopic.php?t=60&start=20 . I downloaded the bin file for the "ESP32-C6-DevKitC-1-N8" from here https://circuitpython.org/board/espressif_esp32c6_devkitc_1_n8/ , which I do not know to be exactly compatible with the Xiao ESP32-C6, have not tested it fully.
Tools like the "Web serial ESPtool" did not work for me https://learn.adafruit.com/circuitpython-with-esp32-quick-start/web-serial-esptool
Tested my flashing with the LED blink in Thonny IDE:
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries
# SPDX-License-Identifier: MIT
"""CircuitPython CPU temperature example in Celsius"""
import time
import microcontroller
import board
import digitalio

led = digitalio.DigitalInOut(board.IO18)
led.direction = digitalio.Direction.OUTPUT

while True:
    print(microcontroller.cpu.temperature)
    print("On!")
    led.value = True
    time.sleep(0.5)

    print("Off!")
    led.value = False
    time.sleep(0.5)
Here I document my experience: https://fritzenlab.net/2024/07/16/using-the-esp32-c6-with-circuitpython-flashing-the-bin-file/


text:
timers interrupt is not working in esp32s2 board
C:\Users\Admin\AppData\Local\Temp\.arduinoIDE-unsaved2024610-7740-sfbutd.e9d77\sketch_jul10a\sketch_jul10a.ino: In function 'void setup()':
C:\Users\Admin\AppData\Local\Temp\.arduinoIDE-unsaved2024610-7740-sfbutd.e9d77\sketch_jul10a\sketch_jul10a.ino:97:22: error: too many arguments to function 'hw_timer_t* timerBegin(uint32_t)'
   97 |   timer1 = timerBegin(0, 80, true);  // 80 MHz APB clock / 80 = 1 MHz (1 us per tick)
      |            ~~~~~~~~~~^~~~~~~~~~~~~
In file included from C:\Users\Admin\AppData\Local\Arduino15\packages\esp32\hardware\esp32\3.0.2\cores\esp32/esp32-hal.h:84,
                 from C:\Users\Admin\AppData\Local\Arduino15\packages\esp32\hardware\esp32\3.0.2\cores\esp32/Arduino.h:36,
                 from C:\Users\Admin\AppData\Local\Temp\arduino\sketches\943207E00B32310A1DFC79D26F7275B3\sketch\sketch_jul10a.ino.cpp:1:
C:\Users\Admin\AppData\Local\Arduino15\packages\esp32\hardware\esp32\3.0.2\cores\esp32/esp32-hal-timer.h:35:13: note: declared here
   35 | hw_timer_t *timerBegin(uint32_t frequency);
      |             ^~~~~~~~~~
C:\Users\Admin\AppData\Local\Temp\.arduinoIDE-unsaved2024610-7740-sfbutd.e9d77\sketch_jul10a\sketch_jul10a.ino:99:23: error: too many arguments to function 'void timerAttachInterrupt(hw_timer_t*, void (*)())'
   99 |   timerAttachInterrupt(timer1, &dim_check, true);
      |   ~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Users\Admin\AppData\Local\Arduino15\packages\esp32\hardware\esp32\3.0.2\cores\esp32/esp32-hal-timer.h:50:6: note: declared here
   50 | void timerAttachInterrupt(hw_timer_t *timer, void (*userFunc)(void));
      |      ^~~~~~~~~~~~~~~~~~~~
C:\Users\Admin\AppData\Local\Temp\.arduinoIDE-unsaved2024610-7740-sfbutd.e9d77\sketch_jul10a\sketch_jul10a.ino:101:3: error: 'timerAlarmWrite' was not declared in this scope; did you mean 'timerWrite'?
  101 |   timerAlarmWrite(timer1, freqStep, true);
      |   ^~~~~~~~~~~~~~~
      |   timerWrite
C:\Users\Admin\AppData\Local\Temp\.arduinoIDE-unsaved2024610-7740-sfbutd.e9d77\sketch_jul10a\sketch_jul10a.ino:103:3: error: 'timerAlarmEnable' was not declared in this scope; did you mean 'timerAlarm'?
  103 |   timerAlarmEnable(timer1);
      |   ^~~~~~~~~~~~~~~~
      |   timerAlarm

exit status 1

Compilation error: too many arguments to function 'hw_timer_t* timerBegin(uint32_t)'

what is your question? ... please add a focused, answerable question to your post

Hi Saranya, there are multiple errors above, which one did you want help with?

I had questions ridicularized, closed and deleted for way less that this one. How come the moderators do nothing?

Your code seems to be based on an earlier ESP32 Arduino Core version. You can either downgrade the ESP32 Arduino Core to a version earlier than 3.0.0 or you can change the code to use the newer Timer API. See https://docs.espressif.com/projects/arduino-esp32/en/latest/migration_guides/2.x_to_3.0.html#timer.

I think Espressif is changing the API for timer usage.
In 3.0.2 (which is the one you are using), the new API is timerBegin(uint32_t frequency), you can see the library example here. For version 2.0.17 or earlier, the API is timerBegin(0, 80, true), as seen here.
You have two options:

roll back your ESP32 Arduino Core (Do it on IDE Tools->Board->Board Manager menu) to v2.0.17 if you want to use the API that you used in your sketch; or
port your code based on the new Timer API with the help from the new API documentation.

If you are new to Arduino programming, the option one would be easier for you.


text:
atmega328p on breadboard using ftdi to upload sketches @8mhz 3.3v
I'm having trouble getting the atmega328p chip to upload sketches using my ftdi. It always comes up with an error saying not in sync.
I have an 8Mhz crystal with 22pf capacitors. The weird thing is I could flash the bootloader using my avrispmkII @ 3.3v. AFAIK this tells me the chip is running. I have an led connected to pin7. It doesn't flash when turn the power on.  However it does flash when powered from 5v and everything is working fine. I could upload sketches using the ftdi.
I have the ftdi on a breakout to pin headers. I have the reset pin wired up to the DTR via a 100nf capacitor. The reset has a 10k pull up. CTS pin is grounded. The usart is as follows tx (atmega) ---> rx(ftdi)  and rx(atmega) to tx(ftdi). I have also switch between 3.3v and 5v logic using the vccio pin on the ftdi. I.e. vccio = 5v if atmega is 5v.
I know the programmer need to know what voltage am using, how critical is it, since I don't have a 3.3v regulator to hand. I used a lm338 and it's coming out as around 3.2
I selected arduino pro/mini @ 8mhz 3.3v atmega328p when I flashed the bootloader
##############################################################

pro328.name=Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328

pro328.upload.protocol=arduino
pro328.upload.maximum_size=30720
pro328.upload.speed=57600

pro328.bootloader.low_fuses=0xFF
pro328.bootloader.high_fuses=0xDA
pro328.bootloader.extended_fuses=0x05
pro328.bootloader.path=atmega
pro328.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
pro328.bootloader.unlock_bits=0x3F
pro328.bootloader.lock_bits=0x0F

pro328.build.mcu=atmega328p
pro328.build.f_cpu=8000000L
pro328.build.core=arduino
pro328.build.variant=standard

##############################################################

output from avrdude
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as DA
avrdude: safemode: efuse reads as 5

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as DA
avrdude: safemode: efuse reads as 5
avrdude: safemode: Fuses OK

avrdude done.  Thank you.

pin 7 of the 328P is VCC. Per the ATmegaBOOT_168.c "/* onboard LED is used to indicate, that the bootloader was entered (3x flashing) */". Where this pin is PB5, pin 19 of the 328p or D13. Or is YOUR code attempting to blink a pin.

once programmed voltage is very flexible. See SFE's BigTime Watch Kit it runs directly on a coin cell with oscillator. which runs with "Arduino Pro or Pro Mini 3.3V/8MHz" bootloader. Where the Battery drops over time. Note your fuses are BrownOut below 2.9V so your 3.2 should be fine.

To clarify: it reads as if you are saying it ALL works when using the FTDI, even programs. But it does not when the FTDI is connected through the Breakout board. Are you saying FTDI is directly connected and the Reset circuit is not present.

To clarify the atmega 328 is on the breadboard. The ftdi has its auto reset in tact and connected. I used a bench supply at our lab. I t actually starts working at 3.5 and above. Why?

is it 3.2V at 328's VCC or at the LMN338. Is there any AC to it?

By AC  you mean ripple right? Do I just measure it as if it's an ac source

if so it's  3.2vdc between vcc - gnd pins. And the ripple at those pins is 0.004V ripple.

Let us continue this discussion in chat.

I would suspect that the 328P's fuses were not programmed as defined in the boards.txt This needs to be explicitly done.
uno.bootloader.low_fuses=0xff
uno.bootloader.high_fuses=0xde
uno.bootloader.extended_fuses=0x05
uno.bootloader.path=optiboot
uno.bootloader.file=optiboot_atmega328.hex
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F

if not done. several things can go wrong.

oscillator won't start on external crystal
oscillator will be at wrong speed code
wont start at bootloader

Thats not for the bootloader am using. I'm using the arduino pro mini bootloader. That is for the newer uno. I have checked they match what's in the boards.txt

Fuses are correct. See avrdude output at the bottom of the question

yes, that was added to the question after


text:
Multiple interrupts in same sketch
I am trying to create an Arduino program that combines a pulse sensor (that measures the Beats Per Minutes) and a music shield. I am experiencing some difficulties with the coding because the pulse sensor has an extensive interrupt routine that occurs every 2ms while the music shield has its own interrupt.
    Through research I have found that the Arduino Uno cannot have two interrupt routines at
    the same time.

Is it possible to code around this issue in order to have both the interrupt
           routines worK?

I am attaching the code below:
//Include Music Shield Library
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>

// Define everything needed for the Music Shield
#define BREAKOUT_RESET  9     // VS1053 reset pin (output)
#define BREAKOUT_CS     10    // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8     // VS1053 Data/command select pin (output)
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7       // VS1053 chip select pin (output)
#define SHIELD_DCS    6       // VS1053 Data/command select pin (output)
#define CARDCS 4              // Card chip select pin
#define DREQ 3                // VS1053 Data request, ideally an Interrupt pin

//Explain what musicplayer means
Adafruit_VS1053_FilePlayer musicPlayer =
  // create breakout-example object!
  //Adafruit_VS1053_FilePlayer(BREAKOUT_RESET, BREAKOUT_CS, BREAKOUT_DCS, DREQ, CARDCS);
  // create shield-example object!
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

//Variables for the Pulse Sensor
int pulsePin = 0;                   // Pulse Sensor purple wire connected to analog pin 0
//These variables are volatile because they are used during the interrupt service routine!
volatile int BPM;                   // used to hold the pulse rate
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // holds the time between beats, must be seeded!
volatile boolean Pulse = false;     // true when pulse wave is high, false when it's low
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

//Define integer range for the switchcase map function
const int sensorMin = 70;           // sensor minimum, dicovered through research MAY CHANGE
const int sensorMax = 230;          // sensor maximum, discovered through research MAY CHANGE

//Now we are going to set up the sensor and the shield.
//The swtichcase does not need setup because we are not using the serial monitor for it.
void setup(){
Serial.begin(115200);
  Serial.println("Adafruit VS1053 Simple Test");
  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS
//Now we setup the rest of the shield.

  if (! musicPlayer.begin()) {      // initialise the music player
     Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
     while (1);
  }
  Serial.println(F("VS1053 found"));

  SD.begin(CARDCS);    // initialise the SD card

  // Set volume for left, right channels. lower numbers == louder volume!
  musicPlayer.setVolume(05,05);

  musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT);  // DREQ int

}
//Void setup is done, now we tell the arduino what to do with all this information.

void loop(){
   // read the sensor:
  int sensorReading = analogRead(A0);
  //A0 should be BPM
  // map the sensor range to a range of four options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 4);

//In our map range 0=70-110, 1=110-150, 2=150-190, 3=190-230, 4=end(DEAD)
// do something different depending on the
// range value:
//Track 1 is resting music, track 2 is medium beat, track 3 is fast beat, and track 4 is continous beeps.
  switch (range) {
  case 0:    // 70BPM - 110 BPM
    Serial.println(F("Playing track 001"));
    musicPlayer.playFullFile("track001.mp3");
  case 1:    // 110 BPM - 150 BPM
    Serial.println(F("Playing track 002"));
    musicPlayer.startPlayingFile("track002.mp3");
  case 2:    // 150 BPM - 190 BPM
    Serial.println(F("Playing track 003"));
    musicPlayer.startPlayingFile("track003.mp3");
  case 3:    // 190 BPM - 230 BPM
    Serial.println(F("Dangerous"));
    musicPlayer.startPlayingFile("track004.mp3");
  case 4:    // DEAD
    Serial.println(F("DEAD"));
    musicPlayer.startPlayingFile("track005.mp3");
    break;
  }
  delay(1);        //This is the delay of the switchcase.
                   //The Music Shield Requests 100, so this MAY CHANGE
}

volatile int rate[10];                    // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;          // used to determine pulse timing
volatile unsigned long lastBeatTime = 0;           // used to find IBI
volatile int P =512;                      // used to find peak in pulse wave, seeded
volatile int T = 512;                     // used to find trough in pulse wave, seeded
volatile int thresh = 512;                // used to find instant moment of heart beat, seeded
volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

void interruptSetup(){
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

// THIS IS THE TIMER 2 INTERRUPT SERVICE ROUTINE.
// Timer 2 makes sure that we take a reading every 2 miliseconds
ISR(TIMER2_COMPA_vect){                         // triggered when Timer2 counts to 124
  cli();                                      // disable interrupts while we do this
  Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // keep track of the time in mS with this variable
  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise

    //  find the peak and trough of the pulse wave
  if(Signal < thresh && N > (IBI/5)*3){       // avoid dichrotic noise by waiting 3/5 of last IBI
    if (Signal < T){                        // T is the trough
      T = Signal;                         // keep track of lowest point in pulse wave
    }
  }

  if(Signal > thresh && Signal > P){          // thresh condition helps avoid noise
    P = Signal;                             // P is the peak
  }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250){                                   // avoid high frequency noise
    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) ){
      Pulse = true;                               // set the Pulse flag when we think there is a pulse
      IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
      lastBeatTime = sampleCounter;               // keep track of time for next pulse

      if(secondBeat){                        // if this is the second beat, if secondBeat == TRUE
        secondBeat = false;                  // clear secondBeat flag
        for(int i=0; i<=9; i++){             // seed the running total to get a realisitic BPM at startup
          rate[i] = IBI;
        }
      }

      if(firstBeat){                         // if it's the first time we found a beat, if firstBeat == TRUE
        firstBeat = false;                   // clear firstBeat flag
        secondBeat = true;                   // set the second beat flag
        sei();                               // enable interrupts again
        return;                              // IBI value is unreliable so discard it
      }

      // keep a running total of the last 10 IBI values
      word runningTotal = 0;                  // clear the runningTotal variable

      for(int i=0; i<=8; i++){                // shift data in the rate array
        rate[i] = rate[i+1];                  // and drop the oldest IBI value
        runningTotal += rate[i];              // add up the 9 oldest IBI values
      }

      rate[9] = IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // add the latest IBI to runningTotal
      runningTotal /= 10;                     // average the last 10 IBI values
      BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!
      QS = true;                              // set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (Signal < thresh && Pulse == true){   // when the values are going down, the beat is over
    Pulse = false;                         // reset the Pulse flag so we can do it again
    amp = P - T;                           // get amplitude of the pulse wave
    thresh = amp/2 + T;                    // set thresh at 50% of the amplitude
    P = thresh;                            // reset these for next time
    T = thresh;
  }

  if (N > 2500){                           // if 2.5 seconds go by without a beat
    thresh = 512;                          // set thresh default
    P = 512;                               // set P default
    T = 512;                               // set T default
    lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date
    firstBeat = true;                      // set these to avoid noise
    secondBeat = false;                    // when we get the heartbeat back
  }

  sei();                                   // enable interrupts when youre done!
}// end isr

I wrote most of the SFEMP3Shield library. Where it appears that AdaFruit based much of theirs on. That said I have used Timer1 library with mine just fine to invoke the filling of the VS1053.
Where I am suspicious that AdaFruit's Library's did not Interrupt lock out the SPI packets. As I did on the SFEMP3Shield library, as to keep other things from messing up the frame. Where a brief skim of your code, initially looks fine.
You have not described your symptoms.
Where as using 2ms IRQ's and noting the VS1053 library reads the SdCard in 500byte chunks I image these reads are blocking and corrupting your 2ms ISR.
You can try to slow them down, just to see if they stop getting messed up.
You can try to using the polling method of the VS1053, instead of interrupts.
You can try to use the more feature mature SFEMP3Shield library and its documentation noting that it also uses the more mature SdFat. As the stock SD library may be part of your problem.


text:
Scope error in arduino PinChangeInt library
#include<PinChangeInt.h>
#define SensorPin 2

int ledPin = 10;
int BuzzerPin = 12;
volatile byte blip = 0;

void blipcount(){
  blip++;
};

void setup() {
   // put your setup code here, to run once:
   pinMode(SensorPin,INPUT);
   pinMode(ledPin,OUTPUT);
   pinMode(BuzzerPin,OUTPUT);
   PCintPort::attachInterrupt(SensorPin,blipCount,FALLING);
   Serial.begin(9600);
}

void loop() {
   // put your main code here, to run repeatedly:
   if(digitalRead(SensorPin)==HIGH){
      digitalWrite(ledPin,HIGH);
      digitalWrite(BuzzerPin,HIGH);
      Serial.print("blipcoun:\t");
      Serial.println(blip,DEC);
   }

   if(digitalRead(SensorPin)==LOW){
      digitalWrite(ledPin,LOW);
      digitalWrite(BuzzerPin,LOW);
   }
}

I am using arduino uno for a project.I need to record when my sensor gives a high value but i need it to read only falls in pulses.The program is giving  error as
Arduino: 1.6.3 (Windows 8.1), Board: "Arduino Uno"

Sense.ino: In function 'void setup()':

Sense.ino:14:38: error: 'blipCount' was not declared in this scope

Error compiling

please tell me what is the problem with the function.
The library link is
https://code.google.com/p/arduino-pinchangeint/downloads/list
tested the code on both 1.72 and 2.19

void blipcount(){   blip++; }; why the ; at the end of the function?

You have a typo:
PCintPort::attachInterrupt(SensorPin,blipCount,FALLING);

Should be:
PCintPort::attachInterrupt(SensorPin,blipcount,FALLING);
                                         ^

Note the lower-case "c".


text:
Arduino Uno - combined LCD and keypad interfacing problem
I have a problem with the Arduino Uno.
I need to use a 4x3 keypad and 16x2 LCD together with an Arduino Uno. As 4x3 keypad requires 7 pins, I have defined pins 2, 3, 4, 5, 6, 7 and 8 to it. A 16x2 LCD requires 6 pins but only 5 pins remain (9, 10, 11, 12 and 13). Pins 0 and 1 are used for serial.
Please suggest a probable solution.

Welcome to Arduino SE! What exactly is your issue? Pin assignment? Please edit your question to reflect exactly what you need. Thanks!

You could use a shift register to read the switches as outlined by the excellent tutorial Parallel to Serial Shifting-In with a CD4021BE. Quoting the summary:

Sometimes you'll end up needing more digital input than the 13 pins on
  your Arduino board can readily handle. Using a parallel to serial
  shift register allows you collect information from 8 or more switches
  while only using 3 of the pins on your Arduino.

So you would only use 3 pins to read the seven switches, which would leave you with 9 pins to play with, for the LCD.
In addition, you could use a similar method for the LCD, using a shift-out register, and use just 3 pins for the 6 inputs of the LCD. A tutorial for that is Alphanumeric LCD with Shift Register on Arduino – part 1, using the AlphaLCD library or 3-Wire Serial LCD using a Shift Register, which has no library, but provides code.
This would leave you with 6 pins free (out of the total 12 pins, if you exclude pins 0 and 1 for serial), after both the switches and LCD are wired up.
Of course, this solution requires you to purchase one or two shift (in and/or out) registers.
The Arduino IDE may come with a built-in library that use shift registers, but I am not sure about that. Maybe someone can confirm, or refute, this?
I hope that this helps.

Is there any tutorial for LCD and CD4021 using Arduino LCD Library?

@xcoder - I've updated my answer.

Am new at this but I am working on a similar work, it is possible to use the pin 0 for your keypad, the pin is a RX pin by default making the pins(0,2,3,4,5,6,7).
As for the LCD I would suggest you use an i2c backpack, it is a parallel to serial converter and means you would only need to use 2 pins (SDA, SCL which would be connected to pin A4, A5)
Try the code below for the keypad (The code is if you have an i2c backpack)
#include <Wire.h>
#include <Keypad.h> //keypad library
#include <LiquidCrystal_I2C.h> //library for the backpack

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

//define the Symbols on the buttons of the keypads
  char hexaKeys[COLS][ROWS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};

byte rowPins[ROWS] = {0, 2, 3, 4}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 6, 7, 8}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

void setup(){
  Serial.begin(9600);
  lcd.begin(16,2);
  for(int i = 0; i< 3; i++)
  {
    lcd.backlight();  delay(250);
    lcd.noBacklight();  delay(250);
  }
  lcd.backlight();
}

void loop(){

  char customKey = customKeypad.getKey();

  if (customKey){
    lcd.print(customKey);
  }
}


text:
How to read info from an Xbee Pro S2B to an Arduino with a Xbee Pro S2B
I am using two XBee Pro S2B modules. One (Router) connected to the laptop via a UART cable. The other (Coordinator) connected to an Arduino Mega with the sketch below.  All I need it to do is turn a LED on and off and display the status in the IDE serial monitor.  I am using Arduino IDE (v1.6.0).
Arduino sketch:
#include <SoftwareSerial.h>

SoftwareSerial xbee (2,3);

int myData = 0;
int ledPin = 13;

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

    pinMode(ledPin, OUTPUT);
}

void loop()
{
    if (Serial.available())
    {
         int myData = Serial.read();

         if(myData == '1')
         {
             digitalWrite(ledPin,HIGH);
             Serial.write(myData, DEC);
         }
         if(myData == '2')
         {
             digitalWrite(ledPin,LOW);
             Serial.write(myData, DEC);
         }
     }
 }

Where did I go wrong?

You have two serial connections. One for the main USB of the board and one for the XBee.
So you need to read from the XBee and write to the serial USB?
I don't know what speed you have configured for your XBee so I have set it to 9600.
This example reads from the XBee and writes to the Serial/USB port
#include <SoftwareSerial.h>

SoftwareSerial xbee (2,3);

int myData = 0;
int ledPin = 13;

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

    pinMode(ledPin, OUTPUT);
}

void loop()
{
    if (xbee.available())
    {

         int myData = xbee.read();

         Serial.print("Data has arrived on the Arduino");
         Serial.write(myData);
         Serial.println();

         if(myData == '1')
         {
             digitalWrite(ledPin,HIGH);
             Serial.write(myData);
         }
         if(myData == '2')
         {
             digitalWrite(ledPin,LOW);
             Serial.write(myData);
         }
     }
 }

Note: Your example also used Serial.write() with the wrong argument DEC which applies to Serial.print(). X-CTU and Arduino both send ascii which is also what the Serial.print() does. However the Serial.read() just reads the byte so we need to use Serial.write() to send the same bytes back to the other end.
You can also make life a bit easier by replacing xbee.available() with Serial.available(). Then use the Arduino IDE serial monitor to both send and receive. This means that you just use the one USB connection to prove the code.

Hallo, My speed is 9600.  I copied the program but when i tried to validate and upload i get the following error " C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:53:20: note:   no known conversion for argument 1 from 'int' to 'const uint8_t* {aka const unsigned char*}'"

I have changed the "Serial.write(myData,Dec);" to "Serial.write(myData)". Then i can upload it, but it still does not work. does it matter were the router and the co ordinator goes?

What does "still doesn't work mean"? You need to provide more info. For example are you receiving data on the other arduino? did you hook up normal serial so you can trace/debug via the pc serial window? What is the code at the other end?

I am not not receiving any data on the Adruino because nothing is being displayed in the Arduino serial monitor.  I have connected the one xbee to the XCTU program that needs to send a 1 or 2 across to the other xbee/arduino to be displayed in the Arduino serial monitor and opperate a LED.  I do not know what "hook up normal serial" means but both are connected to the laptop.  There is no code on the other end.

I see. Well one thing to do is to add a Serial.println("Hello, some serial was found") command just inside where you check for Serial.available(). I also suggest you post the code from the other Arduino that sends the 1 or 2

There is no other arduino yet.  I am doing baby steps.  The 1 and 2 is being sent directly over the xbee connected to the laptop with a UART cable. I have edited my program with "Serial.println"  and Nothing is being displayed in the serial monitor of the Arduino IDE.  So i think it does not pick up the serial port?  But it has the same baud rate and the other setting of the xbee's are correct because i can do a simple chat with them.

It would help if you were clearer about what is being sent to the arduino and the code you have posted. What are you typing into the Serial monitor?

Ok, I am typing in a "1" or a "2" into XCTU which is connected directly to the one Xbee 2B.  It must then pass the data wireless to the other Xbee 2B which is connected to the Arduino Mega 2560.  The Arduino must process the data and display it in the Arduino Serial monitor and also turn the LED "ON" or "OFF".  If it receives a "1 the LED must turn ON" and a "2 it must turn OFF".  I am using the program above.  No data is transferred across the Xbee's.  The Xbee setup is correct to my knowledge.

Saying the Xbee setup is correct is confusing because you are not using xbee you are just using xctu connected via a 2nd usb cable to Pin2 and 3 on the Arduino? You also have the upload usb cable plugged from the Arduino to the Pc? Both x-ctu and the arduino serial monitor are open and both are set to 9600? I will edit the example to show how to add better diagnostics for problem solving. Hope it helps.

What I ment by Xbee setup, I mean that the PANID's are the same, the DL and DH addresses are set And the buad rate is 9600.  Yes, I have a Uart cable connected to a xbee adapter for Xbee 1.  And the other xbee is connected to a shield (Xbee pro shield) onto the Arduino via a usb cable to the laptop. Yes, both the X CTU and Serial monitors are open at the same time and there baud rate is 9600.  I will appreciate it.  Thank you.

Have you done the loop back test in xctu?

No, I am very new with all of this. What must i do?

Use the arduino.cc or other forum to learn. This site is not geared towards long running educational threads. Just questions with answers. Or open another question. I think I have answered your initial question.


text:
Read values from a txt file on an SD card
I'm trying to read a text file (has numeric values) from SD card. The values in the file like this
87 512
255

I need to read 87 in ch1 and 512  in ch2 and 255 in ch3.
Why did I get on 'SKIP_NONE' 'SKIP_WHITESPACE' was not declared in this scope?
int ch1 = in_file.parseInt(SKIP_WHITESPACE);
Serial.printf("First = %d \n",ch1);

int ch2 = in_file.parseInt(SKIP_NONE, '\n');
Serial.printf("Second = %d \n",ch2);

int ch3 = in_file.parseInt();
Serial.printf("Third = %d \n",ch3);

What Arduino are you compiling for? What core version are you using?

Can I know why the -1 ??!!!

Why the -1? Because some people... (fill in the blanks).  I just corrected the transgression by upvoting your question.  Why?  Because it's a good question, and a downvote without a helpful comment serves no purpose except to discourage you, and that doesn't help anyone and only hurts the community.

Ignore the downvotes. People are allowed to downvote, and they are not required to give a reason. Just ignore them. I'm a moderator and I get downvoted. :P

These symbols were introduced in the Arduino AVR core 1.6.7, in
December 2015. You can find them in Stream.h. They are probably
defined in other cores too.
For some reason, the Teensy cores do not define them. You may consider filing an issue in their GitHub project.


text:
Arduino unstable analog reading when using power supply
As soon as I unplug my Arduino from USB and only use the VIN pin with my 9 V power supply, the analog readings from my Arduino start to get unstable, which means the value fluctuates much more than with USB connected. When I reconnect USB again, the readings are stable again.
I'm trying to build a load scale using a load cell, an INA125P and the Arduino, using this setup here: Instrument Amplifier Calibration.
Therefore I need stable readings. For example, I wrote some code to convert the analogRead() value to grams. While USB and VIN (9 V) connected, I get a stable reading of about 8.3 to 8.7 grams when I put a weight of 8.5 grams on the scale. As soon as I unplug USB, the LCD shows values from 7.8 grams up to 9 grams.
Unfortunately, I don't have any other power supply which I could use to test. I've already tried to use a 9 V battery with the same results. Do I maybe need some additional de-coupling capacitors?

It's more likely that you need a beefier regulator. The on-board regulator on an Arduino can only supply a tiny amount of current (a few tens of mA) at 5V to external circuitry (beyond what the Arduino itself needs). When the USB cable is plugged in, the USB host can supply at least 500 mA (probably more) at 5V without any problem.

First of all what is your board? 'cause different boards have different regulators. And then... If you need precise values, avoid using the supply voltage as reference: it is really noisy and unprecise. Use the internal analog reference if it suits your needs, or otherwise use an external voltage reference. Use the power supply reference only when you don't need precision or you have a ratiometric sensor (e.g. a potentiometer)

I got the same issue where too much ripple from power supply, I saw this article bit late where I used an digital sensor to get away with analog read.

I solved a similar issue by adding a pin from supply to AREF and it's now stable. This fixed a frustrating pH meter issue on my Mega that every time I plugged USB in it would be right, but as soon as I dropped the USB cable it changed the readings.

This answer was reported as "not an answer", I find that false. He just provided an example before his solution (rearranged that now). If his answer is not useful, please use the This answer is not useful button instead of the Flag button.

OK @Avamander. Understood.

Load cell signals are very small and without proper shielding are be susceptible to noise. The USB power connector is likely earth grounded (the clue was battery operation is noisy, exact opposite of expectations!) I suggest testing this hypothesis:

Check with ohm meter if exposed metal on USB connector is connected to earth (chassis on your PC is usually earth connected).
Touch an earth grounded conductor to the signal ground of the load cell amplifier and see of the readings become more accurate.

The final solution is to use properly shielded signal wires between the load cell and the amplifier. Also the signal wires between load cell and amplifier should be a 'twisted pair' to further reduce noise.

I would say that this may be related to the analog reference. Try AnalogReference and see if it helps.

Without much information (software, schematic, hardware, measurements ...) It is hard to tell.
My guess would be that you used vcc as a dc reference and the circuit draws too much current from the battery than it can deliver so bcc dips, leading to a rise and instability in the reading.
Good luck debugging it.


text:
Linker missing using Arduino IDE
I use the Arduino IDE 1.8.5 and it seems the linker disappeared. The error messages are:
arm-none-eabi-g++: warning: {compiler.optimization_flags}: linker input file unused because linking not done\
arm-none-eabi-g++: error: {compiler.optimization_flags}: linker input file not found: No such file or directory

... bla-bla ...

*exit status 1
Erreur de compilation pour la carte Generic STM32F1 series*

I reinstall the IDE and the linker is not reinstalled, the error message remains.
Where should I look/what should I do to complete the compilation ?

key {compiler.optimization_flags} was not replaced by a value so the linker thinks it is an input file. maybe try a newer version of the IDE

Check if all necessary libraries and paths are correctly set up in the Arduino IDE. Also check if the PATH variable includes the path to the ARM toolchain and other necessary tools.


text:
Communication between two hc 05 Bluetooth modules not working
I Have a problem with the connection between two hc 05 modules. The bluetooth modules are paired using AT commands. But when I run the code I cant get any data from the reciever. The bluetooth modules blink together but no data is displayed in the reciever. This is for a RC car that is controlled by a remote controller.
This is the code for the remote
void setup() {

  Serial.begin(38400);
}

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

I have made sure all the baudrates are 38400 and when I just type the numbers in the serial monitor of the reciver it works fine. I have switched the bluetooth modules but It didn't work either. Boath remote and car has TX - RX and RX - TX wiring.
This is the code of the reciever
int data = 0;

void setup() {

  Serial.begin(38400);
}

void loop() {
  if(Serial.available() > 0){
    data = Serial.read();

    Serial.print(data);
  }
}

I used softwere serial as well but It gave me the same result. The reciever is an arduino mega and the transmitter is an arduino nano
Pls help.
Thank you.

reduce your code to sending and receiving one fixed byte

I tryied that but It didn't work, it didn't receive the data on the reciever. Thanks for the reply!

ok I changed it


text:
ESP32 HTTP Request handles Go webserver response, but fails on node JS servers
I've set up an esp32 board (wemos d1 r32) to send a request to a server hosted on my local network. If I set up a very basic go server, the board handles the response fine (200 with the appropriate body content). Once I switch to a Node JS Server, it only responds with a 400 status code. Weirdest of all none of the console.log calls in the route handlers get called, which indicates that it quits before it even gets to the express server. I've tested that the server returns the body & status code I want using postman, all looks good.
I've tried different frameworks (Koa) to see if this is related to Express, but it doesn't work with that either. I assume its something to do with NodeJS?
Express server
import express from "express";

const app = express();
app.use(express.json());
app.post("/", (req, res) => {
  console.log(req.body);
  req.statusCode = 200;
  res.send("200");
});

app.get("/hello", (req, res) => {
  res.setTimeout(50000);
  console.log(req.body);
  res.setHeader("Location", "123");
  res.setHeader("Server", "123");
  req.statusCode = 200;
  res.send("200");
});

app.listen(8090, () => {
  console.log(`Example app listening on port ${8090}`);
});

Go server
package main

import (
    "fmt"
    "net/http"
)

func hello(w http.ResponseWriter, req *http.Request) {
    for name, headers := range w.Header() {
        for _, h := range headers {
            fmt.Fprintf(w, "%v: %v\n", name, h)
        }
    }
    fmt.Fprintf(w, "hello\n")
}

func headers(w http.ResponseWriter, req *http.Request) {

    for name, headers := range req.Header {
        for _, h := range headers {
            fmt.Fprintf(w, "%v: %v\n", name, h)
        }
    }
}

func main() {
    fmt.Println("?")

    http.HandleFunc("/hello", hello)
    http.HandleFunc("/headers", headers)

    http.ListenAndServe(":8090", nil)
}

Arduino script
#include <HTTPClient.h>
#include <WiFi.h>

// #define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include "esp_log.h"

const char* ssid = "xxx";
const char* password = "xxx";

String webserver = "http://192.168.0.19:8090/hello";

String qrCode;

void WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Connected to AP successfully!");
}

void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info){

  WiFi.disconnect(true);
  delay(1000);
  WiFi.mode(WIFI_STA);
  delay(1000);
  Serial.println("Disconnected from WiFi access point");
  Serial.print("WiFi lost connection. Reason: ");
  Serial.println(info.disconnected.reason);
  Serial.println("Trying to Reconnect");
  WiFi.begin(ssid, password);
  delay(5000);
}

void setup() {
  esp_log_level_set("*", ESP_LOG_VERBOSE);
  Serial.begin(9600);
  Serial2.begin(9600);
  Serial.println("Hello, ESP32!");
  Serial.println(WiFi.getMode());
  Serial.println(WiFi.macAddress());

  WiFi.onEvent(WiFiStationConnected, WiFiEvent_t::SYSTEM_EVENT_STA_CONNECTED);
  WiFi.onEvent(WiFiGotIP, WiFiEvent_t::SYSTEM_EVENT_STA_GOT_IP);
  WiFi.onEvent(WiFiStationDisconnected, WiFiEvent_t::SYSTEM_EVENT_STA_DISCONNECTED);

  WiFi.begin(ssid, password);
}

int cnt = 0;

void loop() {
  while (Serial2.available()) {
    int  ch = Serial2.read();
    char character = ch;
    Serial.print(ch);

    // end char
    if(character == 13){
      Serial.print("\n");
      Serial.println(qrCode);
      Serial.println(cnt);
      qrCode = "";
      cnt = 0;
      send(qrCode);
    } else {
      cnt = ch + cnt;
      qrCode = qrCode + character;
    }
  }
}

void tryWifi() {
  WiFi.begin(ssid, password);
  int status = WiFi.status();
  while (status == 6 || status == 4 || status == 5 || status == 1) {
    Serial.print("Failed to connect:");
    Serial.print(status);
    Serial.print("\n");
    delay(1500);
    WiFi.begin(ssid, password);
  }
}

void send(String json) {
  HTTPClient http;

  if(http.begin(webserver)){

      int httpCode = http.GET();
      http.addHeader("Content-Type", "application/json");
      http.addHeader("Host", "something");
      // client.print("Content-Length: ");
      delay(1500);

      Serial.println(httpCode);
      Serial.println(http.getString());
      if (httpCode > 0) {
      Serial.printf("[HTTP] GET... code: %d\n", httpCode);
        if(httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          String payload = http.getString();
          if (payload != "false"){
            Serial.println(payload);
            delay(1500);
          } else {
          Serial.println("Bad Playload");
          }
        } else {

        }
      } else {
      Serial.println("Error sending to HTTP");
      }
      http.end();
    } else {
      Serial.println("?");
    }
}

Your Arduino code reads like this:
  int httpCode = http.GET();
  http.addHeader("Content-Type", "application/json");
  http.addHeader("Host", "something");
  // client.print("Content-Length: ");
  delay(1500);

  Serial.println(httpCode);
  Serial.println(http.getString());
  if (httpCode > 0) {

The call http.GET() actually performs the HTTP request. You're adding headers after you perform the request. They need to be added before it. So your code should read:
  // http.addHeader("Content-Type", "application/json");
  int httpCode = http.GET();

  // delay(1500);   -- there's no need to call delay() here

  Serial.println(httpCode);
  Serial.println(http.getString());
  if (httpCode > 0) {

HTTP status code 400 means "bad request". Some web servers will return this code if headers that they expect to see are missing or have non-sensical values. The Go and Javascript web servers are different implementations and may behave differently with malformed requests.
I've removed "Host" header as HTTPClient does this for you. And there's no need for the delay() call after calling http.GET().
Edit: I also commented out the "Content-Type" header as it makes no sense on a GET request, thanks to @EdgarBonet for mentioning that. I'm leaving it there as a comment to make it clear that that any headers should be added before the request is performed.

Note also that "Content-Type" does not make sense on an HTTP request. The OP probably means "Accept".

@EdgarBonet  Thanks, good point. It does actually make sense on a PUT or POST request that has a body, but not on a GET, which should never have a body. I've edited the answer. I suspect OP was just throwing in random lines of code to see if they fixed their problem.

Thanks for the comments. I had the Content-Type header there as I intend to use a POST request w/ a json body. I've moved the call to set the header before the request is fired, nice catch!

I've figured out after an unreasonable amount of time that the request fails with a 400 as it doesn't have a slash at the end of the URL (http://192.168.1.208:8090 -> http://192.168.1.208:8090/). This must be something specific to NodeJS, as it works ok on a go server.