HC-06 Bluetooth RX & TX voltage (3v3 || 5v) I acquired a HC-06 Bluetooth module, and understand that the voltage on the pins must be 3v3 and therefore requires the use of a voltage divider to lower the Arduino's 5v to 3v3 like this.

But the page where I purchased the product says the following:

  interface level 3.3V, you can directly connect a variety of SCM (51, AVR, PIC, ARM, MSP430, etc.), 5V microcontroller can also be directly  connected, it can not pass without MAX232 MAX232!

Does this mean I can connect without using a voltage divider?

What does "it can not pass without MAX232 MAX232!" mean?

Some chips that run on 3.3v have 5v tolerant inputs. But it doesn't look like the BC417 does (looking at the datasheet).

So just add the voltage divider.


Compilation issues on Arduino Due I wrote an code on Arduino and I getting compilation errors. I am using Arduino Due . I wrote the following code :

void setup() {
  Serial.begin(9600);
  analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
  analogReadResolution(12);   // set the analog input resolution to 12 bit

}

void loop() {

  // code
}

But compiler gave me the following errors :

'analogReadResolution’ was not declared in this scope
‘analogWriteResolution’ was not declared in this scope
‘DAC0’ was not declared in this scope

I'm using Arduino 2:1.0.5 (on Linux). The board list doesn't show Arduino Due (USB programmable).And I don't have Board Manager option. How do I install Arduino SAM Board to compile the program ?

According to the Arduino - ReleaseNotes,

  ARDUINO 1.5 BETA - 2012.10.22

  First release for the unified IDE for both AVR 8-bit and ARM 32-bit   (SAM3 CPUs) architectures.
  This release include the SAM Arduino Core used in the Arduino Due   Board.

So your 1.0.5 version does not allow for Due compilation. Download the most up-to-date version and you will be fine (you will be able to install SAM support).

Then you will be able to at least compile. If you have other problems with your code, please open another question here (in order to keep the one-question-per-post behavior of this website).

Don't install arduino from the debian repository, since that version is not updated regularly. Use the website version


How can I know if I can stack some shield on another shield? Yesterday I tried to stack a motor shield on a servo motor shield already stacked on my Arduino Uno.

But I realized that I have some problem when I try to use both of them. It seems like some energy is lost or the stepper motor connected to my servo motor shield move weirdly slowly.

I already checked online, and I found some explanations about stacking many shields. About making sure the shields don't use the same pins or SS. As a beginner, help would be very helpful. Thank you.

Here are the two shields I use.

Smart Servo Shield for dynamixel
https://store.arduino.cc/arduino-motor-shield-rev3
Smart Arduino Digital Servo Shield for Dynamixel AX
https://www.dfrobot.com/product-958.html

wiki : https://www.dfrobot.com/wiki/index.php/Digital_Servo_Shield_for_Arduino_SKU:DRI0027

On these links, you can find all the specs with the pins used. I think I have some pinß shared by both of them... But not sure.

Does anyone have a solution please? Many thanks in advance.

First you have to compare the pinouts of the two shields. If the shields use completely different pins then yes, you can use them together.

However if they share pins then you need to look in more detail at what those pins are and how they are being used.

In your example you have SPI being used (pins 10-13) for one shield and PWM (3/11) and GPIO (8/9/12/13) and analog input (A0/A1) for the other shield.

You can see now that there is a conflict. For instance pin 13 for the SPI clock for the DFRobot shield is also being used for one of the GPIO pins of the Arduino shield. Pin 12 for MISO is being used as GPIO. Pin 11 for MOSI is also being used for PWM.

Those are disparate functions on the pin, so it can never work.

However if the SPI pins were being used for both shields as SPI then that could work. In that case it's only the "chip select" pin that needs to be unique for each shield, since SPI is a Master-Slave Bus protocol which can be shared amongst multiple shields.


Auto acknowledge failed with nRF 24L01+ and Arduino My transceivers are running fine. I've written a few code and got them running. Then I decided to check the auto acknowledgement feature wherein we can return data back to the sender WITHOUT manually changing the radio modes on both units. But I find that the serial monitor always shows "failed to transmit". Why is this happening, because otherwise they work fine?

I am using maniacbug's RF24master library.

The Tx code is:

#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>

int msg[1] = {1};
int rec[1] = {0};
bool stat = true;
RF24 radio(9,10);
const uint64_t pipe[1] = {0xF0F0F0F0E1LL};

void setup()
{
  Serial.begin(57600);
  radio.begin();
  delay(1000);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.openWritingPipe(pipe[0]);
  radio.setRetries(15,15);
 }
void loop()
{
  if(stat)
  {
    radio.stopListening();
    bool ok = radio.write(msg,sizeof(msg));
    delay(100);
    if(ok)
    {Serial.println("transmitted successfully !!");}
    else
    {Serial.println("faileed to transmit");}
    msg[1]++;
    if(msg[1]>=200)
    {msg[1]=1;}
    stat = false;
    //delay(20);
  }
  if(!stat)
  {
    if(radio.isAckPayloadAvailable())
    {
      radio.read(rec,sizeof(rec));
      Serial.print("received ack payload is : ");
      Serial.println(rec[1]);
      stat = true;
    }
  }

}

and the Rx part is:

#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
const uint64_t pipe = 0xF0F0F0F0E1LL;
RF24 radio(9,10);
int rec[1] = {0};
int ack[1] = {1};
void setup()
{
  Serial.begin(57600);
  radio.begin();
  delay(100);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.openReadingPipe(1,pipe);
  radio.startListening();
  radio.setRetries(15,15);
}
void loop()
{
  if(radio.available())
  {
    Serial.println("payload available....");
    bool ok = radio.read(rec,sizeof(rec));
    if(ok)
    {
        Serial.println("message received !!");
        Serial.print("integer got is : ");
        Serial.println(rec[1]);
        radio.writeAckPayload(1,ack,sizeof(ack));
    }
    else
    {Serial.println("failed to receive the message");}
  }
}

To achieve that you have to do the following -

if ( radio.available() ) { // make sure the read will succeed
radio.writeAckPayload( 1, buf, len ); // prep the ack payload
radio.read( &got_time, sizeof(unsigned long) ); // also shunts out ack payload
}

So your program finally becomes -

#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
int msg[1] = {1};
int rec[1] = {5};
bool stat = true;
RF24 radio(9,10);
const uint64_t pipe[1] = {0xF0F0F0F0E1LL};

void setup()
{
  Serial.begin(57600);
  radio.begin();
  delay(100);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  radio.stopListening();
  radio.openWritingPipe(pipe[0]);
  radio.setRetries(15,15);
 }
void loop()
{
if(stat)
{
    if(radio.write(msg,sizeof(msg)))
    {
      Serial.print( msg[0] );
      Serial.println("...tx success");
      if(radio.isAckPayloadAvailable())
      {
        radio.read(rec,sizeof(int));
        Serial.print("received ack payload is : ");
        Serial.println(rec[0]);
      }
      else
      {
        stat = false; //doing this completely shuts down the transmitter if an ack payload is not received !!
        Serial.println("status has become false so stop here....");
      }
      msg[0]+=3;;
    if(msg[0]>=100)
    {msg[0]=1;}
    }
 }
}

And the RX part becomes -

#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
const uint64_t pipe[1]= {0xF0F0F0F0E1LL};
RF24 radio(9,10);
int rec[1] = {2};
int red;
void setup()
{
  Serial.begin(57600);
  radio.begin();
  delay(100);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  radio.openReadingPipe(1,pipe[0]);
  radio.startListening();
  radio.setRetries(15,15);
}
void loop()
{
  if ( radio.available() ) {
    radio.writeAckPayload( 1, rec, sizeof(int) );
    radio.read( &red,sizeof(red) );rec[0]+=2;
    Serial.print("integer got is : ");
    Serial.println(red);
}
}

Know more about it at the following pages -
https://shantamraj.wordpress.com/2014/07/19/exploring-the-auto-ack-feature-of-the-transceiver/
https://shantamraj.wordpress.com/2014/11/30/auto-ack-completely-fixed/


15x15x15 LED cube with thermal sensors I'm trying to wrap my head around a public art project that I've recently received funding for, and I'm hoping that someone here can help me with a bit of guidance.

The concept I'm working on is a kind of 'digital campfire' that builds and falls in intensity as people approach and depart.

The way I imagine it working is with a 15x15x15 RGB LED cube that plays fire-like animations of varying intensities in response to the presence of nearby people - detected by a 360 degree array of thermal sensors (probably something like Omron D6T sensors, rather than IR movement sensors).

Full disclosure: I'm an Arduino noob. I've tinkered with LEDs and soldering, but even the thought of building a non-responsive 4x4x4 LED cube hurts my brain. That said, I have a couple of months up my sleeve, a bit of cash, and a willingness to forge new neural pathways to get this done.

My main questions at this point are:

Can an Arduino even handle the processing power required to run a thermal activated 15x15x15 LED cube, even with multiplexing?
I'm considering 15-cubed because I want the object to have a fairly large physical presence, and have a relatively high definition. Is there any game-changing reason I should seriously consider something smaller? I anticipate being able to connect to a 240v power outlet (I'm in Australia), but running off battery would be ideal.
How difficult would it be to build a 360 degree thermal sensor array consisting of, say, 8 separate thermal sensors? The programming is clearly beyond me, and I expect to out-source this...

Any help or suggestions would be hugely appreciated. And don't be gentle – if my expectations need to be 're-aligned' to something closer to reality, I'd rather that happen sooner than later.

Cheers,

Adam

The answer to "Can an Arduino even handle the processing power" is probably No, but no one can really answer because you have not specified the problem.

Just for starters you have >3k LEDS, if you want to control RGB that means ~10k devices.

To operate at moderate brightness (10mA per LED) you will need at least a 35A power supply. This will require external high power circuitry to switch/control.

Do you need to individually control each LED? To control 10k devices you will need serious external circuitry.

Do you need to control brightness or just switch individual devices on/off?

You could probably achieve a solution, but 15 modules each controlling 15*15 LEDS may be achievable, 32 or 64 is probably more realistic.

Either way soldering by hand would be impractical, you need to design a board for each module.

You could use an Arduino on each module, but a ATMega chip would achieve the same end, without the unnecessary peripheral circuitry.


ESP8266 GET request code -1 I've read several other posts but I still couldn't solve the issue. I'm trying to connect to a website which is HTTP (not HTTPS) but I always get code -1 as response. If I open the link in the browser it works well. Not sure what I am missing? Here's my full code:

#include <ESP8266HTTPClient.h>
#include <esp8266wifi.h>

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

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);
    Serial.print("Connecting..");

  }
}

void loop() {

  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("www.francescosoave.com/blind/getTime.php");
    http.addHeader("Content-Type", "text/html");
    int httpCode = http.GET();

    Serial.print("HTTP CODE: ");
    Serial.println(httpCode);

    if(httpCode > 0){
      String payload = http.getString();
      Serial.print("PAYLOAD: ");
      Serial.println(payload);
    }

    http.end();
  }

  delay(2000);
}

You omitted the protocol part of the url. The HttpClient implementation requires it.

Use http.begin("http://www.francescosoave.com/blind/getTime.php");

Do not use Content-type header. You do not send any content.

Turn-on debug in Tools menu. Set Debug Port to Serial and Debug Level to HTTP_CLIENT to see the error messages.


Disable Boot Flash completely on ATMega I want to reclaim the space reserved for the bootloader on my ATMega32u4 (Leonardo chip).
But the lowest boot flash size I can see is BOOTSZ=11 which is 256 words (512 bytes). Is it not possible to completely disable it?
Basing this off of this: http://www.engbedded.com/fusecalc

It is not possible to set the bootloader space to 0, but it is possible to unlock the bootloader space entirely by unprogramming the lock bits as well as to enable normal booting by unprogramming BOOTRST in the high fuse byte. Access to the entire chip will then be fully unrestricted.


HC-SR505 PIR Sensor only outputting HIGH I recently bought an HC-SR505 Mini PIR sensor. I connected its positive to my Arduino UNO's 5v, output to digital pin 2, and ground to ground. I used Adafruit's code to test it, but all the serial monitor displayed was "Motion detected", which meant the PIR was always on a HIGH state. I then also tried powering it using 3V3 but the PIR kept on cycling on a HIGH and LOW state. Any help on getting my sensor to actually work would be greatly appreciated.

The PIR sensor has delay of 8 seconds. So when you turn on arduino, take care that no movement is on the PIR, and then after 8 seconds it should detect no movement. And it has always this delay,every time when detects movement.


where to get Arduino WIFO101 library that supports WiFi.beginAP() on board MKR1000 The sketch example from page "Wifi.beginAP()" causes compiler error because the return values are not defined for -WL_AP_LISTENING or -WL_CONNECT_FAILED.

Board: Arduino MKR1000 WiFi

Compiler:  Arduino IDE

Library: Github WiFi101 v0.9.1

Missing:  definition of "WL_AP_LISTENING" and "WL_CONNECT_FAILED"

ERROR....
beginAP.ino: In function 'void setup()':

beginAP:55: error: 'WL_AP_LISTENING' was not declared in this scope

if (status != WL_AP_LISTENING) {

              ^

Arduino WiFi101-MKS1000 examples\beginAP\beginAP.ino: In function 'void loop()':

beginAP:78: error: 'WL_AP_CONNECTED' was not declared in this scope

  if (status == WL_AP_CONNECTED) {

                ^

exit status 1
'WL_AP_LISTENING' was not declared in this scope

It is AP_SimpleWebServer.ino at Github Wifi101 release 0.9.1 examples.
It builds ok by using the old definitions for .beginAP return values.
Problem is Arduino .beginAP page has example that relies on the LATEST Github WiFi101 ("0.9.1++" not released yet).
Also example AP_SimpleWebServer is missing from Arduino Wifi101 page.


Voltage increasing when charging a battery using arduino I am making a solar charge controller using Arduino. So for starting, I thought I should calibrate the voltage so that I am able to read the exact voltage of battery and solar charger. For testing purposes, I do not have any solar panel, so I used a 12V power supply and set its output voltage to 13.56. I used the following calculations for getting exact voltage:

float solarData = 0;
float batData = 0;
float batScale = 0;
float solarScale = 0;
float batPinVolt = 0;
float solPinVolt = 0;
float batVolt = 0;
float solVolt = 0;

Vcc = readVcc()/1000.00;    //getting the exact voltage of arduino
Serial.print(Vcc);
solarScale = analogRead(A0);  //reading solar analog data
batScale = analogRead(A1);    //reading battery analog data
solPinVolt = (solarScale/1024.0) * Vcc;
solVolt = solPinVolt * (9.80 + 2.168)/2.168;    //I used 10k & 2.2k so entered their exact value
batPinVolt = (batScale/1024.0) * Vcc;
batVolt = batPinVolt * (9.80 + 2.168)/2.168;

Initially, I faced few problem regarding the exact voltage of the Arduino which I used as a reference voltage to calculate voltage. But then I found a solution here. So below is the code which calculate the voltage of Arduino

long readVcc()
{
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1125300L / result; // Back-calculate AVcc in mV
  return result;
 }

Now when I uploaded the code, I got the exact values of the voltages.

Now I wrote a logic where if the battery voltage is less than 12V then start charging until it is above 13V. Following is the code:

if((solVolt > batVolt)&& ( batVolt <= 12.00 ))
{
digitalWrite(chargePin,HIGH);  //enable charging
digitalWrite(loadPin,LOW);     //load off
}
else if((solVolt > batVolt)&&(batVolt > 12.00)&& (batVolt <= 13.00 ))
{
 digitalWrite(chargePin,HIGH);   //enable chargin
 digitalWrite(loadPin,LOW);      //load off
}
// // shut down when battery is fully charged or when sunlight is not enough
else if ((batVolt > 13.00) or (solVolt < batVolt))
{
 digitalWrite(chargePin,LOW);    //disable charging
 digitalWrite(loadPin,HIGH);     //load on
}

But when I uploaded the code, the Arduino started showing wrong values of the voltages. Power supply was set to 13.5, but it showed 13.15 and battery voltage was 11.8, but it showed 12.7.

Now due to this what exactly happened was it started charging so the value of battery voltage 12.7 (which is wrong) started increasing. When it was above 13V, Arduino turned off the chargePin. So when the chargePin is low, it shows the exact battery voltage which is low so it again started charging it and this loop keeps on going. This is all because of the wrong values of voltages. Following is the schematic:

I am following the article I found on Instructables. (cannot post more links due to reputation). I want to know why there is change in voltage. Can anyone please help me on what I am doing wrong.

In order to charge a battery you have to apply a voltage to the battery terminals that is higher than the batteries own internal voltage. That's pretty much the definition of charging a battery.

Basically you're trying to do the impossible, you can't measure the batteries off charge voltage while charging it because as soon as you start charging the voltage at that point changes.

When charging your supply is 3.5V and your supply measurement is 13.15. That means you're loosing 0.35V in battery cables and F1.
The battery voltage is 12.7V so that's 0.45V loss in D1 and Q1.

That first loss seems too high and the second one too low, D1 should drop typically drop 0.58V, so you may have some resistor tolerance or noisy reading issues. The total voltage drop seems reasonable but the split looks wrong.

The best solution to what your are trying to do is to measure the charge current.

Move D1 to the other side of R1 so there is no diode drop between your two voltage measurements and add a small resistor in series where D1 used to be. The difference between the two measured voltages and the resistance between those points now tells you the charge current. Stop charging when the current drops below a certain threshold. Larger resistors make it easier to measure accurately but have an obvious efficiency hit, make sure you check the resistors power rating.

You may be able to avoid adding the resistor and simply use the on resistance of Q1 as your resistor. This will be a little variable between devices so it's not suitable for mass production but for a one off it should be good enough as long as it's not too small for you to measure the current accurately.

One further note: With a supply of 13.5V you will never get the battery to 13V. You have a diode in there with a 0.6V drop so the highest you could get is 12.9V. On the plus side this means you can keep charging until the current drops to 0 with no risk of overcharging.
Or alternatively switch D1 for a schottky diode with a drop of around 0.2V


Standalone Arduino with ATMEGA328P / Serial working, but serial programming not (only once after buning bootloader) For my master thesis I've designed a board with an ATMEGA328P-AU as micro controller.

As I want to use some libraries and I like the simplicity, I want to use "Arduino" to program it.
Everything works fine to a point:
I took an Arduino Uno and uploaded the "ArduinoISP" sketch.
I connected the ISP pins and burned the bootloader with board set to "Arduino Duemilanove / Diecimila" - got the message, bootloader burned.
I disconnected the ISP pins, took the ATMEGA out of its socket on the UNO board and connected the serial pins.
Here comes the problem I cant figure out:
Once I have done a above procedure I can upload a sketch and Serial communication is working. But I can only upload it once! The second time (no matter if during the same power-up or at another time) I push the upload sketch button, I get no response for several minutes (I once waited up to 10min to confirm there is nothing coming anymore :)). If I unplug either USB or the TX/RX cables I get the error (or for the USB cable something similar):

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

When I upload the bootloader again I can once again upload a sketch same as before. Then the same problem happens again.
I checked several question on Stackexchange already (specially all points in this one here) and googled the problem, but until now I am not able to find a solution.
As you can imagine it is quite annoying to always unplug the RX/TX cable and hook up the ISP cable again and burn the bootloader.
So my question: What could cause this problem and how can I solve it?
Btw. I am using the Arduino software version I'm using is 1.6.9

There is a problem with your circuit and the way you have it wired when programming. You have failed to use the RTS line for Serial programming. You need to have that line connected to the RESET of the ATMega328, this is as the bootloader for programming ove rserial will not start if the IC is not reset. Also you should burn the Arduino UNO bootloader rather than the one you chosen.

Seems you clarified you were using the diode as ESD protection, thank you. It is the recommended arrangement if you have a capacitor attached to the reset line in noisy environments.

The circuit between the RTS signal and the Arduino RESET pin needs to be this:

            C
 RTS >>----||------->> RESET(PIN1)
           0.1µF

From the same "Have I bricked my Arduino" that you linked, about 3/4 down Nicks post he mentions the use of serial programming of an Arduino

FTDI    Arduino Uno

GND       GND  (black wire on FTDI cable, blue jumper wire)
CTS       not connected
VCC       5V
TxD       D0 (RX)
RxD       D1 (TX)
RTS       To RESET with a 0.1 µF capacitor in series with it (green wire)

What you can do if you don't have the proper serial programmer with an RTS output, you will have to manually reset the microcontroller to enter the bootloader just as the IDE says "Uploading...".


Advanced Arduino Project Help So, I am an Engineer working on a very time tight project.

I want to create a system capable of collecting data from a Photodiode and compiling it in a way that will separate data into four columns which correspond to colours (red, green, blue, yellow) the columns will have rows of data corresponding to a number.

I have elected to use Arduino for this project but need some help on what to get and whether this is possible or not... I have an intermediate knowledge of C, C++ and previous Arduino experience, but have never undertaken something like this.

The project is envisaged to look like this.

Hardware:

Photodiode with RS232-C connection
An Arduino (Which sort is best? now I have Uno and Mega but can purchase others should these not be sufficient for the project)
Touchscreen Interface
Storage capacity (SD card or email/Bluetooth capability or something alike to collect the data to edit on PC).

The Process should is like this: Input = User interacting with GUI on Touchscreen - First page will have Four Colours Available (Once one of these inputs selected let’s say Red, jump to next page) -> Page two will have a Touch Number Pad Input (User selects number, let's say 2 in this case and hits enter), For less complexity this could be on one page correct? ->
The Data will then be read off a Photodiode communicating via RS232-C to Arduino and stored in a .csv or something similar under its previously selected values (Red, 2, Photodiode Value)

Output: A compiled list of all the data collected under their relative user inputs.

I currently have these items but am happy to purchase others.

S130C Thorlabs Photodiode Sensor
Null Modem Cable (Pins are swapped on S130C)
RS232 Shield (DFRobot RS232 Shield V0.1)
Arduino Uno, Arduino Mega
TouchScreen (Duinotech 2.8” TFT LCD)

After re-reading what I wrote I suppose there are a few:

Could I complete this project using Uno and Mega?
Is there a method for compiling data and storing/sending using Arduino?
What are the capabilities of Arduino? Could a project of this complexity be done using Arduino components or is there another microprocessor or microcomputer which would be a better choice for this project?

Your question is incredibly broad. However:

1. Could I complete this project using Uno and Mega?

Yes, almost certainly

2. Is there a method for compiling data and storing/sending using Arduino?

What? Yes, you can store data onto an SD card using a simple level-shifting piece of hardware like this:

3. What are the capabilities of Arduino?

This isn't a reasonable question (it's too broad). I suggest Googling for things people have done. For myself, I made a humidity and temperature sensor using the same processor as in a Uno. It also runs from batteries.

  ... a very time tight project ...

Time is going to be your enemy here. Learning how to drive a touchscreen, save files to an SD card, interpret RS232 data from your sensor, and make it all work reliably is not the sort of thing you will do in 3 days.

Even if you dumped all your hardware on my desk (and I know how to program Arduinos) I would estimate two or three weeks to calmly get each part going individually and then interface them all together.

  Would you suggest using breakout boards over shields?

Shields are well and good if they do what you want them to do. A breakout board will have more flexibility.

  because of pin availability would you suggest trying to use the Mega rather than Uno?

Depends how many pins you need. If you use SPI or I2C you can (probably) drive your display with only a handful of pins.

The Uno will probably have enough, and it has the flexibility that you can easily replace the processor chip if you damage it. You can't do that to the Mega. Plus, more code is written for the Uno so you are more likely to find libraries that work "out of the box" for a Uno.

I wouldn't be getting the "more powerful" device unless you have identified a specific reason to have it. For example, some of the faster and more powerful Arduinos (and other boards) with ARM processors may well do more under certain circumstances, but be somewhat harder to use.


Shrink array to save memory In my project I need three arrays to store data inside.

I define a maximal number of elements as a macro variable. However, at a certain point in the setup function, the program could determine, that the arrays would actually store a smaller number of elements. In other words, it is possible (and even likely) that there is more memory reserved for the arrays than actually necessary.

As I think that memory might be a critical factor on a micro controller like the Arduino, I would like to set the excess memory free.

Is there a way to dynamically resize and shrink the arrays at runtime?

Something like this (pseudocode)

#define maxSize 50
int theArray[maxSize];

int actualSize = getActualArraySize();
// sets actualSize to a value <= 50, let's assume actualSize = 20
shrinkArray(theArray, actualSize);
// shrinkArray doesn't exist :) I need something like that.

This is a common question when designing software. The simple answer (rule of thumb) is statically allocate the maximum size of the array. In this case the maximum size of the arrays. This simple rule will keep you out of trouble and make testing etc much simpler.

Using dynamic allocation (adjusting array size etc) especially for small scale embedded systems such as the Arduino opens a "can of worms" with possible memory (heap) fragmentation and hidden concurrency and performance issues.

If the required maximum size of the array is 32 elements the application has to allow that and there is no memory to save. Statically allocating will make the sketch simpler and easier to test.

Cheers!


Regulation of the temperature using PID I'm making a control system for the heating of a plate using a PID control.

the goal is to regulate the temperature of the plate by changing the power dissipated by the resistance. By using a sensor I read the temperature  of the plate and is then used as the input in the PID control.
I programmed also a signal wave square for the PWM.

but the thing I don't understand is what I'm exactly supposed to do with the output signal I receive.
and I cannot connect between the PWM and the PID.

Code of the square signal:

void setup()
{
  pinMode(9, OUTPUT);
}
void loop()
{
   // phase haute
   digitalWrite(9,HIGH);
   delay(30);
   // phase basse
   digitalWrite(9,LOW);
   delay(70);
   //ton+toff = 0.1;
//   ton = 0.1*Output;
}

Code of PID and the sensor

/********************************************************
 * PID Basic Example
 * Reading analog input 0 to control analog PWM output 3
 ********************************************************/

#include <PID_v1.h>

int val;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);

void setup()
{
  Serial.begin(9600);
  //initialize the variables we're linked to
  Input = analogRead(1);
  Setpoint = 37; //temperature a reguler

  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}

void loop()
{
  val = analogRead(1);
  float mv = ( val/1024.0)*5000;
  float Input = mv/10;
  myPID.Compute();
  analogWrite(3,Output);
  Serial.print("input temperature is :");
  Serial.println(Input);
  delay (1000);
//  delay(1000);
  Serial.print("output is :");
  Serial.println(Output);
  delay(1000);
}

Thank you in advance

A PID only has one input and one output. In your case, the input will be the temperature. The use of the arduino would be to process the raw data of the temperature sensor and relay the temperature to the PID. Depending on the make and model of the PID, there could be certain transfer protocols you must adhere to. There are most likely open source libraries that will take care of transferring the data properly.

Your PID is the piece of hardware that will "decide" when it is appropriate to turn the heater on and off, therefore it shall be responsible for driving the heater. That is what the output of the PID is responsible for.

Lastly, your PID has a set point. In your case, the set point would be the desired max temperature of the plate. This set point is set and altered manually through user input.

On a side note, if this is a personal project or a non deliverable, I'd recommend not using a PID. Try processing and analyzing all of the data exclusively on the Arduino, as it would be a challenging and rewarding task.


bitRead() gives wrong answer Arduino UNO R3 I am trying to read from a quadrature rotary encoder using an Arduino UNO R3. This is done by connecting the encoder's channel A pin to the Arduino interrupt 0 pin (digital IO pin 2). Inside the interrupt routine I then read the value of channel B (connected to digital IO pin 8) to determine the direction of rotation.

I am able to read the correct value of channel B using the digitalRead() function, but when I use bitRead() it always gives me a 0. As far as I know digital IO pin 8 is mapped to PORTB bit 0, so I am using bitRead(PORTB, 0) to read the bit. I also tried to read all of the other pins, but all of them show 0, except the LED at pin 13, which shows 0s and 1s when it gets toggled (It is also the only pin defined to be an OUTPUT pin, whereas the encoder uses INPUT pins).

Below is my code:

int channelA = 0;
int channelB = 8;
volatile int rotateNumber = 0;
volatile boolean interrupted = false;

void setup() {

    Serial.begin(115200);

    attachInterrupt(channelA, rotate, RISING);
    pinMode(channelB, INPUT);
}

void loop() {
   if(interrupted){
       Serial.println(rotateNumber)
       interrupted = false;
   }
}

void rotate(){
  if(bitRead(PORTB, 0) == 1)
     rotateNumber++;
  else
     rotateNumber--;

  interrupted = true;
}

PORTx is the latched value last written there. The external value is found in PINx.


How to fade in and fade out led strip connected to arduino based on continous analog input from capacitative sensor? So I've been trying to get a capacitive sensor made from aluminum foil to work. And I have had success the kind of proximity and readings I need to light up a single LED and produce basic tone. Using this very basic code :

{
  Serial.println(value1);//value that i get from analog sensor
  //this is just to get the values in order for the led and sound
  if (value1<=8) value1=-100;
  analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
  tone(tonepin,value1+100,100);
  delay(10);

All this works perfectly for me, the delay isn't perceivable, the response is for all practical purposes simultaneous to input. Except it's not beautiful, because the LED keeps flickering when values reduce or increase because the jumps are sudden I suppose.

SO I thought I'll try to fade in and fade out to different values from present values.  Used the fading examples. Here:

Serial.println(value1);
  if (value1<=8) value1=-100;

  if (value1+100<=value2+100) {
    for(int fadeValue = value2+100 ; fadeValue <= value1+100; fadeValue +=5) {

    analogWrite(ledPin, fadeValue);

    delay(10);
    }
  }

  else
  {

    for(int fadeValue = value2+100 ; fadeValue >= value1+100; fadeValue -=5)
    {
        analogWrite(ledPin, fadeValue);

    delay(10);
    }
  }
  //analogWrite(ledPin,value1+100);
  tone(tonepin,value1+100,100);
  delay(10);
  value2=value1;

But this takes away the responsiveness, the whole thing is so slow to react, the sound and the light are obviously not in sync as I read my code. But also the light is not really fading, still blinking, but there seems to be some effect but I am not sure.

Any help with what I could do and what I am doing wrong would be nice.

Smooth the change in output value by taking, e.g 10% of the new value, and 90% of the old value. You can try experimenting with different ratios and longer/shorter delays.

int lastValue = 0;

{
  Serial.println(value1);//value that i get from analog sensor
  //this is just to get the values in order for the led and sound
  if (value1<=8) value1=-100;
  value1 = (1*value + 9*lastValue)/10;// smooth the change in value by taking 10% of the current value, and 90% of the previous value
  analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
  tone(tonepin,value1+100,100);
  lastValue = value1;
  delay(10);


How to build an µC controlled power regulator? The idea: Use an Arduino-like µC to control a set of CPU fans by control the voltage the CPU fans receive. My question: How can I do this in an easy way?

Yes, I know, there is PWM but this is not very suitable for this purpose: I did some tests with it but it turns out that the characteristics of PWM fans don't suite my purpose: PWM fans are designed to be controlled between not audible and full speed, not between nearly not rotating and full speed. Even very special fans with a wide range of PWM speed control don't work as well as powering a regular 12V fan with just 5 or 6V.

Which brings me to an alternative idea: It should be possible to send an I2C or SPI signal to some kind of IC that then provides a voltage as required.

Alternatively to that there seem to be PWM controlled voltage regulators available. But that doesn't seem to be a very elegant solution, isn't it?

Or is there an even better way of controlling the voltage output to the fans I'm not aware of?

I'm aiming for a solution that works well and can be build with little effort. Unfortunately I don't know how to do that: I can't find any breakouts I could use right away for that purpose. Probably there are some and I just have not been able to find them? Any help is appreciated!

It's actually very simple, and it indeed does involve using PWM.

PWM is just a signal being on for a percentage of a predefined period.  That percentage is also, when the PWM signal is averaged out, equivalent to a percentage of the peak voltage of the PWM signal.

So if you take a PWM signal and use it to switch a higher power source (say, through a P-channel MOSFET that's being itself switched by an N-channel MOSFET), then add smoothing to that switched output, and you have a variable voltage.

If you want to know what that voltage is you can add a resistor network to the output (assuming it's higher than the voltage the MCU can handle) and read the divided voltage using an ADC.  You can then use that as a feedback loop to adjust the PWM duty cycle to get your desired voltage.

simulate this circuit – Schematic created using CircuitLab

That is precisely* how switch-mode power supplies work. Use PWM to switch a FET that controls an incoming voltage, then smooth it out, adding a feedback network for control.

*Apart from the PWM bit: they often use other methods of switching the signal to get better efficiency at different loads, such as PFM.


Management issues through Blynk I wrote a sketch for controlling the stepper motor under the controls of the Blynk application, the sketch was compiled but there was a problem in that no control was taking place. Receipts and controls occur on virtual pins V1, V2, V3. (The problem is that nothing is controlled), please help solve the problem.

//#include <Stepper.h>
//#define BLYNK_WRITE
//#include <ESP8266WiFi.h>
//#include <BlynkSimpleEsp8266.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor
Stepper myStepper(stepsPerRevolution, 1, 2, 3, 4);

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "[private]";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "S30mini";
char pass[] = "12345678";

int pinData;
int pinData1;
int pinData2;
BLYNK_WRITE(V3) //Button Widget is writing to pin V1
{
  int pinData = param.asInt();
 }
BLYNK_WRITE(V2) //Button Widget is writing to pin V1
{
  int pinData1 = param.asInt();
 }
BLYNK_WRITE(V1) //Button Widget is writing to pin V1
{
  int pinData2 = param.asInt();
 }

void setup()
{
  // Debug console
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
}

void loop()
{
    Blynk.run();

  // map it to a range from 0 to 100:
  int motorSpeed = map(pinData, 0, 1023, 0, 100);
  // set the motor speed:
  if (motorSpeed > 0) {
    myStepper.setSpeed(motorSpeed);
    // step 1/100 of a revolution:
    myStepper.step(stepsPerRevolution / 100);
  }

   if (pinData1 == 1){
      myStepper.step(stepsPerRevolution);
   }

   if (pinData2 == 1){
     myStepper.step(-stepsPerRevolution);
    }

}

By prefixing your pinData variables with int, you are declaring local variables in your BLYNK_WRITE() functions, whose scope is only in that function. The local version is written to, instead of the global.

To fix this, do not declare a new variable in BLYNK_WRITE():

BLYNK_WRITE(V3) //Button Widget is writing to pin V1
{
  pinData = param.asInt();
}
BLYNK_WRITE(V2) //Button Widget is writing to pin V1
{
  pinData1 = param.asInt();
}
BLYNK_WRITE(V1) //Button Widget is writing to pin V1
{
  pinData2 = param.asInt();
}


How to burn a firmware to ESP32 Devkit V1 by using MacBook Pro with USB Type C Adapter? I need to burn a firmware into the ESP32 Devkit V1 by using the MacBook Pro running macOS Catalina with USB type C port only. I get the USB type C to type A adapter with data transfer/sync and connect the ESP32 board to my MacBook by using it.

By following the online tutorial, I install the CP210x USB to UART Bridge VCP Drivers from "https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers".

Both v4 and v5 versions have been tried but still can't see the expected port by inputting "ls /dev/cu.*" in terminal. Only "/dev/cu.Bluetooth-Incoming-Port" can be seen. What is the problem?

My problem is solved. Finally, I found out my Micro-USB cable doesn't support date transfer/sync function.


Arduino Due: ADC gain adjustment problem I want to increase gain of the ADC channel. To achieve this I'm using adc_set_channel_input_gain function from adc.h. Here is the entire sketch:

const byte aPin = A6;

void setup() {
  analogReadResolution(12);

  // Configure ADC gain
  // Arduino/hardware/arduino/sam/system/libsam/include/adc.h
  adc_channel_num_t ch = (adc_channel_num_t)(g_APinDescription[aPin].ulADCChannelNumber);
  adc_set_channel_input_gain(ADC, ch, ADC_GAINVALUE_3);
  Serial.begin(9600);

  // Delay for serial stabilization
  Serial.println("Begin.");
  delay(2000);
}

void loop() {
  int analog = analogRead(aPin);
  Serial.println(analog);
  delay(500);
}

The problem is that output values are not depending on the gain value.

Well, the solution was very simple. We just need to call adc_enable_anch() before changing gain or offset of the ADC. I improved my setup and the sketch works as expected now:

void setup() {
  analogReadResolution(12);

  // Configure ADC gain
  // Arduino/hardware/arduino/sam/system/libsam/include/adc.h
  adc_channel_num_t ch = (adc_channel_num_t)(g_APinDescription[aPin].ulADCChannelNumber);
  adc_enable_anch(ADC);
  adc_set_channel_input_gain(ADC, ch, ADC_GAINVALUE_3);

  Serial.begin(9600);

  // Delay for serial stabilization
  Serial.println("Begin.");
  delay(2000);
}


How to read data from PC I'm new to Arduino.

I'm passing some data from my Android phone to my Macbook via bluetooth (throught the app Sensoduino).

What I'd like to do now is to export that data to my Arduino Mini Pro.

Is there any way to achieve it?

(NOTE: I'm not able to connect my Android Phone directly to the Arduino via Sensoduino)

A simple bluetooth module like a HC-05 wired to your Arduino will give you a  serial stream that can be read and/or written.

With the RX/TX connected to say pins 10 & 11, a SoftwareSerial() object will provide access:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

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

void loop()
{
    int value;

    if (mySerial.available(sizeof(int)))
    {
        value = mySerial.parseInt();
    }
}

If you connect the module to pins 0 & 1 - you can just use the Arduino standard Serial functions, but it will cause problems uploading to the board.  In which case you would disconnect the bluetooth module for uploading.


Ping a sensor for error checking Is it possible to ping a sensor, like DHT22 or 18B20, to check for connection. I want to do an error check in void setup() and make sure all sensors are connected properly.

There is no simple "yes" or "no" answer to this.

You need to check the datasheets and libraries for your chosen devices and see what is available.  Many libraries will have begin() function, which may, or may not, return whether the device is working.

Many may just lock up waiting for communication, and there's not a lot you can do with that short of reprogramming the library to work differently.

Some (especially analog sensors) will return values from their reading functions that are far outside a tolerable range that you could assume indicated a malfunction.

For I2C based sensors you could use a variant of the I2CScanner sketch to look at what addresses are in use before attempting to use the sensors themselves.

Other protocols may have a similar system you can use to examine what is on the bus.


Problem with fading LEDs I got a breadboard with 10 LEDs, 4 of them fade, to be specific:
3, 5, 6 and 9 are working. 0, 1, 2, 4, 7, 8 are not working.

I'm using LEDs and resistors on all spots, they're all the same. Tried changing things around but the problem doesn't seem to be the resistors or the LEDs.

I'm using the following code (I'll highlight the parts for the fading, by marking it between //** comments).

Does anyone know a way to fix this? Or see any problem?

const int inButton = 13;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
int delayTime = 100;
int brightness = 0;
int fadeAmount = 5;

void setup() {
  //**
  pinMode(inButton, INPUT);
  for (int out = 0; out < 10; out++){
    pinMode(out, OUTPUT);
  }
  //**

  pinMode(testLed, OUTPUT);
}

void loop() {
  buttonState = digitalRead(inButton);
  if (buttonState != lastButtonState){
    if (buttonState == 1){
      buttonPushCounter++;
    }
  }

  lastButtonState = buttonState;

  if (buttonPushCounter % 5 == 0){
    for (int i = 0; i < 10; i++){
      digitalWrite(i, 1);
      delay(delayTime / 2);
      digitalWrite(i, 0);
    }
  }
  else if (buttonPushCounter % 5 == 1){
    for (int i = 0, j = 9; i < 10, j >= 0; i++, j--){
      digitalWrite (i, 1);
      digitalWrite (j, 1);
      delay(delayTime / 2);
      digitalWrite (i, 0);
      digitalWrite (j, 0);
    }
  }
  else if (buttonPushCounter % 5 == 2){
    for (int i = 0; i < 10; i+=2){
      digitalWrite(i, 1);
    }
    delay(delayTime);
    for (int i = 0; i < 10; i+=2){
      digitalWrite(i, 0);
    }
    delay(delayTime);
    for (int i = 1; i < 10; i+=2){
      digitalWrite(i, 1);
    }
    delay(delayTime);
    for (int i = 1; i < 10; i+=2){
      digitalWrite(i, 0);
    }
  }
  else if (buttonPushCounter % 5 == 3){
    for (int i = 0 ; i < 10 ; i++){
      analogWrite(i, brightness);
    }
    brightness = brightness + fadeAmount;
    if (brightness == 0 || brightness == 255){
      fadeAmount = -fadeAmount;
    }
    delay(25);
  }
  else {
    int R1 = random(10);
    int R2 = random(10);
    int R3 = random(10);
    int R4 = random(10);
    digitalWrite(R1, 1);
    digitalWrite(R2, 1);
    digitalWrite(R3, 1);
    digitalWrite(R4, 1);
    delay(delayTime);
    digitalWrite(R1, 0);
    digitalWrite(R2, 0);
    digitalWrite(R3, 0);
    digitalWrite(R4, 0);
  }
}

Only pins that support PWM support analogWrite() fully. 3, 5, 6, 9, 10, and 11 do. The rest do not.


Arduino metronome - Change time signature on button press /**************************************/
const int lowestPin = 1;//the lowest one attach to
const int speaker = 13;
int ts = 4;//how many beats you want
int count = 1;
const int keyPin = 12;
int buttonState = 0;
int bpm = 120;
/**************************************/
void setup()
{
  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {
    pinMode(thisPin, OUTPUT); //initialize thisPin as an output
    pinMode(6, INPUT);

  }
  pinMode(keyPin, INPUT);
}

/****************************************/
void loop()
{

  //iterate over the pins
  //turn the led on from lowest to the highest

  if (digitalRead(keyPin) == HIGH && ts == 2) {
    ts = 3;
    delay(2000);
  }

  else if (digitalRead(keyPin) == HIGH && ts == 3) {
    ts = 4;
    delay(2000);
  }

  else if (digitalRead(keyPin) == HIGH && ts == 4)
  {
    ts = 2;
    delay(2000);
  }

  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {

    bpm = pulseIn(6, HIGH);

    pinMode(13, OUTPUT);
    if (ts > 4)
    {
      if (count > 3)
        for (int a = 4; a <= ts; a++) {
          digitalWrite(a - 3, HIGH);
        }

    }
    else
      digitalWrite(thisPin, HIGH);

    if (count == 1)
      tone(13, 1500, 100);
    else
      tone(13, 1000, 100);

    delay(bpm - 52);
    pinMode(13, INPUT);
    digitalWrite(thisPin, LOW);

    count++;
    if (count > ts)
      count = 1;

  }

}

I am trying to make a metronome using Arduino Uno, with 4 LEDs, each LED is a beat. I want to change the time signature every time I press the pushbutton, so that there are different number of beats per measure, but when I do press the button, it runs the code for 2 and 3 beats per measure once, and then goes back to its default, 4 beats per measure.

Sometimes, it even changes without pressing the button, randomly. I am using a 220 ohm resister instead of 10, as 10 starts much more randomly than the 220.

You must have resistors in series with the LEDs. See The care and feeding of LEDs. 330 ohms in series with each LED would be about right in your situation.

With no resistors you are drawing far too much current from the output pins. That would drop the voltage and the processor would reset. Thus it goes back to the default of 4 beats per measure.

It also damages both the processor and the LEDs.

You can tell if the processor resets by putting extra code into setup. For example, after setting the pins to outputs:

 for (int i = 0; i < 10; i++)
    {
    digitalWrite (3, HIGH);
    delay (200);
    digitalWrite (3, LOW);
    delay (200);
    }

If you see pin 3 flashing 10 times, you know the processor has reset.

I think your problem now is that you have a floating input for the switch. When I tried your sketch, with a couple of modifications, it worked fine.

My code:

/**************************************/
const int lowestPin = 1;//the lowest one attach to
const int speaker = 13;
int ts = 4;//how many beats you want
int count = 1;
const int keyPin = 12;
int buttonState = 0;
int bpm = 120;
/**************************************/
void setup()
{
  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {
    pinMode(thisPin, OUTPUT); //initialize thisPin as an output
    pinMode(6, INPUT);
  }
  pinMode(keyPin, INPUT_PULLUP);
}

/****************************************/
void loop()
{

  //iterate over the pins
  //turn the led on from lowest to the highest

  if (digitalRead(keyPin) == LOW && ts == 2) {
    ts = 3;
    delay(2000);
  }

  else if (digitalRead(keyPin) == LOW && ts == 3) {
    ts = 4;
    delay(2000);
  }

  else if (digitalRead(keyPin) == LOW && ts == 4)
  {
    ts = 2;
    delay(2000);
  }

  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {

    bpm = pulseIn(6, HIGH);
    //bpm = 1000;

    pinMode(speaker, OUTPUT);
    if (ts > 4)
    {
      if (count > 3)
        for (int a = 4; a <= ts; a++) {
          digitalWrite(a - 3, HIGH);
        }
    }
    else
      digitalWrite(thisPin, HIGH);

    if (count == 1)
      tone(speaker, 1500, 100);
    else
      tone(speaker, 1000, 100);

    unsigned long now = millis ();
    while (millis () - now < (bpm - 52))
      {
      // quit delay if switch pressed
      if (digitalRead(keyPin) == LOW)
        break;
      }

    pinMode(speaker, INPUT);
    digitalWrite(thisPin, LOW);

    count++;
    if (count > ts)
      count = 1;

  } // end of for each pin

} // end of loop

Note that the input from the switch is now INPUT_PULLUP which means it is pulled HIGH by an internal resistor. Thus, the tests are now for == LOW rather than == HIGH.

Also, instead of a delay for the timing of the metronome, I changed it to testing millis() and seeing if time is up. Otherwise you have to hold the switch down for the entire time that a cycle repeats.


RFID-RC522 not working, red led is on I am working with RFID-RC522 and Arduino UNO. I have check pin configurations again and again tried different libraries. It is not reading card and red led on RC522 is consistently on.

Here's a picture of the card reader I have. If yours looks identical, then this library should work: https://github.com/ljos/MFRC522

The auth_read_write.ino sketch worked for me. Before you install the library, I recommend removing any other MFRC522 libraries from your arduino/library folder.

The only thing I did differently was used a 74HC4050 running at 3.3V between the Arduino and card reader. Some people claim you can connect the reader directly to the Arduino. I didn't want to take a chance of burning out the card reader so I used the 74HC4050.

Here's how I connected it:

Component markings and connections

|-------------------------------------------|
|   SPI    |  UNO  | 74HC4050  | RFID-RC522 |
|----------|-------|-----------|------------|
| SDA (SS) |  10   |     7     |            |
| SDA (SS) |       |     6     |    SDA     |
| SCK      |  13   |     5     |            |
| SCK      |       |     4     |    SCK     |
| MOSI     |  11   |     3     |            |
| MOSI     |       |     2     |    MOSI    |
| MISO     |  12   |           |    MISO    |
| IRQ      |  N/C  |    N/C    |    N/C     |
| GND      |  GND  | 8,9,11,14 |    GND     |
| RST      |   5   |           |    RST     |
| 3.3V     |       |     1     |    3.3V    |
|-------------------------------------------|


Problem with running 2 DC motors with ultrasonic sensor I'm not expert in electrical circuits, maybe I am making a very simple mistake or missing some basic points with my circuit.

What I'm trying to achieve is simple, to run 2 DC motors with an ultrasonic sensor to detect obstacles and change direction. When I unplug the ultrasonic sensor everything is working fine as expected without obstacle detection but when I connect the ultrasonic sensor, sensor always responds with 0 cm distance. Then I removed 9 V battery from the circuit and plug Arduino to computer via USB, sensor works fine but motors are not working properly, it looks like the power from USB is not enough to drive motors at the same time. I've added my circuit scheme below:

How (acoustically) loud are the motors?  If they're the typical RC car motors, they can screech harmonics right up into the 40 KHz range typical of ultrasound ranging sensors, interfering with the sensor's ability to work at all.

How (electrically) loud are the motors?  If RC as above, they throw all sorts of transients onto the power lines (and everything else within electrical pickup range).  You might want to put some ceramic capacitors across the motor leads to absorb some of those transients.

Kudos for the suggestions to provide separate power supplies for the motors and the Arduino / sensor combination.  I'd go even further, and provide separate power for all three, and use opto-isolators for the connection between the ultrasound and the Arduino.

Some years ago I used two Novak Super-Rooster motor drivers for a battle-bot competition.  They were driven by PWM outputs of an Arduino, where 50% duty cycle was off, 0% was full speed reverse, and 100% was full speed ahead.  These were powered by a sealed lead acid battery, and driven full-out, the motors got +/- 12VDC at about 40 amps.  There was a common ground with the Arduino, going to the Super Roosters, but not the motors, and the drivers took care of the electrical shielding, with a little help from the ceramic bypass capacitors I mentioned.  Worked great!


OnKeyPress in a arduino So, I have 3 buttons to a arduino.
I want to detect the button press on the 3 of them.

For that, i've created a function:

int OnKeyPress (int port) {

  int  LastState, BeginState, r;
  r = 0;

  BeginState = digitalRead(port);

  if (BeginState != LastState) {
      if (BeginState == 1) r = 1 ;
  }

  delay(5);
  LastState = BeginState;
  return r;
}

I want to instantiate 3 instances of this code, separately and they have to retain this variables int  LastState, BeginState, r; for each button, and the next time the function runs on the loop, the variables are the same of when they ran last time.

Just, how?

This is an ordinary method (function) which can not be instantiated. It is necessary to write a class with 1 or more methods in it in order to instantiate multiple copies of that class and the method(s) with in that class.

The integers "LastState", "BeginState" and "r" only have scope within the method and will not survive after returning from the method.  There are several approaches to preserve these variables from one call to the next.  They can be declared as static integers.  Or they can be defined globally.

It appears you are recreating the existing Bounce library.  I encourage you to continue if you are learning.  However, you may want to look at the Bounce library's code for guidance.


How to read RPS for fast rotation with status change method in Arduino? I'm trying to calculate the coming RPS from rotary encoder. I am  trying to get it by checking the status with digitalRead. However, I can not get more than 6 RPS. Any solution? I will be obliged for your help.
Following is the code.

float rps;

void setup() {
  Serial.begin(9600);
  DDRC &= ~_BV (1); // pinMode (A1, INPUT);
}

void loop() {
  static int lastReedState;
  static unsigned long lastTransition;
  int reedState = (PINC & _BV (1)) == 0; // digitalRead (A1);
  // On a rising transition of the reed switch:
  if (reedState == LOW && lastReedState == HIGH) {
    // HIGH LOW measuring the low period
    // Compute time since last valid transition.
    unsigned long now = micros();
    unsigned long revolutionTime = now - lastTransition;
    // measuring the High period
    // Compute the RPS
    rps = 1.00 / (12.00*revolutionTime) *1000000.00;
    // 12 is rotary encoders resolution
    // Remember this transition.
    lastTransition = now;
  }
  // Remember last state.
  lastReedState = reedState;
  Serial.println(rps);
}

For one channel I'd use Input Capture capability on Timer/Counter 1. Without debouncing it'll be pretty easy.

If you want to read 8 inputs simultaneously, you can use Pin Change interrupts and Timer/Counter 1 as a timebase. If you don't use Serial communication, you can use whole PORTD, otherwise you can use for example 4 channels on PORTC and 4 channels on PORTD. But again, debouncing will be little bit challenging.


Arduino IDE monitor multiple USB ports simultaneously Is it possible to monitor multiple USB ports simultaneously in Arduino IDE while running only ONE instance of the IDE?

If not, which solutions come alternatively to mind?

If you are only interested in monitoring the output, a simply python script can be run to monitor the port. This sample takes an input of the port number(assuming they get named ttyUSB1, ttyUSB2, ect...  Or you can modify it to be a hard coded port.  Also make sure the baud rate matches with what your arduino is running (115200 in the example)

You can then run this script in two separate terminals, one for each port

#!/usr/bin/env python3

import serial
import sys

if len(sys.argv)<2:
    print("Please give serial port number")
    exit()
port=sys.argv[1]
ser= serial.Serial('/dev/ttyUSB'+port,115200,timeout=5)

while True:
    try:
        print(str(ser.readline().strip()))
    except:
        print(sys.exc_info())
        ser.close()
        exit()

Start the program like so

python3 ./programName.py 1 (or ./programName.py 0, etc)

The number dictates which of the ttyUSBx devices you are trying to watch (will match with what you see in the arduino IDE).


Arduino UNO capacitive sensor not working This is a visualization of my Arduino connections:

I wish to read the data using the Capacitive sensor Library. iv'e tried the following code but variables total1, total2, total3 always have the value 0 and i don't know what is wrong.

My code:

// Import the CapacitiveSensor Library.
#include <CapacitiveSensor.h>

// Name the pin as led.
#define speaker 11

// Set the Send Pin & Receive Pin.
CapacitiveSensor   cs_2_3 = CapacitiveSensor(2,3);        // 10M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4);        // 10M resistor between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_5 = CapacitiveSensor(2,5);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_6 = CapacitiveSensor(2,6);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_7 = CapacitiveSensor(2,7);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_8 = CapacitiveSensor(2,8);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_9 = CapacitiveSensor(2,9);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil

void setup()
{
  cs_2_3.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example

  // Arduino start communicate with computer.
  Serial.begin(9600);
}

void loop()
{
  // Set a timer.
  long start = millis();

  // Set the sensitivity of the sensors.
  long total1 =  cs_2_3.capacitiveSensor(60);
  long total2 =  cs_2_4.capacitiveSensor(60);
  long total3 =  cs_2_5.capacitiveSensor(60);
 /* long total4 =  cs_2_6.capacitiveSensor(60);
  long total5 =  cs_2_7.capacitiveSensor(60);
  long total6 =  cs_2_8.capacitiveSensor(60);
  long total7 =  cs_2_9.capacitiveSensor(60);*/

  Serial.print(millis() - start);        // check on performance in milliseconds
  Serial.print("\t");                    // tab character for debug windown spacing

  Serial.print(total1);                  // print sensor output 1
  Serial.print("\t");                    // Leave some space before print the next output
  Serial.print(total2);                  // print sensor output 2
  Serial.print("\t");                    // Leave some space before print the next output
  Serial.print(total3);                  // print sensor output 3
  Serial.print("\t");                    // Leave some space before print the next output
  Serial.print("\n");
}

As found on the Capacitative Sensor Library page (emphasis added):

  Use a 1 megohm resistor (or less maybe) for absolute touch to activate.
  With a 10 megohm resistor the sensor will start to respond 4-6 inches away.
  With a 40 megohm resistor the sensor will start to respond 12-24 inches away (dependent on the foil size). Common resistor sizes usually end at 10 megohm so you may have to solder four 10 megohm resistors end to end.
  One tradeoff with larger resistors is that the sensor's increased sensitivity means that it is slower. Also if the sensor is exposed metal, it is possible that the send pin will never be able to force a change in the receive (sensor) pin, and the sensor will timeout.
  Also experiment with small capacitors (100 pF - .01 uF) to ground, on the sense pin. They improve stability of the sensor.

The two emboldened points suggest that for a touch-piano, it would likely be advantageous to use a lower value resistor such as 1MΩ. Because the sensitivity increases as the resistor value increases, you want to use the lowest possible resistor value to reduce jitter & interference among your signal wires.

Also, later on the page:

  The grounding of the Arduino board is very important in capacitive sensing. The board needs to have some connection to ground, even if this is not a low-impedance path such as a wire attached to a water pipe.

Ensure the Arduino is not run from a battery or unplugged laptop. For capacitative sensing to work, a stable ground connection is needed (via a DC plugpack or USB wall-wart is fine).

As a general note, try testing with only one capacitative connection first, then when that works, re-add the others.


A question on physical locations of the registers in ATmega328P When I read about registers I always encounter the following illustration:

So there are 32 registers in the above diagram. They are processor registers.

But in the data-sheet of ATmega328P at page 428 there is a section called "Register Summary".

Here in that list there are much more than 32 registers. Do the rest of the registers physically stay somewhere else?

Lest's take an example of ADMUX register. Where is that register physically inside the DIP? It is not one of the 32 registers? And if stays somewhere else how does it connected to the ALU?

You are confusing CPU registers and SFRs, Special Function Registers.

CPU registers only exist within the CPU core. SFRs exist within the RAM bus's memory map.

CPU registers are used by the CPU to execute instructions and do calculations, etc. SFRs are a part of the logic of the rest of the chip and directly affect the working of the various peripherals.

As far as the CPU is concerned an SFR is just a bit of SRAM, but it affects physical workings when written to, and reflects physical states when read from.


How do I know the IP address assigned to an ESP8266? I have programmed an ESP8266 using the circuit and program below. I tried to open the SerialMonitor once the program is uploaded to the ESP8266. I am getting an error when I am trying to open the SerialMonitor.

  Error opening serial port 'COM5'. (Incorrect serial port)

What is the way to get the IP address assigned to the ESP8266?

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

//SSID and Password of your wifi router
const char* ssid = "Moto";
const char* password = "reset1234";

ESP8266WebServer server(80);

void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid, password); //Connect to your WiFi router
  Serial.println("");
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
  server.begin(); //Start server
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient(); //Handle client requests
}

If you give your board a name with

WiFi.hostname("MyESP8266");

(for example) you can then look on your router in the section that lists DHCP assignments (on my Netgear it's Attached Devices). That should then show you the IP address of all the attached devices, including the ESP8266 which you will easily identify by its name.

Another option is to use mDNS. Look at some of the examples that come with the ESP8266 core and libraries to see how.


Adding devices makes I2C read 0 I'm using an Arduino Due with a logic level converter to interface with two different 5v sensors via I2C. Being of poor quality, these sensors have no data sheet.

When either one of these sensors is plugged in, I am able to read from it without issue. The moment I plug the other one in as well, the I2C stops working, and I just get 0. I know that it's not an address collision issue, because they have different addresses.

I tried adding an additional set of pull-up resistors (such that they are in parallel with the built-in ones) in order to counteract potentially increased bus capacitance, but no dice.

What could be causing this issue? I apologise for asking such a noob question.

Your problem is probably from the level converter. Which one did you use?
Most level converters are uni-directional, and don't work for I2C.
See the App note and device from NXP:
http://www.adafruit.com/datasheets/an97055.pdf


Program to run two motors with Motor driver I'm trying to make a program that would run two motors clockwise and then anticlockwise. But my program is causing my motors to only run clockwise everytime . It doesn't run anticlockwise at all. Can anyone help me find the bug?

Main code:

void loop()
{
  // turn on motor A
  digitalWrite(In1, HIGH);
  digitalWrite(In2, LOW);
  // set speed to 150 out 255
  analogWrite(EnA, 150);
  // turn on motor B
  digitalWrite(In3, HIGH);
  digitalWrite(In4, LOW);
  // set speed to 150 out 255
  analogWrite(EnB, 150);
  delay(2000);
   digitalWrite(In1, LOW);
  digitalWrite(In2, HIGH);
   digitalWrite(In3,LOW);
  digitalWrite(In4, HIGH);
  // now turn off motors
  digitalWrite(In1, LOW);
  digitalWrite(In2, LOW);
  digitalWrite(In3, LOW);
  digitalWrite(In4, LOW);
  delay(2000);
}

check this one

void loop()
{
  // turn on motor A
  digitalWrite(In1, HIGH);
  digitalWrite(In2, LOW);
  // set speed to 150 out 255
  analogWrite(EnA, 150);
  // turn on motor B
  digitalWrite(In3, HIGH);
  digitalWrite(In4, LOW);
  // set speed to 150 out 255
  analogWrite(EnB, 150);
  delay(2000);
   digitalWrite(In1, LOW);
  digitalWrite(In2, HIGH);
   digitalWrite(In3,LOW);
  digitalWrite(In4, HIGH);
  // now turn off motors
  delay(5000);
  digitalWrite(In1, LOW);
  digitalWrite(In2, LOW);
  digitalWrite(In3, LOW);
  digitalWrite(In4, LOW);
  delay(2000);
}


Is it possible to have an array of int arrays? I have a huge number of arrays, each with a series of numbers each referring to an LED on a strip. I want to be able to address each one by a number, so the logical solution to that for me was to make the whole thing into an array. Can that be done, or is there a better work around that can be implemented?

Yes you can have arrays inside arrays.

The array would be declared as:

int arrayName [ x ][ y ];

where x is the number of rows and y is the number of columns.

The example below declares and initializes a 2D array with 3 rows and 10 columns:

int myArray[3][10] = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
                       { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 },
                       { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 } };

To access the value of 27 (and save it into myValue):

myValue = myArray[2][6];


Referencing Serial output I'm confused with what I'm reading.

I have Serial communicating with my PC (USB) and SoftwareSerial over RS485 to a remote PC. I don't want to duplicate all of my print statements to be able to send output to either (or both) terminals. What I want to do is have a single set of print statements (think of a list of error messages) and then be able to output a message to either Serial or SSerial depending on which needs it. Does this make sense?

Almost all of those things you do which involve functions like print, println, and write all derive from the Print class.  You could have an array of Print objects and print to whichever you like.

Print* outs[] = {&Serial, &Serial1, &mySoftSerial};

//  Later somewhere in code:

outs[0]->println("This prints to Serial");
outs[1]->println("This prints to Serial1");
outs[2]->println("This prints to mySoftSerial");

for(int i = 0; i < 3; i++){
  outs[i]->println("This prints to all 3.  You could even make this bit a function");
}


radio.write () always returns 0 I'm trying to send a char [] through an NRF2401 but the radio.write () method always return 0. Check that msg contains the message read from str.

#define TAM 50

RF24 radio(9,10);

const uint64_t pipe = 0xE8E8F0F0E1AA;

char  msg[TAM];

void setup() {

  Serial.begin(9600);

  radio.begin();

  radio.openWritingPipe(pipe);
}

void loop() {
    if(Serial.available() > 0){
      String str = Serial.readString();
      str.toCharArray(msg,TAM);
      if(!radio.write(msg, TAM)){
        Serial.println("Message not send");
      }
      else
        Serial.println(msg);
    }
}

What am I doing wrong?

Edit1:
What I have noticed, is that the first time I was allowed to send it but the others no longer.

Edit2:
Remove the keyboard input by a char [] and sent it to without problems. Why can this be? Anything else happen when I make a keyboard entry?

I hope you resolved your issue by now, but I had the same problem with an Arduino UNO/nRF24l01+ combination and this question was one of the search results.
In my case, the write() call returned false, but the receiver received the message.
As soon as I added one of the ubiquitous Adapter Boards into the mix the write() call started returning true.
My uneducated guess is that the sending and then the switch from transmit to receive and then waiting to receive the ACK used a bit too much power or something like that.
In any case, even though everyone recommends adding a capacitor and I had the adapter boards on hand, I had thought to tough it out without one and see how far I could get.
I kicked myself for the wasted time, but I learned a lot in the process and I'm having a lot of fun with the transceiver boards now. I'm glad that I didn't just shrug and say "well the message got through so who cares?"


Custom build of arduino on a pcb I am running my Arduino based from the ATMEGA328P-PU chip from a 4v battery with this setup:

Everything works great and now I will like to make my project permanent building a custom PCB from easyeda.com. Anyways this question is not about how to create the custom PCB I have already made one and it works great. This is the PCB that I created:

Because I liked it so much now I want to build it even better. For example now I will like to combine the crystal with the 22pf ceramic capacitors into one small part.

Question

Can I use ----THIS---- part instead of the basic 22pf capacitor and the big 16Mhz crystal? In other words I want to replace the left picture with the right picture:

If its possible to use part 7325-1600A2210-00 then where can I find information on what pins to connect to the atmega328 chip and what pins to connect to ground? 7325-1600A2210-00 has 4 pins. To me it makes sense to connect 2 of the pins to pins 9 and 10 and the other 2 pins to ground. Will this work?

Can I use ----THIS---- part instead of the basic 22pf capacitor and the big 16Mhz crystal?

No. That is just a crystal. You still need the capacitors.  If you want a single device then you need a ceramic resonator.

Also you're lacking any decoupling capacitors in your circuit. You may find it works for now, but it will become flaky when you start getting it to do things.


Reading text/strings via processing I'm trying to control an led attached to my arduino via key presses on my laptop.When i hold down a key, the led should light up, and when i release the key, the led should turn off.

While my code works ATM, i am wondering why my code will not work if i replace the numbers in my code with text/strings.

Processing code(Working)

import processing.serial.*;
Serial myPort;

void setup(){
  println("The available ports are: ");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
  myPort.buffer(8);
  size(500, 500);
}

void draw(){
  if(keyPressed){
    if(key == 'r' || key == 'R'){
      myPort.write(1);
      println("red");
    }

  }

}

void keyReleased(){
  myPort.write(2);println("released");
}

Arduino Code(Working)

int red = 7;

void setup(){
  Serial.begin(9600);
  pinMode(red,OUTPUT);
}

void loop(){

}

void serialEvent(){
    int input = Serial.read();
  if(input == 1){
    digitalWrite(red,HIGH);
  }else if(input == 2){
    digitalWrite(red,LOW);
  }
}

Processing Code (Not working)

import processing.serial.*;
Serial myPort;

void setup(){
  println("The available ports are: ");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
  myPort.buffer(8);
  size(500, 500);
}

void draw(){
  if(keyPressed){
    if(key == 'r' || key == 'R'){
      myPort.write("red");
      println("red");
    }

  }

}

void keyReleased(){
  myPort.write("released");
  println("released");
}

Arduino Code(Not working)

int red = 7;

void setup(){
  Serial.begin(9600);
  pinMode(red,OUTPUT);
}

void loop(){

}

void serialEvent(){
    int input = Serial.read();
  if(input == "red"){
    digitalWrite(red,HIGH);
  }else if(input == "released"){
    digitalWrite(red,LOW);
  }
}

From the above example, i get the error ISO C++ forbids comparisons between pointers and integers.After googling the error, it was suggested that i replace the double quotes with single quotes, after which the arduino code is able to compile, but the processing code gives an error "badly formed character constant(expecting quote,got e)".

I then tried changing using double quotes for processing and single quotes for the arduino quote, but predictably, it did not work.

Why does my code work when i pass numbers to the arduino via serial communication, and my code fails when i use text strings?

The problem is that you're mixing different variable types. It's kinda an oil/water scenario.

Basically, the serial.read(); command returns an integer, -1 if there's nothing in the buffer. If there is something, it will return the character code (i.e. 93 = a). Because of that, it's an integer. When you put something in single quotes, it compiles as the equivalent ISO character code.

So, when you do input == 2, it is integer [compared to] integer. When you do input == "string", you're doing integer [compared to] string, thus you get errors. BTW: a string is a type of pointer.

So, what you have to do is this:

string input = "";
if(serial.avaliable()) {
    delay(100); //Wait for all data to be received
    while(serial.avaliable()) {
        string = string + char(serial.read());
    }
}
if(input == "yay_it_works!) {
    //Done!
}


Using pushbutton to make Stepper motor rotate 90 degrees Using a 28BYJ-48 Motor with a ULN2000 Driver. The motor works fine since I can rotate it using serial input.
Pushbutton is connected properly, Can light up an led if I connect one.
I want the motor to rotate 90 degrees everytime I push the button. When I run the code below the LEDs on the driver just blink rapidly, when I press and hold the button they stop blinking, keeping the state they were on already. e.g. if the LED A on the board was on at the moment I press the button, It stays on. If it was off, It stays off. you get the Idea.

code used:

#include <Stepper.h>;

 // pushbutton pin
 const int buttonPin = 2;

 int STEPS = 32;
 Stepper stepper(STEPS,8,9,10,11);

//create a variable to store a counter and set it to 0
int counter = 0;
void setup()
{
  pinMode(buttonPin, INPUT);
}

void loop()
{
 // local variable to hold the pushbutton states
  int buttonState;

  //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
  buttonState = digitalRead(buttonPin);

  //if the button is pressed increment counter and wait a tiny bit to give us some          //time to release the button
  if (buttonState == LOW) // light the LED
  {
    counter++;
    delay(150);
  }

  if(counter == 1)
    stepper.step(512);  // zero degrees
  //else reset the counter to 0 which resets thr servo to 0 degrees
  else
   counter = 0;
}

EDIT 1: Modifying the code @Matej gave me, I was able to debug the problem that was causing the stepper to not rotate. the code:

#include <Stepper.h>

// pushbutton pin
const int buttonPin = 2;

const int STEPS = 32;
Stepper stepper(STEPS, 8, 9, 10, 11);
int val = 2048;

//create a variable to store a counter and set it to 0
int counter = 0;

unsigned long last_button_time = 0;   //for aving last millis

void setup(){
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
  stepper.setSpeed(1000);
}

void loop(){
  bool buttonState;   // local variable to hold the pushbutton states

  //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
  buttonState = digitalRead(buttonPin);
  //if the button is pressed incremen counter and wait a tiny bit to give us some          //time to release the button
  if(buttonState == HIGH && millis() - last_button_time > 200){ // light the LED
    last_button_time = millis();
    counter = 1;
    Serial.println(counter);
  }

  if (counter == 1) {
    Serial.println("Please Write the desired angle");
    val = Serial.parseInt();
    delay(5000);
    counter = 0;
    if(Serial.available() > 0) {
    Serial.println("Stepping: ");
    Serial.print(val);
    stepper.step(val);
    counter = 0;
    Serial.println(counter);
    }
    else {
      Serial.println("ERROR LOOPING THROUGH IF STATEMENT");
    }
  }

}

The Serial output looks like this:

1
Please Write the desired angle
Stepping:
00
1
Please Write the desired angle
Stepping:
20480
1
Please Write the desired angle
Stepping:
20480

please note that In the first attempt, I wrote "2048" in Serial input to define the value of the integer (val), and nothing happened. in the second and third attempt, I also wrote 2048 (0 at the end is the counter variable) and the motor started shaking, but it didn't rotate.

I edtied few things in your code. I am not sure if LOW value is correct, so I replaced it with HIGH. Second thing is timing. I removed all delay() functions instead of it you can see usage of millis(). That's for handling interval between button press and button release - second part of if will check if last time of button press is bigger than 200ms, if yes, move stepper. Last things is stepping. You can see here stepper.step(STEPS/4);. STEPS is variable which you declared on the top of code. It's called steps per revolution, one revolution is 360° so 90° will be STEPS/4.

Here is the code, read it and test it:

#include <Stepper.h>;

// pushbutton pin
const int buttonPin = 2;

const int STEPS = 32;
Stepper stepper(STEPS, 8, 10, 9, 11);

//create a variable to store a counter and set it to 0
int counter = 0;

unsigned long last_button_time = 0;   //for aving last millis

void setup(){
  pinMode(buttonPin, INPUT);
  stepper.setSpeed(1000)
}

void loop(){
  bool buttonState;   // local variable to hold the pushbutton states

  //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
  buttonState = digitalRead(buttonPin);

  //if the button is pressed increment counter and wait a tiny bit to give us some          //time to release the button
  if(buttonState == HIGH && millis() - last_button_time > 200){ // light the LED
    last_button_time = millis();
    counter++;
    stepper.step(STEPS/4);    //90° degrees
  }
}


usart sketch uploaded using makefile gives unusual behaviour This is a simple usart program in avr c which just transmits a character.

#include <avr/io.h>
#include <util/delay.h>
#define F_CPU 16000000UL
#define BAUD 9600
#define BAUD_PRESCALLER ((F_CPU / (BAUD * 16UL)) - 1)
void send_val(unsigned char);
int main() {

UBRR0H = (uint8_t)(BAUD_PRESCALLER>>8);
UBRR0L = (uint8_t)(BAUD_PRESCALLER);
UCSR0B = (1<<TXEN0);
unsigned char x = 'B';
while(1) {

    send_val(x);
    _delay_ms(1000);
}

return 0;
}

void send_val(unsigned char v) {
while(!(UCSR0A & (1<<UDRE0)));
UDR0 = v;

}

when I upload this code via the Arduino IDE, everything is fine and the code works as expected.The LED labeled "L" on the PCB is still.

but, when I upload the code using the following Makefile, the code uploads successfully but the outcome is unexpected. I see a weird character(see EDIT) and the LED "L" blinks a couple of times in that 1 sec delay.

CC=avr-gcc
OBJCOPY=avr-objcopy

CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

led.hex: led.elf
    ${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

led.elf: led.o
    ${CC} -o led.elf led.o

install: led.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:led.hex

I referred the Schematics and the led is connected to SCK but I don't understand why the makefile is causing it to trigger.
that blinking of LED is what I think is causing the issue. Does the IDE have some other specific flags while uploading the code or am I committing some silly mistake?

EDIT: I wrote a small program to see the values in the device node /dev/ttyACM0. the ASCII value of the weired character(looks like a question mark) is actually 255.

another issue I noticed is that when I touch the solder beneath the pin 13 (only pin 13) the led L goes off!

As led L is connected to pin 13 I thought this is some hardware issue with my board but then I uploaded the blink led example code, touched the solder and everything is fine.

what could be the actual issue? this is getting mysterious.

The -mmcu=atmega328p compiler flag is needed not only for the compile
phase, but also for the link phase. Otherwise the linker will not know
which CRT (C run time) to link with your program, and it will link none.
The CRT is responsible for things like initializing the stack pointer,
clearing r1 (as required by the AVR calling convention) and calling
your main().

Edit: the following simplified Makefile should work if you have a
modern version of avrdude that understands ELF files:

CC     = avr-gcc
MCU    = atmega328p
CFLAGS = -Os -DF_CPU=16000000UL -mmcu=${MCU}
PORT   = /dev/ttyACM0

led.elf: led.c
    ${CC} ${CFLAGS} $< -o $@

install: led.elf
    avrdude -c arduino -p ${MCU} -P ${PORT} -b 115200 -U $<

Otherwise you can keep your rules for led.elf → led.hex → install.


Issues with Arduino UNO printing repeated "double" on serial monitor A weird is happening which i can't figure out why. First I had issue communicating with SIM800L.
So i tried checking the USART Hardware to see what UNO sends to SIM800 using small piece attached below.
The sketch is to compares what i send from serial monitor with strings "Hello", "heLLo" and "Hello" expecting to get Found .... or No match found.
each line string i send, the serial monitor prints twice WHY?,
The first says not found and the second say Received == ........ WHY?
**See the output of serial terminal
when i typed "Hello" with quotes.
12:03:46.536 -> Buffer Received= "  No match found
12:03:46.569 ->
12:03:46.569 -> Buffer Received= Hello"
12:03:46.603 ->     Found Hello
when i typed "HELLO" with quotes.
12:03:55.855 -> Buffer Received= "  No match found
12:03:55.888 ->
12:03:55.888 -> Buffer Received= HELLO"
12:03:55.921 ->     Found HELLO**

****when i typed "heLLo" with quotes.
12:04:04.016 -> Buffer Received= "  No match found
12:04:04.049 ->
12:04:04.049 -> Buffer Received= heLLo"
12:04:04.082 ->     Found heLLo
12:04:04.115 ->****

When i typed without quotes, all i get No match found
char buffer[100];
uint8_t index=0;

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

void loop()
{
  if(Serial.available()>0)
  {
    index=0;
    while(Serial.available())
    {
      buffer[index++]=Serial.read();
    }

    buffer[index]='\0';
    Serial.println(' ');
    Serial.print("Buffer Received");
    Serial.print(buffer);
    Serial.print('\t');
    if(strstr(buffer, "Hello")!=NULL) Serial.println("Found Hello");
    else if(strstr(buffer, "HELLO")!=NULL) Serial.println("Found HELLO");
    else if(strstr(buffer, "heLLo")!=NULL) Serial.println("Found heLLo");
    else Serial.println("No match found");
    Serial.flush();
  }
}

Note: Suspecting my PC hardware and serial driver,
so I tried it in my Ubuntu 20.04 and window 10 installed with Arduino IDE 1.8.13
suspecting it may be crystal, i tried two different boards and used even Atmega328P core.
I also suspected my keyboard "ENTER" key, so i tried the serial monitor "send" button.
with no difference.
I seems to run short is ideas so i am posting to the community. Let me have your advice and experience too.
Thanks.

As Majenko and DataFiddler already stated in the comments, you are reading the Serial interface in the wrong way, because you seem to misunderstand a specific point involving the interface.
The Serial (UART) interface knows only of individual bytes, which are send asynchronously over the lines. It does not have any context of a full packet or message. When you type in some data into the Serial Monitor and then press "Send", the data will be send, but not as one big bunch of data. The individual bytes are delayed.
The first delay comes with the nature of the interface itself, as you send with a limited baudrate. With a baudrate of 9600 the Arduino is way faster, than the bytes can arrive. So when you first get a result higher than zero from Serial.available(), the rest of the message is not yet received. Thus with your current code you would only process only the first part of the message.
The second delay comes with the fact, that you and the Serial program on your PC cannot control, when exactly each byte is send. Thats done by the driver. So it might happen, that there is a small gap between 2 bytes somewhere in your message. You cannot mitigate this without writing your own driver and you cannot predict this.
So, what to do now? You should read data, when it is available, and put it into a buffer. And only, when a full message was received, you should process the data. Now you need to know, where the end of a message is. Mostly a delimiting character (like the newline character \n) at the end of the message is used. So you read, if available, and only process the message, when you have read the delimiting character. Something like this:
unsigned int buffer_pos = 0;
char buffer[50]="";

void loop(){
    if(Serial.available()){
        char c = Serial.read();
        if(c == '\n'){
            buffer[buffer_pos] = '\0'; // End the message as C string with a null character
            // process the message here
            buffer_pos = 0;
        } else {
            buffer[buffer_pos] = c;
            buffer_pos++;
        }
    }
}

buffer holds the message. buffer_pos is the current position in the buffer. We terminate the message with the null character, to get a valid C string in the buffer. After processing the message, we set the position back to zero, to receive the next message. When you send data from your PC, you need to make sure, that the message is ended with the newline character.
Now you are independent on when exactly the data is send.

DataFiddler stated in the comments, that without a delimiting character you can simply delay for enough time, so that the data has enough time to arrive. He also stated, that it is ugly. It is a bad coding style. A long delay will impact the responsiveness of your program, while a short delay may give you problems with longer messages. So I suggest, that you directly use the correct way to read the Serial interface. Then you don't have such pitfalls.


fatal error ESP8266WiFi.h: No such file or directory I want to turn my ESP8266 into an access point so that I can connect directly to it.
I use the following sketch, but when I select
GENERIC module ESP8266 from menu, the libraries ESP8266WiFi.h and ESP8266WebServer.h become available but I was unable to upload the sketch.
Also when I select board as Arduino Uno (Which i have really) and then what to upload then the above two files becomes unavailable and says fatal error no such file... no idea what to do next.
#include <ESP8266wifi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include<WiFi.h>
#include<SoftwareSerial.h>
SoftwareSerial esp(2,3);
IPAddress local_IP(192,168,4,22);
IPAddress gateway(192,168,4,9);
IPAddress subnet(255,255,255,0);
 String ssid="Wisal";
 String pass="12345678";
 ESP8266WebServer server(80);
 boolean isAccessPointCreated=false;
void setup(){
  esp.begin(115200);
  Serial.begin(115200);

  WiFi.mode(WIFI_AP);
  Serial.print("Setting soft-AP configuration ... ");
  Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");

  Serial.print("Setting soft-AP ... ");
  Serial.println(WiFi.softAP("ESPsoftAP_01") ? "Ready" : "Failed!");
  Serial.print("Soft-AP IP address = ");
  Serial.println(WiFi.softAPIP());

}

void loop(){
  while(esp.available()>0){
    char a = esp.read();
      if(a == '\0')
        continue;
      if(a != '\r' && a != '\n' && (a < 32))
        continue;
      Serial.print(a);
   }
}

The ESP8266 core for Arduino that you're trying to use is for programming ESP8266 directly. You are trying to program an Uno with an ESP8266 connected to it for use as a WiFi module. For that application the ESP8266 core is of no use. For your application it's most common to run the AT firmware on the ESP8266 and communicate via serial. If you're doing that I recommend the WiFiEsp library:

https://github.com/bportaluri/WiFiEsp

Since you're uploading to the Uno you should have Arduino/Genuino Uno selected in the Tools > Board menu.


AtTiny85 and MMA8452Q accelerometer cannot connect using i2c I am trying to connect the MMA8452Q with AtTiny85 using the TinyWireM library.
I made the proper hardware setup with  pull-ups on  SCL and SDA pins - tested it on Arduino
Uno and it works, however when i connect the Tiny I cannot even get the handshake.
The following code produces output 13 instead of 42 (0x2A)

HARDWARE SETUP

MMA8452 Breakout ------------AtTiny85

3.3V -------voltage regulator------ 5V

SDA -----------^^(330)^^----------- PB0 (on attiny programmer marked as 5)

SCL -----------^^(330)^^----------- PB3 (on attiny programmer marked as 2)

GND --------------------------------- GND

(I also tried different pins with no luck)

CODE

//---bluetooth console communication stuff---//
#include <SoftwareSerial.h>
#define rxPin 1 //not important - needed for initialization
#define txPin A2
SoftwareSerial blueTooth(rxPin, txPin);
//      ---     //

#include "TinyWireM.h" // Used for I2C

// The SparkFun breakout board defaults to 1, set to 0 if SA0 jumper on the bottom of the board is set
#define MMA8452_ADDRESS 0x1D  // 0x1D if SA0 is high, 0x1C if low

#define WHO_AM_I   0x0D

void setup() {

  blueTooth.begin(9600);
  delay(1000);
  TinyWireM.begin(); //Join the bus as a master
  delay(1000);
 }

void loop() {
   byte c =0;
   c = readRegister(WHO_AM_I);
   blueTooth.println(c);
   delay(1000);
  }

 // Read a single byte from addressToRead and return it as a byte
byte readRegister(byte addressToRead) {
  TinyWireM.beginTransmission(MMA8452_ADDRESS);
  TinyWireM.send(addressToRead);
  TinyWireM.endTransmission(); //endTransmission but keep the connection active

  TinyWireM.requestFrom(MMA8452_ADDRESS, 1); //Ask for 1 byte, once done, bus is released by default

  while(!TinyWireM.available()) ; //Wait for the data to come back
  return TinyWireM.receive(); //Return this one byte
}

Would anyone know how to get it right?

On an ATtiny85 pin 5 (PB0) is SDA and pin 7 (PB2) is SCL for the I2C interface.  You're using the wrong pin for SCL.

Additionally, your pull-up resistors are too strong.  Somewhere between 4.7K Ohm and 10K Ohm are recommended for pull-up's on the SDA and SCL lines.


Atmega32u4 external 8MHz clock Does anyone know how to configure the Atmega32u4 to run using an external 8MHz oscillator ?

I needs to still be responsive to the Arduino IDE

Thanks

See §28.2 in Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf, which explains usage of various fuse bits.

Also see engbedded.com/fusecalc, which lets you easily figure out fuse settings.  Fusecalc also tells you the strings to use as part of avrdude command strings.

Once you know the fuse settings, send them to your device via a command like

avrdude -p m32u4 -c usbasp -u -U lfuse:w:0xEF:m -U hfuse:w:0xD5:m -U efuse:w:0x07:m

or like

avrdude -p m32u4 -P $port -c arduino -u -U lfuse:w:0xEF:m -U hfuse:w:0xD5:m -U efuse:w:0x07:m

where $port represents a port name like /dev/ttyUSB0.

Note, it makes sense to read the fuses first, and put the readings into Fusecalc to see what they correspond to.  You can read the fuses via a command like

avrdude -p m32u4 -P $port -c arduino -U hfuse:r:-:i


Battery voltage monitor right after deep sleep i have my esp32 module in deep sleep and i use it with a couple of buttons using a wake up that detect the button pressed
now i'd like to have a battery level to send to a server right before going back to deep sleep. How can i do it?
and what cheap rgb led do you suggest using?

Using "battery level" (voltage)  is poor way to monitor its useful life. Battery discharge  characteristic varies with its technology.
On the other hand many electronics devices are very tolerable as far as "supply level " AKA voltage.

RGB LED light intensity can be made to monitor different voltage, however, I fail to see how you propose to send the LED intensity level /state to other device.

Addendum

As I pointed out - the battery useful life depends on technology.
You mentioned AAA , hence I assume alkaline battery.
Then I would suggest software solution.
Let the server monitor the actual running time of your device.Then measure or calculate the load your device is drawing from the battery.
Then determine or calculate the discharge curve of your battery and let the server "output" the battery life / discharged level in relation to time. Perhaps I misunderstood and you actually wanted the RGB LED to be connected to the server. Then you can display green LED up to 80% of battery life and so on ...Keep in mind that the discharge curve is pretty abrupt at the end of battery useful life,


Programming pic microchip I have a few pic chips, mainly pic16f72 and pic16f73 on old ups circuits, realized they are not that bad. Their adc capabilities are my point of focus.

I have an esp32 (my first mcu) and i am very disappointed mainly because its adc being crap, I did some research on programming pic chips, some could be programmed via an arduino but my chips were not mentioned anywhere. I wanna program them via my esp32..

Is there a way to program them via arduino (esp32 in my case)? I can build some basic circuits but diy pic programmers require a preprogrammed pic chip which I can't produce if I can't program one already.

It seems, that you are talking about 2 different things:

The programming/burning of the PIC can be done via an Arduino (so you don't need to build a complex PIC programmer circuit). It is irrelevant, what microcontroller type is on the programmer, as long as the programmer speaks ISP (the programming protocol). So even, when your specific PIC is not mentioned at your found sites, it should work nonetheless. The connections are every time the same, though of your specific PIC the used pin functions might be on other pins (consult the datasheet for this).
An Arduino project - meaning the sketch/program, that was written for a normal Arduino, is normally not easily reusable. PICs are different microcontrollers with different hardware, so you need to port those projects to your specific microcontroller, which might involve extensive changes. When you have an Arduino Project, that was directly written for your PIC, then you can reuse it. (Be sure to install the correct core for your PIC in the Arduino IDE)