Playing a pcm file through a speaker with arduino I'm trying to play an audio file through a speaker with arduino.
However, I do not want to use pre-constructed libraries such as the tmrpcm library.

I was instructed to perhaps even recreate the tmrpcm library, and my process so far is that I managed to extract the data chunk from the wav file in integers, and I also managed to turn the wav file into a pcm file.

I am currently studying http://playground.arduino.cc/Code/PCMAudio this link in order to gain more insight about how I might play the pcm file with the speaker. However, I'm stuck with the general concept of the code. In fact, I'm confused with the general concept of playing the pcm file through the speaker.

In my understanding, playing a music through the speaker works by outputting series of voltages to the speaker, so that the current in accordance with the magnetic field creates an outward force onto the voice coil with a certain frequency that creates the sound.

So my question is, what does the data in the pcm file actually mean? The integers cannot be frequencies, and by graphing it I can see that they are amplitudes in a waveform, but what kind of input they are continues to elude me.

So summing up my questions,

What is the theoretical aspect behind the link :http://playground.arduino.cc/Code/PCMAudio
What does the data in a pcm file (or even a wav file) actually represent?

Thank you so much.

You are right that the values in a wav file are amplitudes. 16 bit signed values to be precise.

And that amplitude is just a voltage. Negative values are normally a negative voltage, but they don't have to be. They can be just a voltage below a pre-determined mid voltage around which the wave swings (known as a DC offset).

To play the waveform you just have to generate the corresponding voltages at the right times. That is usually done using a timer so you get the frequency right. For instance a 44100Hz file has to have a sample voltage generated 44100 times per second. 44100 samples will be a sound clip lasting 1 second.

But of course the Arduino cannot generate a voltage, so instead PWM is used instead. Filtered through a low-pass filter it turns into a voltage. It also uses 50% duty cycle as "zero" for the waveform, which is scaled to fit into the resolution of the PWM.  The PWM has to be running at a considerably higher frequency than the sample frequency of the waveform so it has a chance to represent a voltage before it is asked to change again.


analogRead() doesn't read more than 500Hz I connected a wave generator to the analog pins to read the frequencies of the waves generated. I used different frequencies of sine waves with a minimum of 0V and maximum of 5V.
Whenever the voltage is greater than 2.5V, I made one of the digital pins HIGH, and LOW when less than 2.5V. Now by measuring the square wave from the digital pin, it always has the same frequency as the sine waves until 500Hz.
After 500Hz, the square wave's frequency doesn't agree with the sine wave, which made me think that the problem is in the analogRead(). Is there a way to have higher frequency?
Code:
const int sensorPin1 = A0;
const int sensorPin2 = A1;
const float maximumPower = 2.5;
int calibration = 1;

void setup() {
  Serial.begin(57600);
  pinMode(6, OUTPUT);
  digitalWrite(6, LOW);
}

void loop() {
  int voltage2 = 3;
  int voltage1 = 3;
  int sensorVal = abs(analogRead(sensorPin1) - analogRead(sensorPin2));
  float ratio = abs(analogRead(sensorPin2) / analogRead(sensorPin1));
  float voltageDifference = (sensorVal / 1024.0) * 5.0;
  float power = calibration * voltageDifference;
  if (power >= maximumPower || voltage1 <= 1 || voltage2 <= 1) {
    digitalWrite(6, LOW);
  }
  else {
    digitalWrite(6, HIGH);
  }
}

You have 4 calls to analogRead() in your loop. At about 112 µs per
call, that's already taking 448 µs. Add to that the time taken by the
floating point calculations, and you are likely to end up with something
in the order of 500 µs per loop iteration. This should give you a
sampling rate close to 2 kHz, which should allow you to detect the highs
and lows of an input signal up to 1 kHz, provided the duty cycle is
close to 50%.
There are a couple of easy optimizations that could be done here. Two of
the calls to analogRead() serve no purpose, as the results are never
used. And the floating point calculations are also pointless. The whole
loop can be simplified to this:
void loop() {
    if (abs(analogRead(A0) - analogRead(A1)) >= 512) {
        digitalWrite(6, LOW);
    } else {
        digitalWrite(6, HIGH);
    }
}

This should take about 224 µs per iteration. If you need to go faster,
you will have to increase the working frequency of the ADC. This can
cost some accuracy, but if accuracy is not critical to your application,
it can be a good trade-off. See Nick Gammon's page on the Arduino
ADC for details. If that's not enough, you will have to use
external components, e.g. an analog subtractor made from an op-amp, and
a couple of comparators.


Best way to read CSV from SD card and store values by date I am starting a project in Arduino and I need to read data from an CSV stored in an SD card. The data is stored as the following:

id, value, date

What I want to do is read the file, filter by date and then store the values by id. Each id will correspond to different values from that same date.

Is it possible to do something like this?

Thank you very much for your advice.

I highly suggest checking out this YouTube video (https://www.youtube.com/watch?v=5v5A3j7Rrco), especially around 21:30. It goes over in detail to do exactly what you are asking for, mainly the headings with IDs for each data point. At the end of the day you are going to need something that looks similar to this:

float id = 0; //used to provide a numbered ID to each data point

void setup(){
//initialize all your once-run variables and such
}

void loop(){
  //Write Log File Header
  File logFile = SD.open("NAME.csv", FILE_WRITE);

  if (logFile){
    logFile.println(", , , ,"); //Just a leading blank line, incase there was previous data

    String header = "ID, Time, Light, Temp"; //These will be the headers for your excel file, CHANGE "" to whatevr headers you would like to use
    logFile.println(header);
    logFile.close();
    Serial.println(header);
  }

  else {
    Serial.println("Couldn't open log file");
  }
}
}

This is all code that I currently use to do the exact same thing as you, and its a small edit from what Jeremy Blum does in the YouTube video I just linked you too. This is how the header files will look on an excel sheet, I took a screenshot of an actual file I have created using this method:


2.4Mhz clock for 3-wire SPI using Arduino Mega 2560 I am trying to develop an Arduino sketch for ADS8320 ADC IC, which is 3-wire SPI. I need a 2.4MHz serial clock for the SPI interface. I tried the code below, but I don't know how to generate clock pulses at 2.4MHz clock speed.

#define CLK 22
#define DBIT 24 // so
#define CS 26

#include <SoftwareSerial.h>

int v = 0;
float Ctemp, Ftemp;

void setup()   {
  Serial.begin(9600);
  pinMode(CLK, OUTPUT);
  pinMode(DBIT, INPUT);
  pinMode(CS, OUTPUT);
  digitalWrite(CS, HIGH);
  digitalWrite(CLK, LOW);
}

void loop()   {
  v = spiRead();
  if (v == -1)   {
    Serial.print("No sensor \n");
  } else   {
    Serial.println(Ftemp);
  }
  delay(100);
}

int spiRead() {
  int value = 0;
  digitalWrite(CS, LOW);
  delay(2);
  digitalWrite(CS, HIGH);
  delay(220);
  /* Bring CS pin low to allow us to read the data from
    the conversion process */
  digitalWrite(CS, LOW);
  /* 1st 5 clock cycles  */
  digitalWrite(CLK, HIGH);
  delay(1);
  digitalWrite(CLK, LOW);
  digitalWrite(CLK, HIGH);
  delay(1);
  digitalWrite(CLK, LOW);
  digitalWrite(CLK, HIGH);
  delay(1);
  digitalWrite(CLK, LOW);
  digitalWrite(CLK, HIGH);
  delay(1);
  digitalWrite(CLK, LOW);
  digitalWrite(CLK, HIGH);
  delay(1);
  /*
    Read bits 16-0 from ads8320 for the adc. Loop for each bit reading
    the value and storing the final value in 'adc'
  */
  for (int i = 16; i >= 0; i--) {
    digitalWrite(CLK, HIGH);
    value += digitalRead(DBIT) << i;
    digitalWrite(CLK, LOW);
  }
  // check bit D2 if HIGH no sensor
  if ((value & 0x04) == 0x04) return -1;
  // shift right three places
  return value >> 3;
}

'
i have added the code i tried with arduino spi library still i don't get any result

 // inslude the SPI library:
 #include <SPI.h>

 // set pin 10 as the slave select for the digital pot:
 const int slaveSelectPin = 10;

 void setup() {
 // set the slaveSelectPin as an output:
 pinMode(slaveSelectPin, OUTPUT);
 // initialize SPI:
 SPI.beginTransaction(SPISettings(2400000, MSBFIRST, SPI_MODE0))

 void loop() {
 while(1){
 spiread(slaveSelectPin);
 }
 }

 void spiread(int slaveSelectPin) {
 // take the SS pin low to select the chip:
 digitalWrite(slaveSelectPin, LOW);

 receivedVal = SPI.transfer(val);
// take the SS pin high to de-select the chip:
digitalWrite(slaveSelectPin, HIGH);
}

It's hardly possible to generate a stable and exact frequency with your method.
Imagine you have an interrupt routine interrupting your spiRead() or any function called inside: Your clock will be extended by the ISR runtime.
Apart from this:

I'm not sure if your LOW phase is long enough (there's no delay between setting CLK from LOW to HIGH. If 2.4 MHz is the max frequency for the chip, it should be at least 208ns.
However:
If you are sure that the runtime of digitalWrite is always longer than 208ns, you could remove your delay() at all. The resulting frequency is the maximum possible you can achieve with your method.
The smallest delay() is 1ms, which leads to a maximum of something < 1 kHz (or even 0.5kHz for a 50:50 signal).
You should use delayMicroseconds() to get at least 500kHz.

But what I'm really wondering:
Why are you implementing bit banging instead of simply using the SPI library?


How fast can I drive a stepper motor? I have a 28BYJ 48, 5V stepper motor. After some trial and error I got it working with the all the sample examples in Arduino IDE.

However when I increase the speed of the motor using setSpeed() beyond 15, the motor stopped rotating. Following is the configuration in which I am running the motor.

const int stepsPerRevolution = 2048;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
myStepper.setSpeed(15);

I wanted to understand what factors limit the speed. And how fast can I rotate this motor?

Thanks,

Manish

"I wanted to understand what factors limit the speed. And how fast can I rotate this motor?"
Read through the data sheet for your motor-the answers are there. Each different motor has its own data sheet. This will require some work on your part to find the data sheet and the info from it you require. Which can be used to deduce the answer your question.


what pins are attached to ethernet shield SD card? I have ARDUINO ETH SHIELD 06 - Rev 03. https://www.adafruit.com/product/201
what pins are attached to Ethernet shield SD card?

Arduino communicates with both the W5100 and SD card using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used to select the W5100 and pin 4 for the SD card.


Lock screen if I leave my seat? Background: I change the job and in the new company you need to pay pizza for the whole team if you forget to lock your screen :-)

I want it to be automated: I walk away and the screen should lock. No additional action should be required. Keyboard shortcuts, special mouse movements or unplugging devices from USB are not valid solutions.

How could this be solved (with or without arduino)?

Please write slowly, I never worked with sensors or arduino before :-)

I need this for Mac and Ubuntu.

Sorry, no Arduino required, but you probably already have a web cam on your desktop. If you don't mind being observed like Schrodinger's Cat, you can use a small utility like YawCam in Windows or Motion on Linux to trigger the screen lock when you are no longer visible at your console.


How to reduce current from a AC TO DC power supply for arduino use I have a AC to DC converter that was originally used for recharging the PSP, I stripped the 2 wires of the output and was wanting to use it for my arduino instead of using a 9V battery, it's output is 5V 2000MA, is there a way to reduce the current in order to use it for the arduino and im guessing the 5V is enough to power it...right? Im kinda new to electronics and the arduino so any help is much appreciated :D.
Thanks,
Liam.

You don't need to reduce the current.

2000MA (2 amps) means the power supply is CAPABLE of supplying this (without overheating). Anything less than this, and your device will work perfectly.

Your Arduino will DRAW a certain number of milliamps (amps), this is the amount of current that will ACTUALLY run through your circuit.


Do all arducam need the "Arducam-F Shield"? The information on this is so greatly lacking to the extent that no related youtube videos could be found, no internet material and the seller seems to be very important and not answer to my questions as he is supposed to.
Also he appears to be the only seller to offer such a variety of arduino cameras.

I want to choose colored arduino camera for my project, but I am unable to receive enough information so that I can choose the appropriate arduino camera.

The most important for me to know is does all arduino cameras need the arducam-f shield board in order to work properly (i.e be programmable, colored, with "decent" quality and be able to capture photos in less than 1~2 seconds)

This is "5MP Mega pixel OV5642 Sensor Camera Module w CS mount Lens" It costs US $29.99. The description doesn't mention the need of any other 3rd party hadware in order to work.

This bellow is "Arducam-F Shield V2 Camera module shield /w OV2640 for Arduino UNO MEGA2560 DUE" it costs US $29.99 and is a camera that evidently comes with this magical shield. We can see that the version is slightly older than that on the other cameras.

This is "2 Mega pixel Camera Module MT9D111 JPEG Out + HQ lens" for US $21.99 and also, like in any other description, the need of shields is not mentioned

And this is "2Megapixel MT9D111 Auto Focus lens camera flex module with Adpater board" that has autofocus, is 2MP like the one above, comes with .... ?Adapter board"? (nothing like that is shown in the pictures or described in the description) and costs only US $9.99. It looks ugly compared to other cameras.

These was the 4 example arduino cameras I would choose from and do all of them need arduino shields in order to do what a camera should do?
(Explaining differences, pros and cons will be very useful to everyone who are in the same boat as I am)

You have three requirements:

Good quality (colour)
High resolution
Fast operation

Those three requirements together mean you cannot use a normal Arduino.

The Arduino has nether the memory nor processing power to directly communicate with a camera module.
The ones you can communicate with have internal buffer memory and use a slow UART interface to transfer a frame. That is not fast.
The Arduino cannot deal with a large picture regardless of speed. All you can do is pass the image through to somewhere else for processing. Slowly.

So you can either have very low resolution or slow speed.

So use a Raspberry Pi or something similar which is more capable of using a camera (indeed, the Pi has a dedicated camera connection).


Arduino Nano LED not working I am just starting with Arduino and was trying to make the LED example work. I changed the script as follows to keep the LED on:

#define LED_PIN 12
#define LED_RX_SIG LED_BUILTIN

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_PIN, OUTPUT);
  pinMode(LED_RX_SIG, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_PIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  //delay(1500);                       // wait for a second
  //digitalWrite(LED_PIN, LOW);    // turn the LED off by making the voltage LOW
  //delay(1500);                       // wait for a second
  //digitalWrite(LED_RX_SIG, HIGH);
  //delay(1000);
  //digitalWrite(LED_RX_SIG, LOW);
  //delay(1000);
}

I setup the Nano board, LED and a 220ohm resistor on a breadboard. The D12 port on Nano is connected to one end of the 220ohm resistor using a jumper cable. The other end of the resistor is connected to the positive (longer end) of the LED. The negative end of the LED is connected to the GND pin on Nano. The setup is shown in the image below:

What's wrong with the setup and why the LED is not lit?
Sorry in advance for such novice question and any help will be greatly appreciated. Thanks

As your program is currently written, you should see your LED light. I see nothing wrong with your program or your wiring. I am also assuming that you had no errors while compiling and downloading the program.

With the rest of the lines uncommented, what you should see is your LED light up for 1.5 seconds and then off. Then after another 1.5 seconds, the on-board LED should turn on and then off (both 1 second).

If you have wired up the LED wrong (or a bad connection), you should at least still see the on-board LED flash about once every 5 seconds. If you don't see this then something else is wrong.

One thing I notice from the photos is that you have no way of powering your circuit. (I realise this may just be while you took the photo). Plug a USB cable into the Arduino and the other end into the computer. You should see the LED called "POW" light up.

To verify your LED circuit, try disconnecting the jumper at D12 and connecting it to 5V and you should see the LED light. If this works then your circuit is OK so replace the jumper back at D12.

If the LED still does not light up when the jumper is connected to 5V then we need to dive into that circuit. Possible reasons include:

The LED is dead -> replace the LED
The breadboard is not making good connection -> wiggle the leads (to scratch away any corrosion) or twist together the wires where possible or even solder them together.
The jumper wires are manufactured poorly (eg. the plastic wasn't stripped before crimping) -> check the jumper crimps.
The LED has been manufactured wrong and what should be the anode is actually the cathode (I have seen this) -> reverse the polarity of the LED.
The resistor is burnt out -> replace the resistor.


Need assistance with program for POV Project I've created a very basic POV project.

It has a 12V DC motor with a piece of wood on it.
The wood has 6 LEDs on it as well as a copper ring.
The power is delivered to the LEDs from brushes connecting to the copper ring and from the shaft of the motor (the ground is attached to the base of the motor.) I'm using a TCRT5000L Sensor to count the RPM and have attached the LEDs to pin 13 and ground of the Arduino. (I've attached white tape to one side of the wood so that the sensor only counts one rev.)

I need help (please) with the program.

This is the code that I am using:

int pin = 13;
volatile  int tcnt = 0;
volatile  int lastcount = 0;
volatile int state = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(pin, OUTPUT);
  attachInterrupt(1, blink, RISING);
}

void loop() {
  Serial.println(tcnt);
  if (tcnt != lastcount)
  {
     digitalWrite(pin, HIGH);
     delay(10);
     digitalWrite(pin, LOW);
     delay(10);
     lastcount = tcnt;
  }

   delay(10);

}

void blink() {
  tcnt = tcnt + 1;
  state = !state;
}

My first issue is that the when I use the code above, the lights don't seem to switch on / off on the exact same area. They are within 30 degrees but certainly not precise.

The second issue (and the biggest) is that I'm sure that this code is not the best way to do what I need. For example, if I wanted to use this as an analog clock, so that the lights would only show on the current hour / minute, how would I do this?

Any help is greatly appreciated.

Your third delay is the issue. It means you have up to 10 ms before you notice the need to turn on the light. Try this:

const byte pin = 13;
volatile bool detected;

void setup() {
  pinMode(pin, OUTPUT);
  attachInterrupt(1, blink, RISING);
}

void loop() {
  if (detected)
    {
    delay(10);
    digitalWrite(pin, LOW);
    detected = false;
    }

}

void blink() {
  digitalWrite(pin, HIGH);
  detected = true;
}

Now that immediately turns on the LED, so it will always happen at the same time. Then in the main loop you notice it is on, wait 10 ms, and then turn it off.


Can I power Arduino with 12V 1.2A adapter I am new to arduino and i am making a smart energy meter for my home. I want to run the arduino months so, how to power arduino with a adapter, I have a 12V 1.2A adapter is it ok to power arduino with it or not?.
Thanks in advance.
As i said i want to run it long time.

If it is an Arduino Uno Rev3 SMD, the documentation (see Juraj's comment) is of relevance here, click the tab "Tech Specs" to find:

Operating Voltage     5V
Input Voltage (recommended)   7-12V
Input Voltage (limit)     6-20V

While the microcontroller's (ATmega328P) operating voltage is 5 V there is an on-board voltage regulator to make the board work within the input voltage range of 6 to 20 V (max limits) or the recommended range of 7 to 12 V.
Operating this Arduino with a 12 V power adapter is within spec and therefore safe to do. The current rating of the adapter of 1.2 A is also more than sufficient to run the Arduino.


Can Bus to receive and transmit on the same mcu So I've been working on a project over the last few month using homemade boards on a CAN bus. It's working well when using a board as a sender and another one as receiver.
I now have 3 boards and on which there are several sensor.
My purpose here is to be able for every board to share data and use other from another mcu.

An quick overview of the project for a better understanding :
I'm trying to automate a RC plane.

MCU-1 : Potentiometers + GPS

MCU-2 : 1 accelerometer + 1 barometer

MCU-3 : 1 differential pressure transmitter + 1 radio transmitter

I'd like to be able, for MCU-1 to receive and use data from MCU-2 and in the same time to transmit data to MCU-3. (They both have many more components and tasks to achieved, that why I don't have all the sensors on the same board)

I don't think it's important but MCU1 and 3 are ATmega328p (the one from the nano board) and MCU2 is an ATmega2560

My question :
Is it possible ? I mean is it possible to have a MCU running as a Sender and a Receiver at the same time ? and how to do it ? :)

Also is it possible to have a MCU running as a receiver, let's say 90% of the time and sender 10% (or after an update) ? If the first situation isn't possible this one could be a solution for my project.

Thank you

Undeadguy

Yes, it is possible.

  CAN is a multi-master serial bus standard for connecting Electronic Control Units [ECUs] also known as nodes. Two or more nodes are required on the CAN network to communicate. The complexity of the node can range from a simple I/O device up to an embedded computer with a CAN interface and sophisticated software.

  -- Wikipedia

You should understand how collision detection works in a multi-master CAN bus and ensure that you implement it (or it is implemented in your chosen CAN library) to allow reliable operation:

  The CAN specifications use the terms "dominant" bits and "recessive" bits where dominant is a logical 0 (actively driven to a voltage by the transmitter) and recessive is a logical 1 (passively returned to a voltage by a resistor). The idle state is represented by the recessive level (Logical 1). If one node transmits a dominant bit and another node transmits a recessive bit then there is a collision and the dominant bit "wins". This means there is no delay to the higher-priority message, and the node transmitting the lower priority message automatically attempts to re-transmit six bit clocks after the end of the dominant message. This makes CAN very suitable as a real time prioritized communications system.

  The exact voltages for a logical 0 or 1 depend on the physical layer used, but the basic principle of CAN requires that each node listens to the data on the CAN network including the transmitting node(s) itself (themselves). If a logical 1 is transmitted by all transmitting nodes at the same time, then a logical 1 is seen by all of the nodes, including both the transmitting node(s) and receiving node(s). If a logical 0 is transmitted by all transmitting node(s) at the same time, then a logical 0 is seen by all nodes. If a logical 0 is being transmitted by one or more nodes, and a logical 1 is being transmitted by one or more nodes, then a logical 0 is seen by all nodes including the node(s) transmitting the logical 1. When a node transmits a logical 1 but sees a logical 0, it realizes that there is a contention and it quits transmitting. By using this process, any node that transmits a logical 1 when another node transmits a logical 0 "drops out" or loses the arbitration. A node that loses arbitration re-queues its message for later transmission and the CAN frame bit-stream continues without error until only one node is left transmitting. This means that the node that transmits the first 1 loses arbitration. Since the 11 (or 29 for CAN 2.0B) bit identifier is transmitted by all nodes at the start of the CAN frame, the node with the lowest identifier transmits more zeros at the start of the frame, and that is the node that wins the arbitration or has the highest priority.

  For example, consider an 11-bit ID CAN network, with two nodes with IDs of 15 (binary representation, 00000001111) and 16 (binary representation, 00000010000). If these two nodes transmit at the same time, each will first transmit the start bit then transmit the first six zeros of their ID with no arbitration decision being made.


Detect certain characters and if not a consequence How can I program in Arduino Uno a serial.available that will detect some chars that aren't supposed to belong in a list of options, like this:

void lerRespostaUtilizador(){
  if(Serial.available('s' && 'v' && 'r'){
    Serial.println("Podes visualizar: (s)inais de controlo, (v)ariaveis do sistema e conteudo de (r)egistos.")
  }
  switch(Serial.read()){
    case 's': // Mostrar sinais de controlo
      mostrarSinais();
      Serial.println("Podes visualizar ainda: (v)ariaveis do sistema e conteudo de (r)egistos.");
      Serial.println("");
      break;
    case 'v': // Mostrar variáveis do sistema
      mostrarVariaveis();
      Serial.println("Podes visualizar ainda: (s)inais de controlo e conteudo de (r)egistos.");
      Serial.println("");
      break;
    case 'r': // Mostrar conteúdo de registos
      mostrarRegistos();
      Serial.println("Podes visualizar ainda: (s)inais de controlo e (v)ariaveis do sistema.");
      Serial.println("");
      break;
    }
}

What I want is if the user inserts some chars that aren't 's', 'v' or 'r', a message will appear saying what they can insert to obtain certain results.

I would rewrite that as something like this:

void lerRespostaUtilizador(){
  while (!Serial.available());
  switch(Serial.read()){
    case 's': // Mostrar sinais de controlo
      mostrarSinais();
      break;
    case 'v': // Mostrar variáveis do sistema
      mostrarVariaveis();
      break;
    case 'r': // Mostrar conteúdo de registos
      mostrarRegistos();
      break;
    default:
      Serial.println(F("Podes visualizar: (s)inais de controlo, (v)ariaveis do sistema e conteudo de (r)egistos."));
    }
}


I want a bar type display for my Arduino Project I am trying to make a smart table project. But I have stumbled upon one problem, that is I don't know which display should I use. I need a display that has roughly aspect ratio of 2:1 but also has a relatively high pixel density. I have purchased a 2.42 inch display based on SSD1309 but the display is way too pixelated for my use. Do you have any display recommendations for me?
This is the display that I have bought:

The display I am trying to achieve is like this:

It looked like the display that I'm trying to achieve uses a custom made display. Is there anyway I can achieve that kind of look (at least similar in quality) with displays on the market?

As Majenko already stated, the second image shows a custom display. It is not pixelated, because each shown element/symbol has it's own element in the LCD. When you have one of these displays, you might be able to reuse it for your project, but that is advanced.
In the case of pixel based displays with a significantly higher resolution than the standard SSD1309 driven LCD or OLED displays, you are mostly out of luck. There might be fitting products, though they most likely will be expensive and are not as easy to drive, as the standard ones. AVR based Arduinos, like Uno, Nano or Mega, are also not really good for driving high res displays.
The way to go depends on your exact requirements.

You could - as Majenko suggested - ditch the Arduino and use an old smartphone. If you need more control over the smartphone for your project, than the standard Andriod gives you, you could install an open source OS on the phone.

You could move to a Single Board Computer, like the Raspberry Pi Zero, and buy a display for it. There are many displays for Raspberry Pis, that should have enough resolution. Though most of them are larger than a normal smartphone display.


Arduino Core for the Raspberry Pi Pico I recently bought a Raspberry Pi Pico to play with, and am attempting to upload my first program to it the Arduino way, as my own operating system rather than a c++ program over an existing operating system (meaning to replace the built-in Raspberry Pi Pico operating system which runs MicroPython, not in the sense of running Linux, Windows, Mac, or any derivative or fork). I have not found any record of people hacking it like that - is it possible? If so, how would I go about it? Sorry if this is in the wrong Stack Exchange.

Here is the library for the Arduino IDE and a Raspberry Pi pico.
https://github.com/lrusak/Arduino-Core-Pico
Just install normally as a .zip.


Understanding the contents of a library in C So this is a question not just about the #include  but most all includes you find while programming in C.

So I understand a library is prewritten code and when you include that library are you able to used certain function that are included in that library.

What I have always wanted to know is: where can you find the "instruction set", in C, for these libraries?

How can I find out what commands are available for me to use with this library?

hope this makes sense.

thank you everyone.

What I have always wanted to know is: where can you find the "instruction set", inc C, for these libraries?

The libraries are usually found in the libraries sub-folder under your sketchbook folder (wherever that is). There is also another libraries folder inside the IDE install folder for the "official libraries".

  How can I find out what commands are available for me to use with this library?

Usually the library documents them in one way or another. Try looking inside the .h file used by the library to see what functions are exposed.


Does HC-05 module buffers the data received? I am using HC-05 bluetooth module for sending large data(80-100KByte) from my phone to arduino-uno.
I had found that this module has a flash chip of 8Mbit  (SST39VF800A) but the datasheet of HC-05 has nothing about buffering of the data to be transmitted or data received.
I need clarity about the buffering of data so that I can change the data rate from the phone for better communication.

I didn't find any help in any data-sheets I could find, either. So I'd suggest a simple experiment, sending increasingly large packets before the other side attempts to read anything, until some data goes missing. The packets don't even need to be very sophisticated if all you want to know is whether N_received == N_sent and for what maximum 'N'.
Update:

All bytes were received correctly if there is no delay but with
increasing delay in reading from HC-05 data was not fully received and
with delay greater than 800ms only 63Bytes were received.

If you're collecting data as it arrives, then you can't measure the buffering. When you wait until all data has been set before you try to read any, the number of bytes you receive is the buffer size. It sounds like a 63 byte buffer, probably only what the HC-05's hardware UART can buffer, without using any of its memory to increase that.


28 BYJ stepper motor runs faster using delay() and little slower using millis(), why? I'm working to develop a code for the stepper motor to use it in a project. And since using delay() isn't as efficient as millis(). So I first developed the code that use delay with 1ms delay between the steps which is the fastest I could do with this stepper motor.

Then I developed similar code using millis() with same 1ms delay but it didn't feel as smooth/fast as the one with delay() function.

So what's the reason for that?

These are the code:

With delay():

    void clockwise(void){
        digitalWrite(in4, HIGH);
        digitalWrite(in3, LOW);
        digitalWrite(in2, LOW);
        digitalWrite(in1, LOW);
    delay(1);
        digitalWrite(in4, HIGH);
        digitalWrite(in3, HIGH);
        digitalWrite(in2, LOW);
        digitalWrite(in1, LOW);
    delay(1);
        digitalWrite(in4, LOW);
        digitalWrite(in3, HIGH);
        digitalWrite(in2, LOW);
        digitalWrite(in1, LOW);
    delay(1);
        digitalWrite(in4, LOW);
        digitalWrite(in3, HIGH);
        digitalWrite(in2, HIGH);
        digitalWrite(in1, LOW);
    delay(1);
        digitalWrite(in4, LOW);
        digitalWrite(in3, LOW);
        digitalWrite(in2, HIGH);
        digitalWrite(in1, LOW);
    delay(1);
        digitalWrite(in4, LOW);
        digitalWrite(in3, LOW);
        digitalWrite(in2, HIGH);
        digitalWrite(in1, HIGH);
    delay(1);
        digitalWrite(in4, LOW);
        digitalWrite(in3, LOW);
        digitalWrite(in2, LOW);
        digitalWrite(in1, HIGH);
    delay(1);
        digitalWrite(in4, HIGH);
        digitalWrite(in3, LOW);
        digitalWrite(in2, LOW);
        digitalWrite(in1, HIGH);
    delay(1);
}

With millis():

  void stepper_run_cw(void){
  stepper_step_cw(1,0,0,0,1);
  stepper_step_cw(1,1,0,0,1);
  stepper_step_cw(0,1,0,0,1);
  stepper_step_cw(0,1,1,0,1);
  stepper_step_cw(0,0,1,0,1);
  stepper_step_cw(0,0,1,1,1);
  stepper_step_cw(0,0,0,1,1);
  stepper_step_cw(1,0,0,1,1);
}

void stepper_step_cw(uint8_t m_in1, uint8_t m_in2, uint8_t m_in3, uint8_t m_in4, uint8_t delay_time){
  if (!stepper_run){
    digitalWrite(in1, m_in1);
    digitalWrite(in2, m_in2);
    digitalWrite(in3, m_in3);
    digitalWrite(in4, m_in4);
    stepper_start = millis();
    stepper_run = 1;
  }

  if(stepper_run){
    stepper_current = millis();
    if(stepper_current - stepper_start >= delay_time){
      stepper_run = 0;
    }
  }
}

Maybe for the second function you want something like this:

 void stepper_run_cw(void){
  stepper_step_cw(1,0,0,0,1);
  stepper_step_cw(1,1,0,0,1);
  stepper_step_cw(0,1,0,0,1);
  stepper_step_cw(0,1,1,0,1);
  stepper_step_cw(0,0,1,0,1);
  stepper_step_cw(0,0,1,1,1);
  stepper_step_cw(0,0,0,1,1);
  stepper_step_cw(1,0,0,1,1);
}

void stepper_step_cw(uint8_t m_in1, uint8_t m_in2, uint8_t m_in3, uint8_t m_in4, uint8_t delay_time){
  unsigned long temp, i;
  for (i=0;i<delay_time;i++){
    temp = millis();
    while (temp == millis){};//wait for millis to change
  }
    digitalWrite(in1, m_in1);
    digitalWrite(in2, m_in2);
    digitalWrite(in3, m_in3);
    digitalWrite(in4, m_in4);
}

This code is also avoiding the millis overflow issue if you run your board for a long time.

Still, apart for a improved timing, there is no gain in using millis(), you still have to wait for millis to change, you might want to use a timer interrupt to do the job in background.


How to use #define in a library I'm trying to write? I have written simple code to enable toggling of serial.print debug data.

  #define DEBUG
  #ifdef  DEBUG
    #define DEBUG3(x,y,z) Serial.print(x);Serial.print(" ");Serial.print(y);
     Serial.print(" "); Serial.println (z)
    #define DEBUG2(y,z) Serial.print(y);Serial.print(" ");Serial.println
     (z)
    #define DEBUG(z) Serial.println(z)
    #define DEBUGln  Serial.println("");
  #else
    #define DEBUG3(x,y,z)
    #define DEBUG2(x,y)
    #define DEBUG(x)
    #define DEBUGln
  #endif

Then I can just call DEBUG3("words",value,"words"); anywhere in the sketch and it will automatically print out the text, int, strings, etc with a single space between and automatically go to next line etc etc.

Just define the correct number of fields to print and separate using commas.

If I want to turn off debug then I just comment out #define DEBUG at the top.

Now the issue is I don't want to copy in this code every time I want to use it, so it makes sense to make it a library so that I can just call something like:

#include <SERIAL_DEBUG.h>
#define DEBUG     (or //#define DEBUG) //to enable or disable

The reason being that sometimes I might want to print up to 10 things on a single line (not very often but it could happen).

This is my first library attempt and I'm having a hard time finding any information on how I would go about setting up the .h and .cpp files for this type of #define DEBUG(x) Serial.println(x) and the #define DEBUG (from sketch) parts.

Not a direct answer to your question, but I would suggest a different
approach based on streaming output, as described in the Arduino
Playground: Adding Streaming (insertion-style) Output. In
a nutshell, you define the << operator for Serial (and any other
object that inherits from Print) in a way that allows you to write
things like:

Serial << "My name is " << name << " and I am " << age << " years old.";

Now you can define a Debug object which would be, depending on whether
you want debugging output or not:

an alias to Serial
a dummy object that just discards its input.

Example:

#define DEBUG_ON

// From https://playground.arduino.cc/Main/StreamingOutput
template<class T> inline Print& operator<<(Print &obj, T arg)
{ obj.print(arg); return obj; }

#ifdef DEBUG_ON
# define Debug Serial
#else
class DummyStream {
public:
    template<class T> DummyStream& operator<<(T arg)
    { (void) arg; return *this; }
} Debug;
#endif

void setup()
{
    const unsigned long BAUDRATE = 9600;
    Serial.begin(BAUDRATE);
    Debug << "Serial port open at " << BAUDRATE << " bps\r\n";
}


What image formats are accepted for displays? Sorry if there is information missing, im new to the topic.

I have an ESP32 connected to a Waveshare 7,5" RWB display, and i can display images by converting them to .xbm and including the hex code in the sketch.
So far, so good.

But heres my question: What exactly are the requirements? Because when looking at the .xbm image code, i see that its a pattern like this:

0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00

But when i used a python script

import binascii
filename = 'test.png'
with open(filename, 'rb') as f:
    content = f.read()
print(binascii.hexlify(content))

to convert an image to hex code, i got this:
b'89504e470d0a1a0a0000000d4948445200000280000001800802000000b2...'(continues for thousands of characters, didnt want to paste all of that here

However, when trying to run the sketch that successfully displayed the first hex code with the second image code, i got this error(cut out the big string clutter again):

...0000000049454e44ae426082};

^

C:\Users\Administrator\Desktop\SPI_test_example\SPI_test_example.ino: In function 'void loop()':

SPI_test_example:167:21: error: 'showBitmapExample' was not declared in this scope

   showBitmapExample();

                     ^

SPI_test_example:171:51: error: 'showFont' was not declared in this scope

   showFont("FreeMonoBold9pt7b", &FreeMonoBold9pt7b);

                                                   ^

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

So, i would like to know - does the image code have to have exactly the format i mentioned first? This is very important for me because i want to automate the process from inputting any image to using the resulting code to feed the display.

Thanks in advance!

EDIT: As far as my understanding goes, both formats are the same data, just that the first one is displaying a white pixel as 0xFF,0xFF,0xFF and the second one as FFFFFF.

This is not a question of image format but of what format c accepts data in.

What you have is a python representation of binary data in hexadecimal encoding. That can only be used with python.

C represents hexadecimal values by prefixing them with 0x.

You will have to change your python code to output each byte individually and prefix it with 0x and separate each one with a comma. That can then be wrapped in an array structure.


Using an external pull-up resistor vs INPUT_PULLUP When would one would prefer to use an external pull-up resistor vs the internal:

pinMode(fanPin, INPUT_PULLUP);

Dredging through the forums and this site, the commonly recommended value for a pull-up resistor is seems to fall at 10K.

However, the ATmega32U4 datasheet's Table 29-1 says that RPU or "I/O Pin Pull-up Resistor" is between 20K and 50K ohms.

This question asks about internal vs external pull-ups for a simple button, but I'm asking in the general case.

What types of projects would fare better with internal pull-ups, and what type of projects would be better off with external pull-ups?

What are the considerations for preferring one over the other?

At the present, my project is hooking up an AM2302 / DHT22 temperature sensor.

There is no OUTPUT_PULLUP that I am aware of. Use INPUT_PULLUP for most things.

Add 3.3K (3.3V) or 4.7K (5V) external pullups for I2C. If you saw a 'scope trace with 10K I2C pullup on 5V system and even short wiring, the rise time is really slow. 4.7K is much quicker.

10K for external pullup works well for slow things, like buttons, switches.  If the wire lengths are longer, then 4.7K could be used as well, maybe even 1K if the wires are long.  If running on battery power, 10K is better as there is less current flow when the input is low.


ESP32 runtime error in 2d array I am trying to serial print the value of b[0][0].

Has to be zero but it dose not work!

Here is the code

void setup() {
  Serial.begin(115200);
  byte b[321][241];
  Serial.println(b[0][0]);
}

void loop() {

}

If the array is small like b[2][2] it dose work

In theory esp32 has ram of  520 KiB SRAM so can this be a problem?

Here is the error code

rst:0x8 (TG1WDT_SYS_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8

The code complies fine but the error gets when esp32 is running

esp32 version for arduino is 1.0.4

The ESP32 uses FreeRTOS to run everything, and that includes the Arduino API. Your code is running in a thread of its own ("loopTask"), and that task by default has 8192 bytes of stack allocated to it.

xTaskCreateUniversal(loopTask, "loopTask", 8192, NULL, 1, &loopTaskHandle, CONFIG_ARDUINO_RUNNING_CORE);

You cannot create local variables and other stack data that totals more than 8192 bytes.

Instead you will either have to have the variable as a global variable (or static local) so it gets allocated in the global data segment, or use new or malloc to create it on the heap (and don't forget the corresponding delete or free call when you're done with it).


Can I drive this relay shield with an Arduino Due? Sorry I'm new to electronics while I've some experience in coding. This let me very curious about the Arduino Due board: it is super powerful and I can run some C++ code that I can not with the normal Arduino Uno. But I lack in electronic theory, sorry if the question is a little bit dumb.

Can I drive this shield with an Arduino Due? The Due board is at 3.3V while the relays in the shield are at 5V.

What do I need to make them run smoothly?

Actually I'd like to run 5 of those shield with only one Arduino Due board. Do I have some problem with power supply?

You'd have to remove the yellow jumper. Connect 3.3v to the VCC and 5v to the JDVCC. But please double check that JDVCC is connected to one side of all the relays.

This way the opto-couplers are activated by 3.3v signals, which in turn activate the transistor (5v) used to engage the relay.


Waiting for an AT command to complete I'm looking for a way to wait for a response from an AT command to return OK or CONNECTED or whatever the command returns when it's true.

I can check if the serial is available, but that means I have to manually guess what time between commands to give them time to connect or start.

Function:

void ModemCommand(String command) {
  //Send command to modem
  mySerial.println(command);
  Serial.println(command);
  delay(100);
  while (!mySerial.available()) {
    //Wait for Response from modem
    Serial.println(F("No response yet"));
    delay(1000);
  }
  while (mySerial.available()) {
    Serial.write(mySerial.read());
    //Print response from modem
  }
  Serial.println("");
  //Linefeed after reponse
  delay(10);
}

Code example:

ModemCommand(F("ATE0"));
//Turn on echo
ModemCommand(F("AT+CFUN=1"));
//Turn modem functions on
waitSec(8,F("turning on Modem functions"));
ModemCommand(F("AT+CGREG?"));
//GSM attached?
ModemCommand(F("AT+CSQ"));
//Signal Quality
ModemCommand(F("AT+CSTT=\"internet\""));
//Set APN
ModemCommand(F("AT+CIICR"));
//Connect to APN GPRS
waitSec(8,F("connecting to APN GPRS"));
ModemCommand(F("AT+CIFSR"));
//Get IP

Does anybody know how to do this?

You would need to create a buffer which will populate over each loop so you dont block the main loop while waiting the all string.

When you get the string or your buffer is full, just check whatever is the response, and based on that you can make your decision.


Arduino programming through HC06 My goal is not upload sketch to Arduino Pro mini through bluetooth module HC06. I have made a breadboard version of DTR signal simulator which takes LED status pin as a source. The output from the detector goes to RST pin of Arduino. When connection is initiated the status LED stops blinking and output pin goes low and than high which leads to Arduino rebooting. This part works fine. Unfortunately avrdude from Arduino IDE does not see the bootloader and shows the following error in the console:

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

I have noticed that HC06 stops blinking with some delay after a connection is initiated. I suspect that this might be a problem. To overcome this issue the boot loader should probably be changed. Unfortunately I am not familiar with the embedded C programming, thus if someone has experience in changing the bootloadder, please help me to solve this puzzle.

The following is a scheme of detector:

Setting serial speed on your computer side doesn't change speed on the HC-06 side. So you have to set the same speed for HC-06 interface (and in your sketches) as a bootloader is using.


How to power an Arduino using automated mains/rechargeable battery switching? I'd like to power my Arduino circuit like a smartphone. That is:

When the device is unplugged, power by rechargeable battery
When the device is plugged in, power by mains and charge battery at the same time

I'd like to not go the expensive shield route and instead purchase some inexpensive breakout boards from Aliexpress or eBay if possible. I'm willing to put in the time to learn if someone will point the way.

Can someone please provide some guidance?

Yes, charging a battery and supplying an Arduino at the same time is possible as long as we manage the caveats (see below) of in-circuit charging.

This is what I use:

a 3.3V Arduino (a Pro Mini in my case),
a regular Li-Ion battery,
a charging controller that supports constant voltage (CV) and constant current (CC) charging,
optionally, a 6V solar panel.

This is how it works:

charger is fed via solar panel and/or USB supply,
battery is continuously supervised and charged on demand
Arduino is connected to the output side of the charger

This works because the load that the Arduino presents is relatively small compared to what the charger can feed (and what the battery can take).
During recharging the charge current will predominantly flow through the battery.
And since the current through the battery drops once it gets full, the charger can still recognise this drop and finish the charge cycle – even though the Arduino is connected all the time.

Example setup:

I took some quick snapshots, please excuse the image quality. Charger is in the center, Arduino to the upper left, battery in a holder to the lower left, solar panel to the upper right.

The Arduino has a voltage regulator, but I don't use it in this setup. An explanation why and when to use the regulator is beyond the scope of this question and a matter for another answer.

In the first photo the charger input is only connected to the solar panel, but the panel voltage is low. So the charger is actually off and the Arduino is running off the battery.

In the second photo the charger is now connected to a USB power supply. The charger is on and in CC/CV charge mode (as indicated by the red LED of this charger model).

In the third photo the charge cycle is completed, the battery is full (as indicated by the blue LED of this charger model). Note that the charger could determine the charge completion even though the Arduino is connected and running (no power saving tricks involved here).

Background info:

The charger switches between CC and CV mode, depending on the level of discharge the battery is in. Particularly, my charger uses CC mode in case the voltage on the battery side is below 4V and CV mode in case the voltage on the battery side is above 4V. The current limit can be configured and the voltage limit is hard coded to around 4.2V, which makes the circuit save for a device like Arduino.

Image source: Nanjing Top Power

Other chargers may have other thresholds, but that doesn't matter as long as it fits your battery type and uses constant current/voltage only.
I have no particular recommendation for a charger, but so far have a good impression of the one I used in this answer.

Caveats:

There are a couple of cases to consider, though:

Deep discharge

Should the battery voltage ever go below around 2.9V (e.g. deeply discharged battery), the charger will switch into trickle charge mode where only very small amounts of current are passed to the battery – too little current (i.e. too low a voltage) for the Arduino to run. Arduino will go into brown-out and try to restart until the battery has recovered. So this can become a state in which your Arduino won't respond for an unknown amount of time.

High load

If the load connected to the battery draws a current that isn't small anymore – compared to the battery charge current – then the charger cannot recognise a full battery anymore, since the current as seen by the charger will never fall off at the end of any charge cycle. So watch out how many gadgets you connect to this kind of in-circuit charger.

Wrong charger type

There are a multitude of ways to charge a battery. Things like trickle charge, pulse charge, timer based charging, and so on.
None of these would likely work, as the voltage those charger types generate could upset the Arduino and the load the Arduino presents could upset the charger.

Please also note that some chargers don't supervise the battery. With Li-Ion or Li-Poly (and other) batteries this would be a very bad idea. Always choose a charger appropriate for your battery.

Alternatives

The charger I use employs a linear regulator. That's not very efficient, other topologies are possible. But they might require supply filtering for the Arduino.

Shameless plug

I wrote a library for the purpose of supervising an Arduino's supply voltage (and chip temperature). This technique allows to check the battery level without any additional components. That library is called CoreSensors.

Further links:

New TP4056 Lithium Cell Charger Module with Battery Protection
Solar Pannel and LiOn or Lipo
How to autoregulate a TP4056 for maximum solar power extraction


Attiny84 and 2-Axis Joystick I have a Parallax 27800 2-Axis Joystick wired up to a AVR 14 Pin 20MHz 8K 12A/D - ATtiny84. The joy stick sends out a x y analog signal. I have programmed the Attiny84 to read the signals and set one of the attiny84 pins (high or low) depending on the direction of the joystick. In this example, each pin is wired up to a LED. The problem I am having is there is about a 1 second delay for the LED to light. The Attiny84 has a built in 8MHz clock. Would connecting an external 20MHz crystal fix this issue?

int UD = 0;
int LR = 0;

int DWN = 0;
int UP = 1;
int LEFT = 4;
int RT = 5;

int LRMID = 0;
int UPMID = 0;
void setup(){

  pinMode(DWN, OUTPUT);
  pinMode(UP, OUTPUT);
  pinMode(LEFT, OUTPUT);
  pinMode(RT, OUTPUT);

  digitalWrite(DWN, LOW);
  digitalWrite(UP, LOW);
  digitalWrite(LEFT, LOW);
  digitalWrite(RT, LOW);

  //calabrate center
  LRMID = analogRead(3);
  UPMID = analogRead(2);
}

void loop(){

  UD = analogRead(2);
  LR = analogRead(3);
  // UP-DOWN
  if(UD < UPMID - 5){
   digitalWrite(DWN, HIGH);
  }else{
   digitalWrite(DWN, LOW);
  }

  if(UD > UPMID + 5){
   digitalWrite(UP, HIGH);
  }else{
   digitalWrite(UP, LOW);
  }
  // LEFT-RIGHT
  if(LR < LRMID-5){
   digitalWrite(LEFT, HIGH);
  }else{
   digitalWrite(LEFT, LOW);
  }

  if(LR > LRMID +5){
   digitalWrite(RT, HIGH);
  }else{
   digitalWrite(RT, LOW);
  }

  delay(100);

}

While @alexan_e’s suggestion fixed your practical problem, I would argue that it did not address your root cause, which is that whatever board setting you’re working from in boards.txt assumes a clock rate of 8MHz, while in reality your fuses are set to boot the microcontroller at 1MHz. This caused your delay(100) to take 800ms, and was the entire reason for the slowdown.

Instead of fixing this at runtime, as aleman_e suggested, it seems more natural to me to bring your fuse settings into alignment with your compiler settings, using the “burn boot loader” Arduino command (which on Attinys generally does NOT burn a boot loader, but only sets the fuses to be in sync with the compiler settings).

If your application is not going to become much more complex, running at 1MHz might be a more efficient choice than running at 8MHz.


how can I send a variable to println? this is my method

void mensaje_sms()
{
  string numero = "777777";  // this is my variable
  SIM900.print("AT+CMGF=1\r");
  delay(100);
      SIM900.println("AT+CMGS=\"591"numero"\"");
//IM900.println("AT+CMGS=\"59177777777\""); //only in this way does it work
      delay(100);
      SIM900.println("SEND NUMERO VARIABLE RODO");
      delay(100);
      SIM900.println((char)26);
      delay(100);
      SIM900.println();
      delay(5000);
      Serial.println("SMS sent successfully");
    }

how can I send a variable to println?

Change:

SIM900.println("AT+CMGS=\"591"numero"\"");

to

SIM900.print("AT+CMGS=\"591");
SIM900.print(numero);
SIM900.println("\"");

Note that only the final call is to println() (which just prints a carriage-return character at the end.)


Arduino C, Led > binary alternative all lights I'm trying to alternatively have a random int generate a binary number with 4 lights.

This is my current code, However, it seems that all the lights(leds) go on, I don't think the minus option works. As in, it won't take a value from the currently randomized digit. (randombinary = randombinary - x)

I also tried just "randombinary - x"

const int button = 2;
const int redone = 13;
const int redtwo = 8;
const int greenone = 12;
const int greentwo = 7;
int randomnumber = 0;
int randombinary = 0;

void setup() {

  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(2, INPUT);

}
  void loop() {

delay(1000);

  int randomnumber = (1, 15);
  randombinary = randomnumber;

  if (randombinary >=8){
    digitalWrite(redone, HIGH);
   randombinary = randombinary - 8;
  }
 else {
   digitalWrite(redone, LOW);
 }

  if (randombinary >=4){
    digitalWrite(greenone, HIGH);
   randombinary = randombinary - 4;
  }
  else {
    digitalWrite(greenone, LOW);
  }

  if (randombinary >=2){
    digitalWrite(redtwo, HIGH);
  randombinary =  randombinary - 2;
  }
  else  {
    digitalWrite(greentwo, LOW);
  }

  if (randombinary >=1){
    digitalWrite(greentwo, HIGH);
  randombinary =  randombinary - 1;
  }
  else  {
    digitalWrite(greentwo, LOW);
  }

  }

Would appreciate any help!

Code review (one possible solution can be found below)

Absolute numbers in the code, like 15 as the limit for the random numbers are generally considered harmful. It would be better to give all absolute numbers a constantsname and use these throughout. The OP code did not use the constants for the pins, for instance.
Writing similar pieces of code in a row makes maintenance hard. Therefore, group similar items in any kind of list, like an array, and iterate over them.
Functions should have expressive names clearly stating what is going on inside.
Functions should be short and concise, ideally having only a few lines.

Try something along these lines:

// setting the number of bits to analyze, corresponding pins and corresponding powers of two.
// the latter is here for instructional purposes although it is redundant.
const int numberOfBits = 4;
const int randLimit = 15;   // 2^(1+numberOfBits)-1 actually;
int ledPins[numberOfBits] = {13, 8, 12, 7};
int bitValue[numberOfBits] = {8, 4, 2, 1}; // the powers of two

void turnOffAllLeds ()
{
  Serial.println ("turning all off");
  for (int i = 0; i < numberOfBits; i++)
  {
    digitalWrite (ledPins[i], LOW);
  }
}

void selectivelyTurnOnLeds(int value)
{
  turnOffAllLeds ();

  // now for each bit, check if it is set in the value, if yes: turn on corresponding led
  for (int i = 0; i < numberOfBits; i++)
  {
    if ((value & bitValue[i]) > 0)
    {
      digitalWrite (ledPins[i], HIGH);
    }
  }
}

void setup()
{
  for (int i = 0; i < numberOfBits; i++)
  {
    pinMode (ledPins[i], OUTPUT);
  }
}

void loop()
{
  selectivelyTurnOnLeds (random (randLimit));
  delay (1000);
}

P.S. When posting a question, please also post what your code is supposed to do. If it were not for a lazy prechristmas workday, I would not have taken the time to reverse engineer your code.


Disable auto-reset Mega 2560 on serial monitor open using 60 ohm resistor I tried preventing my Arduino Mega 2560 from restarting every time I open the serial monitor. This link didn't work for me at all.

I tried connecting the RESET pin to 3.3v pin via a 60 ohm resistor and it worked for me. The question is: If I leave that resistor permanently connected, will this solution damage my board as time passes?

A 22uF cap between reset and ground does work on my Mega 2560 - opening the serial monitor will not restart the program. However, the Mega is then not downloadable. Therefore, I grounded the cap thru a normally closed relay and connected its control to a digital output. I normally operate with the relay closed. When I want to download a new program I open the relay first. It works great :-)


Would an infinite loop inside loop() perform faster? When you're writing a typical sketch, you usually rely on loop() being called repeatedly for as long as the Arduino is running. Moving in and out of the loop() function must introduce a small overhead though.

To avoid that, you could presumably create your own infinite loop, like this:

void loop()
{
    while (true)
    {
        // do stuff...
    }
}

Is that a viable way to improve performance? Will it cause other problems if loop() never returns?

The part of the code on an ATmega core that does setup() and loop() is at follows:

#include <Arduino.h>

int main(void)
{
        init();

#if defined(USBCON)
        USBDevice.attach();
#endif

        setup();

        for (;;) {
                loop();
                if (serialEventRun) serialEventRun();
        }

        return 0;
}

Pretty simple, but there is the overhead of the serialEventRun(); in there.

Let's compare two simple sketches:

void setup()
{

}

volatile uint8_t x;

void loop()
{

    x = 1;

}

and

void setup()
{

}

volatile uint8_t x;

void loop()
{
    while(true)
    {
        x = 1;
    }
}

The x and volatile is just to ensure it isn't optimised out.

In the ASM produced, you get different results:

You can see the while(true) just performs a rjmp (relative jump) back a few instructions, whereas loop() performs a subtraction, comparison and call. This is 4 instructions vs 1 instruction.

To generate ASM as above, you need to use a tool called avr-objdump. This is included with avr-gcc. Location varies depending on OS so it is easiest to search for it by name.

avr-objdump can operate on .hex files, but these are missing the original source and comments. If you have just built code, you will have a .elf file that does contain this data. Again, the location of these files varies by OS - the easiest way to locate them is to turn on verbose compilation in preferences and see where the output files are being stored.

Run the command as follows:

  avr-objdump -S output.elf > asm.txt

And examine the output in a text editor.


Arduino motor shield will only work in one direction I have this Arduino motor shield which is hooked up with two DC motors. The board is the same as this one from Sparkfun.

A PWM output controls the speed of the motor, and a digital out controls the direction. The problem is that it only works in one direction, namely if the direction pin is high.

With the direction pin HIGH and 255 is written to the PWM pin, Vout on the terminals is similar to Vin. If I reverse the direction by setting the direction pin LOW I would expect Vout to be -Vin, ie. the polarity reversed. But not so. I get a little more than zero volt across the terminals.

It's the same for both channels.

Edit: The setup is powered from a 9V power adaptor through the barrel jack on Arduino.

Is the board defective, or am I misunderstanding something?

SOLUTION: Thanks to the edited post (especially #3) in the accepted answer, I not only looked at the schematic (again), I actually understood it. I had already noticed the jumper called V-LOGIC which on the picture from Sparkfun was set to 5V where it on my shield was not set. I really didn't know what it was used for, but I set it to 5V so it was the same. But by looking at the schematic and the inverters, I realized that the inverter was fed from V-LOGIC which was connected to 5V. And bingo: I had not connected the 5V pin on the shield, only vIN which I assumed would be sufficient. The thing is, I am awaiting a set of stackable headers instead of the ones supplied, so I only connected the minimum numbers of pins because I will need to desolder them when I get the new headers.

I think you may be having an issue with how you are powering the shield.  Are you trying to do it with just your USB connection?

In your photo, I do not see a connection to your Arduino's barrel jack or to the Vin connector of the shield itself.  According to the SparkFun site:

  The Ardumoto Shield should be powered through one of two power supply inputs. Pick one or the other:

  The barrel jack input on the Arduino.
  The Vin input on the shield

  If you don’t want to use the Arduino’s barrel jack input, you can use the Vin input on the shield instead. This voltage input will supply both the shield and the Arduino. Like the motor outputs, this connection is broken out to both a 3.5mm screw terminal and a 0.1"-pitch header.

  Do not supply power to both the Arduino barrel jack input and Vin on the shield!

I hope this helps!

EDIT BASED ON COMMENTS
Since you are properly powering the shield, I would recommend the following (see the shield's schematic for specifics):

Maintaining the connection shown above (with the addition of the 9V power supply connected to the barrel jack) ensure that you are able to properly set the DIRA input.  You can check this with a multimeter on pin 7 of the LN298 whenever you are trying to switch directions.
If you are getting the expected results on pin 7 (pin goes HI when your code wants the motor to go one direction and pin goes LOW for the other) - check pin 9... the value here should always be the opposite of what you are setting for DIRA on pin 7.  If that is all good, then you probably have an issue with the LN298.
If you are not getting the expected results at pin 9, but pin 7 looks good, then you are having a problem with the 74HC1G04 IC (although I would doubt this since you are having problems with both the A and B motor outputs).
If you are not getting the expected results at pin 7, then double check the code to make sure you have set and cleared the correct output pin.  I would also check the solder joints of the connectors on the shield - you can set a multimeter to do a resistance check from the shield's connector (pin 12) to the direction input on the LN298 (pin 7).  If the continuity is measuring close to 0 ohms then there is probably an issue with your code.
If your code looks good, I have also had issues with bad outputs on the Arduino - you can check to see if you are properly toggling the direction pin (pin 12) on the Arduino without the shield connected.  Then, if the pin is not toggling, there is probably an issue with your Arduino - try toggling a different (unused) pin and jumpering it.


Arduino uno + 5 IR obstacle sensor I have IR sensor with current draw 100ma i have to connect 5 of them is i can connect all 5 with arduino directly or i have to use external power suplly for them

An Arduino UNO has a max current of 20 mA per IO Pin and a max current of 200 mA of all Pins together. If you intent to drive the senders with the pins then this is impossible.

If you power the Arduino with USB, the VCC current is limited to 500 mA (thermo fuses). If you power it externally, it depends on the power supply. Using the voltage from the Vcc Pin is risky (IMHO), because the Arduino needs power too.

So with 100 mA per sensor I would definitively use an external power supply.


Best multiplexer for a led cube I had fun making a 3x3x3 led cube. Now I want to build a bigger one. I'd like to find out the best IC for it. I've seen that some projects uses multiplexer like 4051 or 74HC595.

I'd like to make it at least 8x8x8 (so the multiplexer has to easily be spotted in cascade), possibly supporting also the pwm (to fade the leds).

And I'm a little bit scared by the real time with a lot of LED.. do I have to solve the problem in hardware (with a "faster" multiplexer) o via software?

Those aren't multiplexing chips. Those are just chips to give you more outputs than your arduino has.

The multiplexing is just done on the microcontroller. But it depends on how you are wiring the leds. You can wire the cube to use less digital outputs, but you'll end up with a less bright leds.

You could use no multiplexing. That way the leds are lid with a 100% duty cycle. But for that you'd need 512 outputs.

You can choose to light up only one level at a time. That way you only need 72 outputs (64 for the leds, and 8 for selecting the level). This is a form of multiplexing. Since only one level is lid at a time, the leds have a duty cycle of 12.5%. Please note that because of the way humans perceive light, it will look more like 1/3rd the brightness, instead of 1/8th (so that's great). Also note that since you only need one level to be on at a time, some people prefer to use a decade counter IC for that.

You could also choose to only light one row at a time. That way you only need 24 outputs (8 for the leds, 8 to select which row, 8 to select which level). But you'd need some additional circuitry to combine row- and level-selection.

There are specialized multiplexing IC, but those only support rows and colums (not level). So you need 1 chip for each level, and more problematically you need to run 8-row and 8-culumn wires for each level to the bottom. That's quite a bit of wire, which might ruin the aesthetics of the cube.

In short. There are quite a few ways of making a 8x8x8 cube. I'd suggest finding a well documented build from someone else that you like and follow that.

Quite a bit of information. I hope it's of help. If you have any more question feel free to ask.


Repairing Analogue Inputs on Uno? After a long afternoon, chasing a fault on my project, I've come to find that I've damaged 2 out of the 6 Analogue Inputs. Their ADC reading doesn't display 0 when grounded, nor a known ADC value from a sensor.

I've identified the problem to the voltage divider sensors that were connected to these particular Analogue Inputs, I've since researched that topic and made some alterations.

I don't suppose by buying a replacement chip, will solve the problem of 2 bad Analogue Inputs? So I can save the hardware and reduce cost?

Thanks in advance for any help you can provide.

Stu

If the Analog input of your Arduino Uno is damaged, then unfortunately you have damaged the pins on the ATMEAGA328P chip directly.

As per the schematic below of Arduino Uno R3, the pins A0 to A5 are connected directly on the Pins 23 to 28 of the ATMEGA328P chip.

Therefore if you say that the 2 out of 6 Analog pins have been damaged then the only way to fix that is to replace the ATMEGA328P chip with a new one.

More can be read here about the UNO's hardware design.

PS. When replacing the ATMEGA328P chip, be sure to program the new chip with the Arduino Bootloader so you can upload sketches to it, otherwise it won't work ;)

Cheers!


Reading and comparing data from Arduino Uno EEPROM I'm trying to read compare data from EEPROM (Arduino UNO). Reading is working fine but comparing it using the '==' operator is not working as expected.

//string 'True' is already stored in EEPROM

int addr = 0;
char value = EEPROM.read(addr);

Serial.println(value);// this line successfully prints the letter 'T'

// but this function is not working
if (value == "T") {
  Serial.println("foo");
}

There is a HUGE difference between "string" and 'c' 'h' 'a' 'r'.

You are comparing address of string "T" with the numerical value of character 'T'.

The expression: if (value == 'T') will be much better.


Where can I find the complete list of Arduino Serial Command & Query Strings? I am planning to use the Arduino as a replacement for a USB-Controlled Digital I/O device, which will be integrated into an existing C++ software package that I created. I understand that the Arduino acts like a Serial device to a PC. Every serial device can be controlled by its own set of commands and queries. However, the only commands and queries that I've found for the Arduino involve flashing one-time programming to it from the "inside" rather than providing real-time automated control from the "outside."

Can anyone tell me where can I find the complete list of Arduino serial command & query strings? Thanks.

The Arduino has no "standard" serial commands.

It is a programmable device which you have to program yourself. The only serial commands it can respond to are the serial commands you yourself program it to respond to.

There are projects around that provide a serial interface, but they are generally designed for one specific purpose, and the commands or protocol they implement are unique to that project.

The closest to what you are asking for is the Firmata firmware, which comes with the IDE, and can be used to control the Arduino through the serial port using programs on your PC.


Can I compile a sketch for my attiny85 without an arduino board? I have a lot of Raspberry Pi's laying around, so I want to use those to program my attiny85 chips. The problem is that most of the code examples, libraries, and documentation out there assume you're using Arduino. Can I run Arduino commandline software on my Raspberry Pi, and use that to program the attiny85?

I'm trying to compile an RF24 program for the attiny using avr-g++, but I'm running into too many dependency errors, and I wonder if things will just be easier if I use Arduino software.`

Why wouldn't you be able to?

The compiler runs on the computer, not on the Arduino board. You don't need a board to be connected to compile either. If you enable verbose output during compile in the Arduino IDE settings it will tell you where it puts the resulting .hex file, after which you can use avr-dude to upload it to the target MCU.

If you want to use Arduino libraries you'll need to use an core for ATTiny devices (e.g. ATTinyCore). But either way you don't need an Arduino board to compile.

I'd also echo what @Marcus says, for the small devices you are better off completely ditching the Arduino stuff (it's such badly written, bloated, and inefficient), and simply starting with a nice clean C file.

There is nothing stopping you using the Arduino IDE or the avr-libc tools which it uses. If you add your own main() function in a C file and don't put anything in the .ino file you will be able to compile without any of the bloat.


Programming problem I need both if else cases to work but only else loop is running #include <SoftwareSerial.h>
#include <Servo.h>
Servo myservo1, myservo2, myservo3;

int bluetoothTx = 14;
int bluetoothRx = 15;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
myservo1.attach(9);

//Setup usb serial connection to computer
Serial.begin(9600);

//Setup Bluetooth serial connection to android
bluetooth.begin(9600);
 }

void loop()
  {
    if(bluetooth.available()>0)
     {
      if(bluetooth.available()>=4)
       {
        char buffer[4];
          for(int i=0;i<4;i++)
         {
          buffer[i]=bluetooth.read();
         }
       int incomingValue = atoi(buffer);

      if(incomingValue>=1000 && incomingValue<=1360)
        {
           unsigned int servopos = bluetooth.read();
           unsigned int servopos1 = bluetooth.read();
           unsigned int realservo = (servopos1 * 256) + servopos;

         if (realservo >= 1000 && realservo < 1360)
          {
              int servo1 = realservo;
              servo1 = map(servo1, 1000, 1360, 0, 360);
              myservo1.write(servo1);
              Serial.println("servo 1 ON");
           delay(10);
            }
           }
          }
         if(bluetooth.available()==2)
          {
            char inbit=bluetooth.read();
            if(inbit=='A'||inbit=='D');
           {
            char myval= bluetooth.read();
            if(myval== 'A')
            {
              myservo1.attach(9);
            }

             if(myval== 'D')
              {
               myservo1.detach();
              }
             }
            }
           }
          }

There are so many things wrong with that program I can't begin to sort it out.

Here's some of the most glaringly obvious errors:

if(bluetooth.read() >=0 && bluetooth.read() <=360)

Read a character. Check it's at least 0. Read a second character. Check it's less than 360.  Since characters are between 0 and 255 that will always succeed if there is one character of any form to read (if there is no characters to read you get -1).

else if(bluetooth.read()=='A'||'B'||'C'||'D'||'E'||'F');

Read another character and compare it to 'A'. This if is true if the character read is A. It also succeeds if B, or if C or if D, etc. That's not "if it's equal to C", just "if C". C is a character literal, so it's equivalent to a number. Any number that is not 0 is TRUE, therefore it's equivalent to:

if character is A or TRUE or TRUE or TRUE...

Which of course is just true, so it will always succeed regardless.

char myval= bluetooth.read();
if(myval== 'A')

Read yet another character from bluetooth (I sure hope there are enough there...) then compare it to a list of characters that are the same as you looked at above. You're comparing a new character this time, not the one you compared with the list a few lines beforehand.


Firmware backup and restore I need to have the firmware stored somewhere on the board in order to get back to it after flashing a new firmware.

Is there a way to store a backup of the firmware somewhere, and use a button to erase a newer firmware and get back to the old one, without re-flashing the old firmware again ?

Yes. You need to create a factory partition and upload your bin file to there.

You can read more about ESP32 partitions here

Note that none of the partition schemes in the ESP32 core have factory partitions, so you will need to create a custom one and link it to a menu entry (look at the boards.txt file to see how that is done).

The existing partition files are just .csv files within the ESP32 core. Copy one and modify it, then link that to a menu entry using the new file name.


Arduino pin 3 to 7 used in serial data transfering Good day.

I am new in Arduino so please bear with me. I need to know if Pins other than Pin 0 and 1 can be used as a serial connection. I have 3 devices that needs to be connected to Arduino via USB, but when I saw the specification of Arduino, it only implicate that only pins 0 and 1 is used for serial rx/tx. So is it possible to connect the other 2 usb connector via pin 2 to pin 5

Thank you very much for your answer

pins 0,1 are rx/tx for the hardware UART peripheral. Arduino (I assume UNO/Nano) have just one hardware UART.

there is a software library which makes use of any 2 pin to simulate hardware UART pin behavior for additional software UARTs (this is called bit banging). these "software" UARTs are not as fast as hardware ones and can't be relied on for fast baudrates (speeds). but for 9600kbps, they're good.
keep in mind, that despite they are easy to implement and versatile, they use CPU time when communicating and if you are using interrupts in your code, data flow will be affected.

https://www.arduino.cc/en/Reference/SoftwareSerial


compensate weight due to acceleration (loadcells) I'm trying to make a weighing scale that works in a lift. I'm using load cells to measure the weight, let's say it's F. Then I use that weight F and g which i know is 9,81 m/s^2 to calculate the mass of the object like this.
F = m*g <=> m = F/g

This works when the lift is in rest (or when moving with constant speed) but when it accelerates the weight F increases and because of that the mass also increases. Is there a way to compensate this weight(/extra force) due to acceleration?

The force due to acceleration is: F = m*a
So to calculate the weight while accelerating the formula is:
F = mg + ma or F = m(g + a)
Note, of course, that a can be positive or negative depending on whether the elevator is accelerating or decelerating.
The trick here is to know what "a" is.  The best approach is probably to get an accelerometer and use its reading in your calculations.
By the way, the mass is always a constant here.  It does not change, in Newtonian Physics at least, due to acceleration.


publish json data to mqtt I am trying to publish JSON data to mqtt with following code snippet

#include <Arduino_JSON.h>
JSONVar data;
data["temperature"] = temperature;
data["humidity"] = humidity;
data["pressure"] = pressure;
data["chipId"] = chipId;

String jsonString = JSON.stringify(data);
client.publish("esp32/data", jsonString);

But getting following error

/home/ubuntu/Arduino/libraries/PubSubClient/src/PubSubClient.h:144:12: note:   candidate expects 4 arguments, 2 provided
Multiple libraries were found for "PubSubClient.h"
 Used: /home/ubuntu/Arduino/libraries/PubSubClient
Multiple libraries were found for "Wire.h"
 Used: /home/ubuntu/.arduino15/packages/esp32/hardware/esp32/1.0.4/libraries/Wire
Multiple libraries were found for "Adafruit_BME280.h"
 Used: /home/ubuntu/Arduino/libraries/Adafruit_BME280_Library
Multiple libraries were found for "Adafruit_Sensor.h"
 Used: /home/ubuntu/Arduino/libraries/Adafruit_Unified_Sensor
Multiple libraries were found for "SPI.h"
 Used: /home/ubuntu/.arduino15/packages/esp32/hardware/esp32/1.0.4/libraries/SPI
Multiple libraries were found for "Arduino_JSON.h"
 Used: /home/ubuntu/Arduino/libraries/Arduino_JSON
Multiple libraries were found for "WiFi.h"
 Used: /home/ubuntu/.arduino15/packages/esp32/hardware/esp32/1.0.4/libraries/WiFi
 Not used: /opt/arduino-1.8.10/libraries/WiFi
exit status 1
no matching function for call to 'PubSubClient::publish(const char [11], String&)'

Whats is wrong here ?

What's your last error message?

no matching function for call to 'PubSubClient::publish(const char [11], String&)'

Read the documentation for the publish() method in PubSubClient:

  int publish (topic, payload)

  Publishes a string message to the specified topic.

  Parameters

  topic - the topic to publish to (const char[])

  payload - the message to publish (const char[])

Look at the parameters you're using. You're passing a String as payload. publish() expects payload to be a char[] (essentially the same thing as a char*) - a C language string. This is the error you're seeing.

Read the documentation for String. How do you get a char* from a String? The c_str() method.

You need to change

client.publish("esp32/data", jsonString);

to

client.publish("esp32/data", jsonString.c_str());

As for your other warnings, it looks like your Arduino libraries are a mess with multiple conflicting libraries installed; if you want to get rid of the warnings, clean up your libraries.


ATTINY85 with RGB LED I'm trying to DIY about a dozen BlinkSticks (discontinued, Adafruit) pictured here

I'm thinking to use a Digispark ATTINY85 to control a single RGB LED to show the status of some program running under Linux. Here is the proto board I have my eye on:

I could either use a single individually addressable RGB LED with a built-in WS281X controller

or a plain RGB LED with each color pin connected to a GPIO pin on the TINY85.

This is my first Arduino project, so I'm not familiar with the best way to approach this project. I'm trying to keep the part count low as well so the serial data approach is appealing too. Has anyone done this before and can explain their setup?

Prior work I've found for the simple control approach:

The newest blinkstick uses an addressable led, while the Adafruit kit appears to use a regular 4 pin RGB led. These are easier to get.

The digispark and the blinkstick are almost identical, but they use different pins for the USB connection. So to use the firmware for the blinkstick on the digispark, you need to change the pin numbers in usbconfig.h

#define USB_CFG_DMINUS_BIT      3
#define USB_CFG_DPLUS_BIT       2

PS. the pin numbers in usbconfig.h don't seem to match the schematic, so I'm not sure what's going on


Help me get my robotic car to work? So I recently followed a tutorial on youtube and I've assembled the car and connected all the wires.

What I've done:
Car

Now in the video, when the guy connects all the wires, the wheels constantly turn while in mine they're completely still. Is this a problem? Is it an indicator of some connection issue or something else?

For context, here is the schematic:

The ENA/ENB (enable A/B) pins have to be at HIGH level (either hardwired or set by an mcu). There exist lots of different driver boards (mostly based on the same ICs) which sometimes don't provide this enable pin, but they are "enabled" by default. You didn't tell us which board you use, but you'll know.


Question about configuration EEPROM or Flash I want to make an external (not related to Arduino) computer application that creates a big 'setup file' (like max. 64 KB). This setup file contains lookup tables (which are configurable and the tables with data themselves).

This 'setup file' needs be stored in the Arduino.

Now I thought of the following alternatives:

Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM).
Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB).
Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted.
Use a SD card and read information from there; however, I read 512 bytes SRAM is needed.

To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms.

Can you please give me some more information which alternative would work or not? Or maybe I missed out something trivial or an alternative is impossible?

Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM).

Perfectly viable - although an SPI Flash chip would be more appropriate.

  Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB).

It is the bootloader that can write to flash. I don't thing the main program can write to flash, or it would wipe itself out. You may need a special bootloader with your own protocol and upload program to go with it.

  Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted.

Perfectly viable, but tricky to say the least.

  Use a SD card and read information from there; however, I read 512 bytes SRAM is needed.

Yes, 512 bytes of SRAM, since that is the size of one block on an SD card. But an UNO has 2048 bytes of SRAM - more than enough for SD card support.

The SD card would be my route of choice. It's the easiest from a user's perspective (slip the card into their computer and copy the files), and pretty simple and straight forward to connect and program the Arduino for.

  To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms.

If you know where in the file the byte are then you can seek() straight to them. Takes almost no time. 20ms is an eternity for a microcontroller.


Rotary encoder I2C LCD menu I am trying to make a menu for a monitoring/control system.  I am not sure how to make this without interrupting my current code which needs to be monitoring my system at all times to shut off if it reads overload. It is mostly swtich () and case x: stuff. I have looked into attachInteruupt and rotary encoder examples, but none have really helped me figure out how to display a multiple layer menu where I can select to see the system readings as well as edit outputs.

There are a lot of posts here on rotary encoders with LCDs, but I can't seem to find a good skeleton menu code that works well and uses current libraries.  My biggest problem right now is making the menu layers without interrupting my monitoring code running in the background.

you might want to consider timed routines or interrupts.

For timers https://playground.arduino.cc/Code/Timer1 or similar can help.

When using interrupts be sure to be minimalistic because atmegas do not behave well when interrupts take too long to process.

About menus there are several, most of them dynamic and some requiring user display + nav code.

This open-source menu lib (https://github.com/neu-rah/ArduinoMenu) is static, that is good for bigger projects because it stores a lot on flash.

(-) you can not change menu at runtime (however it support value fields)
(+) requires no user code base
(-) setup involves several parts (inputs/output)
(+) non blocking polled mode. Just call the poll function on your code loop, the menu will just return if it has no input or output
(+) supports a lot of display devices, including i2c lcd
(+) supports encoder (interrupts (PCINT) or timed driver)
(-) atmega2560 interrupts (PCINT) only on 3 ports, PCINT might require pin mappings (not sure), but if needed the PCINT library examples can print one for you.


Arduino Controlling a stepper motor How can I get an Arduino to do the following to a Stepper Motor installed on a "Lead-screw" attached to my table-saw's Fence?

Turn the "lead-screw" clockwise when I press a given button, UNTIL I release the button.
Turn the same "lead-screw" counter-clockwise, when I press another button, UNTIL I release the button.
Adjust a "speed" knob, to control the motor's speed when the fence is moving; from very fast to very slow; and even stop when the control is completely counter-clockwise.
Turn a switch off, which will remove all control to the motor; so I can turn the shaft manually without resistance, whenever I do not want the fence to be under control of the motor.

That is ALL I need.

It is that simple. So what do I need? What do I need to purchase? I am a novice.

I've got to ask here.  Why use a stepper?
This would be fairly easy with two button switches and a regular DC motor.  One switch provides power to drive the motor CW the 2nd motor drives it CCW.

You would still need to choose a motor with the right torque but IMHO this method would be WAY easier than using a stepper, and arduino, writing code, etc.


Question on a car kit I bought recently bought an UNIROI Smart Car kit.
(UNIROI Smart Robot Car Kit Arduino Robot Kit with 4 Wheel Drive, Arduino UNO R3 Board, Ultrasonic Sensor, Infrared Tracking Module (No Welding Required) https://www.amazon.co.uk/dp/B07CWS344R/ref=cm_sw_r_cp_tai_wQExCbHT0YM8K)

I bought some extra things with it to make it more interesting, but the problem is is that I need to connect more pins to the Arduino but they are all taken up by the car. What I have noticed is that there are these extra pins along the side of the Arduino board as you can see here: https://imgur.com/a/j1Q8QVu

I know you guys don’t have it in hand, but I thought I’d give it a shot to see if any of you know I can use those pins.
The description of the car also quotes
“Extended Pin Interface. The chassis is designed with
extended pin interface for Arduino UNO, only need to solder pins for using, more convenient to develop
and build your own robot car kit”

Appreciate any help you guys got.

It seems that you'll have to do some extended modifications to the design. In fact, all Arduino Pins (D0 - D13, A0-A5) are connected to components on the board and thus in use.

Schematics and Code: https://mega.nz/#F!Xbg1FA5L!qGah_HlLFJ_NKxv7ILLY2g folder "5 SCH".

This means that the only way that you'll get new components into this project are:

removing components  and re-programming the firmware to not use them

e.g., the two tracking-sensors left&right -> A2 and A3 are free
e.g., the speaker pin (D13). Who needs a speaker?

restructuring components

e.g. for the analog sensors: instead of using the Arduino's analog pins, throw a I2C ADC module (e.g. ADS1115) in the build and change the firmware to get the analog values via that new module; making this project use an I2C bus will free all analog pins and cost 2 pins (SCL + SDA). The I2C bus has the additional benefit of being able to connect more than one device to it -- you can e.g. put a I2C GPIO expander (e.g. MCP23017) on it to gain 16 more digital I/O -- more than the Uno had to begin with.


upload.tool not used in custom boards.txt? I've created a custom board in boards.txt and changed the upload.tool to a nonsense value, and yet when I do an upload the IDE still calls avrdude.

For example, In boards.txt I've changed the line...

tile.upload.tool=avrdude

...to...

tile.upload.tool=nogood

...and added these lines to platform.txt...

# NOGOOD programmer

tools.nogood.cmd="dir"
tools.nogood.program.pattern="dir"
tools.nogood.upload.pattern="dir"

...and reloaded the IDE and hit upload.. and it still runs AVRDUDE.

(Note that my board ID is tile)

I've verified that I am editing the correct boards.txt by changing the cores key to nogood and this does generate an error.

Is boardid.upload.tool not the right place to change the recipe called when upload is hit?

How/where does the boardid.upload.tool=toolname key in boards.txt get mapped to the tools.toolname.upload.pattern key in platforms.txt?

I am using Arduino IDE version 1.8.3.

The custom boards.txt is in the directory Arduino\hardware\Move38\avr.

This full custom platform package is here...

https://github.com/bigjosh/Move38-Arduino-Platform

Thanks!

From https://github.com/bigjosh/Move38-Arduino-Platform#programmers:

  Since there is no bootloader in a tile, all code must be programmed rather than downloaded.

When you do an "Upload Using Programmer", the tool is specified in the {programmerID}.program.tool property in programmers.txt. The {boardID}.upload.tool value is only used for a standard upload.

Since programmers.txt is not in your hardware package, this makes it very inconvenient to customize. What's worse is that the platform.txt associated with the selected programmer is used, rather than the one in your hardware package, for "Upload Using Programmer". For this reason, some popular hardware packages include their own copies of all standard programmers. The downside of this is it really clutters up the Tools > Programmer menu if you have multiple of these packages installed.


Servo won't stop rotating I have an Arduino Uno R3 board and after some time not in use it seems to have corrupted. My code is below, basically I want to rotate a servo 90 degrees every 12 hours but as soon as I plug it in the servo starts rotating non-stop. Have tried multiple delay steps and shortening and lengthening the write but the same effect happens.

#include <Servo.h>

Servo myservo;

void setup {
  myservo.attach(10);
}

void loop() {
  myservo.write(90);
  delay(3600000);
}

I suppose you are using a continuous servo otherwise you won't be able to make it turn 90° more than twice (a normal servo has a varying angle of only 180°).

Now if you are using a continuous servo, you have to be aware that the value you pass to myservo.write() does not represent an angle anymore!

With a continuous servo, the value passed to myservo.write() now means a speed of rotation where, but the rnage of acceptable values is the same as for a normal servo, i.e. [0; 180]:

0 means max speed clockwise
90 means no motion
180 means max speed counter-clockwise

Now if you want to turn the servo exactly 90°, then you must know the max speed of the servo, and from that, compute the time during which you must let it turn:

// Start turning clockwise
myservo.write(0);
// Go on turning for the right duration
delay(TURN_TIME);
// Stop turning
myservo.write(90);

The problem here is to compute TURN_TIME. For this, you must check the datasheet of your servo.

On my own servo, a Feetech Micro 1.3kg Continuous Rotation Servo FS90R, the max speed is:

0.12s/60° when powered with 4.8V
0.10s/60° when powered with 6V

However, with the Arduino UNO, the supplied voltage should be exactly 5V, neither 4.8V, nor 6V.

If we take a linear approximation, then we can apply the following formula to find out the speed T (in s/60°):

T = (0.12 - 0.10) * (V - 4.8) / (4.8 - 6.0) + 0.12

Hence, for 5V, we can take it for granted that the max speed should be:

T = (0.12 - 0.10) * (5.0 - 4.8) / (4.8 - 6.0) + 0.12 = 0.116667

Since we need 90°, this means we must run the servo at its max speed during:

T' = T * 1.5 = 0.175s

Hence we now have the following program:

#include <Servo.h>

#define TURN_TIME 175

Servo myservo;

void setup {
    myservo.attach(10);
    // Initially the servo must be stopped
    myservo.write(90);
}

void loop() {
    // Start turning clockwise
    myservo.write(0);
    // Go on turning for the right duration
    delay(TURN_TIME);
    // Stop turning
    myservo.write(90);

    // Wait for 12h
    delay(12 * 3600 * 1000);
}

Of course, you will need some eperiments to find the exact right values; you may also find out that the servo may be sensitive to noise and even when it should not move (value = 90), it does move (not fast, but still it moves).


Wrong characters received with Bluetooth Mate Gold using Software Serial I have a Bluetooth device from Sparkfun which I would like to use with the Arduino Mega. If I connect the module via the hardware serial pin everything works fine but when I use other pins like 12 and 13 with SoftwareSerial, the communication doesn't work as expected.

THE CODE

#include <SoftwareSerial.h>

int bluetoothTx = 12;
int bluetoothRx = 13;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(115200);
  bluetooth.print("$$$");
  delay(100);
  bluetooth.println("U,9600,N");
  bluetooth.begin(9600);
}

void loop()
{
  //Read from bluetooth and write to usb serial
  if(bluetooth.available())
  {
    char toSend = (char)bluetooth.read();
    Serial.print(" Receiving: ");
    Serial.println(toSend);
  }

  //Read from usb serial to bluetooth
  if(Serial.available())
  {
    char modeS = Serial.read();
    Serial.print(" Writing Blu: ");
    Serial.println(modeS);
    bluetooth.print(modeS);
  }
}

I'm using an Android App (BlueTerm) to test the communication.

Here is what I get when sending a letter from Android to Arduino.

 Receiving: ÿ
 Receiving: ÿ
 Receiving: ÿ
 Receiving: ÿ
 Writing Blu: d
 Writing Blu: d
 Writing Blu: d

I'm not able to receive anything from the Arduino.

I've tried decreasing the baudrate but nothing changed. Do you have any advice?

Update

I have tried without the following lines but nothing changed... It seems that the module can be used only with the hardware serial pins 0 and 1... It's a shame

bluetooth.print("$$$");
delay(100);
bluetooth.println("U,9600,N");
bluetooth.begin(9600);

Maybe you fixed your issue, but I'm writing to help other people.

void loop()
{
  if (bluetooth.available())
  {
    dataFromBt = bluetooth.read();
    Serial.print("Receiving:");
    Serial.println((char)dataFromBt);