text:
Arduino randomly stops sending data to python over serial
I want to send commands to Arduino over USB Serial from my python program and Arduino should send back received command to make sure data wasn't lost. However Arduino randomly stops sending data back. For debugging purposes I made builtin LED blink in the loop function. When Arduino stops sending data the LED slows down blinking (about 2-3 times).
I tried this on Arduino Uno and Arduino Nano to make sure it is not damaged board.
Here is my Python code responsible for communication:

class Communication(ABC):
    def __init__(self) -> None:
        self.history: list = []
        self.response_history: list = []
        self.last_responses: dict = dict()
        self.queue: collections.deque[str] = collections.deque()
        self.is_sending: bool = False
        self.command_recived_condition: threading.Condition = threading.Condition()

    def append_commands(self, commands: str) -> None:
        commands = map(lambda x: "c"+x, map(lambda x: x+";", filter(len, commands.split(";"))))
        for command in commands:
            self.queue.append(command)

    def append_and_send(self, commands: str) -> None:
        self.append_commands(commands)
        if not self.is_sending:
            self.sender: threading.Thread = threading.Thread(target=Communication.send_commands, args=(self, ))
            self.sender.start()

    @abstractmethod
    def send_command(self, command: str) -> bool:
        """ Sends command to the controller, waits for the response and tries again if command was not recived succesfully """
        pass

    @abstractmethod
    def listen(self) -> None:
        pass

    @abstractmethod
    def check_for_response(self, command: str) -> None:
        pass

    def send_commands(self):
        self.is_sending = True
        commands = self.queue
        while len(commands) > 0:
            command = commands.popleft()
            self.send_command(command)

        self.is_sending = False

class Serial_comunication(Communication):
    def __init__(self, port: str) -> None:
        super().__init__()
        self.serialcom = serial.Serial(port, 4800)

        self.listen()

        time.sleep(0.1)
        self.send_command("PING;")
        time.sleep(0.1)

    def listen(self) -> None:
        def listen_util() -> None:
            chars = []

            while True:
                if self.serialcom.inWaiting() > 0:
                    time.sleep(0.01)
                    try:
                        char: str = self.serialcom.read().decode()
                    except UnicodeDecodeError:
                        print("decoding err")
                        continue
                    print(char, end=" ")

                    if char[-1] == '#':
                        response_str = "".join(chars)
                        category, content = response_str.split("::")
                        self.last_responses[category] = content
                        self.response_history.append(response_str)
                        chars.clear()
                        print("\n", response_str)
                        if category == 'Info: recived':
                            with self.command_recived_condition:
                                self.command_recived_condition.notify()
                    else:
                        chars.append(char)

                time.sleep(0.01)

        self.listener = threading.Thread(target=listen_util)
        self.listener.start()

    def check_for_response(self, command: str) -> None:
        print("check")

        if self.last_responses.get('Info: recived') == command:
            print('possitive')
            return True

        return False

    def send_command(self, command: str) -> None:

        while True:
            time.sleep(0.1)
            self.serialcom.write(command.encode())
            print("sent", command)

            with self.command_recived_condition:
                self.command_recived_condition.wait()
                print("waited")

            if self.check_for_response(command.strip().strip(';')):
                break

And my Arduino Code responsible for communication:
#define INPUT_SIZE 50
char input[INPUT_SIZE + 1];

bool check_for_orders(Order& cmd, char *val, uint8_t& place)
{
    if (Serial.available() > 0)
    {
        // Read input from Serial until ; what means command has ended
        size_t size = Serial.readBytesUntil(';', input, INPUT_SIZE);
        input[size] = 0; // Add null terminator

        Serial.print(F("Info: recived::"));
        delay(10);
        Serial.print(input);
        Serial.print(F("#"));
        Serial.flush();

        // Check if command is not empty
        if (input[0] != 0)
        {
            // syntax is "order:pattern_place:value"
            cmd = static_cast<Order>(atoi(strtok(((char*)input)+1, ":"))); // Get order numer and convert to enum
            place = atoi(strtok(NULL, ":")); // Get place number from input (only 0 or 1 is allowed)
            char *value = strtok(NULL, ":"); // Get value from second part of string

            if (value == 0) // If value is empty then syntax is invalid
            {
                return false;
            }

            // Otherwise copy order name and value to c-strings from main function
            strcpy(val, value);
            free(value);

            return true;
        }
        else // Probably never gonna happen
        {
            return false;
        }
    }
    return false;
}

The check_for_orders function is run every time loop function is run.
Here is what python printed when I sent the following commands ["PING;", "c0:0:0;", "c0:1:0; c15:0:100,600,20,2,0,200,255,170,255,200;"]
sent PING;
I n f o :   r e c i v e d : : P I N G #
 Info: recived::PING
waited
check
possitive
sent c0:0:0;
I n f o :   r e c i v e d : : c 0 : 0 : 0 #
 Info: recived::c0:0:0
waited
check
possitive
sent c0:1:0;
I n f o :   r e c i v e d : : c 0 : 1 : 0 #
 Info: recived::c0:1:0
waited
check
possitive
sent c15:0:100,600,20,2,0,200,255,170,255,200;
I n f o :   r e c i v e d : : c 1 5 : 0 : 1 0 0 , 6 0 0 , 2 0 , 2 , 0 , 2 0 0 , 2 5 5 , 1 7 0 , 2 5 5 , 2 0 0 #
 Info: recived::c15:0:100,600,20,2,0,200,255,170,255,200
waited
check
possitive
sent c1:0:1;
/* and it got stuck */

Do someone know why something here is getting stuck and/or how to solve this problem?

4800 baud (I guess that is your baudrate) is pretty show. Depending on how often and how much you send you can easily overload the serial interface. Have you tried using a bigger baudrate? And can you provide a minimal working example, that shows your code? I mean a full working code, but without any non relevant code in it and that still shows your problem.

don't free(value)

I removed free(value) - rookie mistake - but that didn't completely solved the problem (but reduced frequency of occurrences).
Seems like declaring array like char val[50] and passing it to function as char* val was a bad idea. I changed array declaration to char *val = new char[50] and now seems like everything works fine.

Sending char* val is fine as long as: 1. you don't overflow the val; 2. you allow the last byte for NULL byte; 3. the val is always NULL terminated, no matter the size or you also send the size of it


text:
opencv reading the display and doesnot provide serial communication with arduino
I was creating a project where the following part of the code reads certain area of the display(which i screen shared from mobile)
import cv2 as cv
import numpy as np
from PIL import ImageGrab
import serial
arduinodata = serial.Serial('com5',9600)

def led_on():
    arduinodata.write(b'1')

def led_off():
    arduinodata.write(b'0')
i=1

while True:
    screen = np.array(ImageGrab.grab(bbox=(0,0,1920,1080)))
    #define the screen resulation
    screen_res = 1920, 1080
    scale_width = screen_res[0] / screen.shape[1]
    scale_height = screen_res[1] / screen.shape[0]
    scale = min(scale_width, scale_height)
    #resized window width and height
    window_width = int(screen.shape[1] * scale)
    window_height = int(screen.shape[0] * scale)
    #cv.namedWindow('Resized Window', cv.WINDOW_NORMAL)
    cv.resizeWindow('Resized Window', window_width, window_height)
    resized = screen.resize()
    health_bar = screen[262:268, 142:365]

    health_grayed = cv.cvtColor(health_bar, cv.COLOR_BGR2GRAY)
    count1 = cv.countNonZero(health_grayed)

if i==1:
    e =count1
    i=0

if e>count1:
    led_on()
    e=count1

if e<count1:

    e=count1

and whenever the value of the count1 variable decreases i want the Arduino led should be turned on
this was the arduino code
char serialData;

void setup() {
  // put your setup code here, to run once:
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
  Serial.begin(9600);

}

void loop()
  // put your main code here, to run repeatedly:
{
  if(Serial.available() >0)
  {
    digitalWrite(13,HIGH);
    delay(1000);
    digitalWrite(13,LOW);

   }

}

But the led is turning on but does not turns off . I don't know why
can anyone please help me

This happens because you are not reading from Serial.
When you send data to the Arduino, it gets placed in the Serial buffer. Serial.available() then returns the number of bytes in the buffer. The bytes are removed from the buffer by Serial.read()ing them, which you don't do. Since you don't remove any bytes from the buffer, Serial.available() will always return a number greater than zero from the moment on, that the first byte arrives. After the delay you turn the LED off via digitalWrite(13,LOW);, but in the next loop iteration the if statement is again executed (as described above). This happens so fast, that you think the LED just stays on. In reality it gets turned of for maybe a few microseconds and then turned on again.
You are sending a single byte for the LED to react. So it would be the simplest solution to just read a single byte from the buffer inside of the if statement. The result can be discarded.
void loop()
{
  if(Serial.available() >0)
  {
    digitalWrite(13,HIGH);
    delay(1000);
    digitalWrite(13,LOW);
    Serial.read();
   }
}

The Serial.read() removes one byte from the buffer and returns it (so it gets discarded here). This way the LED blinks for every byte, that the Arduino receives over Serial.

Note: Depending on how fast you are sending the data you might want to make more clear, that you have individual bytes. With the above code the LED will light up for 3 seconds straight if you send 3 bytes in (relatively) fast succession (meaning consecutive bytes less than a second apart). To make it more clear, that you have 3 individual bytes, you can add a delay() call after turning the LED off. That gives you the chance to actually see it turning off.

source: Stack Exchange

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

sort: votes


text:
My bluetooth module keeps sending out constant exports
So I have a bluetooth module hooked up to my arduino to control an LED light, something simple to turn on and off. But the app im using constantly is either sending something or receiving. This causes the circuit to not work at all and I cannot figure out what is going on.
void setup() {
   Serial.begin(9600);
   pinMode(8, OUTPUT);
}

void loop() {
   if(Serial.available()>0)
      {
         char data= Serial.read();
         switch(data)
            {
               case 'a': digitalWrite(8, HIGH);break;
               case 'd': digitalWrite(8, LOW);break;
               default : break;
            }
         Serial.println(data);
      }
      delay(50);
}

Your Arduino code is only sending, if it received some data. We don't know your app, so it might be constantly sending data. You could test that by connecting TX of the bluetooth module to TX on the Arduino, holding it in reset and then look at the Serial monitor, what was received there. (or you can use a sketch with a SoftwareSerial interface)

If you send a char from your app, you will send such char plus '\n' or '\r\ or both. For each char your sketch will print a (blank) line.

enable hex rx in your app ... i think that it will allow you to see non-printing characters

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


text:
What is required to run a program preciously uploaded and working from Arduino IDE via PC... (Nano 33 IoT)... but now powered via VIN, not USB?
The Arduino IDE works beautifully with the Nano 33 IoT using the IDE and is powered via USB. I now want to disconnect the USB and power thru the VIN pin (6-22V). The green led comes on but the program is not there or not running. Please help.  thank you!

Does this answer your question? MKR GSM 1400 Works only when connected to computer

Once you upload your code into the Arduino, it is there, burned into the flash memory of the microcontroller and it runs no matter how you power your board.
However, if in order to run your program is dependent on the Serial interface, for instance you added a line like while(!Serial) and you have not connected the USB cable, the program will loop at that point and will not continue.
For more information please upload your code.

you made the same error as OP. you didn't search for an existing answer


text:
External Power for MicroServo (SG92R)
Why won't my MicroServo run at external 5v power supply? , I've tested my power supply and can light up 1 LED and also run the servo mainly on arduino and it works just fine. Im currently using a computer power supply using the red wire(5v). I'm not very knowledgeable with voltage and stuff and im hoping someone can answer.

and here is my power supply...

I've checked the power supply terminals but nothing is wrong there. Also, i've tried 10k potentiometer to be supplied by it but when i read it in serial.begin it just reads "0, 0, 0, 0, 1023, 1023, 1023, 1023" over and over again. Sorry about the formats im still new.

are you trying to power the servo by using only one wire connected to the power supply?

Im using ground and red wire to connect to servo and yes using power supply to power the servo

even adapters that supplies 4.8v volts still won't power

Did you connect all grounds? You might want to show us your circuitry.

Or take a picture of your project such that it is clear how components are connected.  That is, a picture where it is clear where all the wires are are going.

The image you uploaded shown quite clearly that you have not connected the grounds between the Arduino circuit and the servo circuit. In order for it to work, the servo should reference the signal line to ground, currently only PC power supply is providing ground, so the Arduino signal line is floating.
Check out the attached image and connect the GND as shown in dotted yellow line.

Oh wow , it works now. Didn't know about that, I thought as long as the GND and +5 of servo must be connected to power supply terminals it'll work. Im learning new things thanks alot

You are welcome, you can also mark the answer so it will show as solved your issue.


text:
Atmel SAMD21 microcontroller not making a USB port anymore
My custom board with Atmel SAMD21 microcontroller (same as Arduino MKR Zero) is not making a USB port since yesterday. The board was working fine before that.
Please suggest ways to resolve this issue. What are the possible reasons for such an issue?
Since reset is equivalent to powering the board ON and OFF which has not resolved the issue, can burning the bootloader again help?
Further information:

The board seems fine. It powers ON and OFF in the usual manner.
This problem with the USB port connection happened while I was trying to upload the code.

The USB pin connections on the board have been checked as well as tested with different USB wires.
Appreciate your help.

Does this answer your question? Why is the IDE not able to find the board despite it being clearly seen and selected?

Press reset twice to activate the bootloader.

The custom board does not have a reset button. Is there another way to get into the bootloader mode? Also, there is a GPIO pin-out for reset pin. Will burning the bootloader again help with the problem?

A wire can do the job of a reset button.

Yes, this worked. Appreciate your help Majenko ! :)

Solutions to the problem:

External Hardware Reset -- using a reset button (that I externally managed to solder using the Reset pin-out) -- to get into bootloader mode and start the program from the beginning

Thanks Majenko, from the comments.

Burning bootloader again may also work (theoretically) - I have not tried and tested it.

For detailed understanding - follow this post - https://forum.arduino.cc/t/atmel-samd21-microcontroller-not-making-a-usb-port-anymore/882504/5

What are the possible reasons for such an issue?

I noticed that calling
Serial.begin(115200);
...
SerialUSB.begin(115200);

in the script can cause this.
See post Seeeduino XIAO stopped connecting - Enter Bootloader Mode is not working


text:
run a function for a certain amount of time!
i'm working on a project where i need to run a function for 20 minutes and the function writes to memory using EEPROM every minute. How can i make the function run for 20 minutes, i was thinking of using millis to measure the time between starting time and current but i'm afraid that when the millis rolls over and the the difference in time becomes negative my program will break and my function will run forever . Is there any way to make a function run for a certain amount of time, or will millis handle the rollover if we use unsigned variables for all variables for millis();

the difference will not become negative ... this has been covered here many times

See this answer for an explanation. Using unsigned variables, and subtracting will definitely work.
Not only will unsigned variables not become negative (by their very nature) but the rollover will be handled smoothly and accurately.

I would flag this as not an answer. it is a comment

Well, it perfectly answers will millis handle the rollover if we use unsigned variables for all variables for millis();

it is a comment - it answers the question. It looks "short enough" to be a comment, and I note there is such a comment under the question. However comments under the question are for clarifying the question and not answering it. If I am wrong, then someone can explain why, and perhaps vote it down. Which I note hasn't happened.

Another way to solve this problem is using cronAlarm. It can provide precise control on timings and you can schedule your job also. https://www.arduino.cc/reference/en/libraries/cronalarms/


text:
Dropping a 75V power supply to power an Arduino Mega
I'm looking to power an Arduino Mega using this IPC-5 power supply from Teknic since I will have a free port (the other powers a servo). I would like to use this extra port to power my Arduino rather than draw power from another source. The problem is that this is 75V coming out which would eat up the Arduino.
Is it as simple as hooking up a resistor in series with the Arduino to bring the voltage down to about 7V for the Arduino? If that's the case, then how can I determine the unknowns to find the appropriate resistor?
Correct me if I'm wrong, but if I apply Ohm's Law and Kirchhoff's Rules, I can set up this relationship: 75V = IR + 7V. Can I make an assumption for the current to solve for the resistance?
This is my first real Arduino project, so my knowledge of many things that y'all may consider common knowledge is lacking.

The short answer is NO, you can't do that. Consider the size of the resistor needed to dissipate all that wattage and the fact that the current is not stable so it is practically impossible.
What you need is a DC to DC converter.

Thanks for your answer! I believe this is the solution to my problem.

Is it as simple as hooking up a resistor in series with the Arduino to bring the voltage down to about 7V for the Arduino?

No, it certainly is not.

Can I make an assumption for the current to solve for the resistance?

No, you cannot. You never assume anything in electronics without a very very good reason.
You require a suitably rated voltage regulator (a switching DC/DC regulator for those kind of voltages) to convert the voltage properly.

Are there any options out there for a 75V to 7-12V drop? My initial search is telling me that this drop is huge.

Yes, there are options out there. Here's an example of 75v to 5v: https://www.distrelec.de/en/dc-dc-converter-industrial-18-75v-5v-15w-xp-power-dtj1548d05/p/30183412


text:
unbrick Nano RP2040 connect using Uno
I think I have bricked my Nano RP2040. How do I unbrick using a Uno or Mega? I found instructions for using another Nano, but only have the one.

are you certain that the unbricking instructions are Nano specific?

I don't think you can unbrick it like a regular Arduino Nano, since there isn't a bootloader that is programmed into the RP2040 chip.

You don't actually need a Uno or mega to unbrick the device.
You need to place a jumper wire between the GND and REC pins.
This will force the bootloader to load, a mass-storage device will appear on the computer. You can than upload a UF2 file to the drive to restore it.
You can read more about it in the arduino documentation.
https://docs.arduino.cc/tutorials/nano-rp2040-connect/rp2040-01-technical-reference#forcing-bootloader
If it is really bad you might also need to use a flash_nuke.uf2 file first. This removes all files on the Arduino Nano RP2040 connect.

Thank you, Bonnom. Got the Nano working again.


text:
Can I support all these sensors? Will I have enough pins?
So i'm new to arduino and i'm working on a project that will require 3 modules/sensors.
I wanted to know, can all of the following modules work with the arduino mega 2560 that comes with this
touch display?
The other modules (apart from the touch display) would be:

Fingerprint scanner
9g servo

If its not possible, please tell me what hardware I would need to run all these sensors together. Thanks :D.

Yes, easily....

@Majenko Are you sure? because it seems like the display is taking all of the pins, especially the power supply ones.  Also, it says that the fingerprint scanner needs a 12v power supply but as far as im aware arduino can only output 5v

No, the display only uses a tiny handful of the pins. It only plugs into the "Uno" footprint area pins and leaves all the rest blank. You can use power pins for more than one device at a time. If you need a higher voltage power supply then you have to get a higher voltage power supply. That has nothing at all to do with the Arduino.

@Majenko Okay thanks! So all of the other digital pins that come with the mega2560 can be configured to whatever output/input i need?

For simple IO, yes. For analogue there are more than 6 analog inputs. For serial communications there are more UART pins that aren't used, etc.

@Majenko Thank you so much!

if you run out, you can add a nano or pro mini using two serial pins, then have it talk to 1+ sensors.


text:
How to write nonblocking code, for polling sensor at 100 Hz
I'm using this piece of code to try to poll an IMU sensor at 100 Hz (for a AHRS sensor fusion library).
void loop(void)
{
  // nonblocking code variables
  static uint32_t last_ms;
  uint32_t ms;
  // delay between samples
  ms = millis();
  if (ms - last_ms < 10) return;
  last_ms = ms;

  sensor_data (); //...

My 1st question is should I be declaring last_ms as a global variable instead of static?
Also, should this code be at the beginning or end of loop? My understanding is we are basically checking how long the previous loop took. And if it took less than 10 ms (100 Hz) we do nothing. But doesn't that mean that we might still get deviation from 100 Hz due to the time it takes to complete loop (about 2-5ms in my case), so effectively it's 10 ms + loop complete time?
Sorry if this is a stupid question.

see the BlinkWithoutDelay example. I guess it is easy to modify it from 1 Hz to 100Hz

If you want to run something at 100Hz you probably want to use a timer interrupt rather than fiddling with delay values.

I will experiment with that thank you

static/global; meh, same thing really.  2. it should be 100Hz since you restart the clock before running the task, so it won't jitter unles the task takes longer than 10ms, but if that's the case there's no way it will ever work anyway.

Can you configure this particular device to use interrupts rather than polling?

it's the BMX160 from Bosch, and I think so. I will experiment with that, but wanted to understand logic of this also.

should I be declaring last_ms as a global variable instead of
static?

Local static is better, as it limits the scope of the variable to just
where it is needed. Consider making it global only if the code is part
of a tutorial meant for beginners which may be confused by the keyword
static.

should this code be at the beginning or end of loop?

The conditional early return only makes sense if loop() has nothing
more to do once the sensor data is handled, thus this should go at the
very end of loop(). However, if loop() does more than just handle
this data, I think it would be cleaner to avoid the early return: either
put this in a separate function (which can return early), or condition
the handling of the sensor on ms - last_ms >= 10.

My understanding is we are basically checking how long the previous
loop took.

No. The test is looking at how much time has elapsed since the previous
time last_ms was updated, which could be many loop() iterations ago.

But doesn't that mean that we might still get deviation from 100 Hz
due to the time it takes to complete loop (about 2-5ms in my case), so
effectively it's 10 ms + loop complete time?

Indeed. With this logic, 10 ms is the minimum time between calls
to sensor_data(). If you want to ensure an accurate average polling
time, you should update last_ms by adding 10. You will still have
sole jitter though.
A small note about millis(): since the value is updated every
1.024 ms, it occasionally has to jump by two units at once, and has
therefore 1 ms of jitter. For a period as short as 10 ms, I
would rather use micros(). For example:
const uint32_t POLLING_PERIOD = 10000;  // 1e4 us = 10 ms

// Call this from loop()
void handle_sensor()
{
    static uint32_t last_us;
    if (micros() - last_us < POLLING_PERIOD) return;
    last_us += POLLING_PERIOD;
    sensor_data();
    // ...
}

Edit: About why last_us has to be incremented by a constant
amount, consider this alternative:
void handle_sensor()
{
    static uint32_t last_us;
    uint32_t now = micros()
    if (now - last_us < POLLING_PERIOD) return;
    last_us = now;
    sensor_data();
    // ...
}

The code following the if ... return; line will be executed when the
tested condition is false, i.e. when now - last_us >= POLLING_PERIOD.
It may happen that we sometimes have strict equality (now - last_us == POLLING_PERIOD) but, since any code execution takes time, sometimes
now - last_us will be strictly larger than POLLING_PERIOD. Every
time this happens last_us will be incremented by more than
POLLING_PERIOD. This means that the small timing errors accumulate.
If, instead, last_us is updated by adding a constant amount, we still
have timing errors (because of the time needed to execute any code), but
they are not cumulative. In other words, we have jitter, but the
average polling frequency is right.

Thank you very much for the detailed answer Edgar. Good to see that you're still helping out newbies on here. I'll try the updated code using micros. To check I understood, we are using micros to avoid jitters. Still a bit confused on the difference between adding the polling period to our comparison variable, instead of comparing Millis to Millis. I feel I'm missing something, because to me it looks like they both achieve the same thing which is: wait until 10 ms have passed and only then start processing data.. Although you imply there is a difference.

Thank you for the edit, I understand now.

The time range your sensor code will be executed is 10ms to 10ms + the execution time of the first part of the loop (until the return) and the execution time outside of loop(). These additional times don't always apply, but in the worst case you can have up to that additional delay (because it means you are checking the millis() value only so often).
The mentioned additional delay is rather short (microseconds realm). Your sensor code is only executed, when the time is reached. As long as you don't disable interrupts, the Timer0 interrupt will continue to count further for millis(), so its value will increase independently from the execution time of your sensor code.
That is as long as the sensor code also doesn't take longer than 10ms (or a bit less, accounting for some overhead). As your sensor code only takes up to 5ms (according to your question), you should be safe here.
If millis() is accurate enough for you I cannot say. Thats up to your exact requirements. For more accurate timing an own timer interrupt would be better, though that also limits you with what you can do. Inside an interrupt you cannot execute code, that relies on interrupts (like communication over Serial or I2C). Depending on your sensors using your above code is already enough and should work good.

should I be declaring last_ms as a global variable instead of static?

There is no definitive answer to that, but generally it is good to limit the scope of variables to the minimum needed (to avoid possible conflicts). last_ms is not needed anywhere else, so creating it locally and static is a good way to do it. Memory wise it doesn't really make a difference.

Hi Chris, thank you for another detailed answer.


text:
ESP32 send data while blinking LED
Can I program my ESP32 to send a string MQTT data while also blinking the InBuilt LED?
If yes, then how to do so
Thanks in advance

Sure you can. You can use something like the BlinkWithoutDelay example included in the Arduino IDE so that your program can run (for example sending MQTT data) while the LED is turned on and off with the correct frequency. As long as sending the MQTT data does not take longer than the on- or off period of the LED, this will work.

Take a look at the blink-without-delay example to get an idea of how "multitasking" can be implemented. But as @HigorMaiaConcessa mentioned, the ESP supports FreeRTOS where you don't have to care much about how it works.

My opinion is that using multiple cores for extremely simple tasks such as blinking an LED is unnecessarily complex.

The ESP32 have two core, each core can do diferents tasks. Then, you can send data with one core and blink the LED with another core.
To do this, you need to use a multicore programming. I recommend to use the FreeRTOS (ESP32 support this). See more.
Look the example "Let's multitask: Blink with Hello" here, is that what  you want.
Read the documentation about the FreeRTOS in ESP32.
Example in Arduino IDE:
#include <Arduino_FreeRTOS.h>

// define two tasks for Blink & AnalogRead
void TaskBlink( void *pvParameters );
void TaskAnalogRead( void *pvParameters );

// the setup function runs once when you press reset or power the board
void setup() {

  // Now set up two tasks to run independently.
  xTaskCreate(
    TaskBlink
    ,  (const portCHAR *)"Blink"   // A name just for humans
    ,  128  // Stack size
    ,  NULL
    ,  2  // priority
    ,  NULL );

  xTaskCreate(
    TaskAnalogRead
    ,  (const portCHAR *) "AnalogRead"
    ,  128 // This stack size can be checked & adjusted by reading Highwater
    ,  NULL
    ,  1  // priority
    ,  NULL );

  // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
}

void loop()
{
  // Empty. Things are done in Tasks.
}

/*--------------------------------------------------*/
/*---------------------- Tasks ---------------------*/
/*--------------------------------------------------*/

void TaskBlink(void *pvParameters)  // This is a task.
{
  (void) pvParameters;

  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);

  for (;;) // A Task shall never return or exit.
  {
    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
  }
}

void TaskAnalogRead(void *pvParameters)  // This is a task.
{
  (void) pvParameters;
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);

  for (;;)
  {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(sensorValue);
    vTaskDelay(1);  // one tick delay (15ms) in between reads for stability
  }
}

Reference.

Thank you for the help. Are there any Arduino IDE Examples available, since it is more understandable in it

Look this example. I added the example in the answer.

While true, it seems like a large increase in complexity for a relatively low gain (and there are multiple task schedulers for Arduino that don't involve an RTOS). It's also my understanding that unless tasks are specifically pinned to a core there's no guarantee regarding multicore-ness.

So I guess giving same priority to 2 small tasks will make them execute simultaneously. Am I right?

If run in diferents cores, then will execute simultaneously. If run in the same core with the same priority, will run merging each one.


text:
MKR1400-how do I troubleshoot a POST request?
I'm successfully sending a GET request (in the setup function, to load certificates,) but my POST request fails with a bunch of AT errors. I suspect this has to do with the way I'm formatting the POST. Any ideas would be appreciated.
Code follows:
// MKRGSM - Version: 1.5.0
#include <MKRGSM.h>
#include <ArduinoJson.h>
#include <Arduino_MKRGPS.h>

const char PINNUMBER[]     = "";
// APN data

const char GPRS_APN[]      = SECRET_GPRS_APN;

const char GPRS_LOGIN[]    = "";

const char GPRS_PASSWORD[] = "";

DynamicJsonDocument doc(1024);

// initialize the library instance

GSMSSLClient client;

GPRS gprs;

GSM gsmAccess(true);

// Specify IP address or hostname

char server[] = "webhook.site";
char path[] = "/ce480c43-95a8-4f1e-b996-bc02f6d1adaa";
int port = 443;

void setup() {

  // initialize serial communications and wait for port to open:

  Serial.begin(9600);

  while (!Serial) {

    ; // wait for serial port to connect. Needed for native USB port only

  }

  // If you are using the MKR GPS as shield, change the next line to pass

  // the GPS_MODE_SHIELD parameter to the GPS.begin(...)
  delay(200);

  if (!GPS.begin()) {

    Serial.println("Failed to initialize GPS!");

    while (1);

  }
  Serial.println("Starting Arduino GSM ping.");
  // connection state
  bool connected = false;

  // After starting the modem with GSM.begin()
  // attach the shield to the GPRS network with the APN, login and password
  while (!connected)
  {
    if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &&
        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY))
    {
      connected = true;
    }
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  // Use this to load Root Certs the first time
  if (client.connect(server, port))
  // Use this to not load Root Certs anymore as done last time and stored in modem's flash
//  if (client.connect(server, port, false))
  {
        Serial.println("connected");

    // Make a HTTP request:

    client.print("GET ");

    client.print(path);

    client.println(" HTTP/1.1");

    client.print("Host: ");

    client.println(server);

    client.println("Connection: close");

    client.println();
  }
  else
  {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {

  ...GPS stuff happens here

  // print GPS values

  Serial.println();

  Serial.print("Location: ");

  Serial.print(latitude, 7);

  Serial.print(", ");

  Serial.println(longitude, 7);

  Serial.print("Altitude: ");

  Serial.print(altitude);

  Serial.println("m");

  Serial.print("Number of satellites: ");

  Serial.println(satellites);

  doc["latitude"] = latitude;
  doc["longitude"] = longitude;
  doc["altitude"] = altitude;

  String location;
  serializeJson(doc, location);
  Serial.print("Location string: ");
  Serial.println(location);

  Serial.println();

  Serial.println("Starting Arduino web client.");

  // connection state

  if (client.available()) {
    Serial.println("Sending location");
    client.print("POST ");
    client.print(path);
    client.println(" HTTP/1.1");
    delay(5);
    client.println("Content-Type: application/json;");
    delay(5);
    client.print("Content-Length: ");
    client.println(location.length());
    client.print("Host: ");
    client.println(server);
    delay(5);
    client.println("Connection: close");
    delay(5);
    client.println();
    delay(5);
    client.println(location);
    Serial.print("Successfully sent location");

    if (!client.available() && !client.connected()) {

      Serial.println();

      Serial.println("disconnecting.");

      client.stop();
    }
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }

}

Here's what the output looks like:

Location: 32.1208382, 35.2468376 Altitude: 640.40m Number of
satellites: 5 Location string:
{"latitude":32.12084,"longitude":35.24684,"altitude":640.4}
Starting Arduino web client. Sending location
AT+USOWR=0,13,"504F53542068747470733A2F2F"
ERROR
AT+USOWR=0,37,"2F63653438306334332D393561382D346631652D623939362D626330326636643161646161"
ERROR AT+USOWR=0,9,"20485454502F312E31"
ERROR AT+USOWR=0,2,"0D0A"
ERROR
AT+USOWR=0,31,"436F6E74656E742D547970653A206170706C69636174696F6E2F6A736F6E3B"
ERROR AT+USOWR=0,2,"0D0A"
ERROR AT+USOWR=0,16,"436F6E74656E742D4C656E6774683A20"
ERROR AT+USOWR=0,2,"3539"
ERROR AT+USOWR=0,2,"0D0A"
ERROR AT+USOWR=0,6,"486F73743A20"
ERROR AT+USOWR=0,12,"776562686F6F6B2E73697465"
ERROR AT+USOWR=0,2,"0D0A"
ERROR AT+USOWR=0,17,"436F6E6E656374696F6E3A20636C6F7365"
ERROR AT+USOWR=0,2,"0D0A"
ERROR AT+USOWR=0,2,"0D0A"
ERROR
AT+USOWR=0,59,"7B226C61746974756465223A33322E31323038342C226C6F6E676974756465223A33352E32343638342C22616C746974756465223A3634302E347D"
ERROR AT+USOWR=0,2,"0D0A"
ERROR

I could send the data as parameters in the GET query, but that's ugly.

see the GSMWebClient example

I saw that example, but it's a GET.

Your HTTP request is badly formatted.

reading the response is same. and the HTTP request line shouldn't have a complete URL for POST either

Your HTTP request is badly formatted.  You have:
POST https://webhook.site/ce480c43-95a8-4f1e-b996-bc02f6d1adaa HTTP/1.1
Content-Type: application/json

Instead the protocol is implied by the port you are connecting to, and the domain name does not go in the path on the server component - it has its own header.
Your request should look more like:
POST /ce480c43-95a8-4f1e-b996-bc02f6d1adaa HTTP/1.1
Host: webhook.site
Content-Type: application/json
Content-Length: [x]
Connection: close

[location]

Where [x] is location.length() and [location] is the content of the location string.

Thanks, I've updated the code as per your suggestions. Unfortunately, it's still failing. I'm not even seeing it go into the if (client.connect(server, port)) { block, which suggests that there is something wrong with the way I'm initializing the client.

@BorisK You need to add a second newline after Connection: close. In HTTP the headers and content are separated by two newlines. Your original question included this client.println();, but your updated code omitted this.

@gerben I'm not even seeing the "Sending location" output, which suggests the client is not connecting

@Gerben I have swapped SIMs and am now connecting on a GET but failing on a POST. I've updated the original question. If you could take a look, I would be grateful.

The problem was that GSM gsmAccess; needed to be GSM gsmAccess(true). Unfortunately, while that solves the immediate problem, which is that the client was not initializing, there are other issues which deserve a separate question.


text:
DC Motor Acceleration with PWM
I'm not sure why this has been so difficult for me, but I'm trying to control the acceleration of a 10v DC motor with an Arduino UNO and an L298n H-Bridge. Using a 12v regulated power supply to power the motor
For the life of me, I can't get a smooth acceleration/deceleration for this. I want the motor to move back and forth with a potentiometer, slowing down as it reaches the '0' and '10' positions. This works, but it's not very smooth
const byte motorUp      = 4;
const byte motorDown    = 5;
const byte motorPWM     = 6;

const int speed1 = 85;
const int speed2 = 92;
const int speed3 = 100;
const int speed4 = 110;
const int speed5 = 130;
const int speed6 = 190;

int state = 0;

const byte wiper        = A0; //Position of fader relative to GND (Analog 0)
double faderMax = 0; //Value read by fader's maximum position (0-1023)
double faderMin = 0; //Value read by fader's minimum position (0-1023)
byte motorSpeed = 255;  // Raise if the fader is too slow (0-255)
byte tolerance  = 10;  // Raise if the fader is too shaky (0-1023)

void setup() {
  Serial.begin(250000);
  pinMode(motorDown, OUTPUT);
  pinMode(motorUp, OUTPUT);
  pinMode(motorPWM, OUTPUT);
  analogWrite(motorPWM, motorSpeed);
  calibrateFader(); }

void calibrateFader() {
  digitalWrite(motorUp, HIGH);
  analogWrite(motorPWM, 155);
  delay(300);
  digitalWrite(motorUp, LOW);
  faderMax = analogRead(wiper) - tolerance;
  digitalWrite(motorDown, HIGH);
  analogWrite(motorPWM, 155);
  delay(300);
  digitalWrite(motorDown, LOW);
  faderMin = analogRead(wiper) + tolerance;
  delay(2500); }

void loop () {
  moveMotorUp();}

void moveMotorUp() {
  while (analogRead(A0) <= 100) {
    analogWrite(motorPWM, speed1);
    digitalWrite(motorUp, HIGH);
    digitalWrite(motorDown, LOW); }
  while ((analogRead(A0) > 100) && (analogRead(A0) <= 200)) {
    analogWrite (motorPWM, speed2);
    digitalWrite(motorUp, HIGH);
    digitalWrite(motorDown, LOW); }
  while ((analogRead(A0) > 200) && (analogRead(A0) <= 300)) {
    analogWrite (motorPWM, speed3);
    digitalWrite(motorUp, HIGH);
    digitalWrite(motorDown, LOW); }
  while ((analogRead(A0) > 300) && (analogRead(A0) <= 400)) {
    analogWrite (motorPWM, speed4);
    digitalWrite(motorUp, HIGH);
    digitalWrite(motorDown, LOW); }
  while ((analogRead(A0) > 400) && (analogRead(A0) <= 500)) {
    analogWrite (motorPWM, speed5);
    digitalWrite (motorUp, HIGH);
    digitalWrite(motorDown, LOW); }
  while ((analogRead(A0) > 500) && (analogRead(A0) <= 600)) {
    analogWrite (motorPWM, speed6);
    digitalWrite (motorUp, HIGH);
    digitalWrite(motorDown, LOW); }
  while ((analogRead(A0) > 600) && (analogRead(A0) <= 700)) {
    analogWrite (motorPWM, speed5);
    digitalWrite(motorUp, HIGH);
    digitalWrite(motorDown, LOW); }
   while ((analogRead(A0) > 700) && (analogRead(A0) <= 800)) {
    analogWrite (motorPWM, speed4);
    digitalWrite(motorUp, HIGH);
    digitalWrite(motorDown, LOW); }
  while ((analogRead(A0) > 800) && (analogRead(A0) <= 900)) {
    analogWrite (motorPWM, speed3);
    digitalWrite(motorUp, HIGH);
    digitalWrite(motorDown, LOW); }
  while ((analogRead(A0) > 900) && (analogRead(A0) <= 1000)) {
    analogWrite (motorPWM, speed2);
    digitalWrite(motorUp, HIGH);
    digitalWrite(motorDown, LOW); }
  while (analogRead(A0) > 1000) {
    analogWrite (motorPWM, speed1);
    digitalWrite(motorUp, HIGH);
    digitalWrite(motorDown, LOW);
    moveMotorDown(); } }

void moveMotorDown() {

  while (analogRead(A0) > 1000) {
    analogWrite(motorPWM, speed1);
    digitalWrite(motorDown, HIGH);
    digitalWrite(motorUp, LOW); }
  while ((analogRead(A0) > 900) && (analogRead(A0) <= 1000)) {
    analogWrite (motorPWM, speed2);
    digitalWrite(motorDown, HIGH);
    digitalWrite(motorUp, LOW); }
  while ((analogRead(A0) > 800) && (analogRead(A0) <= 900)) {
    analogWrite (motorPWM, speed3);
    digitalWrite(motorDown, HIGH);
    digitalWrite(motorUp, LOW); }
  while ((analogRead(A0) > 700) && (analogRead(A0) <= 800)) {
    analogWrite (motorPWM, speed4);
    digitalWrite(motorDown, HIGH);
    digitalWrite(motorUp, LOW); }
  while ((analogRead(A0) > 600) && (analogRead(A0) <= 700)) {
    analogWrite (motorPWM, speed5);
    digitalWrite (motorDown, HIGH);
    digitalWrite(motorUp, LOW); }
  while ((analogRead(A0) > 500) && (analogRead(A0) <= 600)) {
    analogWrite (motorPWM, speed6);
    digitalWrite (motorDown, HIGH);
    digitalWrite(motorUp, LOW); }
  while ((analogRead(A0) > 400) && (analogRead(A0) <= 500)) {
    analogWrite (motorPWM, speed5);
    digitalWrite (motorDown, HIGH);
    digitalWrite(motorUp, LOW); }
  while ((analogRead(A0) > 300) && (analogRead(A0) <= 400)) {
    analogWrite (motorPWM, speed4);
    digitalWrite (motorDown, HIGH);
    digitalWrite(motorUp, LOW); }
  while ((analogRead(A0) > 200) && (analogRead(A0) <= 300)) {
    analogWrite (motorPWM, speed3);
    digitalWrite (motorDown, HIGH);
    digitalWrite(motorUp, LOW); }
  while ((analogRead(A0) > 100) && (analogRead(A0) <= 200)) {
    analogWrite (motorPWM, speed2);
    digitalWrite (motorDown, HIGH);
    digitalWrite(motorUp, LOW); }
  while ((analogRead(A0) > 10) && (analogRead(A0) <= 100)) {
    analogWrite(motorPWM, speed1);
    digitalWrite(motorDown, HIGH);
    digitalWrite(motorUp, LOW); }
  while (analogRead(A0) <= 10) {
    digitalWrite(motorDown, HIGH);
    digitalWrite(motorUp, LOW);
    moveMotorUp(); } }

I hope it's simpler than this - Any ideas?
Thanks

You have a nice infinitely recursive pair of functions there. You're going to run out of stack space if you leave that running for a while.

It seemed really inefficient to me as well. Know of any libraries that have acceleration? I'm wishing I could find something like the AccelStepper library for stepper motors. Unfortunately I'm limited to a DC motor this time.

@zRockafellow There are multiple libraries that provide value interpolations between values with various mechanisms (e.g., Ramp). Anything that can be done with recursion can be done without it--it's more likely you mean to have a state machine.

I think you need to think a little differently. Instead of "Move it at this speed until you get to here" you need to think more along the lines of "Where am I? Where do I want to get to? How far away is it?"
Basically the further you have to go the faster you want to go. The closer you get to your target value the slower you want to go.
Simply put - you want to convert the distance between your current and target positions into a proportional speed.
Take one variable: the target value that you want to get to. Take one reading: the current location of the fader. Subtract one from the other.
Take the sign of the result - that defines what direction you want the motor to turn in.  Take the "absolute" (abs(...)) value of the result - that is the distance you are away from your target.  Divide that absolute value by a speed factor to keep it within the range of your PWM, or lower if you want to go slower. Set the speed of the motor to that result.
So if you want to get to 0 and you are currently reading 1000 from the fader then:

Difference = 0 - 1000 = -1000
Sign is negative, so set direction to "down".
Distance is abs(-1000), or 1000.
Divide by 4 (max ADC is 1023, max PWM is 255 - 1023/4 = 255) = 250
Set speed to 250

Then a moment later you may be reading 738 from the ADC - so this time:

Difference = 0 - 738 = -738
Sign is negative, so set direction to "down".
Distance is abs(-738), or 738.
Divide by 4 (max ADC is 1023, max PWM is 255 - 1023/4 = 255) = 184
Set speed to 184

Keep doing that until you get to your target value (or within a certain tolerance of it) at which point you stop and wait for a new target value to be selected (or automatically change the target value as per your sweep demo - if 0 then set to 1023. If 1023 then set to 0).
This method then allows you to go directly to any value you choose with a deceleration as it approaches that target.

Hi Majenko, Thanks for the details! I've been trying to wrap my head around how to implement PID control into this project. I'm still not sure how to set it up though. I tried following your instructions, but you lost me at "Take the sign of the result"


text:
Send/Stream BLE (Bluetooth Low Energy) data with high data rate with Arduino
My project is to transfer an image wirelessly via BLE from my Sparkfun EDGE board using the Arduino IDE to another laptop. In the following, for simplicity, I have reduced the program to transmit integers via BLE. This already works but it takes a long time (~0.5 seconds) to transfer a few bytes. However, from the BLE specifications, much more should be possible.
This is the stripped down code for the Board using Arduino:

#include <ArduinoBLE.h>
#include "utility/HCI.h"    // needed for sendcommand
#include <string>

const char BLE_PERIPHERAL_NAME[] = "Peripheral Hello World BLE";
BLEService Test("83436682-10c6-4dad-acb1-133927f3f080");
BLEStringCharacteristic HelloWorlds("83436682-10c6-4dad-acb1-133927f3f080", BLERead | BLENotify, 512);

#define SERIAL_PORT Serial
#define BAUD_RATE   115200 //(originally, 460800)

void setup() {

  // Start up serial monitor
  SERIAL_PORT.begin(BAUD_RATE);

#ifdef BLE_Debug
  BLE.debug(SERIAL_PORT);         // enable display HCI commands
#endif
  BLE.setLocalName(BLE_PERIPHERAL_NAME);
  BLE.begin();

  BLE.setAdvertisedService(Test);

  Test.addCharacteristic(HelloWorlds);

  BLE.addService(Test);
  BLE.advertise();
//BLE part end
  }

void loop(){
    int period=3000; //minimum time [ms] to be spent in each loop. This is to give the BLE enought time to transmit. To be adjusted depending on the test.
    unsigned long timing=millis();

    BLE.poll();

    int v1;
    v1 = rand() % 100;

    //Generate 8 integer to be transmitted
    String sixteen=String(v1);
    for (uint32_t ccc=0; ccc < 8; ccc=ccc+1){

      v1 = rand() % 100;
      sixteen = sixteen + " " +String(v1);
    }
  HelloWorlds.writeValue(sixteen);
  SERIAL_PORT.print(sixteen);
  SERIAL_PORT.print("   ");

   while(millis() < timing + period){
   }

  }

The code compiles, runs on the EDGE board and I receive the random bytes on my phone (NRF app) as well as on the other laptop.
On the other laptop, I use gatttool in the Ubuntu terminal to receive the packets:
gatttool -I
connect C0:4B:39:C9:B1:04
char-read-hnd c

(I obtain the handle "c" through inspecting the characteristics before).
Then, I do receive the String, but it takes the some hundreds of milliseconds until the integers are displayed. I also automated this in a Python script using pexpect and then print the timestamps after the sendline and expect command and it shows the time difference of ~hundreds of milliseconds.
The data rate that I target should be at least hundreds of bytes per second.
Thank you kind community.

Why you are using a deprecated tool for this? Do it with Bleak then update the question with the time you record via your script please.


text:
Unwanted ghosting with charlieplexed LEDs
I have a very simple PCB that uses 3 GPIO on a ATtiny85 to control 6 LEDs using charlieplexing.
When I try to program certain patterns of lit LEDs (pseudo PWM) I get some LEDs lighting dimly when they should be fully off.
Example where only top or bottom three LEDs should be on alternately:

You can see that LEDs 2 and 5 are dimly glowing rather than being fully off.
I do not have problems when lighting the LEDs one at a time in sequence.
I do not have problems lighting odd and even LEDs alternately.
The schematic is:

The buttons are used to change up and down through 6 modes of operation. Mode 0 lights the LEDs one at a time in sequence. Mode 1 alternates the odd and even LEDs. Mode 2 lights upper or lower three LEDs alternately (and has ghosting problem), the other modes just steadily illuminate the corresponding LED.
The code is split into several files:
main.ino:
Button leftButton = Button(3);
Button rightButton = Button(4);
Sequencer sequencer = Sequencer(200); // ms per step
Alternator alternator = Alternator(0b00101010, 0b00010101);

void setup() {
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
}

// ------------------------------------------------------------------

const int maxMode = 5;
int mode = 0;

void loop() {
  if (leftButton.wasPressed())  {
    if (++mode > maxMode) { mode = 0; }
    initMode(mode);
  }
  if (rightButton.wasPressed()) {
    if (--mode < 0) { mode = maxMode; }
    initMode(mode);
  }

  switch(mode) {
    case (0): sequencer.check(); break;
    case (1):
    case (2): alternator.check(); break;
    default: lightLED(mode); break;
  }
}

// ------------------------------------------------------------------

void initMode(int mode) {
  switch (mode) {
    case (0): sequencer.reset(); break;
    case (1): alternator = Alternator(0b00101010, 0b00010101); break;
    case (2): alternator = Alternator(0b00111000, 0b00000111); break;
  }
}

Alternator.ino
class Alternator {

  private:
    unsigned long whenChanged = 0;
    int interval = 500; // ms
    byte pattern, pattern1, pattern2; // bitmap
    int count = 0;

  public:
  Alternator(byte pattern1, byte pattern2) {
    this->pattern1 = pattern1;
    this->pattern2 = pattern2;
  }

  void check() {

    if ((millis() - whenChanged) > interval) {
      if (pattern == pattern1) { pattern = pattern2; }
      else                     { pattern = pattern1; }
      whenChanged = millis();
    }

    if (++count > 5) { count = 0; }
    if (((pattern >> count) & 1) == 1) {
      lightLED(count);
    }

  }

};

Sequence.ino
class Sequencer {

  private:
    int seq;                            // LED# 0-5
    unsigned long whenLastStep;         // ms
    int stepTime;                       // ms
    const int aDay = 24 * 3600 * 1000;  // ms

  public:
    Sequencer(int stepTime) {
      if (stepTime < 1) { stepTime = 1; }
      if (stepTime > aDay) { stepTime = aDay; }
      this->stepTime = stepTime;
      this->seq = 0;
      this->whenLastStep = 0;
    }

    void check() {
      if ((millis() - whenLastStep) > stepTime) {
        lightLED(seq++);
        if (seq > 5) { seq = 0; }
        whenLastStep = millis();
      }
    }

    void reset() {
      this->seq = 0;
    }
};

Charlieplex.ino
const int highs[6] = {0,1,2,1,2,0};  // GPIOs for LEDs 0-5
const int lows[6]  = {1,0,1,2,0,2};

// Manipulates 3 GPIO outputs to light one of 6 LEDs.
void lightLED(int i) {
  int h, l;     // pin to set high, low
  if (i < 0 || i >= 6) {
    h = 99; l = 99;  // all LEDS off
  } else {
    h = highs[i];
    l = lows[i];
  }

  for (int j=0; j<=2; j++) {
    if (j==h || j==l) {
      pinMode(j, OUTPUT);
      if (j==h) {
        digitalWrite(h, HIGH);
      } else {
        digitalWrite(l, LOW);
      }
    } else {
      pinMode(j, INPUT); // tri-state
    }
  }
}

Buttons.ino
class Button {

  private:
    int pin;
    const int DebounceDelay = 100;      // milliseconds
    int lastState = HIGH;               // Previous status of button
    unsigned long whenLastPressed = 0;  // Last time button was pressed

  public:
    Button(int pin) {
      this->pin = pin;
      pinMode(pin, INPUT_PULLUP);
    }

    // Was there an up (HIGH) to down (LOW) transition since last call, and still held down?
    bool wasPressed() {
      bool result = false;
      if ((millis() - whenLastPressed) > DebounceDelay) {
        int state = digitalRead(pin);
        if ((state == LOW) && (lastState == HIGH)) {
          result = true;
          whenLastPressed = millis();
        }
        lastState = state;
      }
      return result;
    }

};

I'm not sure where I am going wrong, any ideas?

I'd use direct access to the port (but it's not neccesary). And first set all outputs zero, then all set as inputs (if you left any output high and switch to input mode, there will be internal pull up enabled). After that you can set output mode for correct pins and one of them as HIGH. (for three pins it might be enough just RESET all pins and then set correct output mode and next loop set values)

Charlieplexing code doesn't reset the state of unused pin and if the port value is HIGH + mode INPUT, it means the pull-up is enabled.
Solution is reset all pins to LOW before code starts changing directions. And the last step would be setting correct pin to HIGH.
If you want to do it in single loop, you might observe really short pulses (it might or might not be visible - at the higher frequencies it'll be more obvious)
It could be also much faster than using digitalWrite and pinMode, something like:
  void charlieplex(uint8_t i) {
    constexpr uint8_t clrpins = ~(_BV(PB0) | _BV(PB1) | _BV(PB2));
    constexpr uint8_t dirs[]  = { 0b011, 0b011, 0b110, 0b110, 0b101, 0b101};
    constexpr uint8_t outs[]  = { 0b001, 0b010, 0b010, 0b100, 0b001, 0b100};

    PORTB &= clrpins; // clear output pins
    DDRB  &= clrpins; // clear direction pins (0 == input, 1 == output)
    if (i < 6) {  // such easy condition if you use:  uint8_t i
      DDRB  |= dirs[i]; // And set the correct pins as outputs
      PORTB |= outs[i]; // And set the correct pin as high
    }
  }

It's not tested, but it should be pretty much it

This code works very well. Small fix needed for my particular LED ordering: constexpr uint8_t outs[]  = { 0b001, 0b010, 0b100, 0b010, 0b100, 0b001};

it's possible, I was doing it according to the led numbering, and here and in the original code it looks like 3-4 and 5-6 are swapped

Ah yes, I changed the LEDs around when laying out the PCB to simplify track routing and didn't update the schematic! So my fault. :-)

Simply adding a digitalWrite(pin, 0) before each pinMode(pin, INPUT) in my code fixed the LED ghosting in my charlieplexing badgelife project. Simple and thanks for the explanation, missed the pullup issue in other docs.

A secondary issue is that using millis() to update the timestamps will cause the interval to cumulatively drag.
To keep the interval constant, update:

whenChanged with interval
whenLastStep with stepTime.

Alternator.ino
void check() {

  if ((millis() - whenChanged) > interval) {
    if (pattern == pattern1) { pattern = pattern2; }
    else                     { pattern = pattern1; }
    whenChanged += interval;  // Constant interval.
  }

  if (++count > 5) { count = 0; }
  if (((pattern >> count) & 1) == 1) {
    lightLED(count);
  }

}

Sequence.ino
void check() {
  if ((millis() - whenLastStep) > stepTime) {
    lightLED(seq++);
    if (seq > 5) { seq = 0; }
    whenLastStep += stepTime;  // Constant time step.
  }
}

This subtle difference is explained very well by @edgar-bonet in his answer about polling a sensor at 100 Hz.
Also, Button::wasPressed() is prone to a negative blip occurring at the time of sampling the input pin, i.e. the blip will be interpreted as a continuous press of DebounceDelay (100 ms). Compare with this simple debouncer I put on GitHub.


text:
Assistance with PID DC Motor Acceleration
I'm working on a project that uses an Arduino UNO and a motorized fader to send and receive MIDI data from my computer/musical keyboard. I'm trying to set up my motor with PID to control the position and speed of the motor - Been having some difficulty, but after watching a few tutorials I think I'm starting to grasp the idea.
Here's the code that I came up with so far - I'm not sure if this is correct for PID control or not, but it makes my motor respond very strangely to any positioning data that is coming in.
#include <SoftwareSerial.h>
#define rxPin 2
#define txPin 1

SoftwareSerial midiSerial (rxPin, txPin);

const byte wiper = 0; //Position of fader relative to GND (Analog 0)

const byte motorUp   = 4;
const byte motorDown = 5;
const byte motorPWM  = 6;

double faderMax = 0;
double faderMin = 0;

byte motorSpeed = 150;  // Raise if the fader is too slow (0-255)
byte tolerance  = 10;  // Raise if the fader is too shaky (0-1023)

int incomingCommand;
int incomingNote;
int incomingVelocity;

int currentPosition;
unsigned targetPosition;
unsigned long distanceToTarget;
unsigned PIDspeed;

void setup() {
  midiSerial.begin(31250);
  Serial.begin(250000);
  analogWrite(motorPWM, motorSpeed);
  calibrateFader();
}

void calibrateFader() {
  digitalWrite(motorUp, HIGH);
  analogWrite(motorPWM, motorSpeed);
  delay(300);
  digitalWrite(motorUp, LOW);
  faderMax = analogRead(wiper) - tolerance;
  digitalWrite(motorDown, HIGH);
  analogWrite(motorPWM, motorSpeed);
  delay(300);
  digitalWrite(motorDown, LOW);
  faderMin = analogRead(wiper) + tolerance;
}

void loop() {

  while ( midiSerial.available() > 0) {
    incomingCommand = midiSerial.read();
    incomingNote = midiSerial.read();
    incomingVelocity = midiSerial.read();
    midiSerial.write( incomingCommand);
    midiSerial.write( incomingNote);
    midiSerial.write( incomingVelocity);
    targetPosition = incomingVelocity*8.05511811024;
    currentPosition = analogRead(A0);
    distanceToTarget = targetPosition-currentPosition;
  }
  PIDspeed = abs(distanceToTarget)/6;

  if (distanceToTarget >=0) {
    analogWrite(motorPWM, PIDspeed);
    digitalWrite(motorUp, HIGH);
    digitalWrite(motorDown, LOW);
  }

  if (distanceToTarget <=0) {
    analogWrite(motorPWM, PIDspeed);
    digitalWrite(motorDown, HIGH);
    digitalWrite(motorUp, LOW);
  }
}

Updated code:
#include <SoftwareSerial.h>
#define rxPin 2
#define txPin 1

SoftwareSerial midiSerial(rxPin, txPin);

const byte wiper = 0; //Position of fader relative to GND (Analog 0)

const byte motorUp = 4;
const byte motorDown = 5;
const byte motorPWM = 6;

double faderMax = 1023;
double faderMin = 0;

byte motorSpeed = 150;  // Raise if the fader is too slow (0-255)
byte tolerance = 10;  // Raise if the fader is too shaky (0-1023)
byte Proportional = 12;

unsigned int incomingCommand;
unsigned int incomingNote;
unsigned int incomingVelocity;

unsigned int PIDspeed;
int currentPosition;
int targetPosition;
int distanceToTarget;

void setup()
{
    midiSerial.begin(31250);
    Serial.begin(250000);
    calibrateFader();
}

void calibrateFader()
{
    digitalWrite(motorUp, HIGH);
    analogWrite(motorPWM, motorSpeed);
    delay(300);
    digitalWrite(motorUp, LOW);
    faderMax = analogRead(wiper) - tolerance;
    digitalWrite(motorDown, HIGH);
    analogWrite(motorPWM, motorSpeed);
    delay(300);
    digitalWrite(motorDown, LOW);
    faderMin = analogRead(wiper) + tolerance;
}

void loop()
{
    while (midiSerial.available() >= 3)
    {
        incomingCommand = midiSerial.read();
        incomingNote = midiSerial.read();
        incomingVelocity = midiSerial.read();
        if (targetPosition <= 1023)
        {
            midiSerial.write(incomingCommand);
            midiSerial.write(incomingNote);
            midiSerial.write(incomingVelocity);
        }
        targetPosition = incomingVelocity * 8.05511811024;
    }
    currentPosition = analogRead(A0);
    distanceToTarget = (targetPosition - currentPosition);
    PIDspeed = (abs(distanceToTarget) / Proportional) + 90;
    analogWrite(motorPWM, PIDspeed);
    if (targetPosition <= 1023)
    {
        if (distanceToTarget > 60)
        {
            digitalWrite(motorUp, HIGH);
        }
        if (distanceToTarget < 60)
        {
            digitalWrite(motorDown, HIGH);
        }
        if ((distanceToTarget >= -60) && (distanceToTarget <= 60))
        {
            digitalWrite(motorDown, LOW);
            digitalWrite(motorUp, LOW);
        }
    }
}

In this version, the motor is actually less responsive than before. I think it must have to do with the data that's coming in from my DAW, which isn't consistently a piece of command, note or velocity data. For example, if I select a different track in my DAW, it sends data into my Arduino. When I read anything greater than 0 bytes, the data still comes in, but the note, command and velocity readings are more sporadically located. It was suggested by another that I try using a MIDI parser, but that's a different topic I suppose.

what were you expecting to happen? ... what happened instead?

I was hoping to add a proportional speed control that would allow the motor to accelerate and decelerate to a specific 'target position', which is being fed into my Arduino via a MIDI cable. What happened is that my motor began behaving very sluggishly when receiving any data. In order to get the motor to move at all, I'd have to feed data into it constantly

i would start at the beginning ... write the minimum code required to turn the motor in one direction at slow speed ... then edit to minimum code to turn slow for 5 seconds and  change speed to medium and run for 5 seconds, repeat .... from that you will learn what is required to keep the motor happy

You are not doing any PID calculations. Is that really, what you want? Or do you want to accelerate and deccelerate your motor symmetrically?

Everything that I've heard from previous users of these motorized faders swear that to have fluid movement, you must use PID rather than PWM. I was thinking that the 'Proportional' value would accelerate my motor proportionally slower as it gets to the target position? Is that not correct?

PID is a type of (feedback loop) control. PWM is just the way a motor can be driven with variable speed. Totally different things. And you need PWM to actually drive the motor. With with PID you could then calculate the PWM value needed. Yes, PID will make it slower near the target position (depending on your chosen parameters for the PID) though I think you won't get a smooth start. Its definitely not the same as ramping up and down with fixed acceleration. So it depends on what you want. PID might work well for you

IMO this sounds more like an interpolation issue (e.g., Ramp library I mentioned the other day): go from x to y following this acceleration/etc curve.

I see 2 main problems with your code, that would make it behave strangely:

You are calculating the new motor speed and decide about the direction based on the variable distanceToTarget. But this variable is only updated, when there is data coming from your MIDI interface. I guess thats only happening, when you want to change the target position. But the motor control runs on every loop iteration, which will be way more often, than you can get the MIDI data. To solve this please move the lines
  currentPosition = analogRead(A0);
  distanceToTarget = targetPosition-currentPosition;

out of the while(midiSerial.available() > 0) loop. Just put then right after it.

At the start of your midi code you check for more than zero bytes being available from midiSerial, but then you are reading 3 bytes in total, without knowing, if there are actually 3 bytes to read. SoftwareSerial.read() will not wait for a byte to come in, it will just return -1. So it can very well be that, just one byte is already received, when the midi code is executed. The rest will be received later. So the rest of the variables is just garbage/invalid. Also this means that sender and receiver are now misaligned. The other 2 bytes (which are received later) will then be handled by the midi code next time as if they were byte 1 and 2 (not 2 and 3). So the next transitions will also be garbage/invalid, until it aligns itself again by chance.
To solve this you should check for at least 3 bytes being available (since you want to read 3 bytes):
  while ( midiSerial.available() >= 3 ) {

Note: As of your comments you seem to have a misunderstanding, what PID and PWM actually is.

PWM is just a way to drive the motor with variable speed by turning the pin on and off very fast, with different ratios between on and off time. With a high ratio towards on time the motor will turn faster than with a low ratio towards on time. This ratio translates to the range from 0 to 255 on an Arduino. So you need PWM to drive a motor with variable speed on the Arduino. You cannot cut that out.

PID is a closed feedback loop control. It denotes a way to calculate a new output value (PWM motor value) based on the measured input value (measured current position). PID stands for Proportional Integral Differential, so for the different terms in the calculations. With PID first the deviation between measured input and target/setpoint is calculated then the PID function is evaluated (with its proportional, integral and differential part of the deviation). With that you get the output value, that you can feed to your output device (the motor here).
PID has nothing to do with PWM. They are totally different things. Only when driving an electromechanical device you might need PWM in the same system as PID. PWM is the hardware way of driving the motor, PID is the way to calculate the output value in a closed feedback loop to reach the target position smoothly and fast.

Actually with your current code (when corrected as described above) already does the proportional part of PID (since you calculate the new speed from the distance to target, so the deviation from the target position). To get full PID you would also need to implement the rest. I would suggest using the Arduino PID library, which already handles the calculation for you. You just need to call it correctly (refer to the examples of the library).

Thanks so much for the details! I'll try this out asap

I'm definitely still trying to understand the concept of PID. I'm glad I've at least got the Proportional section correct (thanks to Majenko in a previous post). I'll try out that library with this and see if I can get it to work out.

There is a fundamental problem with the way you are reading the serial data. Read this excellent article by @Majenko:
https://majenko.co.uk/blog/reading-serial-arduino
The following code will read the last 3 bytes. If, for example, there are 9 bytes available, it will ignore the first 6 bytes:
while (midiSerial.available() >= 3)
{
    incomingCommand = midiSerial.read();
    incomingNote = midiSerial.read();
    incomingVelocity = midiSerial.read();
. . .
}

This will read the next 3 bytes:
if (midiSerial.available() >= 3)
{
    incomingCommand = midiSerial.read();
    incomingNote = midiSerial.read();
    incomingVelocity = midiSerial.read();
. . .
}

Here is the tweaked loop() which:

uses if (midiSerial.available() >= 3) to read the next 3 bytes.
clips the targetPosition if it's out of bounds (0 to 1023).
clips the PIDspeed if it's out of range (0 to 255).
switches the other motor control signal off before enabling the current one just in case the targetPosition crossed zones between loop() iterations.

const int QUIESCENT_BOUNDARY = 60;
const float INCOMING_VELOCITY_SCALE = 1023.0 / 255.0;

byte incomingCommand;
byte incomingNote;
byte incomingVelocity;

void loop()
{
    if (midiSerial.available() >= 3)                // Use `if` to get the next 3 bytes available.
    {
        incomingCommand = midiSerial.read();
        incomingNote = midiSerial.read();
        incomingVelocity = midiSerial.read();
        midiSerial.write(incomingCommand);
        midiSerial.write(incomingNote);
        midiSerial.write(incomingVelocity);
        targetPosition = incomingVelocity * INCOMING_VELOCITY_SCALE;
        if (targetPosition > 1023)                  // Clip if out of bounds.
        {
            targetPosition = 1023;
        }
    }
    currentPosition = analogRead(A0);
    distanceToTarget = targetPosition - currentPosition;
    PIDspeed = abs(distanceToTarget) / 6;           // TODO: Tune the PID equation.
    if (PIDspeed > 255)                             // Clip if out of range.
    {
        PIDspeed = 255;
    }
    analogWrite(motorPWM, PIDspeed);
    if (distanceToTarget > QUIESCENT_BOUNDARY)      // Above the positive bound of the quiescent zone.
    {
        digitalWrite(motorDown, LOW);               // Switch the down control off before switching the up control on.
        digitalWrite(motorUp, HIGH);
    }
    else if (distanceToTarget < -QUIESCENT_BOUNDARY)// Below the negative bound of the quiescent zone.
    {
        digitalWrite(motorUp, LOW);                 // Switch the up control off before switching the down control on.
        digitalWrite(motorDown, HIGH);
    }
    else                                            // In the quiescent zone.
    {
        digitalWrite(motorDown, LOW);
        digitalWrite(motorUp, LOW);
    }
}

That should help you to tune the PID equation.


text:
Why am I getting Invalid head of packet (0xF0) error when trying to upload code to esp8266?
Solved : In Mac I went back to Tools --> Boards Manager, then removed 3.0 and downgraded to 2.5 and it started working. I found the solution in this thread.

The current connection between uno R3 and esp8266 is
UNO ----- ESP8266
RX — RX
TX — TX
GND — GND
3.3V — VCC (used bread board)
3.3V — CH_PD (used bread board)
GPIO - GND

UNO ----- UNO
Reset -- GND

Then ESP8266 send "OK" when I send AT from the serial monitor. When uploading the red light and blue blinks in esp8266 and rx and tx light blinks at uno r3.
I had to do sudo launchctl stop /dev/cu.usbmodemxxx before running below command.
Since I have GPIO connected to GND, I though that would trigger the programming mode, but for some reason it gives Invalid head of packet. I get same error when trying to upload code from arduino IDE.
I tried below command too from cmd line.
$sudo python esptool.py -t --chip esp8266  --port /dev/cu.usbmodemxxx --before no_reset flash_id
esptool.py v2.8
Serial port /dev/cu.usbmodemxxx
Connecting...TRACE +0.000 command op=0x08 data len=36 wait_response=1 timeout=0.100 data=
    0707122055555555 5555555555555555 | ... UUUUUUUUUUUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
    55555555                          | UUUU
TRACE +0.000 Write 46 bytes:
    c000082400000000 0007071220555555 | ...$........ UUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
    5555555555555555 5555555555c0     | UUUUUUUUUUUUU.
TRACE +0.000 Read 3 bytes: f8fef0
TRACE +0.000 Read invalid data: f8fef0
TRACE +0.000 Remaining data in serial buffer:
.TRACE +0.056 command op=0x08 data len=36 wait_response=1 timeout=0.100 data=
    0707122055555555 5555555555555555 | ... UUUUUUUUUUUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
    55555555                          | UUUU
TRACE +0.000 Write 46 bytes:
    c000082400000000 0007071220555555 | ...$........ UUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
    5555555555555555 5555555555c0     | UUUUUUUUUUUUU.
TRACE +0.001 Read 1 bytes: f0
TRACE +0.000 Read invalid data: f0
TRACE +0.000 Remaining data in serial buffer: f0f0
.TRACE +0.056 command op=0x08 data len=36 wait_response=1 timeout=0.100 data=
    0707122055555555 5555555555555555 | ... UUUUUUUUUUUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
    55555555                          | UUUU
TRACE +0.000 Write 46 bytes:
    c000082400000000 0007071220555555 | ...$........ UUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU

......

A fatal error occurred: Failed to connect to ESP8266: Invalid head of packet (0xF0)

Below is the image of the arduino IDE with code and board selected as esp8266.

I am following this post https://iot-guider.com/esp8266-nodemcu/how-to-program-esp8266-with-arduino-uno/ and I have exact same hardwares.
UPDATE:
When I tried this connection in Windows it starts uploading code without error. So, my guess is its something to do with MAC.

This reads as if you're omitting some info... what is the role of the UNO? Are you using it to flash the ESP? Also, which GPIO are you pulling to GND? The ESP has many of these. Flashing an ESP also requires pulling three GPIOs up or down. Finally I note that you connect RX to RX and TX to TX -- normally, you need to connect TX (transmit) to RX (receive) on a serial connection.

@orithena I was following this post https://iot-guider.com/esp8266-nodemcu/how-to-program-esp8266-with-arduino-uno/ I have the exact same hardware.

From that article: "Also, connect the RX and TX lines of both." -- this means to connect TX on UNO to RX on ESP and RX on UNO to TX on ESP. I'm repeating that because your question lists those connections wrong. I'm also a bit concerned that those instructions show to connect the 5V TX/RX of the UNO to the 3.3V TX/RX of the ESP...

"Also, connect the RX and TX lines of both." this line does not necessarily say, I say this because the image connects RX of esp8266 to RX of uno and TX esp8266 to TX of uno.  By the way I did tried connect RX-TX and TX-RX get the same error. I also tried connecting with 5 V and I get same error.

The Atmega328 is being held in reset - essentially dormant. This technique borrows the Uno's auxilliary 16U2 chip, the USB <-> TTL converter to program the ESP. The Rx & Tx connections are correct as viewed as between the PC and the ESP, and the '328 plays no part in the communication, in this case. I share your concern about driving the 3.3v ESPs receive pin with a 5v transmitter, however.

I have tried both 3.3v and 5v and again tried 3.3v in a new esp8266 always get same error.

select Port in Tools menu

@Juraj updated the image. The image I had earlier was taken when not connected (I just wanted to show my configuration).

No matter what a tutorial on the internet says, connecting Rx to Rx and Tx to Tx is definitely not correct andin the worst case it can even harm your hardware. you have to connect the transmitting pin of A to the receiveing pin B and vice versa. If it still doesn't work, the error is somewhere else.

@SimSon When the flip the RX and TX connection I get time out error.

The tutorial you linked to can not be trusted! There are mayor mistakes:

They connect a 3.3V device with a 5V devices without taking any measures to convert the logic levels.
Connecting Rx to Rx (or Tx to Tx) is typically not what you do if you want to communicate between devices. A transmitting line must be connected to a receiving line for that. In case the arduino is Serial.print()ing something himself, a bus contention can cause a short circuit and harm the UART pins.
They are plugging the ESP into a breadboard which simply doesn't work! This will short several pins and possibly kill some hardware. At least it can't work like that.

I don't know if the person who did this tutorial just has no idea or is trolling, but you need to find a different tutorial (and - I'm sorry to say - possibly get a new ESP).
If all you want is to use the arduino as a USB to UART bridge, I suggest to remove the atmega chip from its socket on the arduino or make sure that it doesn't run a sketch were it prints something. The UART pins should also be configured as inputs.

Every other tutorial in internet is using ESP with bread board though.

The 5 holes (A,B,C,D,E) of a row are connected together on those breadboards. Can you show me another example where an ESP01 is put onto a breadboard? Maybe they use one of the ESP-based modules, like the nodeMCUs, which can be used on a breadboard. Pin headers with two rows are generally not very suitable for breadboards...

This is another one https://youtu.be/ZJnpgYlelEA?list=LL . Also I was able solve the issue, in my Mac I went back to Tools --> Boards Manager, then removed 3.0 (I had 3.0 version) and downgraded to 2.5 and it started working (meaning started uploading the code and the code in esp8266 was executed as expected). Yes, this is still using ESP01 on bread board. I have edited and mention this in top my question.

@solti in that video, the person uses jumper wires to connect the esp to the breadboard. What I wrote still applies...

you point 2 is not valid. the goal is to use the USB of the Uno, not to connect to ATmega.

@Juraj I see, I will edit my answer. But is it actually okay to do so? What if the ATmega is running code and printing something? In my opinion this should not be done unless there are current limitung line drivers involved... ehich are not on the arduino.

the ATmega should have a sketch without Serial.begin (BareMinimum, Blink) or reset wired to ground


text:
Serial communication detect
guys.
I am workin on a project. I have two channel for Serial RS232 communication. Main and Stand-By channel. If Main channel has some problem and, cannot communicate for 15 seconds then I want to start Stand-By channel communication. How can I do that? I want to listen to channel's RX with Arduino. I think I can use MAX 232 for Serial to TTL convert. Can I listen to channel's RX with Arduino then Can I decide which channel should work?
Thank you,guys..

You could look to see if the signal is toggling. If it hasn't toggled, i.e. flatlining at logic 1 or logic 0, for more than 15 seconds, then switch to the other comms link.

If it is important to get information from one point to another, you might try a physical layer and protocol layer that is more robust than RS232.  However, if you are in the mind set of learning, the I encourage you to design in layers or robustness on top of RS232.  Such as constant pining, error detection, error correction and protection switching.

Assuming there are not large groups of data but mainly control have you looked at CAN, it is a very robust interface.


text:
Getting Arduino 1.0.x to run on Guix: error: expected initializer before ‘_GLIBCXX_NORETURN’, error: ‘std::abort’ has not been declared, etc
I'm looking to get arduino 1.0.x to work on my Mint/Guix hybrid box in order to hack around with 3D printer firmware. Unfortunately I can't get the stock void setup () {} void loop () {} to compile. I get the following compilation error:
  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
Arduino: 1.0.6 (Linux), Board: "Arduino Mega 2560 or Mega ADK"
In file included from /home/blueberry/.guix-profile/include/c++/stdlib.h:36,
                 from /home/blueberry/Software/arduino-old/arduino-1.0.6/hardware/arduino/cores/arduino/Arduino.h:23,
                 from sketch_jun23a.ino:3:
/home/blueberry/.guix-profile/include/c++/cstdlib:57: error: expected initializer before ‘_GLIBCXX_NORETURN’
/home/blueberry/.guix-profile/include/c++/cstdlib:59: error: expected initializer before ‘_GLIBCXX_NORETURN’
In file included from /home/blueberry/Software/arduino-old/arduino-1.0.6/hardware/arduino/cores/arduino/Arduino.h:23,
                 from sketch_jun23a.ino:3:
/home/blueberry/.guix-profile/include/c++/stdlib.h:38: error: ‘std::abort’ has not been declared
/home/blueberry/.guix-profile/include/c++/stdlib.h:40: error: ‘std::exit’ has not been declared
In file included from /home/blueberry/.guix-profile/include/c++/cmath:42,
                 from /home/blueberry/.guix-profile/include/c++/math.h:36,
                 from /home/blueberry/Software/arduino-old/arduino-1.0.6/hardware/arduino/cores/arduino/Arduino.h:25,
                 from sketch_jun23a.ino:3:
/home/blueberry/.guix-profile/include/c++/bits/cpp_type_traits.h:69: error: expected `{' before ‘_GLIBCXX_VISIBILITY’
/home/blueberry/.guix-profile/include/c++/bits/cpp_type_traits.h:69: error: expected constructor, destructor, or type conversion before ‘(’ token
In file included from /home/blueberry/Software/arduino-old/arduino-1.0.6/hardware/arduino/cores/arduino/Arduino.h:235,
                 from sketch_jun23a.ino:3:
/home/blueberry/Software/arduino-old/arduino-1.0.6/hardware/arduino/variants/mega/pins_arduino.h:59: error: expected `}' at end of input
/home/blueberry/Software/arduino-old/arduino-1.0.6/hardware/arduino/variants/mega/pins_arduino.h:59: error: expected `}' at end of input

Guix clobbers the Arduino IDE include paths, even when my Nix environment is run. I can't get snapd to run on my box, setting up a custom Guix environment does not fix the problem, flathub doesn't have arduino 1.0.x available. Where can I go from here? Thanks.

Guix clobbers the Arduino IDE include paths, even when my Nix environment is run.  Isn't that a bug you should report to the Guix people? All the Arduino IDE should be doing is set up an environment where PATH correctly points to the used compiler, and then execute avr-gcc etc. (see e.g. https://github.com/arduino/ArduinoCore-avr/blob/master/platform.txt#L20-L23) with some flags. It's quite miraculous to me how it's able to bend the include paths to end up finding stdlib.h in /home/blueberry/.guix-profile/include/c++/stdlib.h..


text:
Arduino Zero and micro SD card not working
I have an Arduino Zero processor (atsamd21g18a) with a microSD shield connected (check images of schematics)

The point is that I cant make it to work, not with sd.h sketch and not with sdfat.h sketch.
Chip-select for the SD card is A3 or digital pin 17.
sd.h sketch
#include <SPI.h>
#include <SD.h>

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  SerialUSB.begin(9600);
  delay(1000);

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

  SerialUSB.print("Initializing SD card...");

  if (!SD.begin(A3)) {
    SerialUSB.println("initialization failed!");
    return;
  }
  SerialUSB.println("initialization done.");

  if (SD.exists("example.txt")) {
    SerialUSB.println("example.txt exists.");
  } else {
    SerialUSB.println("example.txt doesn't exist.");
  }

  // open a new file and immediately close it:
  SerialUSB.println("Creating example.txt...");
  myFile = SD.open("example.txt", FILE_WRITE);
  myFile.close();

  // Check to see if the file exists:
  if (SD.exists("example.txt")) {
    SerialUSB.println("example.txt exists.");
  } else {
    SerialUSB.println("example.txt doesn't exist.");
  }

  // delete the file:
  SerialUSB.println("Removing example.txt...");
  //SD.remove("example.txt");

  if (SD.exists("example.txt")) {
    SerialUSB.println("example.txt exists.");
  } else {
    SerialUSB.println("example.txt doesn't exist.");
  }
}

void loop() {
  // nothing happens after setup finishes.
}

sdfat.h code
const int chipSelect = A3;
/*
 SD card read/write

 This example shows how to read and write data to and from an SD card file
 The circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4

 created   Nov 2010
 by David A. Mellis
 updated 2 Dec 2010
 by Tom Igoe
 modified by Bill Greiman 11 Apr 2011
 This example code is in the public domain.

 */
#include <SdFat.h>
SdFat sd;
SdFile myFile;

pinMode(chipSelect, OUTPUT);

void setup() {
  delay(5000);
  SerialUSB.begin(9600);
  SerialUSB.println("Serial start");
  //while (!SerialUSB) {}  // wait for Leonardo
  //SerialUSB.println("Type any character to start");
  //while (SerialUSB.read() <= 0) {}
  delay(1000);  // catch Due reset problem

  // Initialize SdFat or print a detailed error message and halt
  // Use half speed like the native library.
  // change to SPI_FULL_SPEED for more performance.
  if (!sd.begin(chipSelect, SPI_HALF_SPEED)) sd.initErrorHalt();

  // open the file for write at end like the Native SD library
  if (!myFile.open("test.txt", O_RDWR | O_CREAT | O_AT_END)) {
    sd.errorHalt("opening test.txt for write failed");
  }
  // if the file opened okay, write to it:
  SerialUSB.print("Writing to test.txt...");
  myFile.println("testing 1, 2, 3.");

  // close the file:
  myFile.close();
  SerialUSB.println("done.");

  // re-open the file for reading:
  if (!myFile.open("test.txt", O_READ)) {
    sd.errorHalt("opening test.txt for read failed");
  }
  SerialUSB.println("test.txt:");

  // read from the file until there's nothing else in it:
  int data;
  while ((data = myFile.read()) >= 0) SerialUSB.write(data);
  // close the file:
  myFile.close();
}

void loop() {
  // nothing happens after setup
  SerialUSB.println("loop done.");
}

I am not sure if it is a hardware or software issue, but soldering and tracks are good.
Its like the hardware gets frozen, so I cant really see the serial messages. I know its not a serial issue because I can make a simple print serial script and it shows up. I think it might be related with libraries, or maybe some hardware limitation?
Can I use any pin as Chipselect? is digitalpin17 / A3 right?

what do you mean? PA04 is analogpin3 or digitalpin17 on samd21g18a . If you mean the comments on the sketches I use it is because they are examples of arduino and should work on any board as long as you change cs pin, thats why the second says pin4 as cs

Oop, yep, mis-remembered--pinout confirms.

Z1 to Z5 are varistors for overvoltage protection? Why does VDD of the SD card connect to 3.3V via a 1.69kOhm resistor and not directly? Can you check with a logic analyzer whether there is correct activity on the SD card's SPI bus? Also in the sdfat.h example you probably want to replace sd.initErrorHalt(); with { sd.initErrorPrint(); SerialUSB.flush(); } to get the error message.

Yes, z1 to z5 are varistors of 3,3V. I could not make the sd card to work so I ended up checking schematics on google and I copied what I thought could help. thats why I added the varistors and the series resistor on the vdd. I made a previous question about a proper schematic for sd card because everything I see online is actually different, but didnt really get a proper answer. I dont have a logic analyzer, but I have a scope, I will try to see what I get. I will try the change on the sdfat code. I put a tft screen on the spi, and it does work but it has a different CS.

Update here. I managed to get the sd card working. Adding a resitor to the 3,3V pin of the sd card was an absolute mistake beacuse it was making the volttage to drop. So I put a jumper there for now. Another thing was adding a pull up resistor on miso. Also one varistor seemed to be damaged so I removed it. Now the SD card is working fine, but the timestamps funcions of sdfat library make the board freeze. I will try to fix that but apparently it involves edditing the library. Does anyone know how to edit the library for this?


text:
Elegoo remote code program only running once
I want this program to receive multiple signals from the elegoo ir remote and produce different tones using the passive buzzer. I have attempted to add onto the basic example provided by adding a makeSound() function.
The serial monitor outputs different values for a button if I hit it multiple times. Is there a way to make it so that each button will give a consistent value so I can keep the pitch the same for each button?
#include "IRremote.h"
#include "IR.h"
#include "pitches.h"

IRrecv irrecv(RECEIVER);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'

void setup() {
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn();
}

void loop()
{
  int tmpValue;
  if (irrecv.decode(&results)) // have we received an IR signal?
  {
        tmpValue = results.value;
        Serial.println(tmpValue);
        makeSound(tmpValue);
    }
    irrecv.resume(); // receive the next value
  }

void makeSound(int tmpValue) {
Serial.println(tmpValue);

  if (tmpValue > 0) {
    Serial.println("In if statement");
    tone(8, NOTE_D5);
    delay(500);
    noTone(8);
  }
  if (tmpValue < 0) {
    Serial.println("In if statement");
    tone(8, NOTE_G1);
    delay(500);
    noTone(8);
  }

}

If you separate out the problem into having something to do with the remote code or the tone code, you remove the other from the question and you're more likely to get useful help.

simplify the code ... receive data and print it ... nothing more ... do not decode ... do not activate buzzer ... when that works as expected, then decode


text:
Question about MIDI library
I'm trying to replace this code with something that uses the Arduino MIDI library:
#include <SoftwareSerial.h>

#define rxPin 2
#define txPin 1

SoftwareSerial midiSerial (rxPin,txPin);

void setup() {
  midiSerial.begin(31250); }

while ( midiSerial.available()) {
    incomingCommand = midiSerial.read();
    incomingNote = midiSerial.read();
    incomingVelocity = midiSerial.read()*8.05511811024;
  if (incomingVelocity <=1023) {
    midiSerial.write(incomingCommand);
    midiSerial.write(incomingNote);
    midiSerial.write(incomingVelocity); } }

Here's what I came up with:
#include <MIDI.h> // MIDI Output
MIDI_CREATE_DEFAULT_INSTANCE();

byte MIDIChannel;
byte programByte1;
byte controlByte1;
byte controlByte2;

void setup() {
  MIDI.begin();
}

void loop() {
 if (MIDI.read()) switch (MIDI.getType()) {
      MIDIChannel = MIDI.getChannel();
    case midi::ProgramChange:
      programByte1 = MIDI.getData1();
      break;
    case midi::ControlChange:
      controlByte1 = MIDI.getData1();
      controlByte2 = MIDI.getData2();
      break;
    default: break;
    }
}

Does that look correct? It doesn't function as smoothly as the version that uses SoftwareSerial

what exactly is your question?

"Does that look correct?" It doesn't seem to take in any MIDI input data

how do you know this?

I've updated the code above and added the rest of the commands to my switch-case setup, so I'll keep searching for the data I'm looking for, which is specifically the 'command' data. Should be straightforward with some digging

The first code transmits MIDI data, and the second receives it, so they are not having the same functionality, actually opposite functionality. Also, do not use software serial for MIDI. It works ok for single notes, but if you start using e.g. CC data, you sometimes miss data, which is very problematic when these are MIDI Note Off messages.

The second piece of code doesn't do anything useful. I think it will not even compile (instruction after switch without case)


text:
Store Integer Value of Money on an RFID Tag
I am working on making an Arduino based arcade. I want each user of the arcade to have an RFID card that stores the amount of credits (basically money) they have. I know that RFID tags have 1028 bytes of storage on them, but I don't know how to write an integer value to them.
The amount of credits each user has would be stored on the RFID, as well as their PIN.
The PIN would be 4 digits, with each digit an integer from 0-9, as is the standard with PINs. It would be stored as a single integer, between 0000 and 9999.
The credit would ALSO be stored on each card. This would be between 0 and 99 (Most that can be loaded at a time). This, too, would be treated as a single integer, for ease of use.
Both integers would be of the Arduino type int.
I am using the MFRC522 library with an RC522 reader/writer. I have an Arduino Uno, but can easily switch to an Arduino Nano.
Can someone tell me how to:
A. Write an integer value (stored as a variable in the sketch or accessed from the RFID memory) to an RFID card?
B. Access that information and retrieve it as an integer I could operate on (+,-,÷,×, etc)?
Thanks in advance!

You can read data with :
status = mfrc522.MIFARE_Read(blockNum, readBlockData, &bufferLen);

and write data by:
status = mfrc522.MIFARE_Write(blockNum, blockData, 16);

However, there's a lot more to it, so check examples of the RFID library, or this external articles:
https://www.electronicshub.org/write-data-to-rfid-card-using-rc522-rfid/
https://playground.arduino.cc/Learning/MFRC522/
When you read the data in a memory block, you can get the bytes out you need and convert them to an int, or the other way around for writing.

So blockNum would be replaced with the block number of the target, and blockData would stay the same?

I'm not 100% sure what you mean ... blockNum is an integer (value) number of the target, and block data is the buffer containing the content of that block (of the target), which is typically a 8 bit array (typically unsigned byte*)

I wasn't sure what in the above code was placeholders and what was meant to stay the same when I make the sketch

blockNum is an input parameter (meaning it doesn't change). readBlockData is changed (with the data that is read), as well as bufferLen which contains the number of bytes read (and to not overflow the read buffer).  blockData (for writing) does not change the buffer (but changes the actual RFID tag content).