text:
How to use this 3-pin slide-switch?
I purchased these slide switches recently because I want to use them in my project:

But I don't know what to connect up the three pins to and I can't find any information about them online. Nor can I find sample code. Can someone show me how to wire them up and provide sample code please? I just want to be able to check their state and save it as a boolean variable.

As stated by the seller, this is an SPDT switch.

Sample code? For how to read a switch? Really?

It has only two positions and three pins. You'll figure out how it works in less than a minute if you use a multimeter in the continuity test setting. You dou have one, do you? If you don't, I really recommend adding one to your shopping basket next time.

for use purely by sensing with an MCU, you can ignore or even cut off one of the outer pins, then it's just a button (logically), for which examples abound.

As others have said, this is a SPDT (Single Pole Double Throw) switch. The center pin is common. When the switch is slid one way, it connects the center pin to the outer pin on that side. When you slide the switch the other way, it connects the center pin to the opposite outer pin.
See the link about SPDT switches Edgar provided in his comment: http://www.learningaboutelectronics.com/Articles/What-is-a-single-pole-double-throw-switch-SPDT
That explains these switches pretty clearly.
Connect the center pin of the switch to a digital pin on your Arduino. Connect one of the outer pins to ground.
Set the digital pin on the Arduino to INPUT_PULLUP mode.
Then, when you read the digital state of the pin, if it is LOW, the switch is closed. (Slid to the side of the pin you attached to ground.)

Since it has two possible positions, and three pins, you have a connection between pin 1 and 2 when position 1 is selected, and between pin 1 and 3 when position 2 is selected.
As BSF comment below, the middle pin is common. This means it will be connected to the outside pins depending on where the switch is moved towards.
However, you always can verify this, in the following way:
To find out which is pin 1, pin 2 and pin 3, use a multimeter. Set it to continuity mode, or if you don't have that mode, to resistance mode, and put the red/black probes to two random pins. Check if the resistance is 0, in that case you know those two pins will be connected when position 1 is selected. If there is resistance, try other pins with the probes, until you know which are connected.
Than switch the position, and do it again.
Instead of a multimeter you also can 'hardwire'  it to e.g. 5V -> pin 1, pin 2 -> resistor of 220 ohm -> LED -> GND
And change pin 1 and pin 2 until you found which pins connect for which positions.
To use it for you Arduino, check for a normal simple switch example, but these are two in one, one for each position.

Pin 2, the one in the middle is always the common. There is no other possibility with a slider switch.

@SBF Ok ... my test would have the same conclusion, but good to know it's always the middle position which is common.

The key point of Michel's post is that you can figure out how a switch is wired in a few minutes with a multimeter. This is a very good skill to develop.

@DuncanC thanks for the compliment ... upvoted your answer as it confirmed something I thought should work (pullup + LOW active), assuming on MCU's with internal pulldown resistors HIGH active should work equally).

These switches are actually a lot more simple than you would think.  You have two positions, but you really only care about one of them, since if it's not in that position it must be in the other.
The central pin is the common, and when slid to one side it connects that central pin to the corresponding outside pin.
So you just use the central pin and one of the outside pins as if it were any other on-off switch or pushbutton.  Treat it exactly the same (pullup resistor, which may be internal to the AVR chip, and connect the IO pin to ground through the switch).
If it's "on" (reads LOW) then the switch is in one position. If it's "off" (reads HIGH) then it's in the other position.
The only times you'd want to use both outer pins is if you were wanting to direct a signal to one of two different places, or select between two different incoming signals, or if the switch were a "3 position on-off-on" switch where it can be in either outer position or neither position (centre off), in which case you treat it as two separate switches, but with a common central pin that connects both to ground.

So which pin should I connect to ground?
And which pin should I connect to Arduino's #2 to get this sketch to work? http://man.hubwiz.com/docset/Arduino.docset/Contents/Resources/Documents/www.arduino.cc/en/Tutorial/DigitalInputPullup.html

Connect any pin to ground. The pin you connect to #2 depends which pin you connected to ground. If you connected the central pin to ground then use one of the outside pins. If you connected one of the outside pins to ground then connect the central pin to #2. All the switch consists of is three metal posts and a sliding lump of metal that moves across the top of those posts.


text:
Why won't Wifi Shield detect any networks? Even really close
I just purchased an Adafruit Wifi Shield CC3300 and strapped it onto my Arduino Uno board.
I'm running this basic sketch that I found to test the functionality of the Wifi Shield: http://arduino.cc/en/Guide/ArduinoWiFiShield#toc1
Of course in my home I have Wifi, so I expected this sketch to show my Wifi name. However it doesn't. Instead I get this output on my serial monitor:
Init...
** Scan Networks **
Initializing Wifi...
MAC: 0:0:0:0:0:0
Scanning available networks...
** Scan Networks **
number of available networks:0
Scanning available networks...
** Scan Networks **
number of available networks:0

It just keeps going forever detecting zero networks.
I even took the Arduino and stood 3 feet away from my Wifi router. Still nothing.
I even tried making my cell phone a Wifi hotspot and holding it right next to the Arduino. Still nothing. And why does it say the MAC Address 0:0:0:0:0:0?
Can anyone suggest a fix?
FYI, here is a photo of what my setup looks like:

Do you know if the Adafruit wifi board is compatible with the Arduino wifi shield libraries? Adafruit provides their own libraries on their tutorial page here: https://learn.adafruit.com/adafruit-cc3000-wifi?view=all#download-the-library I would try using their code with their hardware first.

Also what's up with the headers floating, are they even soldered to your WiFi shield?

Was this ever solved?  I'm having the same issue with an Arduino Uno and the Wifi/SD Shield.

source: Stack Exchange

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

sort: votes


text:
Can I Interrupt on any keypress on this keypad?
I'm learning how to write code interrupt code. I just experimented with my first toy example that I got from here:
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}

void loop() {
  digitalWrite(ledPin, state);
}

void blink() {
  state = !state;
}

Now I'm trying to incorporate interrupts into my own project. I have a circuit that looks like this using an Arduino Uno Wifi Rev2, Membrane 3x4 Matrix Keypad, a buzzer, some resistors and an RGB LED:

Can I write code such that it interrupts any time any of the keys is pressed (and I can still tell which key is pressed)? How would I do that?

you could use diodes to connect all the columns to an interrupt pin ... keep all the rows low .... when any button is pressed, an interrupt is generated ... the interrupt would activate a keyboard scan to determine which key caused the interrupt

Uno WiFi Rev 2 supports external interrupt on every pin, but that is not useful here

Interrupt are great for counting things, but taking human input via interrupt can lead to some really confusing code.  You have to start protecting against things getting corrupted because the input comes in the middle of some other part that’s acting on input.  The classic example is a button press.  This line if(buttonState != oldButtonState && buttonState == LOW) is just fine in most code.  But if you use an interrupt to read the button and set buttonState then that line is a huge bug.

see the schematic here ...https://arduino.stackexchange.com/questions/34054/multiple-buttons-on-single-interrupt-how-to-debounce .... since you are using Uno WiFi, you do not need a separate interrupt pin .... just bring all rows low ... pressing any key will interrupt on column pins

Interrupts are for things that happen too fast to sample with normal code.  That doesn’t include a human pressing a button.  Interrupts are NOT a cure for the fact that you’ve coded some other part of the code with blocking functions like delay.  It seems at first like a good idea, but you’ll find out quickly that it would have been much easier to just write non blocking code for things.

No, you can't. Owing to the fact that you have to manually cycle through each row (or column, depending on which way you are holding your head at the time) in order to read which keys are pressed there is no way to relate a button to an interrupt.
The only possible way would be to use an external keypad interface chip (you could roll your own with another Arduino) which has an interrupt signalling facility in it.

Why can't I do what Jsotola mentioned in the comment above?

@SaqibAli, even though it is doable, it is more trouble than it is worth ... but it may be a good learning experience

Yes, that might work, but as jsotola says, it's not worth it. Unless you have a specific reason to require an interrupt just use polling.

"Can't" is too strong. You can if you use diodes, as jsoltola says. "You can, if you wire it correctly using diodes, but coding interrupts is tricky and probably not worth the trouble" would be more accurate.

I mean yeah you “can” put wooden tires on your car.  It would be stupid and counterproductive but you “can” in just the same sense.

You “can” buy dozens of high powered lasers to heat up a pan to make cookies.  It would be cool but terribly expensive and hard to do.  But you “can” in the same sense.  Actually I think laser cookies is probably a better idea.

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


text:
How to use this Toggle Switch?
I purchased this toggle switch recently because I want to use it in my project:

But I don't know what to connect up the three pins to and I can't find any information about it online. Nor can I find sample code. Can someone show me how to wire it up and provide sample code please?

Did you read the description? It's basically a push-button toggle switch that connects and disconnects the middle pin from either of the two side switches with every click.

the description suggests that it is a SPDT with center off ... that means that the switch has three states

It's basically a push button. Possible examples depend on what you want to do. As it seems, you simply want to start interfacing it with Arduino, just use it as a normal push button. Use the DigitalInputPullup example, that comes with the Arduino IDE:
Middle pin to pin 2 on the Arduino
One of the other pins to ground (depending on which state you want to be reflected with a HIGH in the Arduino)
The other pin unconnected

Look at these two schematics. The left one is a normal push button. It connects, when pressed and disconnects, when released. The right one is your button. When pressed it disconnects the upper  pin and connects to the lower pin. When released vice versa.  When you don't use the upper pin, your button behaves just like the push button on the left.

simulate this circuit – Schematic created using CircuitLab

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


text:
Different dht21 readings on different arduinos
First of all, let me begin by saying that I'm still pretty much a rookie.
I have a project with a dht21, an LDR and an ultrasonic distance sensor. I have 3 different arduino uno boards, namely:

A (supposedly) original arduino uno r3.
A chinese nhduino, arduino uno r3 clone.
And this one, sitting on top of this.

I've been playing around with the three boards for the last couple of months, testing a variety of sensors and having the same results with the three boards, as expected. But then, with the aforementioned setup, I'm getting very different readings on the DHT21 sensor. If I use the "regular" (first two) arduinos plugged in my laptop, the readings are consistent. But if I use the banana pi(duino), I get the temperature reading correct, but getting weird humidity readings... pretty most of the time a 5% humidity value.
Everything tested on the same room, same sensors and same protoboard. No external power supply.
I'm totally clueless here, any ideas of what could be the problem?
Thanks.

Do you have multiple DHT21's as well as multiple boards? If so, I assume the error still follows the board, not the sensor.
Is there another library you can use on the RPI, or maybe take the Arduino piece out of the loop, and interface the sensor directly with the pi.  Lets try to figure out which component is giving us the issues. (Sensor, Arduino, Pi, or code)

Only one DHT21, one LDR and one Ultrasonic. Same board, I just plug/unplug jumpers cables. It's not a software problem either, as the BPiDuino has been working like a charm so far with every other digital or analog sensor I've thrown to it. Except for the DHT21. But I think I've found the solution, because now I'm using a breadboard power supply and it's working no matter whether I power the PSU from the banana pi USB or from the barrel jack.

Problem solved. Using a ywrobot breadboard PSU and now it works. I haven't tested current in the circuit but looks like it was just too low. I wish I'd had datasheet for the board to look at. In a language different from chinese would have been ok, I guess.

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


text:
Will we be able to burn arduino zero pro's bootloader?
As arduino.org states, the bootloader is pre-burnt by Atmel at the factory. I'd like to know if it will be possible for us to buy "raw" ICs and burn them at home for our own boards, as we do with the Atmega328 for example.

Burning shouldn't be a problem. Though you might need a JTAG programmer.

My worry isnt that much about the hardware itself but the availability of the bootloader/firmware..

I can't seem to find it. Though my guess it that it will become available, since it's open source hardware/software. The bootloader might however depend on the onboard debug chip.

Hopefully it will be possible. Afaik with Due's its impossible because part of the firmware is burnt by Atmel at the factory..

That's interesting. I didn't know that.


text:
ADC port manipulation
I was modifying this ADC Touch implementation, namely switching analogRead and pinMode to what I thought would be port manipulation equivalents.
I get very different readings (better and more stable in my case).
So, what I think is equivalent is actually quite different. Can someone point the differences to me?
Original:
    pinMode(ADCChannel, INPUT_PULLUP);

    ADMUX |=   0b11111;
    ADCSRA |= (1<<ADSC); //start conversion
    while(!(ADCSRA & (1<<ADIF))); //wait for conversion to finish
    ADCSRA |= (1<<ADIF); //reset the flag

    pinMode(ADCChannel, INPUT);
    _value += analogRead(ADCChannel);

Modified:
    DDRC &= ~(1 << ADCChannel);
    PORTC |= (1 << ADCChannel);

    ADMUX |=   0b11111;
    ADCSRA |= (1<<ADSC); //start conversion
    while(!(ADCSRA & (1<<ADIF))); //wait for conversion to finish
    ADCSRA |= (1<<ADIF); //reset the flag

    DDRC &= ~(1 << ADCChannel);
    _value += analogRead(ADCChannel);

Your modified code doesn't disable the pullup on the pin.
PORTC &= ~_BV(ADCChannel);


text:
How can I host a WiFi network from an Arduino getting a connection from a SIM card?
My friend and I are doing a project and we're stuck on a problem. We tried looking stuff up but it looks like no one documented something similar before.
Basically, what we want to do is have one Arduino (we thought a MKR NB 1500) in a remote location without any available WiFi (or Ethernet) connection be able to host its own Wifi Network. We thought that giving it a SIM card would allow it to communicate to our webserver (API) and to our surprise, it does (yay)! However, we also want people near the Arduino to be able to access the internet. However, that's where we're stuck...
I know that hosting an access point on an Arduino with WiFi is possible. But is it possible for that access point to link the user to the real internet, itself provided by the SIM card?
P.S. : We are open to having two different Arduinos linked together (or more) in order to make this work. We just need to be able to transfer the SIM network to an access point (hotspot basically).
P.P.S : We are also open to using different technologies like ESP controllers... We're just not using a cellular hotspot because of the cost of these things and we want to make it with Arduino or different controllers.

A sim card gives access to mobile data.  Do you really want to use mobile data for your internet?

This might be useful : https://www.iot-bots.com/products/qboard-a-arduino-mkr-compatible-wifi-bt-ble-iot-controller            and if you want to extend the range of your Wi-Fi network cheap, you can use this lib, it is very well documented :https://github.com/martin-ger/esp_wifi_repeater

@RohitGupta I understand it's not ideal but I didn't think of anything else that could work. If I got something like a 1-2gb/month plan for cheap then limited bandwith it could've worked. Do you suggest something else?

@MAK thanks a lot that seems to be what I am looking for. I'll continue to do some research and see if maybe that shield can talk with the MKR and take its connection...

Bridging of two networks at TCP/IP level is done in the TCP/IP stack. It translates addresses from one network interface to other network interface, but both interfaces are handled by the same TCP/IP stack.
An example on an MCU would be translating between esp8266 SoftAP and STA network interface. They are two network interfaces handled by the same TCP/IP stack. And now esp8266 Arduino can handle some Ethernet modules as additional network interfaces of that TCP/IP stack too.
With MKR NB 1500 or any other (mobile) network module attached to Arduino you can't do bridging because the TCP/IP stack is in the firmware of the module and the WiFi or Ethernet shield you would attach to the MKR would have its own TCP/IP stack in the firmware too.
If you are on esp8266, esp32 or other MCU where the TCP/IP stack runs in the MCU, you still can't make it work together with the TCP/IP stack in the external module. Those Ethernet modules esp8266 can use as netwok interaces with its TCP/IP stack are interfaced on the software layer closer to hardware, but the mobile network modules use AT commands without exposing access to lower layers.
What you can do is to proxy some network services as I write in this answer.

This is wrong Bridging of two networks at TCP/IP level is done with IP Network Address Translation (NAT) Protocol.. NAT is a routing solution not bridging.

@MatsK isn't 'bridging' routing?

No, bridging is on layer 2 and routing on layer 3.

@MatsK, ok. I removed mentions of NAT


text:
Python script cannot connect to serial port
I want to control the LEDs with my hand, for this I used the repository https://github.com/paveldat/finger_counter/tree/main. I want to control the LEDs with my hand, for this I used the repository. To connect to the arduino mega serial port, I use the pyserial library, here is the code to which I pass variables.
arduinoData = serial.Serial("com9", 9600)
arduinoData.write(bytes(str(variable), "utf-8"))

to control the LEDs and process data from the serial port, I wrote the following code in the Arduino IDE:
void setup() {
  Serial.begin(9600);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
}

void loop() {
/*
  if (Serial.available() > 0){
    serialData = Serial.read();

    for (int i = 3; i<serialData; i++){
      digitalWrite(i, HIGH);
    }
    }
*/
  if (Serial.available() > 0){
    char serialData = Serial.read();
    if (serialData == '3'){
      digitalWrite(3, HIGH);
      }
    else if (serialData == '4'){
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      }
    else if (serialData == '5'){
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      }
    else if (serialData == '6'){
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, HIGH);
      }
    else if (serialData == '7'){
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, HIGH);
      digitalWrite(7, HIGH);
      }
    else if (serialData == '0'){
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      digitalWrite(7, LOW);
      }

    //Serial.println(serialData);
    //digitalWrite(serialData, HIGH);
    //delay(1000);
  }
}

when I run this code without connecting the camera and just pass the values to the serial port, then everything works. However, when I try to run this code together with the camera, the following error occurs:
serial.serialutil.SerialException: could not open port 'com9': PermissionError(13, 'Access denied.', None, 5)

The camera is a laptop webcam, I have not tested the code with the USB camera, the assumption is that the USB camera will not occupy all serial ports.

What operating system do you use? Are you sure, that "com9" is the correct port, especially when the camera is connected? (as this might change) Can you connect the camera and then open the port in the Arduino IDE?

There is the remote possibility that you also opened the Serial Monitor of Arduino IDE when you connected the USB camera. This may seem unrelated, but the Serial Monitor blocks other programs from using that COM port while it is running.

when I tested the code, my IDE was basically closed @orithena

I use windows 10 when the camera is turned on in the device manager as well as before COM9 is busy with arduino mega @chrisl

If it works fine with one part but not the other, then it may be that both parts are attempting to use the same resources, or that your old run is still using a port and has not been killed.  End your python piece with an exit call or simply del arduinoData

The problem with accessing the port is solved, it was busy since I tried to open it every time in a loop that receives an image and displays it on the screen. I took out the code for a cycle, but the LEDs did not start.
here is the updated code:
import cv2
import time
import os
import serial
import HandTrackingModule as htm

wCam, hCam = 640, 480

cap = cv2.VideoCapture(0)
cap.set(3, wCam)
cap.set(4, hCam)

folderPath = "fingers" # name of the folder, where there are images of fingers
fingerList = os.listdir(folderPath) # list of image titles in 'fingers' folder
overlayList = []
for imgPath in fingerList:
    image = cv2.imread(f'{folderPath}/{imgPath}')
    overlayList.append(image)

pTime = 0

detector = htm.handDetector(detectionCon=0.75)
totalFingers = 0

def arduino_write(totalFingers):
    arduinoData = serial.Serial("com9", 9600)
    arduinoData.write(bytes(str(totalFingers+2)+"\n", "utf-8"))
    arduinoData.close()

while True:
    sucess, img = cap.read()
    img = cv2.flip(img, 1)

    img = detector.findHands(img)
    lmList, bbox = detector.findPosition(img, draw=False)

    if lmList:
        fingersUp = detector.fingersUp()
        totalFingers = fingersUp.count(1)

    h, w, c = overlayList[totalFingers].shape
    img[0:h, 0:w] = overlayList[totalFingers]

    cTime = time.time()
    fps = 1/ (cTime-pTime)
    pTime = cTime

    cv2.putText(img, f'FPS: {int(fps)}', (400, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3)
    cv2.rectangle(img, (20, 225), (170, 425), (0, 255, 0), cv2.FILLED)
    cv2.putText(img, str(totalFingers), (45, 375), cv2.FONT_HERSHEY_PLAIN, 10, (255, 0, 0), 25)

    arduino_write(totalFingers)

    cv2.imshow("Image", img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

authors: Дмитрий Насонов


text:
Serial Buffer stays empty as soon as it becomes empty once
I have a question regarding serial buffer readout.
At program start, I send a serial command to a sensor that 1. activates him and 2. let him send data - that works.
When I unplug the sensor, the serial buffer remains empty and the program goes into the else condition of void loop.
But if I connect the sensor again, the serial buffer should be filled again and the program should jump into the if condition of the void loop. But it does not.
I added the variable i because the serial buffer becomes empty too quickly and the program then sends the start command of the else condition again, even though the sensor is connected and still works. Then the readout gets mixed up...that works too.
Why doesn't the program jumps back in the if condition of void loop when the sensor gets connected again after it was disconnected some time? Then serial.available() should be bigger 0 and it should readout data?
#include <SoftwareSerial.h>
int i = 0;

void setup()  {
    Serial.begin(9600);
    Serial1.begin(9600);
    Serial1.write(Send Start Sequence);
    Serial1.write(Start continuously read out sensor data);
}

void loop() {
  if (Serial1.available() > 0) {
    char incomingByte = Serial1.read();
    Serial.write(incomingByte);
  i = 0;
  }
  else {
    i++;
    if (i > 5) {
      Serial1.write(Send Start Sequence);
      Serial1.write(Start continuously read out sensor data);
    }
  }
}

I second Nick Gammon in recommending a time-based condition, rather than
counting the loop iterations. You can do it in a non-blocking fashion
though:

keep track of when was the last time you communicated with the sensor
if this was too long ago, resend the “start sequence” command

Note that sending the command counts as a communication event, which
rearms the timer. Otherwise you would be repeatedly sending the command
too fast.
// After this delay, assume we lost the sensor.
const unsigned long timeout = 200;

// Last time we communicated with the sensor.
unsigned long last_comm_time;

void loop() {
    // Check the clock.
    unsigned long now = millis();

    // Process incoming data.
    if (Serial1.available() > 0) {
        last_comm_time = now;
        char incomingByte = Serial1.read();
        Serial.write(incomingByte);
    }

    // Try to wake up the sensor if we lost it.
    if (now - last_comm_time >= timeout) {
        last_comm_time = now;  // count this as a communication event
        Serial1.write(start_sequence);
        Serial1.write(continuously_read_out_sensor_data);
    }
}

You could potentially have separate timeouts for “the sensor just
stopped sending data” and “the sensor should be processing the start
command we just sent”. This would be a bit more complex though,
requiring some sort of state machine. If you can use a single timeout
value, things are simpler.

Ach, Edgar! You beat me to it by a few seconds! Anyway, you are right. :)

Your loop going to 5 is going to happen extremely quickly. Instead I would do a delay, say of one second (1000 ms), maybe less. Constantly sending the start sequence my be misinterpreted if the sensor comes online in the middle of the sequence. Plus your (counting) delay would only happen once. Putting a delay in the loop would make it happen every time.

I suggest a different way of recovering from an unplugged sensor:
#include <SoftwareSerial.h>

void setup()  {
    Serial.begin(9600);
    Serial1.begin(9600);
    Serial1.write("Send Start Sequence");
    Serial1.write("Start continuously read out sensor data");
}

unsigned long lastDataReceived;

void loop() {
  if (Serial1.available() > 0) {
    char incomingByte = Serial1.read();
    Serial.write(incomingByte);
    lastDataReceived = millis ();
  }
  else {
    if ((millis() - lastDataReceived) > 5000) {
      Serial1.write("Send Start Sequence");
      Serial1.write("Start continuously read out sensor data");
      lastDataReceived = millis ();
    }
  }
}

What this will do is wait 5 seconds before sending out the new start sequence. At 9600 baud your loop will be a lot faster than incoming bytes. This will be more reliable.

Thanks for your comment. But I think thats a problem, because the start sequence also gets me an answer from the sensor. Then I get every second loop a wrong output, not the value from the sensor but the answer of the start sequence. ATM I get the following: Sensordata, 1, 2, Sensordata, 1, 2, Sensordata, and so on. So I > 2 would be enough, but to be sure..

See my edited answer (it wasn't a comment).


text:
Issues getting WPS working on ESP32
I am trying to implement WPS on ESP32. A WT32-SC01 Plus to be exact.
It seems to working so far that I'll get the WPS connection but then it takes around 5 minutes [!!!] to get IP address from the router.
Also when the WPS connection was successful, after a reboot it do not reconnect but expects a new WPS initialization.
Can you take a look and tell me what am I doing wrong.
Here is my code:
#include "WiFi.h"
#include "esp_wps.h"

#define ESP_MANUFACTURER  "ESPRESSIF"
#define ESP_MODEL_NUMBER  "ESP32"
#define ESP_MODEL_NAME    "ESPRESSIF IOT"
#define ESP_DEVICE_NAME   "ESP STATION"

struct WiFiHandler
{
    bool connected = false;
    bool connecting = true;
    bool wpsDone = false;

    WiFiHandler()
    {
        WiFi.mode( WIFI_STA );
        // WiFi.setAutoReconnect( false );
        WiFi.onEvent( [ = ] ( WiFiEvent_t event, arduino_event_info_t info ) -> void
        {
            switch( event ) {
                case ARDUINO_EVENT_WIFI_STA_START:
                    Output::Message( "Station Mode Started" );
                break;
                case ARDUINO_EVENT_WPS_ER_PIN:
                    Output::Message( "PIN: %d", info.wps_er_pin.pin_code );
                break;
                case ARDUINO_EVENT_WIFI_STA_GOT_IP:
                    Output::StartUpMsg( "Connected" );
                    connected = true;
                    connecting = false;
                break;
                case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
                    Output::Message( "Reconnecting" );
                    WiFi.reconnect();
                break;
                case ARDUINO_EVENT_WPS_ER_SUCCESS:
                    Output::StartUpMsg( "WPS Successfull." );
                    WiFi.disconnect();
                    wpsStop();
                    WiFi.begin();
                    wpsDone = true;
                break;
                case ARDUINO_EVENT_WPS_ER_FAILED:
                    Output::StartUpMsg( "WPS Failed!" );
                    connecting = false;
                break;
                case ARDUINO_EVENT_WPS_ER_TIMEOUT:
                    Output::StartUpMsg( "WPS Timedout!" );
                    connecting = false;
                break;
            }
        } );
    }

    bool initialise()
    {
        int cnt = 0;
        TaskHandle_t taskHandle = NULL;
        xTaskCreate( this->blink, "WiFiConnect", 1000, this, 1, &taskHandle );
        Output::StartUpMsg( "Establishing network connection ..." );

        if( String( WiFi.SSID().c_str() ).length() ) {
            WiFi.begin( WiFi.SSID().c_str(), WiFi.psk().c_str() );
            while( ( WiFi.reconnect() != ESP_OK && !this->connected ) && ( ++cnt < 20 ) ) {
                lv_bar_set_value( ui_BootProgress, lv_bar_get_value( ui_BootProgress ) + 1, LV_ANIM_ON );
                delay( 100 );
            }
        }
        if( !this->connected ) {
            WiFi.begin();
            Output::StartUpMsg( "Please initialise WPS connection on the router." );
            cnt = 0;
            if( wpsInit() ) {
                if( esp_wifi_wps_start( 1000 ) != ESP_OK ) {
                    Output::StartUpMsg( "Can't start WPS" );
                }
                while( WiFi.status() != WL_CONNECTED )
                {
                    delay( 1000 );
                    if( WiFi.status() == WL_IDLE_STATUS && wpsDone ) {
                        WiFi.reconnect();
                    }
                    // if( WiFi.status() == WL_CONNECTION_LOST && wpsDone ) {
                    //     WiFi.disconnect();
                    //     WiFi.begin( WiFi.SSID().c_str(), WiFi.psk().c_str() );
                    // }
                    Output::Message( WiFi.SSID().c_str() );
                    Output::Message( WiFi.localIP().toString().c_str() );
                    Output::Message( String( WiFi.status() ).c_str() );
                }
                delay( 2000 );
                this->connected = true;
            }
        }
        if( this->connected ) {
            while ( !WiFi.SSID().length() )
            {
                lv_bar_set_value( ui_BootProgress, lv_bar_get_value( ui_BootProgress ) + 1, LV_ANIM_ON );
                delay( 100 );
            }
            Output::StartUpMsg( "Connected to: " + WiFi.SSID() );
            while ( !String( WiFi.localIP() ).length() || WiFi.localIP().toString() == "0.0.0.0" )
            {
                lv_bar_set_value( ui_BootProgress, lv_bar_get_value( ui_BootProgress ) + 1, LV_ANIM_ON );
                delay( 100 );
            }
            Output::StartUpMsg( "IP: " + String( WiFi.localIP().toString() ) );
            delay( 500 );
            this->connecting = false;
            this->connected = true;
        }
        return this->connected;
    }

    String getIP()
    {
        return String( WiFi.localIP().toString() );
    }

    String getPass()
    {
        return String( WiFi.psk().c_str() );
    }

    String getNetworkName()
    {
        return String( WiFi.SSID() );
    }

    String getMAC()
    {
        return String( WiFi.macAddress() );
    }

    static void blink( void *pvParameter )
    {
        WiFiHandler *l_pThis = ( WiFiHandler * ) pvParameter;
        for( int i = 0; l_pThis->connecting; i++ )  {
            i%2 ? lv_obj_add_flag( ui_WiFiStatus1, LV_OBJ_FLAG_HIDDEN ) : lv_obj_clear_flag( ui_WiFiStatus1, LV_OBJ_FLAG_HIDDEN );
            delay( 250 );
        }
        l_pThis->connected ? lv_obj_clear_flag( ui_WiFiStatus1, LV_OBJ_FLAG_HIDDEN ) : lv_obj_add_flag( ui_WiFiStatus1, LV_OBJ_FLAG_HIDDEN );
        vTaskDelete( NULL );
    }

    static bool wpsInit()
    {
        int cnt = 0;
        esp_wps_config_t config;
        config.wps_type = WPS_TYPE_PBC;
        strcpy( config.factory_info.manufacturer, ESP_MANUFACTURER );
        strcpy( config.factory_info.model_number, ESP_MODEL_NUMBER );
        strcpy( config.factory_info.model_name, ESP_MODEL_NAME );
        strcpy( config.factory_info.device_name, ESP_DEVICE_NAME );
        esp_err_t status = esp_wifi_wps_enable( &config );

        if( status != ESP_OK ) {
            Output::StartUpMsg( "WPS config failed! " + String( esp_err_to_name( status ) ) );
            return false;
        }
        return true;
    }

    static void wpsStop()
    {
        if( esp_wifi_wps_disable() ) {
            Output::StartUpMsg( "WPS Disable Failed" );
        }
    }
};

Ok people, my router was apparently acting weird. It seems to works fine now!
EDIT: Why the hell someone downvoted my answer? people are weird

how could anyone other than you solve the problem? it is not an Answer.

Nobody because it was a router issue. But as I posted it I assumed it was something with my code.


text:
best practice for performance: empty loop() when using interrupt?
I'm working on a little midi hardware project and I'm using attachInterrupt() to assign a callback function to an interrupt pin.
Nothing gets done in the loop function, so it looks like this:
void loop() { return; }

So far this seems to work out, but I'm wondering if this is a bad practice? I tried adding a short delay() call in there instead but I couldn't really measure if it performed better or worse.

no need for return  ... there is nothing to return to

loop() returns to main() (from where it was called, inside an infinite loop) after every iteration, whether or not you write a return; statement. The only case of such a function not returning one that contains an infinite loop to prevent it.

If you are using just one ISR to check a pin, this boils down to the question, which alternative has more overhead: a loop polling the pin, or the interrupt service entry and exit. You need to measure or look into the assembly code.

There is no particular reason to worry about doing nothing in loop - the processor has to be doing something -  you don't need to give it extra work.
Plus, there is an implied return at the end of functions, you don't need to add your own.
The bigger issue is that interrupt handlers should be short, so that you don't miss another interrupt while you are doing something lengthy in the first interrupt.

I think I can answer my own question.
I realized that I can keep my state change and debouncing logic in the interrupt routine and move everything else to the loop function, which seems cleaner.
edit: well not necessarily cleaner. I agree with @jsotola, ISR should only do the bare minimum.
In the end I figured not even using an ISR in the first place was even better for my use case.

putting too much code into an ISR is just asking for trouble ... especially the debounce code, it hangs the program for too long if it is inside a non-looping code block ... put the debounce code inside loop() so that the interval between keybounces can be measured without pausing the program

Debounce code in an ISR  can be OK if works by rejecting events (say button presses) which occur within say 50ms of the last accepted event because this can be coded without blocking. But, yes, in principle, an ISR should be very lightweight and quick to execute.


text:
What type of pin header is this?
Most of the Arduino uno boards have black female pin header. when i bought a ardiuno uno the digital pins 0 to 7 are made of silver pins. What type of pin  header is that? How to use these kind of pin headers?

it is just the black plastic removed

What makes them basically unusable. You should remove them and solder on a new one

if you do not want to do any soldering, then you may be able to push on another shell ... you could also put heat shrink tubing on each of those forks

These are corrupted female headers so remove them and solder new ones.


text:
Problem when running Servo library with thread (Protothreads)
When running two threads, one for blinking led once every second, one for sweeping the servo 180 degrees. The servo just vibrates.
When I tested adding a serial printout in the run servo for loops for the pos variable it worked but a bit jerky. Any idea what could be the problem?
#include <Arduino.h>
#include <pt.h>
#include <Servo.h>

// put function declarations here:
static struct pt pt1;
static struct pt pt2;
Servo myservo;
int pos = 0;

static int protothreadBlinkLED(struct pt *pt) {
  static unsigned long lastTimeBlink = 0;
  PT_BEGIN(pt);
  while(1) {
    lastTimeBlink = millis();
    PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > 1000);
    digitalWrite(LED_BUILTIN, HIGH);
    lastTimeBlink = millis();
    PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > 1000);
    digitalWrite(LED_BUILTIN, LOW);
  }
  PT_END(pt);
}

static int protoThreadRunServo(struct pt *pt) {
  static unsigned long lastServoUpdate = 0;
  PT_BEGIN(pt);
  while(1) {
    lastServoUpdate = millis();
    for(pos = 0; pos < 180; pos += 1) {
      PT_WAIT_UNTIL(pt, millis() - lastServoUpdate > 150);
      myservo.write(pos);
    }
    for(pos = 180; pos >= 1; pos -= 1) {
      PT_WAIT_UNTIL(pt, millis() - lastServoUpdate > 150);
      myservo.write(pos);
    }
  }
  PT_END(pt);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(LED_BUILTIN, OUTPUT);
  myservo.attach(9);
  PT_INIT(&pt1);
  PT_INIT(&pt2);
}

void loop() {
  // put your main code here, to run repeatedly:
  protothreadBlinkLED(&pt1);
  protoThreadRunServo(&pt2);
}

use PT_SLEEP, instead of millis(), as in example code ... PT_SLEEP is non-blocking


text:
Using Arduino for Industrial process
I was wondering if the Arduino is applicable for Industrial monitoring, I want to make a real time status of the presses in our company. I haven't seen or read much about people using Arduino at an Industrial level, most of what I have seen or read are prototype projects.
I'm new in electronics and don't know if there is a better way of doing this rather than using Arduino. I was thinking of using Arduino Uno and Arduino Ethernet Shield or Wifi Shield.
Any help on some information on how to start on this is helpful.

Related post: http://electronics.stackexchange.com/questions/15535/reliability-of-the-arduino-platform-for-industrial-use/

I wouldn't use the Arduino in an industrial environment, as I wouldn't trust its PCB to be able to handle much noise. Use the Arduino and shields to prototype your application, and then move to a circuit board that uses proper techniques suited to an industrial environment.

From what a have read recently most suggest the same, I wanted to use the Arduino since I don't know how to build my own circuit board, but I guess Ill just have to learn thank you for the advice.

Any recommendations on a "circuit board that uses proper techniques suited to an industrial environment", or are you speaking generically that you should custom-design something and be sure to provide proper protections and isolation on all your inputs and outputs?

Protection and isolation is a start, but you also need to worry about things such as noise and vibration which can shake connectors loose, as well as chemicals and particulates in the air which can corrode or cause malfunction of the electronics.

Good points, hence why I recommended the soldering of the wires on any final product, rather than using jumpers. I just improved my answer below. I've seen professional boards that are 100% waterproofed too via clear-coat finishes. I wonder if you can just dip a whole, final, soldered board, such as a completed Nano project with all wires soldered, into polyurethane or lacquer to give it a protective finish against water, corrosion, humidity, chemicals, etc. You ever heard of doing such a thing?

Full conformal coating? Absolutely. It's not extremely common, but it is done.

I don't see any reason not to use Arduino in an industrial, engineering, or laboratory environment, if it meets your needs and does the job well. It is highly recommended, however, that you provide some sort of pin protection to keep industrial noise or voltage spikes from frying pins. Minimum pin protection could consist of using current-limiting resistors (or better yet, the other, more robust techniques shown here) on pins used for output and input signals. Optical isolation is also a good option, especially if potentially dangerous voltages are being used. Lastly, after you prototype and test your Arduino setup you should solder the wires to the Arduino and provide a protective case. You don't want to accidentally fry the Arduino or a pin via accidental static discharge (hence the case, and pin protection above), and you don't want jumper wires vibrating loose and connections slowly oxidizing over time and loosing electrical connectivity in any type of industrial or laboratory application that is expected to be used regularly (hence replacing your jumper wires with soldered wires). Shields, however, are prob. ok for low-humidity and room-temperature environments, as they are generally much more secure and solidly connected than individual jumper wires.
Note that you can solder wires to any Arduino, even the Uno, Leonardo, or Mega, for example, simply by soldering to the exposed portions of the pins on the bottom of the board. You can also cut off and desolder the female headers and either solder directly to the holes, or solder on male headers that you then solder to other PCBs. I especially like the Arduino Nano, Pro Mini, and Micro since they are small, have exposed holes or male pin headers, and can easily be soldered onto a professionally-manufactured circuit board or cheap protoboard, for better mounting in a final application. Keep reading below for more details on this.
I am an aerospace research engineer and use Arduino in my line of work regularly to solve problems. Here are some examples of current applications in use today, that I implemented, that are based on and using Arduino boards:

sensorless brushless motor RPM sensor, motor commander, and data acquisition device for bench-top testing
linear actuator closed-loop controller (linear stepping resolution is 0.01mm [10um], full moving range is 0 to 15mm); the Arduino commands the actuator driver board via a custom PWM signal using the Timer1 library (http://playground.arduino.cc/code/timer1); position is read via a custom quadrature encoder reader algorithm on the arduino; the actuator is used for very precise aiming of certain instruments; the $30 Arduino is taking the place of a $500 board that the actuator manufacturer makes, and the Arduino gives us much more functionality than the $500 board would give us. The Arduino and actuator will be used to precisely aim a laser for experiments in a wind tunnel.
flight controller interfaces between MATLAB and off-the-shelf Radio Control transmitter (read and write RC PWM & PPM communication signals)
Professional film studio communication interface on robotic, drivable camera system (info sheet & video).

Those are just a few cases. If it works, do it.  Once you prototype with a solderless breadboard, however, it is recommended that you at least hand-solder the final configuration to a permanent prototyping board, to make it more durable and noise-resistant (ie--primarily: so that it will have solid connections that can't corrode, break, come apart, or vibrate free easily).
Here's a soldering article I wrote (http://electricrcaircraftguy.blogspot.com/2014/08/recommended-soldering-kit.html#.VP-JCPzF-So). see the links at the bottom for recommended soldering tutorials. The one about how to make "solder tracks" was especially useful to me once I got past the breadboard stage and started prototyping things on double-sided perf board.
Here are some double-sided prototyping boards (or "perf boards") to look into once you get to this stage: (Ebay search for "double sided pcb") http://www.ebay.com/sch/i.html?_from=R40&ghostText=&_sacat=0&_nkw=double+sided+pcb&rt=nc&LH_BIN=1 -- get the ones with all the little holes in them. You can put the whole thing in a plastic case if you want too. You can permanently solder an Arduino (esp. the Nanos or Micros more easily) to one of these perf boards.
Here's another example of double-sized perf board. (image source: http://www.elecfreaks.com/store/doublesided-protoboard-8cm-x-12cm-p-410.html)

Professional PCBs:
If you need to make more than a few of some device, hand-soldering wires and pieces all over a perfboard can get to be VERY tedious. In this case, you need to design a more professional PCB with custom traces and pads and layout and all for your project. If you don't have PCB-designing skills yet with a professional tool like Eagle or KiCad, you can use Fritzing (http://fritzing.org/home/) to design a PCB, and then send it off to a company like OshPark (https://oshpark.com/) for high-quality, reasonably-priced, low-quantity US-based manufacturing---or send it off to the Fritzing Fab lab in Germany for high-quality PCB manufacturing that supports the Fritzing project. Lastly, for a couple really inexpensive Chinese options, look at ITEAD Studio and Seeedstudio. Fritzing and any other PCB CAD software tool can output the necessary Gerber files for manufacturing.
Quick tip: when designing a PCB, don't use any 90 deg corners for your traces. They can act as antennas (sending or receiving) and cause electromagnetic (including radio) interference and noise. Use multiple 45 deg edges and corners instead.
Once you get your boards back, solder your Arduino to them, and solder any extra parts or hardware to them you need as well. Now you have quite a professional product, even if it has an Arduino soldered right to it.
Summary:
In summary, yes I think Arduino is great. Without it, I wouldn't know how to even blink an LED or load a single code to a microcontroller, because getting into using microcontrollers was just to enigmatic, difficult, and complicated for someone not professionally trained in it, such as an Aeronautical engineer like myself.  With Arduino, however, I learned to build up my skills and solve real-world problems in professional environments.
I am very grateful to Massimo Banzi, David A. Mellis, and others who have made Arduino possible. It has changed my life and my ability to be useful in this life.  My favorite part about it is that even though it is a tool meant to get the non-programmer or lay-person to do basic stuff like blink a light using poorly-written blocking code, it has opened up my world beyond what I ever imagined before, and it is a fully-capable microcontroller that doesn't permanently hide away the low-level stuff. The low-level AVR functions, registers, etc are ALL STILL THERE AND ACCESSIBLE once you get to a level where you need them!
Cheers,
Gabriel Staples
PS: To see many of the very helpful links which I've referenced as I've built up my Arduino and ATmega328 microcontroller skillset, please see this article here, esp. all of the links at the bottom: http://electricrcaircraftguy.blogspot.com/2014/01/the-power-of-arduino.html

An option for very low volume is to print Kikad output onto purpose-built film (using a laser printer) then iron onto blank board. Works well for single sided; tricky for double sided.

Industruino just came out a couple days ago:

https://blog.arduino.cc/2015/09/21/industruino-makes-industrial-automation-easy-now-atheart/
https://industruino.com/page/home
https://www.youtube.com/watch?t=200&v=MhE1zlwsUu0
https://industruino.com/shop/product/industruino-ind-i-o-kit-2

Also:
1. Ruggeduino has much better pin protection than a standard Arduino.
One of the above may meet your need.
(No, I am not affiliated in any way with the above links; I just saw the Industruino the other day on the Arduino website and wanted to point out a couple other options).

If you're going to dump it in the field then I'd look at this one instead, since it has the isolation built-in.


text:
Connecting light and temperature sensors and LEDs to an Arduino
Fairly new to arduino, what is the best and simplest way to connect an LM35 temperature sensor, a GL5528 photoresistor and some LEDs as well as the required resistors to an arduino for recording values? Any tutorials with wiring diagrams for something similar would be helpful.

I'm pretty sure using the text entry box on the top right will find you some.

Hi, like Ignacio hinted, your requests would be easily answered with a search. I provided an answer by doing the search for you.

I meant the site search box, but either or.

The LM35 is a very common temperature sensor. It has 3 pins - Vs, Vout, and Gnd. Connect Vs to the Arduino's Vs pin. Connect the Gnd pin to one of the Arduino's GND pins. The Vout pin should be connected to an Analog input pin. If you google your board, you should find the pinout on Arduino's website. The LM35 pin diagram and information on how to calculate the temperature from voltage is found in the LM35's Datasheet. Here is LadyAda's Temerature Sensor tutorial (note: the tutorial specifies the TMP36, however the two sensors are comparable). Here is an instructable for the LM35 (includes diagrams and source code).
The GL5528 is a photoresistor. That means its resistance changes proportional to how much light strikes its sensor surface. Because of this trait, we can build a Voltage Divider. This will allow us to read in values (again, analog values). AdaFruit's tutorial is very comprehensive and includes diagrams.
LEDs are generally considered output displays (we program to use LEDs as a visual display of state). A good starting place for Arduino LEDs is the Blink Example. we connect an LED and resistor in series with an Arduino output pin and GND or 5v. This allows us to 'write' to the Arduino pin HIGH or LOW, turning the LED on or off.
I found these results by googling 'Arduino LM35', 'Arduino GL5528', and 'Arduino LED' respectively.


text:
What's the function of this transistor on Arduino Mega?
I am trying to get information about the transistor on the Arduino Mega board below:

It says "340P" on the transistor. I want be able to know which model transition is this so that I can check its documentation. It also want to know what it is driving or its function on the Arduino board.

It's a P-channel MOSFET.  It's job is to act as a "dropless" diode.
The principle is this:

MOSFETs have a built-in diode across them in reverse bias (an effect of the chemistry)
The P-channel MOSFET is connected backwards in series with the incoming USB power.
The internal diode conducts power when there is +5V in to the USB to give power to the board.
The diode imposes a voltage drop, but there is enough voltage still to run the circuitry.
An op-amp compares the incoming voltage from the barrel jack (divided by 2) against 3.3V.  If it's less than 3.3V (6.6V incoming) or not there at all, it turns on the P-channel MOSFET
The MOSFET then short circuits the internal diode removing the voltage drop, giving the full 5V from the USB to the rest of the board.

simulate this circuit – Schematic created using CircuitLab
Note: diode shown is internal to the MOSFET.
The MOSFET is designated T2 in the schematic, and is a FDN340P on the reference design, although the actual model is not that critical, as long as the threshold voltage is above about -3V and it can happily handle 500mA or more.

"The diode imposes a voltage drop" I noticed this too and was curios on what's going on. Thanks for your clear answer

As a curiosity: if you connect 5V on the Vin, it'll be injecting current back to the USB (mainly if it's powered down). Or if you accidentally short 3v3 to 5v, threshold voltage jumps over 10V. (the first one was caused by 5V voltage regulator instead of 9V. Second one by some short on shield and 9V on Vin)


text:
How millis() resets itself to 0
Looking at the documentation for the millis() function , it says:

Returns the number of milliseconds since the Arduino board began
  running the current program. This number will overflow (go back to
  zero), after approximately 50 days.

How's this possible? Is Arduino detecting when millis() overflow then resets the value to 0? If so, how does it do it? I just want to know what exactly is going on under the hood with the variable that is being returned by the millis() function.

It is not an exclusive property of millis(). Any counter with a limited number of digits eventually returns to zero. For example, a 4 digit tally counter returns to zeros after 9999.
Under the hood, the variable for millis() is of type unsigned long, which is 32 bits on the Arduino. In this case, the 32 bits (binary 0's and 1's) are similar to the digits (0 thru 9) on the tally counter.
The maximum is 11111111 11111111 11111111 11111111. Once there, millis() returns to zero when you add 1.  The maximum (32 "ones") is 2^32 - 1, which equals 4294967295 in the decimal number system. The maximum value for the counter is, therefore, 4,294,967,295 milliseconds.   Converted to days you get approximately 49.71 days.

Old versions of Windows also maintained a milliseconds count in a 32-bit integer, causing lots of software to misbehave after 49 days uptime.


text:
Preforming impedance termination for UART Communication (TX and RX) pins
I need two Arduino devices (Arduino Mega and Nano) to communicate with each other via UART. The two Arduino devices are long distance apart from each other. The distance is 1.5 meters.

The Arduino 1 TX pin is connected to Arduino 2 RX pin.
The Arduino 1 RX pin is connected to Arduino 2 TX pin.

Now, I have to use resistor to preform impedance termination so that the long distance does not cause transmitting and receiving issues between the two devices. I did some research and found an  image that shows the signal differences when impedance termination is preformed and when it is not.

I have two questions:
1. Since the distance between both Arduino devices is 1.5 meters, what resistor value should I use? How is that calculated?
2. Where do you put the resistors? It's not really clear on where to connect the resistors. Between ground and the RX pins on each device?
I don't know the gauge ratings of my wire but if that information is needed, I am using this wire.

How it all works with line impedances is explained in this old education video: AT&T Archives: Similiarities of Wave Behavior

@KIIV Nice video. I wonder why those old education videos are more comprehensive than modern education videos in Universities.

The relevant parameter is not the length of the link, but its
characteristic impedance. For a twisted pair connection, this is
typically in the order of 100 to 120 Ω. It should be specified in
the datasheet. Your cable is not a twisted pair, but its geometry is
quite close. Just make sure that there is a ground or Vcc line between
the two data wires in order to minimize cross-talk. If you want to
compute that impedance yourself, here is an online
calculator.
Connect the resistor in series with the TX pin, i.e. between the pin and
the data wire. Note that the pin already has an internal output
resistance of about 25 Ω, so you would add no more than 100 Ω
in series.
If you search online about termination resistors, you may learn tat they
are often put between the receive pin and ground, or even at both the
sending and the receiving end. In high frequency applications, the
latter is often the preferred configuration, as it prevents the signal
to be reflected from either end of the link. However, for logic-level
signals, that configuration would attenuate the signal too much. On the
other hand, terminating only at the receiver would put excessive load on
the TX pin. Thus, sender-side termination is your best option. A
resistor in series with TX does not prevent a reflection at the RX end,
but it prevents the reflected signal to be reflected again and cause
oscillations.

Not sure what you mean as "resistor in series with the TX pin". You mean a resistor from TX pin(Arduino 1 ) to RX pin(Arduino 2). A little image with the drawing would be helpful...

A resistor in the tx to rx line between the two Arduino boards. At the tx terminal connect the resistor, the other side of the resistor connects to the wire.

@Programmer: You cannot put a resistor between TX1 and RX2, unless the resistor is 1.5 m long. You have to put it between TX1 and the wire that goes to RX2, as explained by Rudy. See amended answer.

@Rudy That's what I though. Was just making sure it's what Edgar meant.

@EdgarBonet Not what I meant. I know the resistor is not that long and meant adding it between the connection TX and RX. Your EDIT is clearer and it makes sense it adding the resistor to the sending side.


text:
Connect 5V DC Fan to Ardumoto
I wish to connect 2 simple 5V DC Brushless Fan (80x80x15mm, https://www.sparkfun.com/products/9649) to Ardumoto (https://www.sparkfun.com/products/9815).
Therefore, how to I turn on/off the fan as I do not know how to address it? Do I need to connect a power supply to the Ardumoto, to the Arduino board or 2 separate power supplies to each one of them?
Thanks.

If you look at the schematic on the product page it shows that the Vin from the arduino is connected to the same Vin on the shield and the Vin to the motor driver. So it is either or where you want to connect power.
With regards to controlling the fan, brushless fans are polarized because of the internal control circuitry, this means that it cannot be made to reverse, therefore you should always give the direction pin a high signal. The Sparkfun hookup guide has a example code which shows how to control the motor shield, and some explination.


text:
How to set OTA on ESP 32
I am currently using an evalkit Nina W106-00B board that incorporates an ESP32.
I am desperately trying to implement OTA (Over-The-Air) updates.
I started by modifying my partitions.csv file, which looks like this (without OTA) and works well:
nvs, data, nvs, 0x9000, 0x6000,
phy_init, data, phy, 0xf000, 0x1000,
factory, app, factory, 0x10000, 1M,
storage, data, spiffs, , 0xF0000,
The "factory" partition corresponds to my .bin file containing the code.
The "storage" partition corresponds to my .bin file containing the web pages and .js files.
I tried to modify it so that when I add a new .bin file containing the code, it goes into the "ota_0" partition, for example, and then boots without using the "factory" partition.
This is what it looks like now:
nvs, data, nvs, 0x9000, 0x6000,
otadata, data, ota, 0xf000, 0x2000,
phy_init, data, phy, 0x11000, 0x1000,
factory, app, factory, 0x20000, 1M,
storage, data, spiffs, 0x120000, 0xF0000,
ota_0, app, ota_0, 0x210000, 1M,
ota_1, app, ota_1, 0x310000, 1M,
I can compile and flash it, but when I start my board, an error message appears in the logs:
ELF file SHA256: 73241a5f6639ca7a
Rebooting...
ets Jul 29 2019 12:21:46
rst:0xc (SW_CPU_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0030,len:1256
load:0x40078000,len:13276
ho 0 tail 12 room 4
load:0x40080400,len:3032
entry 0x40080598
assert failed: do_core_init startup.c:339 (flash_ret == ESP_OK)
Backtrace: 0x40081ee2:0x3ffe3a90 0x4008a4bd:0x3ffe3ab0 0x40090fdd:0x3ffe3ad0 0x400d2a13:0x3ffe3bf0 0x400d2abe:0x3ffe3c10 0x4008165e:0x3ffe3c40 0x4007927e:0x3ffe3c90 |<-CORRUPTED
This message keeps looping, and the board attempts to restart without success.
How should I modify my partitions.csv file for it to work correctly?
Thanks,
Zapsalis

the esp32 arduino platform does it for you

i've never modified such a csv file to get ota working on any of the methods Arduino offers ota; www, ide, http...


text:
How to write single binary code to output pin
I am relatively new to arduino and coding in general and im just looking for a code to write a single string of binary code e.g.; "01000111101"
To a specified output pin instead of copying and pasting
"Digital write (high)
Digital write (low)
Etc."
preferably with the option to change speed between bits.
Would be very appreciative for someone to help me out

look at example LED blink code for outputting single bit of data ... look at arrays for indexed list of data ... also at for loops for generating an index value

your question is a general programming question ... it is not Arduino specific, so it does not belong here

It would be easy enough to make this Arduino specific @Arbadatduino if you specified a specific Arduino board and pin.  So edit your TITLE and QUESTION.

If timing is not critical, consider dividing the number of interest by 2. If there was a remainder set the Arduino pin to 1. If not set it to 0. Then delay for as long as needed. Keep doing this until there is nothing left to divide 2 into.
However, sending out data in serial fashion is as old as computers. Likely older. Consequently there are a lot of built in features which do this.  Specifically, it is not necessary to explicitly code up a function to convert a value to serial data. Even on an Arduino.


text:
Determine if a XIAO ESP32C3 is charging
When the XIAO ESP32C3 is charging a LiPo battery, there is a small LED on the board that lights up. Is there any way to access this information in an Arduino program?

yes, there is ... is that really all you want to know?

put an ldr or photodiode up to the LED. you can also use a clamp-style current meter to detect charge current.

No, according to the schematic it's not wired to any pin on MCU.


text:
Display images on Arduino LCD screen from PC
I am new to arduino and I am wondering if it is possible to store image data on my computer and send it to my arduino over the USB cable (which is also used for power) to display on a TFT LCD display I have hooked up. All the tutorials I see involve using an SD card to preload the image data on there beforehand.
Still, my display doesn't have an sd card slot, nor is it practical for my application as the images I want to display will be determined during runtime. I have sent small pieces of data over the COM port to my arduino from my PC but I don't know how I could do it with potentially large image data. The arduino will be plugged into my computer 24/7. If this is possible could I get a little guidance on where to start?  Thank you

receive the data and display it as it is being received

Since you don't give a clue about the TFT you have in mind, I'll try to describe the process using the following assumptions about the TFT that have to be true for the rest to work:

one full frame of pixel data for the TFT used would not fit into the Arduinos RAM, but one line of that frame will,
the pixel data can be sent line by line to the TFT without a need to start the next line inside a certain timeframe (i.e. you could, in theory, just tell the TFT to update line 42 out of order, as an example),
the TFT has its own way of remembering its display data (i.e. does not need a continuous refresh 60 times per second).

In this scenario, your image processing pipeline looks like this:

A program running on your PC decompresses (and possibly resizes) the image file in order to get access to the raw pixel data as it would be displayed on the TFT. This means that this program needs to know the resolution and "data feeding order" of your TFT.
This process then takes one line of the raw pixel data and converts it into a data package to be sent over the serial port. You will need to devise a communication protocol here that your Arduino sketch can work with. The easiest, but not most efficient, way would be to convert it into Base64, because libraries for that exist in practically every language and platform and you are then able to use text-based delimiters like a line break to mark the end of a pixel data line. (Sending binary data is more efficient, but harder and more prone to sychronization errors, because you have no in-band signalling of "end of data line".)
Your Arduino sketch reads that data package (if Base64-encoded: by using Serial.read until you encounter a line break) and converts it back to raw pixel data, in whatever format your TFT (or library for that TFT) needs the data (it might require the color format in e.g. GRB instead of RGB).
This raw pixel data line is then sent to the TFT.

You will have to determine the baud rate you can send over your serial link (determined by maximum baud rates of both PC and Arduino, and sometimes the cable quality in between). Keep in mind that a serial connection is slow; you probably will be able to watch the image rendering on the TFT line by line.
You may be able to make this more efficient by employing something like RLE (Run-Length Encoding) on the pixel data sent over the serial line, but that would be another iteration of your protocol.

Perhaps I am wrong, but TFT LCD stands for Thin Film Transistor LCD, correct?  This description applies to many types of LCDs.  The vast majority of them do not work as described in the answer.  Specifically, it will be very difficult to impossible for an Arduino Uno to display anything on a vast majority of TFT LCDs.

@st2000 OP insinuated that they already have found a tutorial to display something on their TFT, so I stated in my assumptions what that TFT or library must be able to do in order to support this solution.

Ok.  Say so in the answer (something like: I assume you have this or that smart serial port LCD) and I'll upvote it.  Recall that the point of stackexchange sites are to help other people with similar problems find clear / concise answers.

You could "stream" the data from the PC to the LCD, which means you wouldn't need to store it (or maybe store a line or so).
Without knowing which Arduino and which LCD it is hard to give more advice than that.

There are so many different LCDs that with out specifying a specific LCD only very general answers can be provided that may be of limited value.

Just about all Arduinos can handle an Alpha Numeric LCDs. But these have very limited graphics, if any.

Most can handle low resolution B&W Graphics LCDs.

Most can handle sending geometric shapes and alpha numeric to (smart) Serial Port Color LCDs. Only some Arduinos will be able to handle sending arbitrary images (like a photograph) to (smart) Serial Port Color LCDs.

And few will be able to handle sending data to a common TTL or LVDS Color LCDs.


text:
Controlling Stepper motor using RC receiver
I am using Arduino UNO with a DM556 Micro step driver to control the Stepper motor.
PUL+ --> pin 3
DIR+ --> pin 5
RC receiver --> pin 2
Using CH2 of receiver
With out the RC receiver (R9SX) everything works fine, the motor works perfectly. However I cannot figure out how to control it with RC. I tried to find a tutorial using Micro step driver but everybody appears to use Arduino Nano or some other equipment.
The code I am using makes the motor work extremely slow and only in one direction.
I'd really appreciate it if some one can point error in my code or provide me with a suitable one for my use case.
CODE:
// Define Pins
#define RCPin 2
#define DIR 5
#define STEP 3

// Set up time variables for Stepper motor
unsigned long previousMotorTime = millis();
long MotorInterval;

// Set up time variables for RC Read
volatile long Pulses = 0;
int PulseWidth = 0;

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

  // RC Read Setup
  pinMode(RCPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(RCPin), PulseTimer, CHANGE);

  // Set DIR and STEP pins to OUTPUT
  pinMode(DIR, OUTPUT);
  pinMode(STEP, OUTPUT);

  // Set initial direction (LOW = one direction, HIGH = the other direction)
  digitalWrite(DIR, LOW);
}

void loop() {
  digitalWrite(STEP, LOW);

  // Only save HIGH pulse lengths
  if (Pulses < 2000){
    PulseWidth = Pulses;
  }

  // Stepper motor speed, bigger MotorInterval is a slower speed.
  if (PulseWidth >= 1400 && PulseWidth <= 1600) {
    digitalWrite(STEP, LOW); // Motor doesn't move if the joystick is near the midpoint
  } else if (PulseWidth < 1400) {
    digitalWrite(DIR, LOW);
    MotorInterval = map(PulseWidth, 1000, 1400, 1, 25); // Map the RC signal to the motor speed in reverse when the joystick is pulled down
  } else if (PulseWidth > 1600) {
    digitalWrite(DIR, HIGH);
    MotorInterval = map(PulseWidth, 1600, 1984, 25, 1); // Map the RC signal to the motor speed when the joystick is pushed forward.
  }

  // Check if the MotorInterval time has elapsed and step the motor.
  unsigned long currentMotorTime = millis();
  if (currentMotorTime - previousMotorTime > MotorInterval) {
    digitalWrite(STEP, HIGH);
    previousMotorTime = currentMotorTime;
  }
}

// Function to measure the length of the pulses from the remote control
void PulseTimer() {
  static long StartTime = 0;
  long CurrentTime = micros();
  if (CurrentTime > StartTime) {
    Pulses = CurrentTime - StartTime;
    StartTime = CurrentTime;
  }
}

Do you have a spec sheet for your motor?

reduce your program to only the minimal code required to spin the motor in one direction at the highest speed ... does it turn fast enough?

I used some other sketch to check this and it works great.


text:
Arduino AVR Program with default ATMEGA32U4 bootloader instead
I’m working an Arduino program that uses the FastLED library and is all coded in the Arduino IDE (not my choice, just a result of this OOS library).
However, I don’t want to run this on an “Arduino” board. Instead, I want to flash this to a factory fresh ATMEGA32U4 as an MCU for the project. However, the ATMEGA32U4 doesn’t come with the Arduino boot loader, but instead, DFU. I have flashing procedures designed for the DFU boot loader already and I don’t want to go swapping bootloaders.
Would the Arduino program work fine without swapping to the Arduino bootloader? My understanding is yes since the bootloader only controls the boot sequence, and has nothing to do with runtime.

You are using an Arduino Library (in C++), and even an Arduino IDE, so whether you like it or not, you are running the code under the Arduino framework as an "Arduino" board. So what is the issue of trying to avoid the boot loader? Even you set you your programming using {DFU programmer](https://support.arduino.cc/hc/en-us/articles/4408887452434-Flash-USB-to-serial-firmware-in-DFU-mode), you are still running as an Arduino board under the Arduino framework!

Please try this: Export the compiled sketch as hex file and flash it with DFU.

Would the Arduino program work fine without swapping to the Arduino bootloader?

Yes, the bootloader is only there for conveniently changing program memory via serial instructions.
Whatever method you use to put the "main" code there, it will be the same code and will operate the same.


text:
ESP8266 + Arduino Uno: Can't send AT Commands
I'm trying to get the ESP8266 up and running without a FTDI chip, just my Arduino Uno. But it seems really difficult. What I did:

attach the ESPs VCC directly to Arduino Uno 3.3V; RX->TX; TX->RX

Result: surprisingly worked for 2 mins, however the AT commands returned ERROR sometimes. (baud rate: 9600)

attach the ESPs VCC to 3.3V 500mA power supply; RX->TX; TX->RX

Result: AT commands don't work anymore, nothing is displayed in the serial monitor, not even my input; red LED constantly on.

attach the ESPs VCC to 3.3V 500mA power supply; TX->TX; RX->RX

Result: blue LED constantly on, no response, same as before

change back RX/TX connection, experimenting with baud rate (300 - 115200)

Result: blue LED flashes on start, flashes when something is sent (no matter what the baud rate is), however still no output at all.
Suddenly, I was also getting this error while uploading:

ser_recv(): programmer is not responding

Detaching the TX connection solved the problem. Btw, I am also using a voltage divider between TX of the Arduino and RX of the ESP.
Afterwards, the blue LED was on constantly again, even though I haven't changed the wiring... (really weird)
To me it looks like the Arduino Serial monitor isn't sending anything, because I don't even see my input. However, the Arduino can output stuff, therefore I assume a connection between Arduino and PC is existing. Maybe it has to do with the connection between TX -> RX, but I see no shorts, just an ordinary voltage divider (100 Ohm and 200 Ohm resistors).
As you might see, I spent a lot of time trying to figure this out. I'm kind of stuck now, as I'm not sure what else to try. If you have any ideas, tips or advice please leave an answer.
Sorry for my English, it's not my native language. If you don't understand something, feel free to ask.
Hope you can help me!

If you don't get the answer you need or just for future reference, there is a forum dedicated to the ESP8266 that can be found here ... http://www.esp8266.com/

Tx and Rx should be crossed; meaning connect Arduino Tx to ESP Rx and vice versa.
Your second (and first) attempts are correct. Use 1uF capacitor between Vcc and Gnd. This will provide a more
robust connection since the ESP can draw too much current which might cause it to reset.
When using external power supply, hook together the Arduino Gnd to the PS Gnd.
If you get "Programmer is not responding" - disconnect and reconnect the Arduino USB. Also, you shouldn't get this at all since you are not trying to program the Arduino, just use its FTDI as proxy to the ESP. Any serial terminal application can do it (you don't have to use the built-in terminal in Arduino IDE).

When the 8266 is powered from the Arduino there is barely power enough for sending. So there will be power glitches that makes the USB port inactive.
Even a short voltage drop seems to disable the USB port until it is pulled and reconnected.
I struggled with this. One solution is external power for the WiFi chip. One other solution is to put a 1000 uF capacitor on the 3V power line and ground. That has worked for me.

I have powered the ESP module with 3.3V of Arduino itself.
I too used to get the error always until I changed my settings to "no line ending" at the bottom of the serial monitor.
I had kept it to "NL & CR" from other answers that I read here, and that was the reason for errors I suppose. Anyway changing it gave me the AT OK.
You should try that first.

Put CH_PD HIGH for AT mode COM.
Note if you upgrade firmware you need to take CH_PD LOW to write new firmware.
Also note if you upgrade your firmware for the LUA com speed will probably default to 115200 and then SoftSerial wont work.
I found it best to test on Arduino Mega as has extra serial ports.


text:
Arduino Tre, will it ever come out?
Does anyone have any information other than "coming soon" about the Tre?
Could the Tre be stuck in development hell?
Perhaps the new partnership with Adafruit could expidite things, seeing as Ardiuno (.cc) was touting the Tre to be the first Arduino made in the USA?

I'm just giddily awaiting its arrival, so I'm just wondering!

Just buy a BeagleBone Black and plug an Uno into it - you'll get pretty much the same thing without having to wait.

The latest news from Arduino that I can find is in their blog archive that the second round of beta testing is out.
The mentioned this:

When is the Arduino TRE going to be finally on the market? The board is ready, but we don’t have a final release date yet because we are still figuring out some manufacturing matters. We’ll keep you posted!

I'd imagine that the Arduino LLC vs Arduino SLR legal issue is also delaying the production.
Other than that, speculation is all that we know.
P.S: it's still spring until Sunday, June 21! :-)


text:
Nano33 BLE SPI speed and lag
(This is a question re-posted here from the Official Arduino Forum to reach as many people as possible, I hope it is not against the rules)
Hi everyone,
although I am new to the forum I have been using Arduino for a long time. I have recently started working on a project using the Nano33 BLE.
I have searched the web for an answer to my problem (including this forum) but it seems I only get contracdtictory information.
I am taliking to an ADC (MCP3911) via SPI, the comms work fine but I have some issues:

The max SPI speed on 33 BLE seems to be 8Mhz, despite the fact that I have read in many places that is should be 32 MHz (1/2 of closk speed). Please see below a screenshot from a logic analyser (I have tried to lower it and it is fine, I can get lower speeds, but not higher):

There is a lag of ~ 19-26 us between each SPI.transfer() command, I had not seen this lag on AVR (I have used mostly the Nano Every for the same applicaiton, same code and same ADC). Below a screenshot of the logic analyser showing the lag between each SPI.transfer() (I am sending 4 bytes each time, the first is the address, then 3 bytes to read the value fro the MCP3911). Also, the lag is not always the same, it varies.

Has anyone have any ideas? Is there something hidden in the way Arduino implements the SPI from mbed?
In case you ask, here is the routine to read data from the ADC (I am using the library by Ruben J. Stadler):
long MCP3911::read_raw_data(uint8_t channel)
{
    digitalWrite(CS_PIN, LOW);
    SPI.transfer(ADDR_BITS | (channel << 1) | 1);

    byte upper = SPI.transfer(0x00);
    byte middle = SPI.transfer(0x00);
    byte lower = SPI.transfer(0x00);

    digitalWrite(CS_PIN, HIGH);

    return ((((long)upper << 24) | ((long)middle << 16) | (long)lower << 8) >> 8);
}

I appreciate your help, thanks!

this site is not a forum ... it is a question and answer site

I don't know the Nano 33 BLE, but there might be some interrupts from other high level routines kicking in from time to time.
Is the code you used to compare this board with the AVR equivalent? If you use BLE for example, I wouldn't be suprised seeing this kind of delay/jitter...

Hi, the code used on AVR is identical, what changes is the SPI API used. Doing a bit more research looks like this is the normal behaviour for nRF52840 with mbed SPI implementation. It seems the delay is due to the way mbed handles the buffers in the SPI and it takes that long to complete one transaction. Solutions proposed involve DMA or writing the buffers directly (bypassing the APIs), I have seen many people commenting on this for various platforms but unfortunately I am not expert enough to apply any of those solutions to the nRF52840...


text:
My Led blinks rapidly at the reset and stop blinking instantly
So ive been trying to make a program to test if the pins are working correctly but all it does is make my led blink rapidly on reset. the point of the program is that all my pins are connected to the same led, so blink each one of them once and send the number of the blinked pin to the serial.
but the led just doesnt blink and the program gets stuck at the start of pwmoutputtest.

boolean byteinarray(byte array[], byte pbit){
  for(int i=0; i<6; i++){
    if(array[i]==pbit){
      return true;
    }
  }
  return false;
}

void outputtest(){
  for(byte i=2;i<13;i++) {
    pinMode(i, OUTPUT);
  }

  for(byte i=2;i<14;i++){
    if (byteinarray(pwm, i)==false){
      Serial.println(i);
      digitalWrite(i, HIGH);
      delay(1000);
      digitalWrite(i, LOW);
      delay(1000);
    }
  }
}

void analogoutputtest(){
  for(byte i=0;i<5;i++) {
    pinMode("A"+i, OUTPUT);
  }

  for(int i=A0;i<A5;i++){
    Serial.println(i);
    digitalWrite(i, HIGH);
    delay(1000);
    digitalWrite(i, LOW);
    delay(1000);
  }
}

void pwmoutputtest (){
  for(int i=0; i<6; i++) {
    pinMode(pwm[i], OUTPUT);
  }

  for(int i=0; i<6; i++) {
    Serial.println(pwm[i]);
    for(int j=0; i<200; i++){
      analogWrite(pwm[i], j);
      delay(5);
    }
    analogWrite(pwm[i], 0);
  }
}

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

void loop() {
  outputtest();
  pwmoutputtest();
}```

You have connected all the pins together. Then you are setting one pin HIGH (5V) at a time while all others are LOW (0V, aka ground).
So basically you are creating a short each time you set a pin HIGH. The current won't flow through the LED to ground (which would light up the LED), but the current flows through the pins, that are LOW, to ground. And since you didn't mention any current limiting resistors, you are straining the pin output hardware with this massively. If you do this too much, the pin output hardware will fail at some point, making the pin unusable for digital IO.
Instead of keeping the other pins LOW, you need to keep them at high impedance , which means configuring them as INPUT. That would be a function like this (not tested):
void outputtest(){
  for(byte i=2;i<13;i++) {
    pinMode(i, INPUT);
  }

  for(byte i=2;i<14;i++){
    if (byteinarray(pwm, i)==false){
      Serial.println(i);
      pinMode(i, OUTPUT);
      digitalWrite(i, HIGH);
      delay(1000);
      digitalWrite(i, LOW);
      pinMode(i, INPUT);
      delay(1000);
    }
  }
}

tysm i hope i didnt break anything

@Lucas If you think this answered your question, then you can accept my answer to mark your question as solved


text:
Arduino Nano uploading problems
I am having trouble uploading code to my Arduino Nano. It has been very trusty in the past, but I am getting this new error when uploading any code to it:
avrdude: ser_open(): can't set com-state for "\\.\COM15"
This happened a while ago on my Windows 11 Laptop, and I was unable to resolve it, and now it has just started on my Windows 10 desktop.
I tried disabling and re-enabling the CH340 in device manager, restarted my computer, and uninstalled the CH340. After uninstalling it, it has dissapeared and does not even show up in Device Manager at all.
If anybody could provide some help explaining how to make it show up in Device Manager again, and also make it uploadable, I would greatly appreciate it!
Thank you in advance

did you try to change the Processor option in Tools menu?

@Juraj Yes, I did. I beleive it may have something to do with recent Windows updates, but im not sure.

some other program may have possession of COM15

@jsotola I dont think so. It switches ports every now and then, and none of them work. i can upload to any other type Arduino. Doesn't matter the port.

then the Nano has failed in some way ... check for foreign objects inside the USB connector and on the surface of the board ... also try a different cable

@jsotola Likely not. I was using it just fine with the same cable and hardware. I rebooted my PC, did some updates, and now it no longer works.

next step is to plug it into another computer to see if it is recognized

I've seen something about auto updated ch340 driver causing issues and they've solved it by downgrading it.

Finally found something about that:  https://github.com/SHWotever/SimHub/wiki/Arduino---Counterfeit-Fake-CH340G-chips-driver-issues  apparently there are even ch340 fakes :D

@KIIV Thank you soooo much! I have been needing that for so long! After executing it, it operated just fine! I can upload to my Arduino Nano without any problems now. I don't think I can mark that as an answer, and I can't upvote it, but thank you!

I'll make it into an answer, I just wasn't sure if it's it

Apparently there was an update in ch340 drivers early in 2023 and it broke something for counterfeit ch340. Solution is using older version of the driver (and possibly disabling automatic updates for the drivers in the Windows).
Issue description and solution found on github:

Rollback to an older driver manually :
Unfortunately since the incompatible driver is delivered through
windows update it is harder to keep an older driver installed :
Recommended : Block windows drivers update so the newest driver won't get installed automatically:
https://www.makeuseof.com/windows-stop-automatic-driver-updates (note:
while this is required to be able to install and keep the older ch340g
driver but this will affect any of your future devices)
Reinstall an older driver here : 01/30/2019, 3.5.2019.1 CH341SER driver


text:
COM disconnects and program fails when including code trying to initialize SD card (RP2040 Pi Pico W running Arduino)
I'm having an issue where anytime I run a program such as the SD card read write example (Below) the COM port disconnects. The only changes I have made to the example code is I am using SPI1 instead of SPI0 so the pins changed.
When the COM disconnects it comes back about 20 seconds later with an error message in its properties window
"Windows has stopped this device because it has reported problems. (Code 43)
A request for the USB device descriptor failed."
Additionally I am suspicious of these lines through isolating them, if I remove all lines relating to SPI the code doesn't fail and I don't have the COM issue. (though the SD card obviously doesn't work)
  SPI.setRX(_MISO);
  SPI.setTX(_MOSI);
  SPI.setSCK(_SCK);

Thanks!
-Rian
/*
  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:
   ** MISO - pin 4
   ** MOSI - pin 7
   ** CS   - pin 5
   ** SCK  - pin 6

  created   Nov 2010
  by David A. Mellis
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

*/

// This are GP pins for SPI0 on the Raspberry Pi Pico board, and connect
// to different *board* level pinouts.  Check the PCB while wiring.
// Only certain pins can be used by the SPI hardware, so if you change
// these be sure they are legal or the program will crash.
// See: https://datasheets.raspberrypi.com/picow/PicoW-A4-Pinout.pdf
const int _MISO = 16;
const int _MOSI = 15;
const int _CS = 17;
const int _SCK = 14;

#include <SPI.h>
#include <SD.h>

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);

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

  // Ensure the SPI pinout the SD card is connected to is configured properly
  SPI.setRX(_MISO);
  SPI.setTX(_MOSI);
  SPI.setSCK(_SCK);

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

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

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

There is a Raspberry Pi part of Stack Exchange, they may be able to help you better.


text:
Arduino Leonardo Key Detector
I want to make an arduino code on the arduino leonardo that detects when keys are being pressed and to print them to the serial monitor so I can control the arduino with the computer keyboard. I need to know how to detect keyboard presses.

Do you want to plug a keyboard on the Arduino?

I want to connect the arduino to a computer with a keyboard connected to the computer.

you need another program running on the PC that will catch key presses and push them to a serial port. I think most languages can handle this natively or with common used modules. You can just type into the serial monitor to, without any other software, but i assume you want to catch special key presses from other places than the serial monitor...

Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.

If the keyboard is plugged to the computer, there is no way the Arduino
can detect the key presses. You can, however, run a program on the
computer that detects those key presses and forwards that information to
the Arduino.
That being said, if you goal is simply to “control the Arduino with the
computer keyboard”, I suggest you run a terminal emulator on the
computer. This is a program that emulates an old school computer
terminal, like the classic VT100 series. You won't get individual key
events this way: only characters. For example, if you press and hold
Shift, then press A, then release both, the
Arduino will receive a single 'A' character through the serial port,
instead of four individual key events.
On Windows, you can try Putty. On macOS and Linux, you already have
a terminal emulator: you just need a communication program such as
picocom to connect it to the serial port.
You could also use the Arduino serial monitor. This is, however, not a
proper terminal emulator. Specifically, it doesn't send the characters
you type immediately: you have to click on “Send” for that.


text:
Which wireless technology should I use for my outside "check-if-door-is-open" project?
I want to connect a magnetic door open/closed sensor to a device that can transmit (or be queried for, whichever) the state of the door to a hub inside (probably RaspberryPi). The outside unit should...

Operate on as little power as possible (outside unit will consist of board, open/closed sensor, power, and transmitter)
Be able to transmit from my back yard to inside my house (~15 meters to house & 1 or 2 walls).

I am new to this and pretty confused as to whether I should use BLE, Zig/xbee, or 2.4ghz rf (is that different? I am not even sure...).
Other considerations are cost (of course) and ease of use. I am a novice with hardware & want something easy to get up and running.

Had been looking at this when I asked the question: http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24LU1P

NRF24L01+ would be more appropriate, unless you want to go program the 8051 processor that is inside the UL1P (which is not as easy as programming and arduino). Alternatively go with some 433mHz transmitter receiver pair. This frequency is used on most wireless doorbells, and wireless power outlets.

I agree with @Gerben - the nRF24L01+ would probably be the most suitable for your application.  It should have enough range to go 15m through a few walls, and the cost is about as cheap as you can get.
You can pick up cheap Chinese clone modules (not real nRF24L01+ but another chip that operates exactly the same) for around $2 each on eBay.  I by them by the bag full.
There are a few good libraries around for controlling them with an Arduino so programming really isn't much of a problem.
They even have the advantage that they can operate in a mesh network mode if you ever expand your system to incorporate other things.
The connection to the module is a simple 5-wire SPI interface - SDC, MOSI, MISO, Chip Enable and Command Select pins, so you don't even need to mess with lots of wires.
You can read more about using them here: http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01
The best library in existence is the RF24Network library: https://github.com/maniacbug/RF24Network
If you are looking for something more self-contained and stand-alone, you might look at the ESP8266 modules which are a programmable WiFi module.  They can either interface with an Arduino to be controlled through AT commands, which is quite nasty, or they can be programmed directly using an Arduino-like API which can be obtained here: https://github.com/esp8266/Arduino
These modules are a little more expensive, but that cost is offset by not then needing an Arduino in the mix as well.  The NodeMCU is probably the easiest to work with since it contains the USB serial interface on board like an Arduino.  It also has its own Lua based programming environment if you don't mind learning another new language, but you can use it with the Arduino API for ESP8266 above.
The ESP8266 is also supported by the beta version of UECIDE

So I could use this to a) read sensor state b) transmit directly to raspberrypi (or would it need to go thru router?) and c) run for days/weeks without needing recharge? It looks like there are only 8 pins and I assume a couple are for power? Sorry, I'm still pretty confused :(

Two are power and ground. Some are special purpose and need to be placed in a specific state to get it to run (or other states to enter the bootloader, etc), and others are digital IO to do with what you want.  It can connect to a WiFi access point (router) or it can be a WiFi access point for the Pi to connect to, or the Pi can be an access point for the ESP to connect to (hostapd). Can it run for weeks without recharge? That depends on a) how you program it (sleep modes etc) and b) what your power source is.

The smaller modules like that, though cheaper, are much harder to work with.  I'd seriously recommend working with the NodeMCU as your first foray into the ESP8266 since it is so much easier to work with.  Yes, it's a little more expensive, but is a great board to develop with.  You could then migrate to a little ESP-01 to build your finished device though.

Alright. Upvoted but upon further consideration this does not answer my question. There are two (plus) alternatives listed and no clear path with regards to power... I appreciate your help but I need "Use X because Y, it has the following API to sleep/wake your unit" etc.. I need a bit more specific guidance. :)

incidentally this unit will be dormant 99% of the time and only really need to transmit when the sensor's state changes. Is wifi as fast-to-connect/low-power as BLE here?

Pretty much every RF module has sleep or low-power facilities.  It doesn't really make that much difference which you choose from that perspective.  Yes, some are easier to sleep than others, but pretty much all can be slept.  WiFi takes seconds to connect.  The nRF24lL01+ doesn't need to connect so it takes no time at all - just the time it takes to come out of low power mode. From that perspective the nRF24L01+ would be a better option, but then you need an Arduino or something similar, again pretty much all options have a low-power or sleep option.  Some are better than others ...

... because of the power options on the board (linear regulators are power hungry and can't be slept) but there are specific arduinos available designed for battery operation.

BTW, see my previous answer for more technical detail about latency and range of the NRF24L01+.