text:
can i use L298N H bridge with 12v 7AH battery?
guys i am working on a rare project so i just need to ask some questions
I have a L298N H bridge motor driver, a Aduino uno board, 12v dc 4000rpm 2ampere motor and a 12v 7ah battery
I just want to ask can i use 12v 7ah battery with my L298N H bridge motor driver
please answer this project is very important to me
please help

Probably, as long as the specifications of the motor and the H-bridge are met. Remember a fully charged 12V battery delvers about 12.7-12.8 Volts. Don’t discharge it beyond 50% (3.5Ah).

Yes, though at 2A you're at the top end of the L298N current limit. Expect excessive heating. You will have to manage your thermal environment appropriately.
You should consider a more capable driver with more current headroom and less heat problems. (Note: the L298N is a very old chip and uses old technology. It's not a good choice for modern drive systems and a more appropriate device should be investigated, for example the MC33931 as the first hit on google).


text:
Using HC-08 bluetooth module with arduino
I have an arduino mega 2560 and a recently purchased HC-08 module and the connection is as the following:
Arduino | HC-08
VCC - VCC
GND - GND
14TX3 - TXD
15TX3 - RXD
When I power up the arduino it shows that flashing light and I am able to see it on my android phone but would only reject the connection every time I tried to pair. Also I am not able to send or receive any data from it at all, here is my code:
#include <SoftwareSerial.h>

SoftwareSerial hc08(15,14) // RX pin, TX pin;

void setup(){
  //Initialize Serial Monitor
  Serial.begin(9600);
  Serial.println("ENTER AT Commands:");
  //Initialize Bluetooth Serial Port
  hc08.begin(9600);
}

void loop(){
  //Write data from HC08 to Serial Monitor
  if (hc08.available()){
    Serial.println("Reading from bluetooth");
    Serial.write(hc08.read());
  }

  //Write from Serial Monitor to HC08
  if (Serial.available()){
    Serial.println("Writing to bluetooth");
    hc08.write(Serial.read());
  }
}

I'd really appreciate help on how to get it working.

Don't use SoftwareSerial when you're using the hardware serial pins. For TX3/RX3 use Serial3. In fact, on the 2560 don't use SoftwareSerial at all - there's only certain select pins it will work on.

Could you send a link to any documentation of this so I can see how to use Serial3

I've now seen I can just use Serial1, 2 or 3 just like I would use Serial. Thanks

But there still is the problem with the pairing being rejected.

But now you should be able to see and control the HC-08 through the Arduino to configure the pairing - however that's done on that board (I've never used one).

I think this is the problem on the hardware setting. It should be:
Arduino | HC-08
VCC - VCC
GND - GND
14RX3 - TXD
15TX3 - RXD
Variable declare:
SoftwareSerial hc08(14,15) // RX pin, TX pin;

void setup(){
  //Initialize Serial Monitor
  Serial.begin(9600);
  Serial.println("ENTER AT Commands:");
  //Initialize Bluetooth Serial Port
  Serial3.begin(9600);
}

void loop(){
  //Write data from HC08 to Serial Monitor
  if (Serial3.available()){
    Serial.println("Reading from bluetooth");
    Serial.write(Serial3.read());
  }

  //Write from Serial Monitor to HC08
  if (Serial.available()){
    Serial.println("Writing to bluetooth");
    Serial3.write(Serial.read());
  }
}

ALSO: the HC-08 uses BLE, unlike the HC-05 and HC-06 and so won't exactly connect through the phone's system bluetooth settings.

source: Stack Exchange

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

sort: votes


text:
Brushless ESC Recommendations
I've got a project in which I'll be controlling 8 24V/10A brushless DC motors with an Arduino Due on a quadrupedal robot. I've been having trouble finding ESCs that would work well for this application and was wondering if anyone could provide recommendations. My ideal ESC would be one with on-board PID control given an encoder. In looking around, I've only been able to find one ESC with this capability but lacked the power output these motors want.
A secondary question would be if it's reasonable to run 8 PID loops on the Due alongside its other tasks (primarily serial data receiving/transmitting). I feel like it might be too much for the Due to handle, but I wanted to get other's opinions on this.
Sidenote: I have enough of a gear reduction between motor and output shaft that fine movements should not be an issue.

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


text:
Is it possible to detach an interrupt for a certain ammount of time
Hardware: Arduino Uno
Software Version: 1.8.13
My sketch has an interrupt service routine that triggers with the rising edge of digital pin 2.
What I want to do now is detaching the interrupt as soon as it has been triggered once and reattaching it as soon as a certain amount of time (>1s) has passed.
However despite of trying I haven't found a possibility to do this.
I have tried detaching it in the ISR itself and reattaching it in the main loop with a delay after manually clearing the interrupt flag. However with this approach the time the interrupt is detached for depends on the point of time the interrupt is triggered, which is undesirable.
Is there a better solution for this? Thank you in advance for every answer

The standard way to do this is just as you described (but with the non-blocking coding style like in the BlinkWithoutDelay example): Detach in the ISR and setting a flag and a timestamp. Then in the main code check the flag and the time since the timestamp was took. In code that looks somewhat like this (Note, that I left out some arguments of the attaching/detachting functions):
volatile byte flag = 0;
volatile unsigned long timestamp = 0;
#define REACTIVATE_INTERVAL  1000

void ISR_function(){
    detachInterrupt(...);
    flag = 1;
    timestamp = millis();
}

void setup(){
    attachInterrupt(..., ISR_function, ...);
}

void loop(){
    if(flag && millis() - timestamp > REACTIVATE_INTERVAL){
        flag = 0;
        attachInterrupt(..., ISR_function, ...);
    }
    // Rest of your main code from here on
}

For this to work correct, you must of course use a non-blocking coding style in your main code, meaning no delay()s (except for really small ones) and no blocking while loops. If you have those in your main code, you should rewrite it to be non-blocking. Not only for this feature, but for any further extension of your project. A non-blocking coding style is an important principle to embrace, especially microcontrollers.

Without a non-blocking coding style, you would need to use a timer interrupt, to reattach the pin interrupt. While that is totally possible, it does not make much sense to configure extra peripherals of the Arduino just for this.

That's exactly what I was looking for. I was irritated by the fact that the interrupt causes the timer to stop incrementing but now it makes sense. Thank you :)

You mean, that millis() will stop counting while inside the ISR? Thats correct. But it doesn't matter here, since we just get the current value and them leave the ISR very quickly


text:
Measure the time between 2 inputs
I am making a small project, and for that, I need to measure the time between 2 inputs.
basically, a program to measure the time elapsed from when digital pin 2 is high to when it again becomes high.

Have you seen the millis() function and the time measurement in the BlinkWithoutDelay example? There are lots of tutorials about millis() on the web

The way to go depends on the time range, that the event will have. The Arduino framework already includes a function for timekeeping: millis(). It returns the number of milliseconds since the startup (much like a clock) and measures the time via the hardware Timer0 and it's interrupts. This function will work good in the 2 digit millisecond range and above. With single digit millisecond or the microsecond domain, you should instead use micros() with works similar, but returns the microseconds since startup. For the low microsecond range and below you would need to work directly with a dedicated hardware timer, configuring it via its hardware registers.
Here I would show the principle of millis()/micros(), since that is most likely what you need. In the following I will only write millis(), but all the calculations can also be done with micros(). The only difference for the calculations is the factor 1000 between milli- and microseconds.
When you look at your watch and want to measure a time difference, you take note of the start time and the end time. Then you calculate the difference to get the event duration. You can do the same with millis():
unsigned long starttime = millis(); // take note of start time
// here the event to measure
unsigned long endtime = millis(); // take note of end time
unsigned long duration = endtime - starttime; // duration of the event in ms

So in your code you need to check for a rising edge of your signal. On every rising edge you calculate the time difference between the last timestamp and the current time. Then you reset the timestamp. Something like this:
int last_input_state = LOW;
unsigned long timestamp;

//setup here

void loop(){
    int current_input_state = digitalRead(2); // get current signal level
    if(current_input_state && !last_input_state){ //check, if signal is now high and was low before
        unsigned long current_time = millis(); // take note of the current time
        unsigned long duration = current_time - timestamp; // calculate the duration and do something with it
        timestamp = current_time; // update the timestamp with the current time
     }
     last_input_state = current_input_state; // update the last input state with the new measured one
}

Note:

This code is non-blocking. It needs to run fast and continuously to work correctly. You cannot do long blocking things in the rest of your code, like using high delay() calls, but you shouldn't do that either way, since that will block anything from going on.
You can go even further to lift the weight from your CPU and use an interrupt to sense the rising edge. You could use attachInterrupt(digitalPinToInterrupt(pin), service_function, RISING); and provide a void service_function(), which does the timestamp measurement and calculation (basically the same code as in the if statement of the code above).

You could do something like this:
unsigned long startTime;
unsigned long elapsedTime;

// Any needed setup stuff
void setup()
{
  ...
}

void loop()
{
  // Wait for input to go high
  while(digitalRead(2) == LOW);

  // Start timing
  startTime = millis();

  // Wait for input to go low
  while(digitalRead(2) == HIGH);

  // Now wait for it to go high again
  while(digitalRead(2) == LOW);

  // Now get the time interval
  elapsedTime = millis() - startTime;

  // Do whatever with the result.
  ...
}

Keep in mind that the millis() value will overflow every 50 days or so.  If you need to run this continuously, you need to check for an overflow and adjust things accordingly.

elapsedTime = millis() - startTime; even works well while millis passes 0 on "overflow". Nothing to adjust.

Altough working with millis(), this is a blocking example, due to the while statements. (Even worse that the Arduino pulseIn function, which has a timeout)

I did not see any requirement to do anything but measure the interval.  Therefore a blocking solution is ok.  Why complicate it if it's not needed?  As is so often the case, there are many many possible solutions.

So one should compare your solution to standard pulseIn.


text:
A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header
rst:0x10 (RTCWDT_RTC_RESET),boot:0x1f (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
I am getting this error in my esp32 devkit v1
How to solve it?
I am using arduino IDE for programming the esp32

google the error ... you really need to do research first, post a question if research fails to resolve your problem

do you have the right com port selected? or CH340 driver si missing? the error in title is from console, the message in text is from Serial Monitor?

@Juraj the error is in serial monitor of arduino IDE


text:
How to make 16 coin vibration motors and 5 servos work at the same time on a Arduino Mega?
I saw in Arduino Mega's datasheet that the sum of currents out of all input/output pins combined should be maximum 200mA. But I want to make 16 vibration motors and 5 servos work together on the same time. I made the circuit(NMOS, flyback diode, etc.) for every coin vibration motor.Also I'm thinking to power the servos with an external power source.Are the circuits enough so i dont pass the 200mA limit? How can I make the whole thing work together?
im using the following components:

NMOS
coin vibration motor
servo motor

You never power motors with an IO pin. All you ever do is send a tiny signal to the controller for the motor, whatever that is for the type of motor you are controlling.

I'm sorry for my english if i didn't put it down correctly. I'm actually using this circuit link. Do you mean that if i do that for all 16 motors i will be ok with this? Thanks for the response.

Yes, that is the standard motor circuit (except there should be some snubber circuit across the motor). Like I said - you don't power the motors with the IO pin. You just send a tiny signal. The current of the motors is irrelevant, and the current of the signal is minuscule. You'd be lucky to total 1mA.

But how is 1mA even possible?

Sorry? What do you mean, how is it "possible"?

I think its too low. Isn't it? I saw that every IO pin draw 35mA.

Do you understand the meaning of the word "limit"?

I tried with a multimeter to measure the IO current draw and it seems that i draw 35mA. Maybe I'm measuring the wrong way. Where should i put the probes to measure correctly?

Current is drawn by a device. The probes should be in series with the device drawing the current.

Thank you for your help!


text:
Two sensors on same ESP-32 board
Need some help on the project I'm currently developing.
I have 3 YF-B2 sensors that I need to connect to the same ESP-32 board and read the data from the sensors and send it via MQTT.
I had it working for 1 sensor but now I want to add the other two and keep sending the messages via MQTT but now with 3 sensors and each with its different value.
Below is the code I have where I added the flow_frequency2/3 and flowsensor2/3 but now the code does not work and I do not get the messages via MQTT.
Can anybody help me out on this?
#include <PubSubClient.h>
#include <EEPROM.h>

/****** Replace the next variables with your SSID/Password combination ********/
const char* ssid = "xxx";
const char* password = "xxx";

/****** Add your MQTT Broker IP address, example: ********/
const char* mqtt_server = "xxx.com";
const char* mqtt_user = "aaa";
const char* mqtt_pass = "aaa";
const char* input_topic = "teste/xxxx/in";
const char* output_topic = "teste/xxxx/out";

/****** FLUXO DE ÁGUA-YF-B2 ********/
volatile int flow_frequency1; // Measures flow sensor pulses
volatile int flow_frequency2; // Measures flow sensor pulses
volatile int flow_frequency3; // Measures flow sensor pulses
unsigned int l_hour; // Calculated litres/hour
unsigned char flowsensor1 = 34; // Sensor Input
unsigned char flowsensor2 = 35; // Sensor Input
unsigned char flowsensor3 = 32; // Sensor Input
unsigned long currentTime;
unsigned long cloopTime;

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void flow () { // Interrupt function
  flow_frequency1++;
  flow_frequency2++;
  flow_frequency3++;
}

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

  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  pinMode(flowsensor1, INPUT);
  pinMode(flowsensor2, INPUT);
  pinMode(flowsensor3, INPUT);
  digitalWrite(flowsensor1, HIGH); // Optional Internal Pull-Up
  digitalWrite(flowsensor2, HIGH); // Optional Internal Pull-Up
  digitalWrite(flowsensor3, HIGH); // Optional Internal Pull-Up
  attachInterrupt(34, flow, RISING);
  attachInterrupt(35, flow, RISING);
  attachInterrupt(32, flow, RISING);// Setup Interrupt
  sei(); // Enable interrupts
  currentTime = millis();
  cloopTime = currentTime;
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;

    if (digitalRead(flowsensor1) == HIGH) {
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency1 * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency1 = 0; // Reset Counter

      String water = String(l_hour);

      Serial.print("Water flow of sensor 1 is: " + water + " L/hour");
      water = water + " , waterflow1";
      client.publish(output_topic, water.c_str());
    }

    if (digitalRead(flowsensor2) == HIGH) {
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency2 * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency2 = 0; // Reset Counter

      String water = String(l_hour);

      Serial.print("Water flow of sensor 2 is: " + water + " L/hour");
      water = water + " , waterflow2";
      client.publish(output_topic, water.c_str());
    }

    if (digitalRead(flowsensor3) == HIGH) {
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency3 * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency3 = 0; // Reset Counter

      String water = String(l_hour);

      Serial.print("Water flow of sensor 3 is: " + water + " L/hour");
      water = water + " , waterflow3";
      client.publish(output_topic, water.c_str());
    }

  }
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;

  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // Feel free to add more if statements to control more GPIOs with MQTT

  // If a message is received on the topic esp32/output, you check if the message is either "on" or "off".
  // Changes the output state according to the message
  if (String(topic) == input_topic) {
    Serial.print("Changing output to ");
    if (messageTemp == "on") {
      Serial.println("on");
      //digitalWrite(ledPin, HIGH);
    }
    else if (messageTemp == "off") {
      Serial.println("off");
      //digitalWrite(ledPin, LOW);
    }
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client", mqtt_user, mqtt_pass)) {
      Serial.println("connected");
      // Subscribe
      client.subscribe(input_topic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
 ´´´

use an array for the flow sensor pins ... use flowsensor[1] instead of flowsensor1 ... then you can use a for loop to iterate through the sensor setup and sensor read


text:
RFMesh (NRF24) for STM32F1
I wanted to know the RFMesh library available for Arduino Uno can be used for STM32F1? Will it work? Or they have seperate set of library for STM32

Have you tried it?

what problem are you having?

I have not yet tried. But wanted to work on that. But I am not sure will it work with STM32 or not. But when I compiled the sketch in Arduino IDE by selecting STM32F1 from board manager it compiled without any error. So I wanted to put this in front of community.


text:
AT firmware upgrade in ESP-01 using Arduino UNO R3
I need to upgrade the AT firmware in ESP-01 by using Arduino UNO R3 serial interface. Do I need to remove the Microcontroller Chip from the DIP socket before burning firmware? Does it going to affect Arduino Bootloader?

Take a look at my answer to another similar question.

Thank you it helped a lot

Do I need to remove the Microcontroller Chip from the DIP socket before burning firmware?

No, just connect RESET to GND to stop the MCU from running.

Does it going to affect Arduino Bootloader?

No.


text:
How to burn the bootloader and upload sketches on ATmega328P U (specifically this model)?
Recently I started to learn embedded electronics and C/C++ and for a couple of days I tried and I am still trying to burn a new ATMega328P U bought from Aliexpress. From what I know new ATMega328P's come with bootloader included, but after I wired everything up and connected the FTDI FT232RL to load the sketch (wiring is completely right after many many hours of checking on the internet for a dozen of pictures), I get errors like "programmer is not responding" in case of sketch upload and "error while burning the bootloader" or "Yikes, signature bla bla". I don't think the FTDI is the problem since the Arduino IDE recognizes it as COM7 on my PC. Now here's my question: is my atmega328p u broken or have I missed something during the process of both (trying to) burn(ing) the bootloader and upload(ing) the blink sketch? (I have also tried uploading the board programmer from Nick Gammon on my arduino Uno and the burning the bootloader AND followed the instructions from arduino.cc "from arduino to microcontroller on a breadboard"). If you need pictures of some sort, I'll provide them

ATMega328 don't come with the (Arduino) bootloader preprogrammed, unless you specifically orders ones that do (where the seller has done that for you). You can't burn the bootloader with the FTDI. You can indeed use a separate Arduino board to act as an ISP programmer, so you can burn the bootloader.

I know I can't do the burn with the FTDI, that's why I tried to use my Arduino UNO to load the ArduinoISP on it and burn the bootloader on ATmega like this... But no luck whatsoever. And I can't find any tutorialnor solution that can fix my problem

Since you don't provide any specifics, we can't do any better than link to those two methods. Did you get any error message when burning the bootloader? Can you verify that the bootloader is installed (led on pin 13)? A picture would help, in case there's something mis-wired.

I don't have anything wired right now, but tomorrow I'll send some pictures here, errors, wiring and whatever can help

There is no such thing as an ATMega328P-U. There's the ATMega328P-PU or the ATMega328-PU - the former is what is used on the Uno, but it sounds like you have the latter.

https://imgur.com/gallery/rAEq9kg

I am not sure if the tutorials vary from model to model. All I want to know is if there is someone who knows a method that is guaranteed to work for my model in the picture above. Or at least show me what is the problem in what I did. I really want this to work and reach higher and higher in knowledge of circuits and programming

Fwiw I’ve come across the ATMega328P U (like the one in your photo) and I suspect it’s not an official Atmel chip (i.e. it might be counterfeit), although I’m not sure, That said, the ones I have seem to be behaving completely normally and can be programmed with a bootloader in exactly the same way.

328P is the model. Package type is the next letter (P for SPDIP) and temperature range the last letter (U = -40C to +85C). There has to be a hyphen between the model and the package type. Anything else is fake. Possibly a 328-PU clone with dodgy labeling.

So it results in the posibility of not being able to correctly burn the bootloader and work with it? (sorry if my questions are too dumb or "captain obvious" - ish, but I'm learning on my own)

Do you have some bare minimum circuit around the MCU? Mainly Xtal (usually 16MHz but the bootloader can be also for 8MHz or the internal 8MHz). Also you have to have "auto reset" circuit too (DTR -> capacitor -> reset pin and pull-up) - otherwise you have to reset the MCU into bootloader mode in short period time before the arduino starts the actual upload...

https://imgur.com/gallery/ZX9el3x, this is the picture with the minimal circuit I think you are talking about. 2 22pF capacitors, 16MHz oscillator, wires for gnd and 5v where necessary and the first 3 pins for FTDI usage. I did saw a schematic with a switch button added for reset functionality, but I didn't give it much attention. Could that be the solution for everything?

@VladGeorge If you have FTDI with accessible DTR, it should be possible to add capacitor between DTR and RESET pin to enable auto reset - info in section auto reset. Otherwise reset button and good luck with pressing reset in the right time. Btw, you should also look into section Decoupling capacitors.

I did try to do that, that's why on the 1st pin I put a 100nF capacitor. And when I try to burn the bootloader I get an error regarding the signature... And the circuit is working because at first I programmed the ATmega that was on the Arduino UNO and managed to get blink and fade sketches working on it. But when switched to the individual ICs... Neither the burn or the sketches worked. I'll try to do it manually, with a button on the first pin, and keep you updated

IT WORKED, FINALLY. I followed this tutorial: https://www.electronics-lab.com/project/installing-the-arduino-bootloader-on-the-atmega328p-microcontroller/, followed exactly as it is explained, made the connections (nothing more, nothing less; I even removed the LED on pin 19 and its resistor) and to my surprise... the bootloader was actually loaded and the sketches were uploading just by using the FTDI. Thank you a lot for your help and information and I hope someday I'll pass this knowledge to someone who will be in the spot I was until now. Have a great time and love ya all


text:
Hand position sensor
What is the simplest way to get an alarm sound when a human raise hands up.
Assuming he is wearing a sensor or whatever as a watch or ring.

tilt sensor .......

A tilt sensor, can be used as what you are trying to say, whenever someone (who wore it) raise his hand or move it, will trigger an alarm.
If you want to carry your alarm with you then...
You can use arduino nano or micro with a sensor and buzzer connected to it to just place it in gloves or watches etc.


text:
GSM900A module is not connecting to the network
My GSM900A module is not connecting to the network. IT continuously blinks(1 sec). The power was given by the Arduino Uno board. Then I tried connecting an external battery(4.2V , 4200mAH). But it didn't work. What kind of a solution would be suitable for this issue?

maybe there is no network to connect to

Maybe you don't live in an area with the right frequency bands for the SIM900A to operate. Does your country even have a GSM network any more? Many don't now. It's old technology. You should be using an LTE modem nowadays.

gsm network is still available in our country.


text:
Using LM70 temperature sensor with Arduino
I am trying to sense the temperature using the LM70 temperature sensor with an Arduino Mega. As you can see in the Datasheet, it uses the SPI protocol. I have made the following connections (VSSOP-8 Package):

SI/O pin --> Pin 50 Arduino Mega.
SC pin --> Pin 52 Arduino Mega.
CS pin --> Pin 53 Arduino Mega.
V+ pin --> 3.3V Arduino Mega.
GND pin --> GND Arduino Mega.

My code does not work (it does not print the right temperature), and I think it can be for two reasons:

I am not reading correctly the information from the sensor. It sends 16 bits, from which the 11 first bits store the data for the temperature.
I am not calculating the temperature in the right way.

This is my code:
// the sensor communicates using SPI, so include the library:
#include <SPI.h>

void setup() {
  pinMode(51,OUTPUT); //MOSI
  pinMode(50,INPUT); //MISO
  pinMode(52,OUTPUT); //CLOCK PIN
  digitalWrite(53,HIGH); //slave select stays high. When we set this to low, the sensor will start to send data.
  SPI.begin();
  Serial.begin(9600);

  //time to set up
  delay(500);
}

void loop() {
    //enable Slave
    digitalWrite(A0,LOW); //Enable communication with slave
    delay(500); //wait for conversion

    int val = SPI.transfer(0x00); // read from sensor
    Serial.println(val); //display reading on serial monitor
    int temperature = val * 0.25;
    Serial.println(temperature); //display temperature on serial monitor

    //disable Slave
    digitalWrite(53,HIGH); //set to High again
}

Please, if you see something wrong in my code, let me know.
Thank you in advance.

digitalWrite(A0,LOW) -- Are you sure about that one?

You are right, it should be digitalWrite(53, LOW). Thank you!!!
However, the code still does not work. Any ideas?

There are several things that are not doing correctly. This is not a complete answer but to provide you some directions on how to get it right.

A0 is pin 54, it is not SS which is pin 53;

On how to use the SPI library properly, I would suggest that you read my blog on SPI, it will also help you to get the data out of data sheet that you need for SPI programming. Based on the timing diagram on the data sheet, you will need to configure the SPI as SPI_MODE2;

LM70 SI/O pin is used as both MOSI and MISO, you will need to connect MOSI to SI/O via a 10k resistor, and connect SI/O direct to MISO, this information is available in the data sheet;

LM70's temperature data is in Two's complement format, To convert it, it needs a little bit work. It is then need to shift down/right using bitshift operator by 5 bits to get ride of the first 5-bits, before finally multiply by 0.25C as per data sheet.

int value = 0x4b1f;  //value from SPI, temp = 125 degree C
int mask = 0x8000;   // mask for MSB
int temp = (-(value & mask) + (value & ~mask)) >> 5;
Serial.print("Temp");
Serial.println(temp*.25);

Read all links that I provided to understand the subjects and give it a try. Good luck!

Your problem lies here:
    int val = SPI.transfer(0x00); // read from sensor
    Serial.println(val); //display reading on serial monitor
    int temperature = val * 0.25;

And it's a twofold problem.
First:
int val = SPI.transfer(0x00);

That only reads the first 8 bits of the data. To get all 16 bits you have to do two transfers and then combine them together with bitshifting:
int bh = SPI.transfer(0x00);
int bl = SPI.transfer(0x00);
int val = (bh << 8) | bl;

That then gives you a value that is right-aligned. you then need to shift it to the left the right number of bits and "sign extend" it to keep it negative if needed.  If you're not interested in the fractional part then it's as simple as:
val >>= 7;
if (val & 0x0100) {
    val |= 0xFE00;
}

Now... what does that all mean?  Well, assume it's currently 25°C. From the datasheet we can see that would give us a reading of 0000 1100 1001 1111 (note there is a typo in the datasheet saying that is 0b9f in hex when in fact it's 0c9f).
Let's do those operations - first the bit shift:
Dec   Hex   Bin
3231  0C9F  0000110010011111 >> 7
25    0019  0000000000011001

Then we look to see if bit 8 is set or not (bit 8 was the most significant bit). If it is then we OR it with bits 9-15 also set. This "sign extends" it.
Let's take a look at -25°C from the datasheet:
Dec   Hex  Bin
-3169 f39f 1111001110011111 >> 7      Shift right 7 bits
487   01e7 0000000111100111 & 0x0100  And with 8th bit
256   0100 0000000100000000           Result is not 0 so is true

"Or" the shifted value with 0xFE00:

487   01e7 0000000111100111 or
65024 fe00 1111111000000000 =
-25   ffe7 1111111111100111


text:
Using Arduino based OpenCR with USB Host Shield 2.0 to connect to PS4 controller
I am trying to use a PS4 controller with my dynamixel setup using the OpenCR 1.0 board. The USB Host Shield 2.0 library is used to talk to the controller, but the current library does not support Open CR 1.0, but it does support other ARM boards. Is it easy to modify the library to talk to Open CR? My guess is that it is just the SPI pins (and other pins) that need to be redefined, but any guidance regarding the same would be great.
https://github.com/felis/USB_Host_Shield_2.0
https://github.com/ROBOTIS-GIT/OpenCR

which library are you talking about ... questions like Is it easy ... are pointless ... it is easy for someone that can write a library, and not so easy for someone that can't even blink an LED

USB_Host_Shield_2.0.zip in https://github.com/ROBOTIS-GIT/OpenCR/tree/master/arduino/opencr_arduino/libraries


text:
how to switch more 230v with arduino?
i am working on a project automatic street lighting with arduino.i am done with the code and the circuit.i am able to switch the AC voltage in my house which is 230v,50hz with a 230v relay but when its comes to implementation there are 30 to 40 street lights are connected and the voltage is very high I think around 415 volts.what should I use to control that? need help

I'm quite surprised that you need to build a project with so high current/voltage/purpose around a coarse Arduino, are you sure of that ? Regarding the loads to switch, a relay is the simplest solution, but according the load type it could possibly have a huge current peak at turn on which will damage very quickly the relay if it's not intended to handle it, think carefully about it !

What is the current per light? Say it's 5 amps per light. For 40 lights you'd need a >415V (430V would be better) relay rated for >200A. (It would be a good idea to get a relay that can handle a little more than your peak power. So if your load is 200A, get a relay that can handle 20% more, or 240A.) That would be a heavy duty industrial relay, and not something you're going to find from a consumer electronics outlet.

You have to use a relay that can handle minimum 415 volts (and keep some reserve).
Also take the current/amperage into account (possibly use multiple relays).

I thaught that but I was unable to get 415v relay!

See e.g. https://nl.mouser.com/Electromechanical/Relays/General-Purpose-Relays/_/N-5g36 ... the list goes to 480 VAC. Tip: I wouldn't buy such high voltage items from ebay or aliexpress.

Thanks.actually I am computer science student I don't know which one to buy exactly so could help me with that! please

Also make sure the relay can handle the current used by 40 lights.

@prajwalmegalamani I also studied software engineering / computer science ... There are mostly two important properties: voltage (make sure it's at least 415V, preferably more, like 480 VAC. And either use multiple relays, one per light, or one per several light or sum up the current used by all of them and see if there is a relay that can have that amperage. E.g. 40 lights * 1 A / light = 40 A. Use a relay that is e.g. minum 45 of 50 A to be sure.

To add some backround to help you choose: The voltage spec of a relay's contacts (not its coil!) is the maximum voltage that it can open (i.e., interrupt) without arcing across the contacts and damaging them. The current spec - again, of the contacts - is the maximum current the contacts can carry while closed, without overheating. (When they're open, of course, they won't be carrying any current).

I took a training course just to be certified to flip an ~ 415 V breaker and strongly recommend that you do not work with those voltages at the current draw of street lights without proper EE training and certification or at least working with someone who knows what they are doing. We are talking dangerous stuff, here.


text:
Good way to get automatically generated code into a sketch
Situation:
Mac OS, Arduino IDE 1.5.6r2
I've got a sketch with several files, all classic .cpp and .h source and header files except the main sketch file. As the project goes more complex I started to generate code automatically by another program. Now I have hard times integrating the generated code it into my sketch. The arduino IDE seems to load the code on opening the sketch. After that, the source files aren't beeing checked for external changes by the IDE (as I would expect it from a real editor like vim). On top of that, when I verify my code the IDE seems to save the files from RAM into a temporary build directory ignoring the contents of the sketch directory further. So if I let my code generator change a source file while the sketch is opened in the IDE, the changes won't reach the build. I had to close the IDE and reopen it. The next thing I tried is to include my autogenerated file from an existing and opened code file inside the IDE. But the IDE ignores files, which aren't opened completely. Hence, the file is missing in the build directory.
Is there a trick to let the IDE take the code unknown to itself along into the build directory? Or how else can I deal with this situation? I don't want to close and open the IDE a hundred times a day.

Select "Use external editor" in the preferences. Not ideal, but it might work for you.

This works. When verifying the sketch, the IDE now checks the content of the directory for new and changed files. The drawback is, I have to switch over to an editor. Probably I'm going to use vim.

According to the release notes starting with V1.5.2 of the IDE you can verify and upload from the command line.
You could use your favorite editor and then use the command line to do the arduino build/upload instead of the IDE.
See: https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc
I have not used it so I can't say if it work well or not.

Ok, I tried and used it. The outcome seems to be ok. I still have to think about using that method on a regular base. It is not the most comfortable way to get things done, but nothing really uncanny. Perhaps I can even do some integrative scripting around it. Thanks a lot.

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


text:
How can I pair a Bluetooth dongle on arduino Yun (openwrt-yun)?
On my Arduino Yun (openwrt-yun, updated to latest version), I have a bluetooth dongle in the usb port; I have installed bluez-libs and bluez-utils (and python-bluez).  They show up as version 5.13.  hciconfig and hcitool work properly.  There does not seem to be any utility installed to pair with a device, nor can I figure out how to get pairing to work by editing config files.
I can find the device with hciconfig and hcitool, but rfcomm can't connect without the pin.  If I try the same sequence on my Linux laptop after pairing with the gui, rfcomm is able to connect, so I know the device is working properly (JY-MCU HC-06 on another Arduino).
All the recommendations I can find on the web indicate I should be able to use simple-agent or bluez-simple-agent, but they are not installed with these packages (there is no bluez-tools package for this distro).  If I manually copy the python script for the agent to the device and run it, it fails, saying that org.bluez can't be found with dbus.  There is no bluetoothd running, and no init script for any bluetooth demon.  None of the bt* tools are available.
I also found a description of how to set a pin code in /var/lib/bluetooth/[bt-addr]/pincodes (where bt-addr is my dongle address) containing a line of the form:
[device-addr]  [pincode]
but this seems to have no effect.
I have also tried settings in /etc/bluetooth/main.conf and /etc/bluetooth/rfcomm.conf, but I think they may only be for incoming connections.
Any help would be greatly appreciated.

It takes me some time to make it work :
1) update drivers
opkg update

opkg install kmod-bluetooth bluez-libs bluez-utils

2) add configuration files in directory /etc/bluetooth
root@Arduino:~# cat /etc/bluetooth/hcid.conf

options {
  autoinit yes;
  security auto;
  pairing multi;
  passkey "0000";
   }
device {
  name "OpenWrt";
  class 0x000100;
  lm accept,master;
  lp rswitch,hold,sniff,park;
  }

root@Arduino:~# cat /etc/bluetooth/rfcomm.conf

rfcomm0{
 bind yes;
 device 00:1B:C1:02:B0:F5;
 channel 1;
 comment "Holux M-1000";
 }

3) Reboot the card
4) test if all is OK
hciconfig

5) put the interface up
hciconfig hci0 up

6) Search for devices
hcitool scan

7) Look for Serial Port capability on the devices
sdptool search SP

8) bind the serial dev
rfcomm -i hci0 connect /dev/rfcomm0 00:1B:C1:02:B0:F5

9) see the information comming from the device (bluetooth GPS in my case)
cat /dev/rfcomm0

Bluetooth support on OpenWRT is broken, simply does not work.

Welcome to Arduino SE! Can you please add more information to your post to explain why it doesn't work on the Yun? Is there an alternative? Thanks!

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


text:
Custom Library Pin Change
I'm using an Arduino Uno with Funduino I2C 1602 LCD display. The LCD display is connected as
LCD
SCL--> A5
SDA -->A4
I need to measure the temperature, pressure and the velocity of a duct flow. So I connected a BMP180 to my arduino with the following connection
SCL--> A5
SDA -->A4
As you can see, both of them are connected to same pins. The connection works fine just for BMP180 but when I add a rotary encoder and print its value on LCD, I'm getting delayed and wrong data.
I'm using this BMP180 library
https://github.com/adafruit/Adafruit_BMP085_Unified
The LCD uses this library (v1.2.0)
https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads
how can I change bmp180 or LCD analog pins in these libraries?

You can have multiple devices connected to the same I2C pin (A4,A5). So both devices worked till you connected the rotary encoder? What pins are the encoder connected to?

actually, I think I'm having a coding problem. Encoder is connected to digital pins so there is no problem with it.


text:
Connecting two pressure sensors with one uno
I'm trying to connect two BMP180s to an arduino uno by using a multiplexer.
Here is the code that a guy has written before:
I imported SFE_BMP180 library but didn't do anything with the "typedef.h" thing.
I'm getting "Data does not name a type" error at the line 9.
How can  I solve this problem?
     #include <SFE_BMP180.h>
    #include <Wire.h>
    #include "typedef.h"

    #define SELECT_PIN 9
    #define ALTITUDE 510.0

#define P1_ACTIVE digitalWrite(SELECT_PIN,HIGH); //delay(10);
#define P2_ACTIVE digitalWrite(SELECT_PIN,LOW);  //delay(10);

SFE_BMP180 bmp1,bmp2;
boolean readSensors(Data *data1, Data *data2);

Data newData(char id)
{
  Data d ;
  d._id = id ;
  return d ;
}
void setup()
{
    boolean failed = false ;
    pinMode(SELECT_PIN, OUTPUT);

    Serial.begin(9600);

    P1_ACTIVE

    if(bmp1.begin()){
        Serial.println("BMP #1 init success.");
    }
    else
          failed = true ;

    P2_ACTIVE
    if(bmp2.begin()){
          Serial.println("BMP #2 init success.");
    }
    else
        failed = true ;

    if(failed){
        Serial.println("Error in BMP180 init.");
        while (1);
    }
}

void loop()
{
  Data d1 = newData('1');
  Data d2 = newData('2');

  boolean read = readSensors(&d1,&d2);

  if(read){
          /* print the value to serial terminal */
...

You can try my BMP080/BMP180 Arduino library
My library doesn't require use of floats of math library, making your sketch very small and fast.


text:
M5Stack - confused about I2C bus voltage
I've recently got one of these nice M5-Though devices (basically a water-proof M5-Core2). They have these 4-wire sockets to connect their sensors. The I2C socket has 4 pins for +5V, GND, SDA and SCL. According to the schematics (bottom of page), the SDA and SCL lines are directly connected to the GPIO pins of the ESP32. That means that most sensors connected to this socket will run the I2C bus at 5V. Even their own sensors (example) have pull-ups to 5V on the SDA and SCL lines.
Isn't this going to fry the ESP32? Different sources say that it's inputs are not 5V tolerant. So far, I always used the 3.3V line to power external sensors from the ESP32 (or added a level shifter).

you example link shows they have a shifters in front of the i2c gpios, and it explains: "use the 3.3V on SDA and SCL, M5Core GROVE provide 3.3V to data pins, 5V to power pin. only 3.3v allowed on VL53L0x". That said, weak pullups aren't as bad as a low-impedance hi/lo 5v signal, but it's easier to "ban" 5v than dig into specific devices and situations.

@dandavis That sentence also occurred to me, but it doesn't make sense in the context. It appears they have copied something from the documentation of the actual sensor which does no longer apply to the whole module. There is no 3.3V pin on the 4-wire line the sensor is connected with. They do use a shifter for the module, but the other way round (the ESP32 is on the left side there).

it clearly shows the module uses 3.3v pullups(R1+2), and a 3.3v LDO (U2) on the module. This allows greater flexibility for the modules as it's easer to convert 5v to 3.3v than boost a 3.3v feed into a 5v one.

i agree the schematics are a bit confusing, but do you really think they would design, make, and sell a modular system where their modules broke their MCU?

@dandavis I would surely hope they won't. But to me it still seems they're operating the MCU outside its specs. And while their products make a mature impression, their documentation does clearly not. It's not the first time I see a modular system that, when giving it a closer look, doesn't fit together.

No, it's not going to "fry" the ESP32, and here's why:
Yes, there are pullups to 5V. Those are 4.7K in your example. The IO pins are connected to 3.3V through ESD diodes. That means that any voltage over and above 3.3V plus the forward voltage of those diodes will be "diverted" away from the IO pin through the diode. IO pins have these ESD diodes built in, but this board has extra external ones added to make it more rugged.
These ESD diodes can handle a finite amount of current flowing through them - the internal ones only a small amount, but the external ones much more.
The 5V will only be a low current because it is connected with a resistor. We can even do some maths here.
Assuming the ESD diodes have a 0.3V forward voltage (as is reasonably typical) we can say that the voltage across the diode will be 5V - 3.3V - 0.3V = 1.4V.
With a 4.7K resistor as a pullup the current through the diode will be 1.4V / 4700 = 298 microamps.
That's way below the limit you'd expect of a small internal ESD diode, let alone a larger external one.
The "frying" of an IO pin happens when too much current flows through the ESD diode and it blows, "failing short", causing the IO pin to be locked in either a HIGH or LOW state for the rest of eternity. Since the current is nowhere near the kind of levels needed for that it's not going to even remotely stress the diodes, and the inclusion of external diodes makes it even safer.

Thanks, that sounds reasonable. But note that the external diodes in the example are to protect the sensor, not the ESP32. I'm worried about the input side of the ESP. I'll be going to attach another type of sensor, one that can operate directly at 5V and has no internal power converter.

@PMF The ESD diodes are not on the peripheral, they are on the main unit. Section "ESD" in the top right of the main schematic. Specifically D6.

Thanks, I didn't understand that part.


text:
How do I get the size of my program at runtime?
(This question is specific for the Arduino Due, but maybe there's a general answer to the question)
I'm using DueFlashStorage to store application data in the flash memory of my Arduino Due. That works quite nicely. The Due has two flash blocks with 256k each. By default, the library writes data to the second flash block. The first flash block is used for the program. My program currently uses around 160k of flash (as the compiler tells me). That leaves about 96k of flash unused, which I could really use to store more application data. I managed to adjust DueFlashStorage to allow writing to the full memory range, but how do I detect where it is safe to write to? (Obviously, I must not overwrite any part of the program)
I have tried something like:
  // this returns the logical address of the first byte in flash (0x80000)
  byte* startAddr = dueFlashStorage.readAddress(0);
  Serial.println((unsigned int)startAddr, HEX);
  int bytes = 0;
  while (bytes < 512 * 1024) // That's the size of the flash
  {
    int* data = (int*)(startAddr + bytes);
    if (*data == 0xFFFFFFFF) // empty flash is initialized with FF's
     {
       Serial.print("Free block at 0x");
       Serial.println((unsigned int)data, HEX);
     }
     else
     {
       Serial.print("Used block at 0x");
       Serial.println((unsigned int)data, HEX);
     }
    bytes+=512;
  }

This seems to work, as the first block detected as "free" is just above the size of the program. However, this approach has some major drawbacks:

It's slow. Running over the whole address space to find the end of the program uses time (and maybe I shouldn't just test the first word of each block)
It's not reproducible. After I have written data to the detected first free block, it's no longer free, so I need another approach (like some magic number) to detect the first data block after the CPU is reset.

Is there a better way for this (like, in the ideal world, a constant I could use)? I don't want to hardcode the data start, because as the program grows (and it's still in development) I would forget to adjust that constant and booooommmm....

exact location far up in flash? you want to have the data on the same location even if the sketch size changes or not?

I'm using some (simple) memory management for allocating flash space for the data. I'm filling it up from bottom to top, much like if it was a file. So the addresses I'm using are relative to the start, but the start can move.

Just to warn you, I minimally tested this, but it seems to work.
In the Due's linker script there are these relevant lines, containing the named rom section.
MEMORY
{
    rom (rx)    : ORIGIN = 0x00080000, LENGTH = 0x00080000 /* Flash, 512K */

Below you'll see:
SECTIONS
{
    .text :
    {
        . = ALIGN(4);
        _sfixed = .;

_sfixed is a symbol they've created to mark the current location, which happens to be the start of the rom section in this case, 0x00080000.  At the bettom of the brace matching the one following .text, you'll see:
} > rom

showing that section goes into ROM, which is why . at the beginning of the .text section refers to the rom section start address.
If you look near the last thing placed in rom, you'll see:
    . = ALIGN(4);
    _etext = .;

So, they've set another symbol there, the one of interest, _etext, the address of which should be the byte of ROM not used, or so I thought the first time through this; turns out it isn't.  I gather you have no use for start of ROM symbol, since it's a static value and at the beginning, so I'll ignore that, but if you cared to make use of it it could be done the same way as follows for _etext.
These symbols don't have any type, but you can make them whatever you want.  If you want to perform arithmetic on a pointer that results, it makes sense to use a char type, so:
extern "C" unsigned char _etext;

I thought this was the end of the story, could just take the address of this symbol, but there is more to it.  Following the regular code is this section:
    .relocate : AT (_etext)
    {
        . = ALIGN(4);
        _srelocate = .;
        *(.ramfunc .ramfunc.*);
        *(.data .data.*);
        . = ALIGN(4);
        _erelocate = .;
    } > ram

They're placing code for the banzai (reset) function (and perhaps other things), which goes into ram ultimately, at this location in ROM.  So, presumably in the start code this is copied from the end of the normal program code into some place in ram.
So, there are two more symbols of interest here, _srelocate and _erelocate.  Declarations for them:
extern "C" unsigned char _srelocate;
extern "C" unsigned char _erelocate;

These symbols resolve to addresses in RAM, so they can't be used directly, but can have their addresses subtracted to get the size of the image in ROM that gets relocated to RAM, leading to:
const unsigned char *rom_end = &_etext + (&_erelocate - &_srelocate);
Serial.print("The end of used ROM is : 0x");
Serial.println((uintptr_t)rom_end, HEX);

When I compile and run a simple test like this and check the serial monitor connection, I see output like:
The end of used ROM is : 0x82FF8

If look at the .bin file produced by the compiler:
$ wc --bytes  build/arduino.sam.arduino_due_x_dbg/efixed.ino.bin
12280 build/arduino.sam.arduino_due_x_dbg/efixed.ino.bin

And 0x82FF8 - 0x80000 == 12280.
When I hex dump flash around this address I can see what looks like it padding out the flash sector with 0x00 bytes before the next unprogrammed flash sector shows as 0xFF.  So you would need to round this up yourself, and if you want be somewhat safer, maybe add some margin.
I don't know how common that configuration in the linker script is.  It's likely that most linker scripts place a symbol there, if they've had some forethought.  But I wouldn't necessarily expect it have the same name.  It's possible they modify it to add more stuff after that symbol.  But for now, for the Due, that would seem to work fine.  It is a bit messy though.

Wow, thanks for the concise analysis. Exactly what I was looking for. Seems to work nicely.

This is specific to the Arduino Due anyway (and it doesn't look like it's toolchain is going to be updated any time soon), so that's fine. If I port this code to another CPU (i.e. ESP32), I need to replace the whole flash part anyway.

Good deal. I had hoped to make the methodology fairly clear to allow future readers to react to changes in the linker script, or to apply the same thinking for a different Arduino, rather than offering a "just do this" type of answer.  Then again, it may also get ignored until heat death, but I thought it was an interesting question to look at. =)

Yea, I was just referring to the fact that https://github.com/arduino/ArduinoCore-sam is quite dead. Nobody seems to care about PRs or issues.


text:
Which reflectance sensor array for a line following robot?
I'm working on a line-following robot with my son. We've found a sensor array on Robot Shop that will help us but .. there's two and I'm not sure which will be the best for us.
The difference between them, as described in this PDF is "The QTR-8A uses a voltage divider for each sensor’s output while the QTR-8RC uses an RC circuit."
What I want to do is detect which sensor the followed line is triggering. All I need is a yes/no. But I'm too new to this to decide which of these two sensors would be best for me.

The main difference between the two models, as stated in the PDF you provided, is the output they provide to the MCU.
The QTR-8A will provide an Analog output, requiring a corresponding analog pin on the microcontroller. The QTR-8RC will provide a Digital output, but will allow the same accuracy of the QTA-8A by measuring the discharge time of the capacitor (HIGH to LOW time), with the advantage of higher accuracy due to the use of RC circuit instead of a voltage divider.
Both seems pretty straight forward, but for your needs, the QTR-8RC might seem more compatible, considering the Arduino Uno has 6 analog I/O pins (you didn't mention which Arduino is going to be used, the Arduino Nano has 8 and the Arduino Mega has 16), and that the QTR sensor provides 8 outputs. The way you could accomplish that with QTR-8RC and 8 digital I/O pins is described in the PDF:

Turn on IR LEDs (optional)
Set the I/O line to an output and drive it high
Allow at least 10 us for the 10 nF capacitor to charge
Make the I/O line an input (high impedance)
Measure the time for the capacitor to discharge by waiting for the I/O line to go low
Turn off IR LEDs (optional)

Great, easy to understand answer. Thanks @Omer!


text:
Connecting to Nano via USB3
I have a Uno (third party) that I connect to my Dell laptop with no problems at all. But I've just received a Nano (also third party) that I just can't get to upload. After lots of interneting, I hit Windows normally-useless troubleshooting tool. That tells me that the USB device (the Nano) doesn't understand USB3 and I should plug it into a USB2 port. Unfortunately, being a new machine there IS no USB2 port.
Is Windows Troubleshooting lying? Is there a problem interfacing with a Nano via USB3?
Edit: Error message is:
stk500_recv(): programmer is not responding

A third party board may well have a different USB-serial chip than the FTDI part used on a nano from Arduino.cc and so may well require a different USB driver.  Your posted error message could quite easily be a result of pointing your software at a serial device other than your arduino clone.

It happened to me: https://kongduino.wordpress.com/2015/08/17/where-are-you-clone/ Turns out that the chip was not the regular FTDI. You might have to look at the USB chip and install drivers for it.

What USB "controller" is on your Arduino

I have run in to similar symptoms while using USB based Arduino clones connected to USB3 ports. Connecting them to a USB2 port on the same PC worked (where this was an option).
For computers that only have USB3 ports, I found that connecting the device via a cheap USB 2.0 hub (not USB3 hub) solved the issue.
I'm not sure why these devices behave like this, but there seems to be something about USB3 ports that these boards don't like.

Windows troubleshooter is just trying to tell you that you've plugged a USB2 device into a USB3 port, thus wasting its USB3 capabilities which could be useful for another device. Of course, if you only have USB3, you can't do otherwise.
USB3 is fully backward-compatible with USB2, so whatever your problem is, it is not related to the fact that you plug the Nano into a USB3 port. Perhaps your problem comes from the fact that your Nano is "third party" - I suppose that means it's not the original device and thus it may not be fully compatible. If my guess is right, try to find out what programmer your Nano clone supports: chances are you just need to select a different programmer type in Arduino settings, or buy a separate programmer supported by your device.

While USB3 is supposed to be backwards compatible, that isn't always true in practice.  Sometimes using a USB 2 hub in between the computer and a legacy device can make things work where a direct connection would not.

1- Check your COM ports, make sure it is correct
2- Arduino Nano will somethime require a driver, download it
3- Reboot your system and see what happens


text:
How can I connect an 8-relay board without using 8 digital pins?
I'm looking to connect an 8-relay board to an Arduino Uno. A board like this one. However, I don't really want to use up 8 digital outputs if I don't have to. Is there some intermediate circuitry I can either buy or build that would do this?
For example, can I connect something to the serial so that sending '3' would result in binary 00000011 and thus turn on relay's 1 and 2?
Alternately, and probably more lazy, is there an extension board that would just give me a pile more digital pins?

Sure, use a Mega instead of the Uno, more memory and 3 times as many pins

You could use shift registers and/or I/O expanders.

You are using a UNO, you have the pins available, you could just use them. With the UNO and the relay board you have everything you already need, otherwise you're going to have to implement something else. A serial "3" is going to require more programming than just flipping the output register, much less overhead. Shift registers work well, but then you'd have to implement that at your relay board end. It's all unnecessary work, unless you have a valid reason to want to do it another way. Eight data wires and a ground IS the lazy way out.

A likely solution is to use the Arduino SPI interface and the Arduino SPI library to control a SPI relay board.  Here is a 6 year old thread talking about such a board. And another more recent relay thread where SPI is brought up.

There are ICs that provide additional I/O ports through either the SPI or I2C busses, such as  MCP23017 or MCP23018 or their 8 port equivalents.
There are many different makes, search Google for "Arduino addition IO Pins"

You can use a MUX/DEMUX. Check out the link. Basically, you can select the output pin by a series of commands that you can do with the Arduino. The relay inputs will be hooked up to the IC's outputs
https://www.sparkfun.com/datasheets/IC/cd74hc4067.pdf

Why should mux/demux help here? With a demux you can "attach" one pin to several outputs, and control which output is selected with the address. If the OP used one of these, he would have to attach +5V on the common input, one relay over each channel except one, and then he could only turn one ONE relay at a time...


text:
ESP32 Partition size and maximum program size
From an ESP32 example code, I extracted the following part, that just prints the flash partition list to the console.
#include <string.h>
#include <assert.h>
#include "esp_partition.h"
#include "esp_log.h"

static const char *TAG = "example";

void setup(void)
{
    Serial.begin(115200);
    delay(200); // Otherwise, the first log entries get lost
    ESP_LOGI(TAG, "Start test");
    esp_partition_iterator_t iter = esp_partition_find(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_ANY, NULL);
    ESP_LOGI(TAG, "Name, type, subtype, offset, length");
    while (iter != nullptr)
    {
      const esp_partition_t *partition = esp_partition_get(iter);
      ESP_LOGI(TAG, "%s, app, %d, 0x%x, 0x%x (%d)", partition->label, partition->subtype, partition->address, partition->size, partition->size);
      iter = esp_partition_next(iter);
    }

    esp_partition_iterator_release(iter);
    iter = esp_partition_find(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, NULL);
    while (iter != nullptr)
    {
      const esp_partition_t *partition = esp_partition_get(iter);
      ESP_LOGI(TAG, "%s, data, %d, 0x%x, 0x%x (%d)", partition->label, partition->subtype, partition->address, partition->size, partition->size);
      iter = esp_partition_next(iter);
    }

    esp_partition_iterator_release(iter);

}

void loop()
{
}

In the project folder, I also have a custom partitions.csv file as follows:
nvs,        data, nvs,      0x9000,  0x6000,
phy_init,   data, phy,      0xf000,  0x1000,
factory,    app,  factory,  0x10000, 512k,
storage,    data, ,         ,        0x40000,

If I run the code, it correctly shows the custom partitions with the above sizes, everything like it should be.
However, the build output says the program uses 207278 Bytes from a maximum of 1310720. If I change the partition scheme selection in the tools menu, the second number changes. I would expect the maximum size to be equal to the size of the factory partition from the custom partition scheme.
If I change the factory partition to be only 100k in size, the ESP32 fails to boot and enters a core-dump-restart-loop.
Is this a compiler bug or am I overlooking something?

See https://arduino.stackexchange.com/questions/96708/esp32-partition-size-and-maximum-program-size-2v for related question.

This appears to be a limitation of the toolchain. The output of processing the partitions.csv file doesn't make it back to the compiler to generate the correct message. The different partition schemes available in the menu come from boards.txt of the ESP32 package. They can be updated, but would be overwritten when the toolchain is updated. For the compiler input, the setting in the menu is relevant, but the actual size of the partitions comes from the partitions.csv file (if it exists).
This means that one has to manually make sure that the size of the factory partition in the csv file is larger or equal to the actual code size. Ideally, it is also equal to the selected partition size from the menu (to get the correct message and eventually error if the binary size exceeds the allocated space).
Some testing shows that if the actual size of the factory partition is smaller than the code size (and smaller than the compiler size limit) the application will successfully build and upload, but fail to run. The chip will enter a startup-reboot-forever loop and not execute any user code. However, whether that is always the case is not guaranteed.


text:
Multiple SoftwareSerial's at the same time?
I need to receive some data from USB and send it to the Android device via Bluetooth. The problem is that multiple SoftwareSerials won't connect at the same time.
Here is my code:
SoftwareSerial bluetooth(2,3);
SoftwareSerial usbConverter(4, 5);

void setup() {
  usbConverter.begin(9600);
  bluetooth.begin(9600);
  checkConnection();
}

void checkConnection() {
  while(true) {
    int areBothDevicesConnected = 0;
    if(bluetooth.available()) {
      areBothDevicesConnected++;
      bluetooth.println("Bluetooth connected");
      if(usbConverter.available()) {
        areBothDevicesConnected++;
        bluetooth.println("USB converter connected");
      } else {
        bluetooth.println("USB converter is not available");
      }
    }
    if(areBothDevicesConnected == 2) {
      bluetooth.println("All devices connected");
      break;
    }
    delay(2000);
  }
}

As far as I understand only one SoftwareSerial can listen at the same time but in my case, I can't even connect both devices. On Android device I always receive USB converter is not available.
My setup:

Arduino UNO.
HC-05 Bluetooth.
USB to TTL converter.

Any clue?

receive some data from USB ... why are you not using  hardware serial for this?

Any clue? is not a question about arduino

I think you misunderstand what SoftwareSerial.available() does. It does not say anything about if the serial port is connected. It returns the number of received bytes in the buffer. When you don't send anything over the interfaces to the Arduino it will always return 0 aka false. Though - as you yourself already mentioned - you cannot receive on two SoftwareSerial interfaces at the same time, so your logic cannot ever work. Use hardware serial for one of the interfaces and rethink your connection check

When you have multiple instances of SoftwareSerial, you need to setup the .listen() method to switch between the instances if you are going to read from them. See https://arduino.stackexchange.com/a/43125/40646

Thank you. That is what I needed!


text:
ESP32 Classic Bluetooth Set Password
I am using ESP32 classic Bluetooth Feature for data transfer. I am using the SerialToSerialBT example. I am able to scan and discover the Bluetooth device from my smartphone. But the pairing is without any security/passcode. It simply pairs immediately. How to make the pairing using PIN/Passkey entry?
Hardware: ESP32 DEV Kit V1
Software Arduino IDE
Code:
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  delay(5000);
  Serial.println("Starting..");
  SerialBT.begin("MyESP32"); //Bluetooth device name
  Serial.println("The device started, now you can pair it with bluetooth!");

}

void loop() {
  if (Serial.available()) {
    SerialBT.write(Serial.read());
  }
  if (SerialBT.available()) {
    Serial.write(SerialBT.read());
  }
  delay(20);
}

the BluetoothSerial header files has bool setPin(const char *pin); (PIN as personal identification number)


text:
Bootloader For Atmega4809
I have designed a project using Arduino Every board which uses MCU Atmega4809 chip and I have used Arduino IDE for programming but now I am planning to design my custom board I have used schematics of Arduino every board available on Arduino website . how can i upload the bootloader (Where can I get the bootloader from ) and how can I upload the Arduino code on new Atmega4809 Chips.

Nano Every doesn't use a bootloader. The ATmega4809 on Nano Every is flashed with the SAMD11 used as UPDI programmer with Arduino firmware.
Optiboot supports ATmega4809 and MCUDude MegaCoreX supports different ATmega4809 configurations and Optiboot.


text:
M5 Lora module and Nano - does not receive / transmit
I'm working on my first Arduino project using LoraWAN8688 ASR6501 M5 module. I would like one nano to send message, and another nano to receive and read it.
I believe they are not sending or receiving data. I can see Transmission led flashing on one of them, but not Receive led on another.
I think, that my Lora module must be configured before it will be used to send and receive data from Arduino.
How can I send AT+ commands to the LORA module to configure it? Do I need any additional cables or connectors, or can I use Arduino to set it up?
Can I use Serial.println("AT+ADDRESS=1"); to set address via andruino?

RECEIVER CODE:
String incomingString;

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("AT+ADDRESS=3");
}

void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()){
incomingString = Serial.readString();
if (incomingString.indexOf("TeamA") >0){
delay(500);
}
}
}

TRANSMITTER CODE:
unsigned long lastTransmission;
const int interval = 1000;

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("AT+ADDRESS=2");
}

void loop()
{
if (millis() > lastTransmission + interval) {
Serial.println("AT+SEND=1,6,TeamA");
delay(2000);
lastTransmission = millis();
}
}

the 9 V battey consists of four AAAA cells ... it is questionable that it has the capacity to power your project


text:
Lessons 2: Spaceship interface
I'm just starting to discover Arduino. Currently, I've done 2 lessons from Arduino book and I have few questions about second circuit.

Why we need to add 10kOm resistors after wire to 2 pin?
Why we need to add resistors after LED?
And why 3, 5, 6, 9, 10, 11 pins with "wave" symbol?

I'm surprised: isn't all that explained in the book? If not, I would not recommend it! Short answers: pulldown resistor to avoid floating input;limit current flowing through the LED to avoid burning it; those are pins allowing PWM to simulate analog output, between 0 and 5V.

Why we need to add 10kOm resistors after wire to 2 pin?

Due to some weird electronic properties, the state of the input to the Arduino is "undefined" when there is nothing connected. When the button isn't pressed down, it is neither connected to 5V or GND; it is left floating. When floating, the input isn't reliable.
To make sure that the input always has some sort of signal, we connect it to ground. However, there is a problem with directly connecting the input to ground. When you would push the button, you would create a short circuit by allowing current to flow directly from 5V to GND without any current limiting.
The solution is to add a resistor to limit the current between 5V and GND. When the button isn't pushed, the input is grounded to allow it to read LOW. When the button is pushed, the 5V rushes in and, since the 5V doesn't use a resistor, "the 5V is stronger," making the input HIGH.

Why we need to add resistors after LED?

An overly simplified explanation: A LED will theoretically pull infinite power (as current) from your power source without a resistor. With too much power, the LED will be destroyed from heat.
Because the LED has some resistance, it will pull up to a finite amount of power, but that usually is much more than the LED can handle (and sometimes what the power supply can supply). We need a resistor there to ensure that the LED can only draw as much power as it can handle.

And why 3, 5, 6, 9, 10, 11 pins with "wave" symbol?

If you look at an Arduino board, it will say DIGITAL (PWM~). That (PWM~) means that any pins with the "~" symbol are PWM pins... pins that can turn on and off their output very fast, in this case to create an illusion that the LED is dimming because the state changes faster than the human eye can detect.

http://arduino.cc/en/uploads/Main/ArduinoUnoFront240.jpg

More explanation for PWM here: Arduino docs, an answer [of mine]

Can you please also explain why the resistor can be put after the LED and not before? Seems to me like full power should already have done through the LED at this point?

@rejeep the resister after the LED is still preventing the electricity from flowing too fast throughout the circuit from the power source to the LED to the ground pin, no matter where it is in that circuit.

Not very intuitive IMO. For example water in a pipe would not behave the same way. Thanks!


text:
Blue LED not switching off
I have a circuit with a blue led, 470ohm resistor and one IR led. I want the led to be switched off when the IR led has a digitalRead value of LOW(i move my hand over it). So I wrote the code:-
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT); // this is the blue led
pinMode(10, INPUT);  // this is the IR sensor's O/P

}

// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // first I give HIGH voltage to the blue LED

if(digitalRead(10) == LOW){  // when the voltage of the IR sensor decreases
digitalWrite(13, LOW); // the blue LED should switch off or have 0 Voltage
}

}

But the blue LED just dims and doesn't switch off. Thanks in advance

What is the ref of the IR LED you are using?

Every time through your loop, the LED is being set to HIGH voltage. This may or may not be followed by setting it to LOW voltage, but since the loop runs again immediately, it's immediately set back to high voltage. This happens so fast that the LED essentially "feels" half voltage and it will dim. Your code needs to be more like this...
void loop() {
  if(digitalRead(10) == LOW) {
    digitalWrite(13, LOW);
  } else {
    digitalWrite(13, HIGH);
  }
}

OR... even like this...
void loop() {
  digitalWrite(13, digitalRead(10));
}


text:
Arduino Fio and BC127 communication
I am using an ArduinoFio and a BC127 (datasheet). I'm having troubles getting the serial connection working properly from the Arduino to the BC127 and viceversa. I wasn't able to communicate with the BC127 and I don't know if is because isn't correctly powered on or something else.
I've connected pin 0 of the BC127 to GND, pin 33 to 3V3 and pin 41,42 (RX, TX) to the TX, RX arduino's pins.
I've tested with the tester that all wires are connected, but the BC127 seems dead.
Any help is appreciated :|

There's a couple of things I would try.
First: Don't use the native Arduino TX/RX pins, they should be left alone to talk to the computer. Use SoftwareSerial instead in start a separate serial connection.
Second: Check that Arduino TX pin (that you declared in softwareSerial) is connected to the BC127 RX and vice versa. Unlike just about every other connection in electronics, serial connections need to have their pins reversed so that TX talks to RX. It's an easy mistake to make and one I've made when not paying attention to what I was doing.
Third: Flow control.
If the BC127 sends data when the Arduino isn't listening the data could be lost, to prevent this the BC127 won't send until the Arduino signals it is ready through flow control.
See the BC127 datasheet page 8, pins 40 and 43. Trying tying UART_CTS to 3V3 and UART_RTS to Ground. That should cause the BC127 to be in a constant 'send' state.
Lastly I'd hook up a couple of LEDs to pins 37 and 38. They should give you some sort of status indication that could be useful in debugging future problems.

use this method for dealing with voltage translation. Also we have IC's which does the level shifting. Works great with higher frequencies as well.

Use voltage level translator. 5v to 3.3V. Dont just connect directly 5v tx to a 3.3v tx...!!

Do you mean 5V tx to a 3.3V rx?

Yes I would use a N channel Mosfet to make 5v to 3.3V communication.

Your answer is likely to get more votes if you describe how to do this. Perhaps a schematic.

Sure I will post the schematic and how I deal with voltage translation devices.


text:
How do I make the Arduino print on my Mac's Arduino IDE through Bluetooth?
This is a basic question, but I really have tried my best to find a solution on the internet to no avail.
I have a fairly normal setup. HC05 module connected to an Arduino. The HC05 is also connected to my Mac's Bluetooth (fairly sure of this bc I used AT Commands to confirm). However, when I select the HC05 port in the Arduino IDE, nothing is printed in that port's serial monitor. Am I fundamentally misunderstanding something?
How do I make the Arduino print on my Mac's Arduino IDE through Bluetooth?
Here's my code:
#include <SoftwareSerial.h>

SoftwareSerial MegaloDon(10, 11);

bool isConnected = false;

void setup() {
  pinMode(9, HIGH); //this pin is connected to "EN" on the HC05 and enables AT commands
  Serial.begin(9600);
  MegaloDon.begin(9600); //
  connectBluetooth();
}

void connectBluetooth() {
    digitalWrite(9, HIGH);
    MegaloDon.println("AT"); //AT command
    if (MegaloDon.find("OK")){
      MegaloDon.println("Bluetooth ON");
      digitalWrite(9, LOW);
      Serial.println("Connected");
    } else {
      Serial.println("Attempting to reconnect...");
      delay(2000); // wait 2 seconds before trying again
    }
  }

void loop() {
  if (isConneced()) {
    Serial.println("conneced?");
    **//I'd like to transmit data to my mac's serial monitor on the Arduino IDE here**

  } else {
    Serial.println("not conneced");
    connectBluetooth(); // Attempt to reconnect
  }
}

bool isConneced(){
  Serial.println("is it conneced?");
  digitalWrite(9, HIGH);
  MegaloDon.println("AT");
    if (MegaloDon.find("OK")){
      isConnected = true;
    }
    else{
      isConnected = false;
    }
    digitalWrite(9, LOW);
}

I see two problems:

Your AT commands don't actually confirm, that the HC05's bluetooth is connected to anything. You are only ever sending "AT", which sets the HC05 to AT mode for a specific amount of time. So basically you are only testing the Serial connection between the Arduino and the HC05. If you want to get other information from the HC05, you need to get into AT mode and then use other AT commands (so commands with the "AT" at the start but other information following that) to check the connection.
So the question is: Is the HC05 really connected to the Mac? The HC05 can be either in device or master mode for bluetooth. When in device mode, the Mac will be able to initiate the connection (like with any other bluetooth device like a headset). When it is in master mode, it itself has to initiate the connection (then the Mac would need to be the device), which would need to be done with AT commands. How exactly do you know, that the HC05 is connected to the Mac and that you are looking at the correct port in the Arduino IDE? Does the port vanish and reappear, when you turn the Arduino/HC05 combo off and a little bit later on again?

In your code you are only sending data through the MegaloDon interface at one point:
 MegaloDon.println("Bluetooth ON");

All the other calls to MegaloDon are the "AT" command. And this line is executed directly after sending "AT" to the HC05 and getting "OK" back. Do you remember what I wrote above? The "AT" command will set the HC05 to AT mode for a limited amount of time (typically 1 or 2 seconds). The firmware on the HC05 will then try to interpret all data send in this time as AT commands. It will not send this data through the bluetooth interface! So, if you want to send that data to the Mac, then you should wait with sending it for a bit, so that the HC05 is no longer in AT mode.

Thank you for the response! I see where I sent wrong. I understand now that because I am using the HC05 as the master, I would need to connect to my Mac from the HC05 itself with AT commands. Do you happen to know where I could find the AT commands/tutorials necessary for this?
Also, I am fairly sure there is a connection(except HC05 is slave) because the port is called smthg like "DSDTECH HC05" and as you said, disappears/reappears when I power on/off the module.

Ohhhh, thank you. I'll make sure to add a delay.
Thank you so much again!

Would the relevant AT commands be AT+LINK=mac address         and
AT+STATE?


text:
Can an ethernet shield function as an adapter?
I want to communicate with my Arduino over a long distance so I decided to use an Ethernet cable between my computer and Arduino. Searching up a few tutorials I've found them all mentioning IP addresses and establishing a network.
Simply put my question is can an Ethernet shield make the Arduino function basically the same as with a direct USB connection into its port(with Serial and all) without having to establish a network/other things. If so, is it as simple as saying something like "Ethernet.begin()" and then continuing?
Thank you, and please note that I (clearly) do not have much TCP/IP experience (but am more than willing to learn).

No, you cannot do that. Ethernet is very different from a serial link.
You will have to deal with IP addresses, port numbers, the notions of
client and server, and so on. Note that, once you manage to establish a
TCP connection through Ethernet, that connection does behave pretty
much like a (somewhat virtualized) serial link. But you have to
establish the connection first. So you will have to study a bit, read
documentations, etc.
Alternatively, if you only need a short-distance link (say, a couple of
km), you can try RS-485 instead of Ethernet. RS-485 is a physical layer
commonly used to transmit regular serial data. From the software point
of view, it is pretty much a regular serial link, save for the fact that
you usually cannot speak and listen at the same time (you could, with
more expensive cabling).

Thanks, your answer was very illuminating. A quick question, to establish the TCP connection between computer and Arduino would I need any components other than the Arduino, Ethernet shield, and my computer?

@iceninja21: You well need a network cable. All the rest is software.

can't you use a crossover cable and a manual IP to connect 2 devices w/o a network?

@dandavis: If you use IP, you are doing networking, even with only two devices.


text:
Using ESP8266 to program Arduino by serial comm
Since ESP8266 can self program on wifi, can we use it to program arduino too with the binary sent via wifi? my arduino is connected with reset+RX+TX pins and shared power.
Has this been already done?

If you use Linux, you can use a simple Telnet to Serial sketch in esp8266 to upload with avrdude to Uno over esp8266. Only on Linux can avrdude use telnet to do a serial upload.
For upload from IDE on any OS there is JeeLabs ESP Link firmware for the esp8266.

plenty of ways on other os to patch things so arduino looks to be connected over serial as far as avrdude is concerned- for example com0com makes virtual serial ports...

@Abel, did you test it?

haven't done it for avrdude yet, but i did have the need to do something similar for a serial user interface program to connect to a stream that had to be encapsulated by ssh first.

tested with pi in the middle (avrdude-com0com-customExe-pi-customProgram-uno).  gotchas found: bootloader baud, and stable re-entry to bootloader.  no reason to believe any other program attempting this over serial would behave differently.  i implemented re-entry via usb port poweroff and poweron via rpi uhubctl, but it might be possible with hardware (reset pin), a modified bootloader, or crashing? the main on command (casting 0 to a function pointer and calling it).

@Abel, my sketch linked in the answer resets the target at new telnet connection. what problem with baud rate?

i didnt use your sketch or telnet.  Just wanted to prove you are not limited to avrdude linux to get the job done- for me avrdude thought it was talking over serial and uploaded just fine.  Can make a connection between avrdude and the nets with other programs.


text:
Can't burn fuse bits on ATMega168 with Arduino Uno as ISP
I have an ATMega168 that I am programming via my Arduino Uno as ISP. I can burn the bootloader and transfer a hex file just fine, but I can't seem to be able to change the fuse bits. I found a lot of people having similar problems, but most still weren't resolved after many years or can't connect to their chip at all.
A weird thing I notice is that my ATMega is recognized as an 328p all the time. I know they're practically identical, but nothing works when I change settings to an 168, I always have to set it to 328p. Avrdude tells me the signature is wrong, whenever I try it with 168. Might that already be an indicator for something being wrong!? I ordered a 168 and it's printed on the chip, so it should be an actual 168.
Furthermore I noticed that I can only use the Baud rate of 115200, but I read that only 19200 should be correct and when I use that I get no response as well.
This is the command I'm trying to use:
avrdude -Cavrdude.conf -patmega328p -PCOM3 -carduino -b115200 -U efuse:w:0x00:m -U hfuse:w:0xDD:m -U lfuse:w:0xFF:m

And the response I get is:
avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0x00 != 0xdd
avrdude: verification error; content mismatch

I tried different software and different USB cables, to no avail.
If anyone could provide any direction I can try and look for a solution or mistakes I might have made, I'd be really grateful!

I got an answer on another forum. I was missing a 10μF capacitor between the Ground and Reset of the Arduino. Not a single documentation, image or video I saw mentioned that. Everything works fine now.

so you could burn the bootloader without the capacitor, but not set fuses?

This official doc mentions the capacitor in the text. Though it is not very clear and is not shown in the wiring diagrams. The official Arduino docs are often not that good

@Juraj It seems that I was addressing the ATMega328p on the Arduino itself the whole time so I probably uploaded everything to that instead of the 168.

@chrisl Thanks for pointing that out! Apparently it's also sufficient to directly bridge the +5V and Reset pin, but I haven't treid that, yet.

it is not possible to burn bootloader to the as ISP programmer Arduino

Alright. The burning process went through without error, though, and I also got verification at the end. So no idea where that data went, was just my guessing :)


text:
Multiplexer 74HC4067, conflict between channels
I am currently working on an Arduino Zero with a 74HC4067 multiplexer and I am experiencing inconsistencies when testing some of the channels.
My class is the following (it should be functional for 8 or 16 channels multiplexers).
Multiplexer.h :
#ifndef Multiplexer_h
#define Multiplexer_h

#include "Arduino.h"

class Mux
{
  public:
    Mux(uint8_t numberOfChannels, byte sigPin, byte adress1, byte adress2, byte adress3, byte adress4 = 0);

    uint8_t muxRead(byte pin);//Read specific mux pin
    void selectMuxPin(byte pin);

  private:
    uint8_t m_numberOfChannels;
    byte m_sigPin ;
    byte m_adress1 ;
    byte m_adress2 ;
    byte m_adress3 ;
    byte m_adress4 ;
    uint8_t m_numberOfAdressPins;
};

#endif

Multiplexer.cpp :
#include "Multiplexer.h"

//**************************************************************

Mux::Mux(uint8_t numberOfChannels,
         byte sigPin,
         byte adress1,
         byte adress2,
         byte adress3,
         byte adress4)

:   m_numberOfChannels(numberOfChannels),
    m_sigPin(sigPin),
    m_adress1(adress1),
    m_adress2(adress2),
    m_adress3(adress3),
    m_adress4(adress4)
{
  if(m_numberOfChannels > 8) {m_numberOfAdressPins = 4;}
  else {m_numberOfAdressPins = 3;}

  //Set adresses to OUTPUT
  pinMode(m_adress1, OUTPUT);
  pinMode(m_adress2, OUTPUT);
  pinMode(m_adress3, OUTPUT);
  if(m_numberOfChannels > 8){pinMode(m_adress4, OUTPUT);};

  //Set adresses to LOW
  digitalWrite(m_adress1, LOW);
  digitalWrite(m_adress2, LOW);
  digitalWrite(m_adress3, LOW);
  if(m_numberOfChannels > 8){digitalWrite(m_adress4, LOW);};

  pinMode(m_sigPin, INPUT_PULLUP);
}

//**************************************************************

uint8_t Mux::muxRead(byte pin)
{
  selectMuxPin(pin);
  bool value = digitalRead(m_sigPin);
  return(value) ;
}

void Mux::selectMuxPin(byte pin)
{
  const int selectPins[4] = {m_adress1, m_adress2, m_adress3, m_adress4};
  if (pin > (m_numberOfChannels - 1)) return; // Exit if pin is out of scope

  for (int i = 0; i < m_numberOfAdressPins; i++)
  {
    if (pin & (1<<i)) {digitalWrite(selectPins[i], HIGH);}
    else {digitalWrite(selectPins[i], LOW);}
  }
}

To make my tests on the 74HC4067, I connect my multiplexer, I put the pin 8 of my Arduino to the "LOW" state and with the help of a jumper cable I test each of the pins via the following code:
#include "Multiplexer.h"

//**************************************************************

Mux Mux0(16, 6, 2, 3, 4, 5);

//**************************************************************

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

//**************************************************************

void loop() {

  //Set pin 8 to LOW for the test with a jumper
  analogWrite(8, LOW);

  //For this test, we print the name of the multiplexer's channel if it's LOW

  bool channel0 = Mux0.muxRead(0);
  if(!channel0)
    Serial.println("Channel 0");

  bool channel1 = Mux0.muxRead(1);
  if(!channel1)
    Serial.println("Channel 1");

  bool channel2 = Mux0.muxRead(2);
  if(!channel2)
    Serial.println("Channel 2");

  bool channel3 = Mux0.muxRead(3);
  if(!channel3)
    Serial.println("Channel 3");

  bool channel4 = Mux0.muxRead(4);
  if(!channel4)
    Serial.println("Channel 4");

  bool channel5 = Mux0.muxRead(5);
  if(!channel5)
    Serial.println("Channel 5");

  bool channel6 = Mux0.muxRead(6);
  if(!channel6)
    Serial.println("Channel 6");

  bool channel7 = Mux0.muxRead(7);
  if(!channel7)
    Serial.println("Channel 7");

  bool channel8 = Mux0.muxRead(8);
    if(!channel8)
    Serial.println("Channel 8");

  bool channel9 = Mux0.muxRead(9);
  if(!channel9)
    Serial.println("Channel 9");

  bool channel10 = Mux0.muxRead(10);
  if(!channel10)
    Serial.println("Channel 10");

  bool channel11 = Mux0.muxRead(11);
  if(!channel11)
    Serial.println("Channel 11");

  bool channel12 = Mux0.muxRead(12);
  if(!channel12)
    Serial.println("Channel 12");

  bool channel13 = Mux0.muxRead(13);
  if(!channel13)
    Serial.println("Channel 13");

  bool channel14 = Mux0.muxRead(14);
  if(!channel14)
    Serial.println("Channel 14");

  bool channel15 = Mux0.muxRead(15);
  if(!channel15)
    Serial.println("Channel 15");
}

For most of the channels it works quite well. When I connect the jumper (pin 8) to a channel of the multiplexer, the name of the corresponding pin is displayed in the console.
However, two channels are problematic. Channel 0 and channel 8. No matter if I connect the jumper to one or the other, I see in the console "Channel 0" and "Channel 8" as if both were connected and the change of state of one would cause the change of state of the other.
Any idea why?
Thanks

I have no idea why. You might want to check the levels on any relevant pin manually with some voltage meter and change the selection via the serial monitor.

Hmm... analogwrite(8,LOW) I´d rather use digitalwrite()

I gather it is part of a learning experiment. Logically this does not compute however there are many reasons something like this could happen. A bad IC is the first thing that comes to mind but they are generally very rugged devices. If you have a scope probe the power supplies to be sure they are clean and stable, if so start by holding it in one of the bad states and take voltage measurements on VCC, Ground, several other pins and the related pins. Your voltage on each pin should be within 0.1V of the appropriate power supply pin.  If not it would indicate a short especially if it goes somewhere mid supply voltage. If this is a breadboard flip the bad pins out and test again. If everything is in speck it is a short, if it still show you probably have a bad IC.

Thank you for your answer (and sorry for my late answer...). After some tests and research I think that the problem comes from the hardware. I prototype on SMD multiplexers that I buy already soldered on a small IC. There must be a problem in the design of the IC that generates interference between the channel 0 and channel 8 track... I have no scope but I'll try to do some tests with a multimeter, this should already give me some indications.

I have done additional tests with the same component but proposed by another supplier and it works perfectly. So the problem was in the hardware.


text:
Why do we add delay when using ultrasonic sensors?
I'm a beginner in Arduino and recently i got myself an Ultrasonic sensor (HC-SR04).
I looked up tutorials on how to measure distance with the sensor and the code I'm using is:
const int trigPin = 8;
const int echoPin = 7;

long duration;
int distance;

void setup() {
  // put your setup code here, to run once:
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2); //why do we delay 2 microseconds

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); //why do we delay 10 microseconds
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration*0.034/2;
  Serial.print("Distance: ");
  Serial.println(distance);
}

I would like to know why do we add delays in the loop function? Appreciate if anyone could explain it.

please read the HC-SR04 datasheet ... https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf

We need to provide the HC-SR04 with a fitting trigger signal. When you read the datasheet of the HC-SR04 you will see that it needs a 10us trigger pulse.
The first delay of 2us is to make sure we are at an established LOW level on the trigger pin, since the pin might have been HIGH before that. We are delaying here to make sure, that the HC-SR04 actually registered the level as LOW, even if it was HIGH before. If we would change from HIGH to LOW and back to HIGH as fast as we can, then the HC-SR04 might not have enough time to actually see the pin going low. Its mostly a measure to ensure the code working correctly here.
The second delay is for the actual trigger pulse. The datasheet specifies it as 10us length, so that is what we delay here. After that we go back to LOW to end the trigger pulse and wait for the echo pulse to come.
You might have read that it is bad to use delays in your code, since they are blocking. That is correct in principle, but normally really short delays in the microsecond range don't really matter for the program flow. Just be away to keep the total delay time in your code low enough to not miss any important events (like button presses).

The microsecond delays make sense but my library also has a 25 ms delay before returning. All the computation is done by this point, so it seems to be just a delay and 25 ms is a long time for a robot.

@user88094 You didn't specify what library you mean. Yes, without seeing the code and context I would also say, that a 25ms delay is not needed.


text:
How to power board plus module with one battery pack
I'm someone who's very new to robotics and the physical side of computers (software guy) so apologies if this is a stupid question. I'm purchasing an Arduino Nano 33 IoT that I'll be using in conjunction with an Adafruit FONA 3G Cellular Breakout (https://www.adafruit.com/product/2687). I'd like to be able to power the entire unit off of one battery pack but my problem is that both the Arduino and the Adafruit 3G unit have separate power inputs. Adafruit's website says that a Lipoly battery is required to run the unit. Is there any way to "pass through" or "split" power between the two units? This way I was thinking I could run everything off of one external battery pack. Optimally I don't have to use a Lipoly battery and I could use a large external battery pack connected to jumpers or a barrel jack.

https://learn.adafruit.com/adafruit-fona-3g-cellular-gps-breakout/arduino-wiring

Note that the SIM4320 has a supply voltage range: 3.4~ 4.2V. So you can't just use any odd battery pack. It also, at times, uses a lot of power, so your battery has to be able to provide these short bursts of current.

you can use a breadboard and jumper cable. connect the VCC and GND of battery to a breadboard, do this for your Arduino and sim card module too. just remember they should be in a one row. GND with GND row, and VCC with VCC row
note: this way is okay just for debugging


text:
How can I rewrite my Bluetooth Classic Arduino code into Bluetooth Low Energy Arduino code (and have everything working the same)
My original code for BT Classic
My Work in Progress BLE Code
I am trying to take all I did in BT Classic and have it working exacly the same in BLE but the Rssi keeps returning 0's in the BLE code and I don't get why, even after I do connect with my iPhone to the Esp32 the Rssi is still read as 0's.
In the BT Classic example everything works perfectly fine, but I am struggling to make my BLE code work.
What the first code does is reading Rssi signal from any device that connects to the Esp32, aproximating a distance based on the values and outputing the resulting Distance and Rssi in a list of pairs form via text that is sent to the other device, continously so that I can use that information to generate a graph and do various things with it.
I tried taking all I did in my BT Code and replicate it in BLE but it's not working at all, with rssi showing as 0 no matter what, and I've also read through the two Gatt Api's and tried replicating the same functions but there were some I didnt find an equivalent for in the BLE GATT Api:
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/bluetooth/esp_gap_ble.html
If anyone can guide me it'd be great. To make a summary, the first 0bin link represents the BT code I need to follow and the second 0bin link represents the BLE code I need to have it working just like the BT code (have it do the same exact things).