Arduino compiled sketch on sd card Hello I have just got my Arduino to read text from a text file and it is running perfectly. I was interested in being able to load a sketch into the Arduino and having it execute it, from and SD card. The Arduino wouldn't be connected to my laptop at all. I researched it and it is possible, with a different boot loader. Which is a bit annoying because I don't want to change the boot loader on my Arduino. I could put it on a standalone atmega chip but lets pretend I don't have those. So I was thinking if you had pre-compiled Arduino code. Which is in hex format and ready to be put on the board, would it be able to be loaded from the SD card? If so how would I go about doing this?

Yes it is possible:

With a different bootloader.

You need something which will erase the old sketch from the chip, read the data from the SD card, and write that into the flash of the chip. The only thing that can do that is the bootloader or some external device (another ATMega328p chip which we have to pretend you don't have).

Due to the way the architecture works you can only execute code out of the flash, so you need to program your sketch into the flash somehow. And that is the role of the bootloader.


NodeMCU second HARDWARE serial TX as a debug port I'm using a NodeMCU board to send commands to my home electricity switching box - using RS485 communication.

For that, I've connected MAX485 TTL-to-RS485 converter module to my TX and RX pins.

Currently, I can see the serial commands (that my program sends via RS485) also on my Serial monitor (in Arduino IDE), because the CH341 on the NodeMCU is bridged to the serial pins of it.

My problem is that if I want to send debug strings to my Serial monitor (like 'time was updated using NTP') - the RS485 bus will get them also.

I found some documentation about second TX pin available that can be used for debug messages, but I have 2 questions:

Will it be a HARDWARE port? I don't want to load another library and deal with software Serial ports.
Is there a way to get its output via the USB cable connected between the NodeMCU and my computer? Or will I have to connect another USB converter externally to that port to get its output into computer?

Many thanks!

ESP8266 Arduino core has Serial1 as write only hardware Serial on io 2 as TX. IO 2 is D4 on NodeMcu and Wemos D1 mini.

To use the USB chip of the NodeMcu/Wemos with Serial1 you could wire io 2 (D4) to TX. This would not disturb the flashing mode, because bootloader would still listen on standard Serial pins. I tested it.

And for RS485 adapter swap the Serial to io 13 (D7) as RX and io 15 (D8) as TX with the Serial.swap() command.


When does the pulsein() function start counting? I have an Arduino Pro mini 3.3V, 8 mHz and I want to use the pulsein() function for a low-going pulse. My question: Does the timer start when the function senses a LOW on the input pin, or when the function senses a high-to-low transition, or either?

Code snippet:

pinMode(3,INPUT); // Signal input to Arduino from pin 2 on LM339  - D3
int pwindow = 6000; // Maximum timeout value for pulsewidth
long pcounterA = 0; // Unfiltered Pulse Width of Channel 1
pcounterA = pulseIn(3,LOW,pwindow);
Serial.print(pcounterA);

Thanks for any help.
JT

According the official Arduino Reference: PulseIn

Fragment:

  Reads a pulse (either HIGH or LOW) on a pin. For example, if value is
  HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then
  waits for the pin to go LOW and stops timing. Returns the length of
  the pulse in microseconds. Gives up and returns 0 if no pulse starts
  within a specified time out.


Programming 328PB from Arduino IDE using Atmel-ICE to ICSP port Updated question.  The original question was based on using 'Upload' from the Arduino IDE, instead of 'Upload Using Programmer' under 'Sketch'.  The problem in getting the Atmel-ICE to work with Arduino IDE appears now to be one of incorrect ICE drivers loaded when I installed Atmel Studio.
Arduino requires libusb-win drivers, which can be checked with Zadig.   Available here: https://zadig.akeo.ie/
This problem was 99% solved (with help) by selecting  and the libusb-win32 driver using Zadig.   I say 99% solved, because my program now loads and runs! , but I do get the red 'X' there as the WCID status.
Apologies if this amendment to the original question is not in the correct context, this is new to me.   Thank You.
Jaco

Hello The 328 "PB" has major issues with running external clocks...(yes I have first hand experience with this PB model)... Try switching to the internal oscillator as I can testify first hand the the external clocks on the PB don't work correctly. They tend to sell the PB a few bucks cheaper because you will only buy them once and only once when you find out how bad the external crystal clock driver is. If you look at the latest datasheet for the PB they try and talk their way out of the bad driver by explaining how you need to match capacitors with the following snippet. I call BS as the 328p never needed such precision on it Xtal1 & 2 pins to run but to be fair they PB is meant to be low power.
This Crystal Oscillator is a low power oscillator, with reduced voltage swing on the XTAL2 output. It gives
the lowest power consumption, but is not capable of driving other clock inputs, and may be more
susceptible to noise in noisy environments.
The crystal should be connected as described in Clock Source Connections. When selecting crystals,
load capacitance must be taken into consideration. The capacitance (Ce+Ci) needed at each TOSC pin
can be calculated by using:
�� + �� = 2�� − ��
where:
• Ce - is optional external capacitors. (= C1, C2 as shown in Figure 11-2)
• Ci - is the pin capacitance in Table 11-3.
• CL - is the load capacitance specified by the crystal vendor.
• CS - is the total stray capacitance for one XTAL pin.
Table 11-


Arduino Leonardo - Using ICSP pins for serial I'd like to know if it's possible to use the ICSP header pins on the Leonardo as GPIO pins, for example for software serial, and how to address them. I've a project which needs all available I/O pins, and I could use having serial comms on those "extra" pins.

From packages/arduino/hardware/avr/1.6.*/variants/leonardo/pins_arduino.h:

// Map SPI port to 'new' pins D14..D17
#define PIN_SPI_SS    (17)
#define PIN_SPI_MOSI  (16)
#define PIN_SPI_MISO  (14)
#define PIN_SPI_SCK   (15)

static const uint8_t SS   = PIN_SPI_SS;
static const uint8_t MOSI = PIN_SPI_MOSI;
static const uint8_t MISO = PIN_SPI_MISO;
static const uint8_t SCK  = PIN_SPI_SCK;

Those are the pin names and numbers you can use. Note that SS/17 is connected to the RX LED.


SIM900 Modem is not responding I'm working with arduino nano and it has interfaced with SIM900 GSM. I'm sending "AT\r" to GSM modem, but not getting response.

void setup()
{
  Serial.begin(9600);
  Serial.println("Setup is Ready");
}

void loop()
{
   Serial.write("AT\r");
   delay(1000);
   if(Serial.available() > 0)
   {
     Serial.println("Data received");
     Serial.println(Serial.read());
   }

}

Serial monitor:

Setup is Ready

ATATATATATATATATATATATATATATATATATAT

I've set the 9600 baudrate to modem and my rx and tx is connected correctly...
What is the problem?

Thanks

You should not use the same Serial interface to debug and talk to your SIM900. You should use a SoftwareSerial interface to talk to the SIM900 and use the hardware Serial to send response back to your computer.

Try this code:

#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of SIM900
const byte txPin = 3; // Wire this to Rx Pin of SIM900

// We'll use a software serial interface to connect to SIM900
SoftwareSerial SIM900(rxPin, txPin);

void setup() {
  Serial.begin(115200);
  SIM900.begin(9600); // Change this to the baudrate used by SIM900
  delay(1000); // Let the module self-initialize
}

void loop() {
  Serial.println("Sending an AT command...");
  SIM900.println("AT");
  delay(30);
  while (SIM900.available()){
     String inData = SIM900.readStringUntil('\n');
     Serial.println("Got reponse from SIM900: " + inData);
  }
}


Error: 'SofwareSerial' does not name a type I have trouble compiling this sketch. The error I get is

  'SoftwareSerial' does not name a type

Any ideas how could I fix it?

#include SoftwareSerial.h

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

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Ready!");

  // set the data rate for the SoftwareSerial port

  // for HC-05 use 38400 when poerwing with KEY/STATE set to HIGH on power on
  mySerial.begin(9600);
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

You forgot the quotation marks, try

#include "SoftwareSerial.h"


Can't connect to Arduino Uno + Wifi webpage I am using this board:

Arduino Uno Wifi

In the manual it says I should connect to its wifi which I did and it says unidentified network. When I go to 192.168.240.1 nothing shows up. How do I find out which ip address I should use? I tried ipconfig /all but it doesn't show anything for the wifi connection.

EDIT:

When I try to flash my ESP8266 with the ESP8266 Download tool it gives me this error:

test offset :  0 0x0
case ok
test offset :  0 0x0
case ok
test offset :  2080768 0x1fc000
case ok
test offset :  2088960 0x1fe000
case ok
test offset :  4096 0x1000
case ok
======
CONNECT BAUD: 115200
============
....._____....._____....._____....._____....._____....._____.....
_____....._____....._____....._____
[2017-11-22 12:00:42,029][ESP8266Loader_spi[1]]
[espDownloader.pyo][line:349][ERROR]: Chip sync error: Failed to connect to
ESP8266: Timed out waiting for packet header
[2017-11-22 12:00:42,029][ESP8266Loader_spi[1]][espDownloader.pyo][line:437]
[ERROR]: ESP8266 Chip sync error esp_sync_blocking.

Picture of my board and current dip switch settings:

I've never seen this sort of board before.  Normally Arduinos communicate with ESP8266's using a serial connection and the AT command set.  I think that is what this board is doing, because it says you will need new firmware if you want to program the ESP.  So you need to find the AT command that gets the IP address.
(Sorry I don't know the command, never used the AT commands, never likely to)


Set start time for arduino uno clock I'm programming an arduino uno with attached screen to be a clock and have the code below. It counts up from zero the milliseconds, seconds, minutes and hours and when it hits 24 hours it starts again from zero.
Does anyone know how I can set the start time that it automatically starts at when it is reset? It will be a one off thing and I don't want it to interfere with the clock resetting to 0 hours after it hits 24. Thanks

#include <Wire.h>
#include <LiquidCrystal.h>

#define MILLIS_OVERFLOW 34359738

/**
 * Clock Variables
 */
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds, minutes, hours;

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup()
{
    lcd.begin( 16, 2 );

}

void loop()
{
    setClock();
    /**
     * After set clock now you have 3 int variables with the current time
     */
     //seconds
     //minutes
     //hours
     lcd.setCursor ( 0, 1);
     lcd.print(hours);
     lcd.print(":");
     lcd.print(minutes);
     lcd.print(":");
     lcd.print(seconds);
     lcd.print(":");
     lcd.print(elapsedMillis);

}

void setClock()
{
    currentMillis = millis();
    /**
     * The only moment when currentMillis will be smaller than previousMillis
 * will be when millis() oveflows
 */
if (currentMillis < previousMillis){
    elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
} else {
    elapsedMillis += currentMillis - previousMillis;
}

/**
 * If we use equals 1000 its possible that because of the mentioned loop limitation
 * you check the difference when its value is (999) and on the next loop its value is (1001)
 */
if (elapsedMillis > 999){
    seconds++;
    elapsedMillis = elapsedMillis - 1000;
}

if (seconds == 60){
    minutes++;
    seconds = 0;
}
if (minutes == 60){
    hours++;
    minutes = 0;
}
if (hours == 24){
    hours = 0;
}

previousMillis = currentMillis;
}

Assume you want the clock to start at 08:42:21, change

int seconds, minutes, hours;

to

int seconds = 21, minutes = 42, hours = 8;

Note that you should always also initialize (as in the second case above), and not only declare (as in the first case) all variables before you first read their values. Otherwise, for local variables you cannot be sure what their initial value is. (Global variables are implicitly initialized to zero if not explicitly initialized.)


First Arduino Uno - Immediate Problems I'm new to Arduinos but researched thoroughly before buying one. Just for context I'm an IT Professional with 20 years in the game, I'm comfortable with Linux/Unix, Windows, Raspberry Pi's, electronics, hardware, software and monitoring/switching COM ports.

I've purchased my first Arduino (actually a Elegoo Uno R3 clone) and have just tried it out of the box connected to two different systems; one Windows 7 64bit Enterprise the other Kubuntu. Despite having the correct COM port selected on both I'm getting similar error messages:

**avrdude: ser_open(): can't open device "\\.\COM15": The system cannot find the file specified.**

or

**avrdude: ser_open(): can't open device "\\.\COM6": Access is denied.**

Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Yes I have tried different COM ports.

Yes I have tried turning off Firewalls

Yes I have tried different USB cables.

I have a solid green LED and a intermittently blinking orange LED.

The suggested Troubleshooting guide + many Forum Threads do not seem to cover this exact error I'm encountering - well they do but they tend to be people with the simple issue of them not selecting the correct COM port or having the same COM port tied up with another task. Then choose the correct port and it works. I'm confident I have the correct COM port and when I click Get Board Info it pulls down the correct board information and serial number etc.

On the Linux system I was seeing a similar behavior with slightly different wording: Permission Denied

On my Windows 7 system I run as a Standard User (as one should, not as an Administrator), but regardless I have tried running the Arduino application normally and as an Administrator user but it has the same result. And it seems strange that it encounters the same style of error across multiple different operating systems.

Have I just been really unlucky and got a dud for my first Arduino or am I missing something obvious?

Thanks for your time and help.

On Linux "Permission Denied" generally means one of two things:

You're not in the dialout group (or you haven't logged out and logged in since), or
Something else is using the serial port.

For 1:

sudo usermod -a -G dialout ashley
<log out or reboot>

For 2:

The most common culprit is ModemManager. The simplest cure is to uninstall it:

sudo apt-get remove modemmanager


Prevent Arduino Mega from setting all Outputs to HIGH on Reset The Arduino Mega 2560 Rev 3 has multiple relays connected to its digital output pins.

Whenever the Arduino is reset (using reset button, turning on Serial Monitor etc), the Arduino turns on all relays then turns them off. I cant find any function in my sketch that causes the outputs to go HIGH then LOW. Assuming this is a normal feature of the Arduino, how can we prevent this and ensure that the outputs do not flip to the HIGH state?

The ATmega2560 itself comes out of reset with all pins in high-Z (DDRx=0, PORTx=0). Your observations are likely due to the bootloader. Check the bootloader source to verify that it is responsible for this.


serialEvents within a class My .ino looks roughly like this

#include "command.h"

Command command;
void setup() {
}

void loop() {
}

command.h

class Command
{
    public:
        Command();
};

command.cpp

#include <Arduino.h>
#include "command.h"

Command::Command() {
  Serial.begin(9600);
}

void serialEvent() {
  while (Serial.available() > 0) {
    char inChar = (char)Serial.read();
    Serial.print(inChar);
  }
}

The serial events don't seem to be happening. It works normally if I move the code out of the class.

When you put the Serial.begin in the constructor and declare the Command object at file scope, the Serial.begin will occur before setup().  Not recommended, perhaps not allowed.

If you do that, the compiler has to figure out that the Serial instance must be constructed before the Command instance is constructed.  It can't always figure out the correct order.

In general, this is why you see many classes with a begin or init method.  This allows the construction of file-scope instances to take place in any order, before setup.  Then setup does the Command.begin(), which finally calls Serial.begin, long after Serial has been constructed.

Also, using SerialEvent is no better than doing the polling in loop().  If you're busy doing something else, SerialEvent does not get called.  If you need to handle characters in the background, in the RX interrupt, you might want to take a look at a modified version for the Serial object(s) I posted, NeoHWSerial.  You can attach a routine to be called whenever a character is received.


Nano + ESP8266 control pins with REST API I connected and flashed successfully an ESP8266 module to a Nano. Now I want to control pins values with a REST API, but all the libraries I found are for using standalone ESP8266 modules (without Arduino) or for Arduino with some other modules like CC3000 etc. Can anybody recommend a library please?

You can use Firmata to control the Arduino pins, just having the ESP8266 publish a web page exposing the Firmata operations you desire to expose and sending the user actions to the Arduino via serial using the Firmata protocol.

To make your life easier you can consider your ESP8266 an equivalent of your serial console: everything you write from the ESP82667 becomes input data on the console for your Arduino and the other way around.

In Firmata, each command can be read from a generic Stream, with Serial being the default implementation.


Using Arduino audio to control an LED light I am looking for a way to control an LED on a circuit board using audio input for learning purposes.

I have written my own speech recognition system using dynamic time warping in Python, but I would like to know if (and maybe what models if not all can do) Arduino can possibly handle the processing of a 70 by 70 O(n^2) matrix traversal with fft or dct operations on audio input divided into 10ms frames.

Any advice will be appreciated.

The Due or Tre may have enough power for this. The Yún may be able to offload it to the more powerful CPU. Every other Arduino will struggle with it.


How to detect the pulse width from microphone as Input? I'm working on a project that detects the pulse width of an audio signal, which uses a microphone as an input. The user gives 2 different types of sounds one last less 0.3 seconds and other lasting less than 0.7 seconds. I've attached the audio visualisation of the signal pic in the attachment.
All want to detect is their pulse widths.

I tried Pulsein() - but as you can see that it has a variable until 0.3 or 0.7 seconds it only detect the first and most peak and returns the value which is almost zero.

But all I need is the total time taken for the pulse to rise from 0 and to variate and then become 0 this total time period is what I require.
would duty cycle help ? or any other functions available to detect two different sounds in arduino ?

pulse width

You will need some sort of interface circuit between your mic and your
Arduino. Best would probably be to have some kind of external peak
detection. This way the Arduino reads instantaneous wave amplitude. The
other option is to only shift and scale the signal so that it fits the
Arduino ADC, acquire the signal at a high enough sampling rate, and
compute the instantaneous amplitude in software.

I suggest you take a look at this sound-meter program. You could use
it as a basis for your own processing.

Then you just have to define a threshold and time how long the amplitude
remains above that threshold.


How to make car turn 90 degrees? I have an elegoo car model and am trying to make it turn 90 degrees whenever it gets to a 90 degree turn. This model has line tracing and it works fine on curved surfaces but doesn't work so on 90 degree turns.
    /Line Tracking IO define
#define LT_R !digitalRead(10)//connected to pin 10. Value is inverted
#define LT_M !digitalRead(4)
#define LT_L !digitalRead(2)

#define ENA 5//input to enable motor A. Controls speed
#define ENB 6//input to enable motor B
#define IN1 7//Control spinning direction of motor A. If one of them is high motor spin(an OR gate)
#define IN2 8//Same motor A
#define IN3 9//3 and 4 are for motor B
#define IN4 11

#define carSpeed 100

void forward(){ //car goes forward
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("go forward!");
}

void back(){ //car goes backwards
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("go back!");
}

void left(){ //goes left
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("go left!");
}

void right(){ //goes right
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("go right!");
}

void stop(){ //power is shut off
   digitalWrite(ENA, LOW);
   digitalWrite(ENB, LOW);
   Serial.println("Stop!");
}

void setup(){
  Serial.begin(9600);
  pinMode(LT_R,INPUT);//takes input from all the sensors
  pinMode(LT_M,INPUT);
  pinMode(LT_L,INPUT);
}

void loop() {

  if(LT_M){
    forward();
    while(LT_M);
  }
  else if(LT_R) {
    right();
    while(LT_R);
  }
  else if(LT_L) {
    left();
    while(LT_L);
  }

  else if (LT_M && LT_R && !LT_L) {
  delay(500);
  right();
  }

  else if (LT_L && LT_R && !LT_R) {
   delay(500);
   left();
    }

First: Your code as 2 problems:

As stated in the comments by PeterPaulKiefer, when you use
  pinMode(LT_R,INPUT);

That is not working as intended by you. LT_R is defined at the top as
  #define LT_R !digitalRead(10)

Thus the compiler will see
  pinMode(!digitalRead(10), INPUT);

digitalRead() will return zero or one, thus you are configuring pin 0 or pin 1 here (depending on the state of the sensor at startup). Instead you need to directly use the pin number (10) or use another define for the pin number itself. Your code only works, because all the pins are configured as INPUT (tristate) at startup of the microcontroller, so that they don't break something with a wrong signal. You got lucky there.

The last two else if statements are never executed:
  else if (LT_M && LT_R && !LT_L) {
      delay(500);
      right();
  }
  else if (LT_L && LT_R && !LT_R) {
      delay(500);
      left();
  }

The conditions here will first evaluate LT_M (in the first statement) and LT_L (in the second statement) respectively. Only if these are true, the rest of the expression will be evaluated. But you already checked for both of them being true above. When they are, the following else if statements don't get executed (thats the logic of if else statements). And if they are false, the code will also not be executed.
When you get to a 90° right corner, the middle and right sensor will trigger. Currently this will lead to the robot just keeping going forward.

So you need to change your code to actually check every every possible combination of the sensor states.
Also keep in mind, that a sharp corner needs way more turning, than a curve. Depending on the width of the line are the distance between your sensors, you might or might not be able to distinguish between those two cases. You should analyze, which sensor states you would have in which situations, write that down and then write code for every state. You could also put all sensor states into one single number, so that it is easier to check for it in the code. Something like this:
byte all_states = digitalRead(2) + 2*digitalRead(4) + 4*digitalRead(10);

Each combination will give you a unique number to work with. Effectively this stores the states of the sensors in one bit of the number each. Bit 0 is for pin 2, bit 1 is for pin 4 and bit 2 is for pin 10. You can also write this with bitwise operators:
byte all_states = digitalRead(2) | (digitalRead(4)<<1) | (digitalRead(10)<<2);

For example: If the right sensor is triggered, but not the others, you would get a binary number 0b00000100, which is decimal 4. If the left and the middle sensor are triggered, but not the right one, this results in 0b00000011, which is decimal 3. Then you could check with a switch statement:
switch(all_states){
    case 0: //No sensors triggered
        break;
    case 1: // Left sensor triggered
        break;
    case 2: // middle sensor triggerd
        break;
    case 3: // middle and left sensor triggered
        break;
    ...
}

You see how it works. The code for each case then goes inbetween of each case and break line.


'Delay command' and bluetooth communication problem I have a project where I send data to Arduino via Bluetooth using an Android application. For example, when I press 1 from the 'bar led' part of the application, an animation needs to happen. When I press 2, a different animation will be displayed. However, because there is a 'delay command' in the animations, there is a delay in data exchange when I press the button. How can I prevent this? Is there a command I can use instead of the 'Delay command'?

void loop() {
  if (bluetooth.available()) {
  while (bluetooth.available())
    {
      bar_analog = bluetooth.parseInt();
      head_analog = bluetooth.parseInt();
      bar_anim = bluetooth.parseInt();
      strip_anim = bluetooth.parseInt();
      motor_speed = bluetooth.parseInt();
      direct = bluetooth.parseInt();
      level = bluetooth.parseInt();
      if (debug) {
        Serial.print("Bar Brightness: ");
        Serial.println(bar_analog);
        Serial.print("Bar Animation Type: ");
        Serial.println(bar_anim);
        Serial.print("Headlight Brightness: ");
        Serial.println(head_analog);
        Serial.print("Strip Animation Type: ");
        Serial.println(strip_anim);
        Serial.print("Motor Speed Level: ");
        Serial.println(motor_speed);
        Serial.print("Direction: ");
        Serial.println(direct);
        Serial.print("Mast Goes: ");
        Serial.println(level);
        Serial.println("--------------------------------");
      }
      if (bluetooth.read() == '\n') {

      }
  }}
  if(bar_anim==1) {
  digitalWrite(8,HIGH);
  delay(50);
  digitalWrite(8,LOW);
  delay(250);
  }
  else if(bar_anim==2) {
  digitalWrite(8,HIGH);
  delay(250);
  digitalWrite(8,LOW);
  delay(50);
}
}

I see 2 problems with your code:

You use the delay() function, which is not good coding style, since it is basically busy waiting. The Arduino will do nothing in this time, also not reacting to any input. Instead you should use a non-blocking coding style, which only does something, when it is time to do so, and will not block until something happens. You can see this style in the BlinkWithoutDelay example, that comes with the Arduino IDE. It uses millis() as a time measure. Think of how you would bake a pizza. You would not sit on front of the oven doing nothing, until the pizza is ready. You would do other things while looking at your watch regularily, checking, if it is time to take out the pizza.
In the Serial communication part you use parseInt(). That can be a problem, since it has a timeout of 1s (standard value). Until the timeout the function will block. This is mitigated, if you consecently send a non-digit character at the end of every value. But it is better to first read a full message (until the newline character \n) and then process the message as a whole.

Also the line if (bluetooth.available()) is not necessary here, since the while loop will do the same.


Does the reset button work when not powered? I'm working on a project and my dad hit the reset button on my Arduino board, unknowingly. If it wasn't connected to any power source or computer, did it still reset? Do I have to upload my code to the board again? Or does the board need power to be reset?

The reset on an Arduino does not erase anything. It merely restarts execution of an already uploaded program. Also the AVR needs to be powered on for it to realize whether it has been reset.

Every time you power on an Arduino it automatically starts code execution from the beginning of the program in the flash memory.


Problems with I2C connection on ESP8266 - 12F, which pins should I use? Previously I had pined the temp/hum sensor HDC1080 with an Arduino using this sketch and everything worked fine. Now I want to run it over an ESP-12F, I uploaded it but it has issues at the time of establishing I2C connection. Basically, I'm not sure if at the end of setup() the I2C connection has actually begun, because I get this at the serial monitor:

As far as I see, the code skips everything related to Wire library. I blame it on the SDA/SCL pins, but actually none of the pins are working for me. I found that default I2C GPIO's are 2 and 14, I tried with them and got no result; later I tried with 12/16, as the commented Wire.begin line says, but it was the same. I even read some possible solutions in this post but I not even have the mentioned libraries.

Could you give me any suggestion, please? This is the sketch I'm using:

#include <Wire.h>

#define HDC 0x40 //B1000000 MSB
#define cociente 65536 //2^16

uint16_t humrawvalue;  //Raw data value, MS byte = valmsb, LS byte = vallsb
uint16_t temrawvalue;  //Raw data value, MS byte = valmsb, LS byte = vallsb
uint8_t humvalmsb, humvallsb;  //Raw 8-bit byte of humidity
uint8_t temvalmsb, temvallsb;  //Raw 8-bit byte of temperature
int incomingByte = 0; //Action input
float humidity, temperature;

void setup() {
  delay(100);
  Serial.begin(9600);
  delay(100);
  Serial.println("Hello");
  //Wire.begin(12,16);
  Wire.begin();
  Wire.setClockStretchLimit(1500);
}

void loop() {
  if (Serial.available() > 0) {    //User presses 1 to start sensor reading
    // read the incoming byte:
    incomingByte = Serial.read();
    yield();
    // say what you got:
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
  }

  Serial.println("---g-");  //Just guideline

  if (incomingByte == 49){
    Serial.println("IIIII");  //Just guideline
    Wire.beginTransmission(HDC);
    Wire.write(0x00);
    Wire.endTransmission(true);
    delay(200);

    Wire.requestFrom(HDC,4,true); //It asks for 4 bytes, 2 bytes per register
    if(Wire.available()){
      Serial.println("     ");
      Serial.println("Measuring: ");
      temvalmsb = Wire.read();
      temvallsb = Wire.read();
      humvalmsb = Wire.read();
      humvallsb = Wire.read();

      Serial.println("====TEMPERATURE====");
      Serial.print("MSB: "); Serial.println(temvalmsb, BIN);
      Serial.print("LSB: "); Serial.println(temvallsb, BIN);
      temrawvalue = temvalmsb <<8| temvallsb; //Locates each byte in its proper place
      Serial.print("Temp: "); Serial.println(temrawvalue, BIN);
      temperature = ((float)temrawvalue/(float)cociente)*165.0-40.0;
      Serial.print("Temperatura [C]: "); Serial.println(temperature);

      Serial.println("====HUMIDITY====");
      Serial.print("MSB: "); Serial.println(humvalmsb, BIN);
      Serial.print("LSB: "); Serial.println(humvallsb, BIN);
      humrawvalue = humvalmsb <<8| humvallsb;
      Serial.print("Hum: "); Serial.println(humrawvalue, BIN);
      humidity = ((float)humrawvalue/(float)cociente)*100.0;
      Serial.print("Humidity [%]: "); Serial.println(humidity);

      Serial.println("     ");
      delay(3000);
    }
  }
  Serial.println("++++"); //Just guideline
  delay(3000);
}

Regards!

Unlike most Arduinos, the ESP8266 doesn't have a hardware TWI, so I²C is bit-banged in software. This means that you can use any GPIO pins. By default, Wire.begin() initializes pins 4 (SDA) and 5 (SCL), but you can specify other pins using Wire.begin(int sda, int scl).

Documentation

(Note: the datasheet specifies GPIO2 as SDA and GPIO14 as SCL, but that doesn't matter, AFAIK, it's just a convention.)


Can I increase the 10 event limit in Simon Monk's Timer library? On Dr. Monk's library page here, he states: "You can attach up to 10 events to a timer." I am wondering if this is a hardware limit, or if it was an arbitrary number he chose for his library.

In Timer.h, he defines the maximum number of timed events like this:

#define MAX_NUMBER_OF_EVENTS (10)

Can you foresee any problems if I changed that to a higher number? My sketch is already approaching the limit of 10 timed events running at the same time, so it would help me if I was able to increase the maximum number of timed events to about 20.

I don't see anything that would cause any issue. Just don't exceed 255.


What's wrong with my Arduino board? When I connect the Arduino to my PC the Led "ON" lights for a second then turns OFF. I wonder if the Arduino has a fault?

Most likely a short between VCC (5 volt) and GROUND. When there is a short the fuse will kick in after a second, and disable the whole board, including the ON-led.

When you disconnect the board, the fuse will reset.

So either the board is faulty of the connection you made to it are.


Why can't most servos rotate more than around 180° I was looking how a servomotor works. I realized that a standard servo can only turn up to 180°, but I didn't understand why. Is it because of the potentiometer?

Fundamentally, because the systems they were designed for convert rotary motion to linear, typically with a range substantially less than 180 degrees (probably more like 120 degrees).

Next, because the control scheme of PWM position pulses is not able to convey requests over an arbitrary range - the mapping of pulse width to position must be limited, and it is sensibly set up to map to something related to the useful range.

Because these limitations in task, a fairly ordinary rotary potentiometer of less than 360 degree range can be employed for position sensing.

Given that the useful range is limited, and the potentiometer relatively easy to damage by over rotation, the gearbox is typically constructed with a mechanical rotation stop somewhere outside the normal range of self rotation.


Sketches not uploading to Micro from Ubuntu 14.04 I recently bought an Arduino Micro to see what all the fuss was about and I figured I'd use it with Ubuntu on an older Dell Latitude. I was able to install all of the files using some tutorials but I have this problem uploading sketches. After plugging in the board, the green top LED is consistently flashing so it seems to be working, but when I try to upload a sketch I get the following error

Connecting to programmer: .avrdude: Send: . [1b]
avrdude: Send: S [53]
avrdude: ser_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding

Any ideas how to fix this? I tried pressing reset during the send as some forums have suggested but it doesnt seem to be working.

I have a Micro and Ubuntu 14.04. I have successfully uploaded sketches to the Micro using IDE 1.0.6. Thus that combination should work.

I suggest you get the sketch compiling OK. Then hold down the Reset button on the Micro, start an upload with your other hand, and release Reset when it says "Uploading".

Try typing

lsusb | grep Arduino

I found with a sketch uploaded which opens the Serial port:

Bus 003 Device 087: ID 2341:8037 Arduino SA

If you hit Reset and wait a second, then do the lsusb again you see a different device:

Bus 003 Device 086: ID 2341:0036 Arduino SA

That one (the 0036 one) is the one it will upload to. You might get 0037 rather than 0036 because I reflashed the bootloader to be the Leonardo one, but the concept is the same.


Connect to more than one Arduino with Adobe AIR I am using the arduinconnector ANE to connect to an arduino baord in an AIR application. https://code.google.com/p/as3-arduino-connector/

Can anyone tell me if its possible to connect to more than 1 board, simply by instantiating additional instances of the ANE and passing in unique port #'s?

Or is there some reason why this isn't possible and a unique AIR application is required for every arduino you connect to?

This seems to be possible with as3Glue as per the docs:

as3Glue is an ActionScript 3 library that enables communication between Flash/Flex/AIR applications and Arduino boards. It can together with one or several Arduino boards be used to monitor sensors (such as rotary encoders and motion detectors), control actuators (such as LEDs and motors) and interface other electronics (such as RFID readers) from Flash, Flex and AIR applications.

as3Glue can be used with as3-arduino-connector as mentioned in the docs:

Using with as3Glue
Download either the SWC or Source Code from the Downloads section of this project for a patched version of as3Glue. This patched version has the exact same interfaces as v20, with a notable exception of the constructor. When you instantiate a new "Arduino" object, replace the IP address and port with the COM port and baud rate. For example :
public var myArduino:Arduino = new Arduino("COM10", 57600);


Writing First Library - Serial Stream Object I have done quite a few projects with Arduino, but have never done more than a "Hello World" in C. I am writing my first library, and a lot of the object oriented stuff is going over my head. Anyway, my library is working as it is supposed to, I pass a float to my function and it formats it properly and sends it out over serial. However, I implemented it in a clunky way. The Arduino API Style Guide mentions a way that seems much better:

  When using serial communication, allow the user to specify any Stream object, rather than hard-coding "Serial". This will make your library compatible all serial ports on Mega and the Due, and can also use alternate interfaces like SoftwareSerial. The Stream object can be passed to your library's constructor or to a begin() function (as a reference, not a pointer). See Firmata 2.3 or XBee 0.4 for examples of each approach.

Can anybody elaborate on how to do this, or show me some code?

Here is a simple example (built and tested with a mega2560), with a class that can be passed a Stream object, and sends a Hello over this generic stream object. When constructing the object, you can pass the Stream object you want to actually communicate:

#include "Arduino.h"

class MyProtocol
{
public:
    MyProtocol(Stream& s):serial(s){}
    void send(){
        serial.println("Hello");
    }
private:
    Stream& serial;
};

MyProtocol p(Serial);

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

void loop() {
    delay(1000);
    p.send();
}

NOTE: The serial.println() is not the Serial global object, note the lower case, it is the internal Stream class variable.

If you are confused with the OO and classes, take into account (while you gain more knowledge about it) that this approach can be also used with a simple function, you can pass the serial parameter. Furthermore, it is not necessary to hardwire the Serial interface for ever, you can in fact switch in run time and use a different channel depending on some condition:

#include "Arduino.h"

void send(Stream& serial){
    serial.println("Hello");
}

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

void loop() {
    delay(1000);
    if(someCondition)
        send(Serial);
    else
        send(Serial1);
}


writing mqtt payload to spiffs file I'm trying to write the payload of a MQTT message into a file in the SPIFFS file system of my esp32 board. I've tried this:

if(file.print((long)payload)) {
   Serial.println("File was written");
}else {
   Serial.println("File write failed");
}

payload is a byte* and file was opened in the setup() function like:

File file;
if(!SPIFFS.exists("/testfile")){
  file = SPIFFS.open("/testfile", "r+");
}

I always get an error when writing to it telling me that the file write failed. Is this the correct approach for what I'm trying to accomplish?

Use file.write(payload, length); for byte array. length should be the count of payload bytes, not the size of the payload array.

print and write return the count of bytes written. It is not meaningful to use the return value as boolean.


How to connect 70 analog sensor to a single Arduino (Mega or Uno) device? I was working on a project in which I need to collect soil moisture data for a farm. For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino. But, this is not possible as there are just 6 analog pins on Arduino Uno and 16 analog pins on Arduino Mega. I have restrictions on the number Arduino that I can use that is just one due to monetary constrains.
        The data would be collected at a delay of 5 seconds. The data gathered would be stored on SD card module which would be analyzed later.
      Any suggestion on how I can collect data from 70 analog sensors on a single Arduino would be highly appreciated. Are there any alternatives that I can use in place of Arduino? I heard that we could do something with AVR  atmega Microcontroller, am I correct? I don't know how to use Microcontroller; any useful resources will be highly appreciated. Thank You.

There are fairly inexpensive chips called "analog multiplexers" which let you choose one input out of a range (8 or 16 is typical). You could take the reading, then switch to a different input, and take another reading.

I have a page about analog multiplexers.

Example of it in operation:

In this example you have 8 inputs, and by setting the A/B/C pins appropriately, one of the 8 is selected and appears at the O/I pin (output/input).

There is a 16-channel model as well. I see the 16-pin chip (74HC4067) available on eBay for $US 1.26 right now. You can get four of them (which would give you 80 inputs) for $4.88.

Also see the Wikipedia article on multiplexers.

  For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino.

Yes, well how will these sections get their data into one place? That is probably the bigger problem.

You may need to use a lengthy cable using RS485 (balanced signals) or maybe cheap radio transceivers.

Trying to use a "single Arduino" on what might be quite a large farm is the issue. It's not the Arduino's fault. You have to have some way of sending the data from the further points to where it is to be collected.


How to use stm32duino control 5110? I want to use stm32duino to control 5110, I use the library http://www.rinkydinkelectronics.com/download.php?f=LCD5110_Basic.zip

Before, I use arduino pro mini to control 5110 by this library, it works well. But when I use stm32, it fails. Whether this library is not suitable for stm32duino ? If so, which library is suitable for me ?

The library you linked to does not indicate it works for STM32 architecture. The display uses SPI, and each architecture has it's own way of implementing such peripherals.

There is this library: https://github.com/KenjutsuGH/Adafruit-PCD8544-Nokia-5110-LCD-library which is a port of the Adafruit 5110 driver to STMduino.


Arduino Tre, will it ever come out? Does anyone have any information other than "coming soon" about the Tre?

Could the Tre be stuck in development hell?
Perhaps the new partnership with Adafruit could expidite things, seeing as Ardiuno (.cc) was touting the Tre to be the first Arduino made in the USA?

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

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

The mentioned this:

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

I'd imagine that the Arduino LLC vs Arduino SLR legal issue is also delaying the production.

Other than that, speculation is all that we know.

P.S: it's still spring until Sunday, June 21! :-)


Controlling a motor with a wav file I've got an SD card and speaker hooked up to my nano and I can play mono audio files easily. My question is, is it possible to control the speed of a motor using the pwm output to the speaker? I tried just hooking the motor in where the speaker was, but that produced no noticeable variations in speed.

Alternatively, is it possible to analyse the wav file on the nano and control the motor that way? (i.e. motor speed is dependant on volume at a given time)

Thanks

Regular sound files will have an even amount of time spend energizing the coil positive and negative, so the motor will not spin around in the normal sense. With a strong enough amplifier it will produce the sounds in the file like a speaker, but it will not noticeably turn.

Actual PWM varies the percentage of the time the signal is HIGH in a fixed frequency square wave, thus all the different values are the same "pitch". Audio varies amplitude and frequency, but the cumulative effect of audio waves is neutral, it spends half of the time below neutral and half above neutral voltage. The simplest analogy I can think of is audio being itself, even vibrations in air, and motor PWM being wind.

I am not sure if it possible to generate a sound file that would turn the motor, it probably depends on the file type. In any case, you would be better off with a far simpler amplifier like a transistor, MOSFET, or H-Bridge on one of your nano's actual PWM pins.

As to whether or not you could analyse the file on arduino, it also depends on file type. The code for the arduino WAV sheild I've seen does not have the arduino actually processing data, but It should be possible with a simple enough file type for arduino to decompress. WAV is not normally compressed, just raw data, so your limits are the RAM and if you can code something to glean volume from the raw data. I don't have much experience in that kind of file processing on AVR so I'm not going to call it either way.


How to read bitmap image on Arduino I want to convert a bitmap into binary array. My bitmap image is 272*208 pixel monochromatic 1bpp image. I'm confused when the width I get from my image is 16 instead of 272, the height is corrected. And when I skip the bitmap header to get bitmap infomation, I got string of meaningless number in my text file.

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

File bmpImage;
File textFile;

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

Serial.print("Initializing SD card...");
if (!SD.begin(53)) {
  Serial.println("initialization failed!");
  return;
}
Serial.println("initialization done.");
int height = 0;
int width = 0;

// Open
bmpImage = SD.open("Circle.bmp", FILE_READ);
textFile = SD.open("test.txt", FILE_WRITE);

bmpImage.seek(0x12);// width in pixel = 16
width = bmpImage.read();
bmpImage.seek(0x16);// height in pixel = 208
height = bmpImage.read();
Serial.println(width);
Serial.println(height);

int imageSize = height*width;

bmpImage.seek(0x36);//skip bitmap header

for(int i = 0; i < height; i ++) {
  for (int j = 0; j < width; j ++) {
    textFile.write(bmpImage.read());
    textFile.write(" ");
  }
  textFile.write("\n");
}

bmpImage.close();
textFile.close();

Serial.println("done write");
}

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

That was a very raw way of trying to read a BMP file. There are a lot of assumptions that might give errors.

The file is a BMP file. The header signature is not checked.
The image offset is assumed to be directly after the file header. It is not read.
The image width is less than 256. Only the lowest byte of the 32-bit image width is read. As 272>256 the low byte is 16.
The image height is less than 256. Only the lowest byte of the 32-bit image height is read.

It is a small bitmap but it will take a very long time to read when reading a single byte at a time. There are methods to improve performance but that is an answer to another question.

A more robust method to read the BMP header and image information is to define them as a struct and read.

struct bmp_file_header_t {
  uint16_t signature;
  uint32_t file_size;
  uint16_t reserved[2];
  uint32_t image_offset;
};

struct bmp_image_header_t {
  uint32_t header_size;
  uint32_t image_width;
  uint32_t image_height;
  uint16_t color_planes;
  uint16_t bits_per_pixel;
  uint32_t compression_method;
  uint32_t image_size;
  uint32_t horizontal_resolution;
  uint32_t vertical_resolution;
  uint32_t colors_in_palette;
  uint32_t important_colors;
};

bmpImage = SD.open("Circle.bmp", FILE_READ);
...
// Read the file header
bmp_file_header_t fileHeader;
bmpImage.read(&fileHeader, sizeof(fileHeader));
...
// Check signature
...
// Read the image header
bmp_image_header_t imageHeader;
bmpImage.read(&imageHeader, sizeof(imageHeader));
...
// Check image size and format
...
// Locate the pixels
bmpImage.seek(fileHeader.image_offset);

The file and image information are stored in little-endian so that works just fine on an AVR.


Sending command through SPI on Arduino UNO I am assuming the default pin configuration is pin 10(SS), 11(MOSI), 12(MISO), 13(CLK) from a default setup, SPI.begin(). The code compiles OK. Not sure about the int valuex and using the SPI.transfer() function.

#include <SPI.h>

int value1 = 0x8026;
int value2 = 0x0801;
int value3 = 0x8027;
int value4 = 0x0000;

void setup (void)
{
  Serial.begin (9600);
  Serial.println ("Starting");
  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV4);

}  // end of setup

void loop (void)
{
  // enable Slave Select
  digitalWrite(SS, LOW);

  SPI.transfer (1);   // initiate transmission
  SPI.transfer (value1);
  SPI.transfer (value2);
  SPI.transfer (value3);
  SPI.transfer (value4);

  // disable Slave Select
  digitalWrite(SS, HIGH);

delay (1000);
}

Not sure about the int valuex and using the SPI.transfer() function.

A couple of things to know:

You are storing an unsigned 16-bit literal into a signed 16-bit variable. You should be using uint16_t value1 = 0x8026; etc. Also, unless you are planning to change the values, they should be const.
SPI.transfer() transfers only 8 bits of data. You are only sending the lowest byte of your valuex variables. SPI.transfer16() sends an unsigned 16-bit value.

To illustrate, this is how your program should look:

#include <SPI.h>

const uint16_t value1 = 0x8026;
const uint16_t value2 = 0x0801;
const uint16_t value3 = 0x8027;
const uint16_t value4 = 0x0000;

void setup(void) {
    Serial.begin(9600);
    Serial.println("Starting");
    digitalWrite(SS, HIGH);  // ensure SS stays high for now
    // Put SCK, MOSI, SS pins into output mode
    // also put SCK, MOSI into LOW state, and SS into HIGH state.
    // Then put SPI hardware into Master mode and turn SPI on
    SPI.begin();
    // Slow down the master a bit
    SPI.setClockDivider(SPI_CLOCK_DIV4);
}  // end of setup

void loop(void) {
    // enable Slave Select
    digitalWrite(SS, LOW);
    SPI.transfer(1);    // initiate transmission
    SPI.transfer16(value1);
    SPI.transfer16(value2);
    SPI.transfer16(value3);
    SPI.transfer16(value4);
    // disable Slave Select
    digitalWrite(SS, HIGH);
    Delay(1000);
}

That will transfer the stream of 8-bit values:

0x01 0x80 0x26 0x08 0x01 0x80 0x27 0x00 0x00


How can I upload .hex files to a Pro Micro using Linux? I have a hand-wired keyboard that uses a Pro Micro board, with an ATmega32u4 chip. I can't seem to flash firmware on it. The commands I've been trying are variations of:

avrdude -p m32U4 -P /dev/ttyACM0 -c avr109 -U flash:w:atreus62.hex

The errors I've been getting begin:

Writing | #######avrdude: error: programmer did not respond to command: set addr
####avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: write block
 ***failed;
 ***failed;
 ***failed;
 ***failed;

And end:

#avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
#avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
# | 100% 0.16s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0x0d != 0x0c
avrdude: verification error; content mismatch
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: error: programmer did not respond to command: exit bootloader

I'm on Arch Linux. Any ideas?

I had the same issue, and it was caused by udev, I found the answer here

It's some obscure bug

Tweaking udev rules solved the problem for me, now all is good, here is the procedure: https://learn.adafruit.com/adafruit-arduino-ide-setup/linux-setup#udev-rules


Connecting external mic to the Teensy I have a Teensy 3.2 and the Teensy audio board.

I was going to connect lavalier microphone to its audio jack but learned that it's only for output.
There are line-in pins though (see "Back Side" scheme). And MIC+GND pins, but these are for, ehm, radio parts microphones, I guess?

Being a complete novice I have no idea how to connect microphone jack (or audio connector) to line-in pins and whether I would need an amplifier between microphone and pins. If so then probably I just can't do it.

I would be grateful for detailed instructions.

It is easier than I thought! I soldered audio jack to MIC+GND, inserted microphone in and it works!
And pretty well :-)
Cheap random lavalier model: Panasonic RP-VC201. I guess any consumer model will do.


Using Intel Galileo Ethernet Port Is it possible to use the galileo's ethernet port through arduino IDE? Or should I buy an arduino ethernet shield? Will I be able to use galileo as a server to which arduino board can send data to?

I suppose you mean the "Galileo integrated Ethernet port" (the on-board RJ45). Then the answer is "no, not directly". The whole code provided by Intel in Arduino 1.6 IDE applies to the W5100 based shield, not the integrated Ethernet interface (which is a bit stupid, imho...)
Technically, however, this is possible, but you will need to create a library in C/C++, which interfaces with the system lib (the Linux one). You can then access to the wonderful world of BSD sockets (much more powerful than then sockets within the W5100)
Note however that the configuration of the integrated Ethernet board is not very easy with the Galileo, because the default Yocto image does not allow you to change default IP parameters (the Yocto image uses DHCP by default). So technically, you need then to deal with a startup script which changes the IP parameters at startup, but it's pretty heavy to do.


Fritzing file for prototyping shield I have a prototyping shield with mini breadboard similar to Adafruit Proto Shield for Arduino Kit - Stackable Version R3.

Is there a Fritzing file for this.

A quick google search turned up a solution in the very first result:

https://forums.adafruit.com/viewtopic.php?f=31&t=36560

It is a contribution from an Adafruit customer.
All credits go to them.

Source thread: https://forums.adafruit.com/viewtopic.php?f=31&t=36560


Read ISO/IEC 14443B (NFC Type B) with PN532 I bought a PN532 from Elechouse (documentation here) because I need to read IDs from Type B NFC cards.

My problem is that even if they say the hardware supports Type B, the official libraries an examples they provide are not made to.

I have not problem reading Type A cards, but nothing happends when I tap Type B cards.

After long searchs on internet I found that absolutely every PN532 sellers have chosen to support only Type A cards in their libraries because according to them, a librari supporting both types would have taken too much space in Arduino's memory.

So today my problem is as simple as that: how to read Type B NFC cards using PN532 on an Arduino UNO?

I'm a bit new in Arduino so after many hours of searching and trying I couldn't figure out how to do it.

I dont have an exact reply but

1) are you certain the other tags are type b?

2) hace you tried connecting the reader using a UART USB cable? You could use libnfc, to check if the reader works.
And going forward at commands FOR the reader are a good way to debbug.


PubSubClient: Subscription working, but callback never called I am using an ESP32 (https://heltec.org/project/wifi-kit-32/) with a AM2302 DHT22 and an LDR, talking to mosquitto on a Linux box.  Publishing data is working fine, other than the "exceeded timeout, disconnecting" lots of people seem to be having.  However, when a message is sent from another client to a topic I am subscribed to, my callback is never called, so I can't consume it.
In my reconnect function, I have
    boolean success = mqttClient.subscribe("sensors/basement/led");
    Serial.print("Subscribe returned ");
    Serial.println(success);

and it does return 1 which I believe is success (usually success is zero but I don't think that's the case here).  I also see the subscription in my mosquitto logs, which are currently cranked up to debug.
1610417274: New client connected from XXX.XXX.XXX.XXX as Basement1 (c1, k15, u'XXXXXXXXX').
1610417274: Sending CONNACK to Basement1 (0, 0)
1610417275: Received SUBSCRIBE from Basement1
1610417275:     sensors/basement/led (QoS 0)
1610417275: Basement1 0 sensors/basement/led
1610417275: Sending SUBACK to Basement1

When I send data to sensors/basement/led from the other client (mqttdash), the server receives it, and sends it to mqttdash, as well as Basement1, which is my ESP32:
It's definitely sending the message to the ESP32:
1610417546: mqttdash-3785c5ce 0 sensors/basement/led
1610417546: Sending SUBACK to mqttdash-3785c5ce
1610417578: Received PUBLISH from mqttdash-3785c5ce (d0, q0, r0, m0, 'sensors/basement/led', ... (1 bytes))
1610417578: Sending PUBLISH to Basement1 (d0, q0, r0, m0, 'sensors/basement/led', ... (1 bytes))
1610417578: Sending PUBLISH to mqttdash-3785c5ce (d0, q0, r0, m0, 'sensors/basement/led', ... (1 bytes))

However, my callback is never called.  Here is the setup of the callback:
WiFiClient espClient;
PubSubClient mqttClient(espClient);
...
void setupMQTT()
{
    mqttClient.setServer(MQTT_HOST, MQTT_PORT);
    mqttClient.setCallback(mqttSubHandler);
    mqttConnect();
}
...
void mqttSubHandler(char *topic, byte *message, unsigned int length)
{
    Serial.print("Message arrived on topic: '");
    Serial.print(topic);
    Serial.print("'. Message: ");
    String messageTemp;

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

Full code at https://github.com/djsegfault/arduino/blob/master/basement_monitor/basement_monitor.ino
Does anyone know why the callback is not being called?  Thanks in advance.

nknolleary, the owner of the library, correctly identified the problem:
You need to call mqttClient.loop() in you main loop. Without that, you are never giving the client a chance to check for any incoming messages.


How to volunteer for arduino projects? I have master in electronics and IT. I know various microcontrollers programming in c. I want to volunteer myself to learn for arduino Projects especially for low Level Drivers etc. Can somebody suggest me Websites or way ?

The Arduino paradigm is based on abstracting the hardware to a few simple function calls.  So many drivers appear simple to the end user (end programmer).

Most go here for a list of libraries (which have already been written) and how to use them.  I believe these libraries are distributed with the Arduino SDK.  To learn more about writing libraries go here. I am not aware of any formal method of submitting Arduino libraries.  If I wanted to find out more I would go here and participate in the forum.  However, using the forums search, I found this specific (several years old) post where it says:

  You can add a page to the Playground section:
  http://playground.arduino.cc/ You might start by adding your website
  with Arduino code to the index of the playground, perhaps a page in
  the Playground section is not needed. The index can contain links to
  websites, to the Arduino forum or to a page in the Playground section.

  You can not change or add to the reference or official libraries.


Break loop/restart program at any time maybe my problem is just that my thinking is wrong. I hope you can help me.
First of all I will point out what I think in general, then I show you some code to work with.

In general my problem is to wrap me head around a push-button (or any other input) that stops (or better restarts) a running program at any time.
If i use the digitalRead(pin-whatsoever)-statement don't I have to tackle the exact mili/microsecond my MC is working on that specific line of code?
I don't want to use an interrupt either, i want to restart the program, not to interrupt it.

My project is some kind of turn-indicators for a bicycle.
The lights shall "run" from right to left on left-turns and vice versa.
But i want to stop the sequence at any point (or at least after one loop-run) if I push the corresponding button again.
After that the MC shall wait for another button-push to run the indicator either till the for-loop is finished or i press the same button earlier.

Another (general) question: Is there a way to get rid of delay-statements and achieve similar results?

Thank You so far.

   // Var-Setup
  const int mtime = 120; // Time between lights lighting up
  const int ftime = 100; // Time between lights turning out

void setup() {
  // put your setup code here, to run once:
  // Pin-Setup
    // LED-Pins
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);

  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);

    // Button-Pins
  pinMode(12, INPUT);
  pinMode(13, INPUT);

}

void right(){
  for(int i=0; i<5; i++){
      // Indicator right with running light (like a "half-knight-rider" ;) )
      // Rise
      digitalWrite(11, HIGH);
      delay(mtime);
      digitalWrite(10, HIGH);
      delay(mtime);
      digitalWrite(9, HIGH);
      delay(mtime);
      digitalWrite(8, HIGH);
      delay(mtime);
      digitalWrite(7, HIGH);
      delay(mtime);
      delay(mtime);

      // Fade
      digitalWrite(11, LOW);
      delay(ftime);
      digitalWrite(10, LOW);
      delay(ftime);
      digitalWrite(9, LOW);
      delay(ftime);
      digitalWrite(8, LOW);
      delay(ftime);
      digitalWrite(7, LOW);
      delay(250);
    }
}

void left (){
  for(int i=0; i<5; i++){
    // Indicator left with running light
    // Rise
    digitalWrite(2, HIGH);
    delay(mtime);
    digitalWrite(3, HIGH);
    delay(mtime);
    digitalWrite(4, HIGH);
    delay(mtime);
    digitalWrite(5, HIGH);
    delay(mtime);
    digitalWrite(6, HIGH);
    delay(mtime);
    delay(mtime);

    // Fade
    digitalWrite(2, LOW);
    delay(ftime);
    digitalWrite(3, LOW);
    delay(ftime);
    digitalWrite(4, LOW);
    delay(ftime);
    digitalWrite(5, LOW);
    delay(ftime);
    digitalWrite(6, LOW);
    delay(250);
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  int sensorL = digitalRead(12);
  int sensorR = digitalRead(13);
  if(sensorL == HIGH){
    left();
  }else if(sensorR == HIGH){
    right();
  }
}

replace each delay chain with a switch statement where each delay is replaced by saving the current millis counter, a increment of the state, a case label for the new state and a if(millis()-timestamp  < timeout) return;

switch(state){
case 0;
      // Indicator right with running light (like a "half-knight-rider" ;) )
      // Rise
      digitalWrite(11, HIGH);
  timestamp = millis();
  state++;
case 1:
   if(millis()-timestamp  < mtime) return;

      digitalWrite(10, HIGH);
  timestamp = millis();
  state++;
case 2:
      digitalWrite(9, HIGH);
//etc.

The for loop around the entire thing will need to be replaced. Make i global and incrementing it in the last state and resetting it as needed. When i has been incremented to beyond 5 you always return.

This means that the left and right functions only do a few things: set the led, check a timestamp against the current time, and increment a state before returning.

This means that they will take very little time to execute and that you can check the button in the main loop() body and if pressed initiate the statemachine or end it (and putting out the LED when needed).


Altering code to run a timer while checking for a data input I am rather new to the Arduino world and am looking for a way to create my own tipping rain gauge with only one Arduino(micro).

I have had some help from a friend to get a loop that checks for when a switch is closed, which signals that the bucket has tipped and thus "x units" of rain have fallen. The code I have for sensing this is:

void loop()
{
  /*
    digitalWrite(4, HIGH);
    delay(500);
    digitalWrite(4, LOW);
    delay(6500);
  */
  int analogValue = digitalRead(8);

  if (analogValue==HIGH)
  {
    Serial.println(count);
    count++;
    delay(250);
  }
}

Then I developed a code to count up in 0.5 second intervals so that I could essentially time stamp when the switch from the first loop was closed/activated. The code for the timer is as follows:

void loop()
{
  while (ssec < 10)
  {
    Serial.print(hour);
    Serial.print(":");
    Serial.print(minute);
    Serial.print(":");
    Serial.print(sec);
    Serial.print(".");
    Serial.print(ssec);
    //Serial.print(" s");
    //Serial.println();
    ssec += 5;
    delay(500);
    Serial.println();
  }
  if (ssec == 10);
  {
    sec++;
    ssec = 0;
    //Serial.print(sec);
    //Serial.print(".");
    //Serial.print(ssec);
  }
  if (sec == 60)
  {
    minute++;
    sec = 0;
  }
  if (minute == 60)
  {
    hour++;
    minute = 0;
  }
  if (hour == 24)
  {
    Serial.println();
    Serial.print("DAY ");
    Serial.print(day);
    Serial.print(" COMPLETED!");
    Serial.print("Data Points: ");
    //Serial.print(count);
    Serial.println();
    Serial.println();
    hour = 0;
    day++;
  }
}

I understand that it is very hard to run these together at the same time due to the fact that I am using a delay function to run the timer.

Are there any ways to essentially run these side by side? Or a library I can use that will run the timer while i have the arduino looking for the switch to close, and I can simply call the timer when I need it?

Thank you for any and all help! :)

What's with the double-spacing? It makes it hard to read.

if(ssec==10);

That is wrong.

Arduino programming traps, tips and style guide

  I understand that it is very hard to run these together at the same time due to the fact that I am using a delay function to run the timer.

I know StackExchange doesn't like link-only answers, but it is this or copy-and-paste:

How to do multiple things at once ... like cook bacon and eggs


A problem with measuring time in a for loop I am familiar with timing using millis() function, but it seems that I have run into a problem with a for loop.
The thing is, I am comparing encoder readings with a value entered via 4x4 keypad. Since I have to enter more than one value, i placed all values from the keypad into an array. Then I created a for loop that will cycle through that array and compare each value with encoder readings, when encoder reached the entered keypad value an LED should light up for 2 seconds. This is where the problem occurs. When it reaches the set value the LED seems to light up for like a fraction of a second. My guess is that the loop is creating some trouble here. Maybe because the loop cycles so fast the LED doesn't have enough time to stay lit. What do you think?

When I tried this program without a for loop (with only one value entered from a keypad), it works fine.
The code below has two arrays with values already entered, so no need or keypad. I used it just for testing. When I solve this problem I will add a keypad.

Please ask if you need any clarification of the code , and thank you in advance

#include <Encoder.h>
#include<Wire.h>
#include<LiquidCrystal_I2C.h>

int led1=14;
int led2=15;
unsigned long encoder;
unsigned long prev_value;
int array1[]={100, 200, 300, 400, 500, 600};
int array2[]={150, 250, 420};
int i,j,k,l;
int brV=6;
int brM=3;
int tolerance=10;
unsigned long oldTime=0.0;
unsigned long newTime;
int dt=2000;
bool testRange=true;
bool testRange2=true;

Encoder myEnc(2,3);
LiquidCrystal_I2C lcd1(0x27, 16, 2);

void setup() {
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
lcd1.init();
lcd1.backlight();
}

void loop() {
  newTime=millis();
  lcd1.setCursor(0,0);
  encoder=myEnc.read()*446/400;
  if(encoder!=prev_value){
    lcd1.clear();
    delay(10);
    prev_value=encoder;
  }
  lcd1.print(encoder);
  digitalWrite(led1,LOW);
  digitalWrite(led2,LOW);

  k=brV+brM;

  for(l=0;l<k;l++){
     for(i=0;i<brV;i++){
        if(encoder>=array1[i] && encoder<=(array1[i]+tolerance) && testRange){
           oldTime=newTime;
           digitalWrite(led1,HIGH);
           testRange=false;
         }
         else if(oldTime-newTime >= dt){
          oldTime=newTime;
          digitalWrite(led1,LOW);
         }
         if(encoder>(array1[i]+tolerance){
          testRange=true;
         }
     }
      for(j=0;j<brM;j++){
         if(encoder>=array2[j] && encoder<=(array2[j]+tolerance) && testRange2){
           oldTime=newTime;
           digitalWrite(led2,HIGH);
           testRange2=false;
         }
         else if(newTime-oldTime >= dt){
          oldTime=newTime;
          digitalWrite(led2,LOW);
         }
         if(encoder>array2[j]+tolerance){
          testRange2=true;
         }
      }
  }

  }

Old time and new time are wrong way round on a part where the LED'd are switched off

else if(oldTime-newTime >= dt){
          oldTime=newTime;
          digitalWrite(led1,LOW);
         }

When simple processors reach the max or min value and continue counting, they overflow and start counting from far end: So 5-8=maxint(largest number)-3
Result is that the difference is a massive number greater then 2000 except every few weeks when millis() overflows and become larger then Unsigned large int can store and starts counting from zero. (many codes fail working on that occasion, your would only works then ;-)
Correct version:

else if(newTime-oldTime >= dt){
          oldTime=newTime;
          digitalWrite(led1,LOW);
         }

Although I have noticed that testrange (both) only returns its value onto true on limited circumstance if input from encoder increased considerably very quickly to catch-up with growing inputs, so the next values will never pass condition to switch them on

if(encoder>=array1[i] && encoder<=(array1[i]+tolerance) && testRange)

will never return true because testRange stays false. Add

testRange=true;
testRange2=true;

at the end of the loop otherwise it does return into true for next loop()iteration. I guess question is if you want other functions to run while LEDs are on or not.

It is a bad habit to make unnecessary variables like i,j,k,l global as they waste memory even when not needed you can define them within structure itself Eg: for(int i=1;... this way as soon as for, while etc loop (brackets close)finishes you get your memory back and you can use variable again


Weird problem with arduino I wrote the code below and the result is not what I expected at all! I'm not sure why it's happening!
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

const uint8_t pat[] PROGMEM = {
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x66
};

void loop() {
  delay(100);
  Serial.println(sizeof(pat));
  for (int i=0; i<8; i++){
    Serial.print(pat[int(i)],HEX);
  }
  Serial.println("");
  Serial.print(pat[0],HEX);
  Serial.print(pat[1],HEX);
  Serial.print(pat[2],HEX);
  Serial.print(pat[3],HEX);
  Serial.print(pat[4],HEX);
  Serial.print(pat[5],HEX);
  Serial.print(pat[6],HEX);
  Serial.print(pat[7],HEX);
  Serial.println("");
  while(true);
}

the output is surprisingly this:

8
008000010
FF0FF0FF0FF66

What is compiler doing in the background but it seems to be messing things up really bad! The loop should be doing the exact same thing as manually writing that code over and over but it's not! How can I fix the loop?

If you want to get a value from PROGMEM you must read it with pgm_read functions. Read the PROGMEM reference.

for (int i = 0; i < 8; i++) {
  Serial.print(pgm_read_byte_near(pat + i),HEX);
}

pat[0] in Serial.print(pat[0],HEX); is an item in a constant array const uint8_t pat[]. it can't change at runtime so the compiler uses the value 0xFF. that is why it is printed ok without pgm_read_byte_near


How to design and debug a custom I2C master-slave system? How to proceed, when in need of a custom I2C master-slave system?

What are the design criteria to apply?

What are the debugging tools one can use to troubleshoot problems?

This tutorial I gave at the Embedded Linux Conference tries to answer the questions, providing links to more detailed description of the topics addressed and using the practical example of driving a 4WD drone, where an Arduino Mini Pro acts as slave and controls the 4 independent wheels.
The original document can be found here.

Note: This answer is currently work in progress, as I adapt the highlights from the link.

Typical Applications of the I2C bus

Interfacing with relatively slow peripherals. Ex: sensors, mechanical actuators.
Controlling “fast” peripherals, that use other channels for exchanging data. Ex: codecs.

In a PC, the Operating System usually interacts over I2C with:

temperature and battery voltage meters;
fan speed controllers;
audio codecs.

In case multiple bus controllers are available, peripherals are grouped by speed, so that fast ones are not penalized by slower ones.

A quick introduction to the I2C bus - key features

Serial bus.
Only 2 lines: Serial CLock and Serial DAta (plus ground).
4 speeds: 100kHz, 400kHz, 1MHz, 3.2MHz.
Typically, 1 master device and 1 or more slaves.
Communications are always initiated by a master device.
Multiple masters can co-exist on the same bus (multi-master).
Open-Drain: both SDA and SCL need pull-up resistors.
“Clock Stretching”

The master controls SCL, but a slave can hold it down (because open drain), if it needs to adjust the speed.
The master must check for this scenario.
A slave can get stuck and jam the bus: need for reset lines from the master to the slave.

Typically 7-bit addressing, but also 10 bit is supported.
Logical protocol: actual voltage levels are not specified and depend on individual implementations. Ex: 1.8V / 3.3V / 5.0V

Reference URLs:

http://www.i2c-bus.org
http://www.robot-electronics.co.uk/i2c-tutorial

Example of Bus Configuration

Characteristics of the Protocol (simplified)

2 message types: read and write
Start / Stop bit - represented as “[“ and “]” in the rest of the answer
Address: 7 or 10 bits
R/W bit: R = 1 / W = 0 Used to discriminate the type of message sent.
Data on the bus: (Address << 1 | R/W)
Registers as information handlers, within the selected device.

Example of Bus traffic

Custom Slaves

Why create a custom I2C slave?

Desired sensor/actuator unavailable with I2C interface.
Less unique addresses available than slaves needed.
Desired custom functionality on the slave:

Semi-autonomous reactions to stimuli.
Filtering/preprocessing input data.

Power optimization: custom “sensor hub” does the housekeeping while the main processor is idle.
Realtime response to inputs.
[your imagination here]

How to design a custom I2C slave?

Define requirements (see previous slide).
Choose microcontroller or microprocessor.
Choose Scheduler or Operating System (if any).
Define communication sub-protocol:

Define parameters and commands to be exchanged.
Organize them into “registers” and choose a free address.

Design of the I2C Master

Key design criteria:

Weight/Dimensions.
Required computational power and average latency.
PC-like device

Embedded device, typically headless.
Preferred programming language: interpreted vs compiled.

Availability of busses/gpios for driving the slave(s):

GPIOs only: bitbang the protocol
I2C: user-space application vs kernel driver.
No GPIOs/I2C interfaces available: USB to I2C adapter.

Debugging: Divide and Conquer

Take direct control of the bus with an ad-hoc device.
Examples:

Bus Pirate (useful also for other busses)
USB to I2C Master adapter, also based on the FTDI FT232R chip.
Custom device (could be a separate project).
Snoop the bus with a logic analyzer or a scope/advanced meter.
Examples:

sigrok/pulseview with compatible logic analyzer
2-channels standalone scope/meter
Use slave-specific In Circuit Debugger/In Circuit Emulator.

Example:
AVR Dragon for AVR chips (Arduino UNO, Nano, Mini, MiniPro)

BUS Pirate

Primarily for development purposes.
Can both sniff the bus and drive it.
Console interface over serial (ttyACM) port, including macros, or programmatic access for several programming languages.
Built-in pullup resistors and voltage sources (5V / 3.3V)
Supports many other protocols.
References: Wikipedia, main page

USB to I2C Adapter

Small footprint.
Suitable for permanent installations.
No need for special connections on the host: it can be used to interface with a typical PC.
Variant available that is also SPI-capable.
No console interface, only serial binary protocol.
Requires protocol wrapper.
Reference: protocol

sigrok and pulseview

sigrok(bakend component) logo

pulseview (visualizer) example

Example of low end logic Analyzer

De-facto standard for PC-driven measurements on linux (but available on other OSes too).
Support for vast range of logic analyzers, scopes and meters.
Various protocol decoders, including I2C.
Useful for visualizing the logical signals and debugging protocol errors.
Even very low end, inexpensive HW can provide a whole new dimension to debugging.
References: sigrok, pulseview, supported hardware

Example: steering a 4WD drone

Prototype built using 2 Arduino Mini Pro.

What does the slave do in the example?

The I2C slave:

Controls the amount of torque applied to each wheel.
Controls the direction each wheel spins.
Measures  the rotation speed of each wheel through an optical encoder (Odometer).
Exposes the parameters above to the I2C Master.

High level block diagram of the I2C Slave.

Selecting the Slave: Arduino Mini Pro

Enough pins/functions to provide for each wheel:

1 PWM output with independent configuration of the duty-cycle.
1 GPIO for registering odometer input as IRQ.
2 GPIOs for selecting:

Forward
Reverse
Idle
Lock

I2C HW block for interrupt-driven i2c exchanges.
Dedicated pins for SPI-based programming.
Small footprint.
Low Cost.
The board layout of the clone represented in the picture is optimized for mounting on a DIL socket.

Slave-specific ICD: AVR Dragon

Supports various programming modes, included SPI programming, through AVRDude.
Doesn’t interfere with normal AVR operations, so it can be left plugged into the system.
After enabling debugWire interface, it allows configuring HW/SW breakpoints, by a dedicated backend for gdb/ddd.

Selecting the OS: ChibiOS

RTOS: preemption, tasks, semaphores, dynamic system tic, etc.
Small footprint: link only used code/data.
Distinction between RTOS and BSP through HAL.
GPLv3 for non-commercial use.
Actively developed, but already mature.
Supports 8bit AVR.

However it had limited BSP support for AVR, lack of:
 - interrupts driver for AVR GPIOs (added).
 - I2C support for AVR slave mode (custom).
Which had to be developed separately as part of the Drone SW for the AVR.

Defining the Communication Parameters

For each wheel:

Duty Cycle of the PWM signal used to drive it - 1 byte.
0xFF = max torque / 0x00 = no torque.
Direction of rotation - 1 byte.

0x00 = idle
0x01 = reverse
0x02 = forward
0x03 = locked

Average period in between slots of the optical encoder - 2 bytes.

Writing anything resets the measurement.

Parameter Index - 1 nibble:

0 = Duty Cycle
1 = Direction
2 = Average Period

Wheel indexes - 1 nibble:

0 = Left Rear
1 = Right Rear
2 = Right Front
3 = Left Front
4 = All

Sub Protocol: Defining the Registers

Register format:   0xαβ
 - α = Parameter Index
 - β = Wheel Index

Address (chosen arbitrarily): 0x10

Bus Pirate format:
 - [ = start bit
 - ] = end bit
 - r = read byte
 - address times 2 (left shift 1), for R/W bit

Example - in Bus Pirate Format

[   i2c_addr   reg_addr=(parm,wheel)   reg_value  ]

[0x20 0x20 0x02]  Left Rear Forward
[0x20 0x21 0x01]  Right Rear Backward
[0x20 0x22 0x01]  Right Front Backward
[0x20 0x23 0x02]  Left Front Forward
[0x20 0x14 0xFF]  Wheels set to max torque

The car spins clockwise.


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

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

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

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

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

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

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


Benchmarking String.toInt() vs Checking individual characters gives unexpected result I'm trying to check whether the input string contains all digits or not. I achieved this using 2 different algos. One is to convert the string to integer using String.toInt() and then checking if its value lies between the integer of length of the input string.

e.g. If input string is "123". The corresponding integer must lie between 100-999.

Second, I wrote a function that iterates over each character of the string and checks if its ASCII values lies between 48-57. If not, it returns false.

When I bench marked these two algos, I found that when the string contains only digits, the 2nd algo is about 9 times faster than the 1st one. But when the string contains even a single non-digit character, the 1st algo takes ~1ms, but the 2nd algo always takes ~5ms. Why is this? I've not been able to figure this out.

The code:

unsigned long start;
unsigned long middle;
unsigned long end;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // send an intro:
  Serial.println("String toInt():");
  Serial.println();
}

void loop() {
  // Read serial input:
  if (Serial.available()) {
    String r = Serial.readString();

    start = micros();
    unsigned long rInt = r.toInt();
    int rLen = r.length();

    if ((rInt >= floor(pow(10, rLen))) || (rInt < floor(pow(10, rLen-1)))) {
      Serial.println("Please enter valid integer value!");
    } else {
      Serial.println(rInt+1);
    }

    middle = micros();

    bool isInt = doesContainInteger(r);
    if (isInt) {
      Serial.println(r);
    } else {
      Serial.println("Please enter valid integer value!");
    }

    end = micros();

    Serial.println(middle-start);
    Serial.println(end-middle);
  }
}

bool doesContainInteger(String s)
{
  int sLen = s.length();
  for (int i=0; i<sLen; i++) {
    char sChar = s.charAt(i);
    if (sChar<48 || sChar>57) {
      return false;
    }
  }
  return true;
}

As pointed out by Majenko in his (slightly annoyed) comment, you need to change your timing code to time only the calculations you want benchmark, not the I/O or other irrelevant code. For checking the conversion using toInt(), for example, try:

// time our conversion
unsigned long start = micros();
unsigned long rInt = r.toInt();
bool invalid = rInt == 0;
unsigned long end = micros();

// print the result
if (invalid) {
    Serial.print("in");
}
Serial.print("valid conversion took ");
Serial.print(end - start);
Serial.print(" microseconds.");

Note that your assumption that a three-character input that's a valid integer will be between 100 and 999 is wrong; "003" and "-17" are both three-character inputs that should be correctly converted.

According to the toInt() documentation, 0 is returned on failure to convert, so I check for that in the code above. But since one can't tell the difference between a successful conversion of "0" and unsuccessful conversion of "abc" or some other non-integer, you really should be sure before you call toInt() that you've got a valid integer int the string.


Is the arduino hackable when using communication shields? Let's say I have an arduino Uno connected to a W5100 ethernet shield. The arduino communicates with the ethernet shield using the tx0 and rx0 pins. When I upload a new script to the arduino using USB, it uses the same tx0 and rx0. So that made me think.

What if I run a script on my arduino that fetches some data from a webpage using HTTP requests but someone manages to hack into my server. Is it possible for the hacker to upload some kind of code to my server, which will erase (when fetched by the arduino) the old script and upload a new arduino script, by making the arduino think it's uploading a new script while it's getting data from the ethernet shield (or other communication shields?)

EDIT: Let's expand the question a bit.. How can I add security to my code to prevent this situation from happening?

You should be pretty safe, at least as long as your code handles the
incoming data properly.

When you upload a new sketch through USB, the USB-to-serial interface
uses the Arduino pins TX0, RX0 and RESET. Your Ethernet shield, on
the other hand, does not control the RESET pin. Pulling the RESET pin
LOW is needed to make the processor enter the bootloader, which in turn
is needed in order to upload a new program. For pulling this pin low,
the malicious code would need not only to break into the Ethernet
shield's firmware, it would also need a hardware hack to access the
pin.

Now, if your own code is not safe, it is conceivable that the malicious
payload tricks your program into jumping to the bootloader or, as
suggesting by Juraj, into triggering a watchdog reset (which ends up
being equivalent). Thus you should treat anything coming from the
network as potentially malicious.


RFID/NFC (13.56 MHz), is it possible to send raw bytes and receive response? I'm trying to implement a card reader (i.e. credit cards) for shopping purposes, and AFAIK those cards are ISO 14443-A compliant (Mifare Classic 1K). I already made an Android app that can send custom APDU to read specific sectors by using raw SendBytes().

Since I need to build a circuit with a custom antenna, I chose Arduino-uno with a NFC module (was thinking about StrongLink SL013), I wanted to know if it's possible to send raw bytes and receive the response from the tag. I only found some higher-level implementation (readSector, writeSector and so on).

RFID protocols require either passive or active tags.  Depending on which you use, either the tag or reader regularly transmits pulses.  Check www.rfidreader.com for more info.  https://www.rfidjournal.com provides valuable resources as well.

Many companies invest heavily in developing RFID technology.  You would be well advised not to reinvent wheels without reeeeally deeeeeep pockets.


Arduino Leonardo keyboard.print keeps printing equal sign I am currently working on a DIY controller for Train Sim World. I am relatively new to the Arduino and the C programming language. My code is structured to look for button presses or PS2 joystick inputs and print a specific character for each button. I have also included a kill switch on pin 3. However when I run the code and open Notepad to see the results, the Arduino keeps printing the = character even if pin 3 is not pulled low. After I pull pin 3 low and press a button, there is a delay of about two seconds during which the = character keeps being printed over and over again, and after these 2 seconds elapse the Arduino prints the character attributed to the button several times before returning to printing = over and over again.

What can I do to fix this?

#include <Keyboard.h>

void setup() {
    pinMode(0, INPUT_PULLUP);
    pinMode(1, INPUT_PULLUP);
    pinMode(2, INPUT_PULLUP);
    pinMode(3, INPUT_PULLUP);
    pinMode(4, INPUT_PULLUP);
    pinMode(5, INPUT_PULLUP);
    pinMode(6, INPUT_PULLUP);
    pinMode(7, INPUT_PULLUP);
    pinMode(8, INPUT_PULLUP);
    pinMode(9, INPUT_PULLUP);
    pinMode(10, INPUT_PULLUP);
    pinMode(11, INPUT_PULLUP);
    pinMode(12, INPUT_PULLUP);
    pinMode(13, INPUT_PULLUP);
}
bool pantograph = 0;
void loop() {
    while (digitalRead(3) == LOW) {
        Keyboard.write("M");
        if (digitalRead(1) == LOW) {
            Keyboard.write("W");
        } else if (digitalRead(2) == LOW) {
            Keyboard.write("S");
        } else if (digitalRead(0) == LOW) {
            Keyboard.write("Q");
        } else if (digitalRead(5) == LOW) {
            Keyboard.write("Y");
        } else if (digitalRead(6) == LOW) {
            Keyboard.write("T");
        } else if (digitalRead(7) == LOW) {
            Keyboard.write("G");
        } else if (digitalRead(8) == LOW) {
            Keyboard.write("K");
        } else if (digitalRead(9) == LOW) {
            Keyboard.write("Z");
        } else if (digitalRead(10) == LOW) {
            if (pantograph == 0) {
                Keyboard.write("P");
            } else {
                Keyboard.write("O");
            }
        } else if (digitalRead(11) == LOW) {
            Keyboard.write(9);
        } else if (digitalRead(12) == LOW) {
            Keyboard.write("N");
        } else if (digitalRead(13) == LOW) {
            Keyboard.write(32);
        } else if (analogRead(A0) > 700) {
            Keyboard.write(93);
        } else if (analogRead(A0) < 200) {
            Keyboard.write(91);
        } else if (analogRead(A1) > 700) {
            Keyboard.print(39);
        } else if (analogRead(A1) < 200) {
            Keyboard.print(59);
        } else if (analogRead(A2) > 700) {
            Keyboard.print("A");
        } else if (analogRead(A2) < 200) {
            Keyboard.print("D");
        }
    }
    delay(1000);
}

The method write with one parameter takes char not string. Use write('W'), not write("W");


Porting my project to multiple Nanos I'm still fairly new to the Arduino world. I got myself a kit with a clone board  couple of months ago and have successfully prototyped the project and got it to the state I want it to be. I now want to create 5 - 10 working models of what I've done.

I'd seen on Amazon that I could get 5 Nano clones for about £10 and this seemed ideal to me. Until I saw that people were complaining that some Nano's aren't quite a direct replacement for the Uno that I have working. There's some kind of problem with loading the software from the IDE.

I really don't want to do anything more than just load my software onto the Nanos "As Is" using the IDE I already have.

Can anyone recommend what I need to look out for to ensure that the Nanos I buy will work this way please?

The Arduino Uno and Arduino Nano are fairly compatible.

Problems:

The board layout isn't the same, Nano's won't wield a classic "shield".
Nano's don't have a barrel jack.
Nano's (usually) have a micro USB connector. While the Uno has another one.
But, Nano's are smaller, withouth leaving out the USB connection.

But wait!

Microcontrollers of the same family are quite scaleable, Nano and Uno might even have the same micro on it! Be sure your Nano has the same Atmega328(P?) chip as your Uno.
Check if the pins you're using, are accessible on the Nano. Then you should be fine.

There is a little problem with cheap Arduino Nano's, I've bought 2, from 2 different vendors. They we're about 3$.

The first one featured a counterfeit FTDI chip. By installing the latest FTDI drivers, my FTDI actually got bricked. I had to undo this by using M_PROG or some EEPROM flashing tool to unbrick the chip, and install older drivers (which didn't corrupt it).
The second one featured an CH340G usb-serial chip. I had to download and install the drivers from a chinese website. But Windows wouldn't install unsinged drivers that easily. You have to go into advanced boot options mode and allow installing unsigned drivers.

Getting these Nano's working took me an reasonable amount of time. But they now are working quite well :)
It's something to take into account when buying cheap.

I wouldn't really bother for the alternative crystal, as long as they're 16Mhz. For time-critical behaviour, I wouldn't rely too much on your crystal.


SIM900A showing Starting modem test...ERROR, no modem answer. Checking IMEI...Modem's IMEI: 0 Edit:
Solution can be found HERE

I am trying to interface Simcom SIM900A GSM (SIM900a Mini DEV Board v3.9.2) and I tryed interfacing it with Arduino UNO. I have connected as:
Pins:
SIM900A - Arduino
=================
VCC     - VDC (+5V)
GND     - GND
5VR     - Connect to Arduino TX (Pin 1)
5VT     - Connect to Arduino RX (Pin 0)

Power Supply (External):
5V 2A

Problem
When I upload sketch of:
Example > GSM > TestModem:

to Arduino, I got this output from Serial Monitor:

Starting modem test...ERROR, no modem answer.
Checking IMEI...Modem's IMEI: 0
Reseting Modem... Modem is functioning properly: IMEI: 0

Other info:

By supplying 5V, 2A the SIM900A Power LED ON continuesly and Signal LED blink with certain period of time which mean I am okay with signal.

I connected SIM900A and Arduino with Male to Male + Female to Female as I don't have Male to Female wires. I tested the wires with Multimeter and it's prefectly working.

I tested uploading other sketches of sending sms but not successful. Note that, I have load + free sms on SIM.

Power supply is actually Adapter (no transformer but circuit) with output of 5.1 Volts

My previous post can be checked HERE
PS:
Yesterday just for a minute I noted: Both LEDs (Power + Signal)  of SIM900A were blinking at same time. But then by restarting it gets Okay again.
Please help. I am likely to die becuase of tension.

Note:

Detailed Solution can be found Here

Excerpt:

My Pins connections were wrong, it should not be: 0 and 1 it should be 2 & 3

Also SoftwareSerial.h is not working with SIM900A

Pins:

All connections should be like this:

SIM900A - Arduino
=================
VCC     - VDC (+5V)
GND     - GND
5VR     - Connect to Arduino TX (Pin 3)
5VT     - Connect to Arduino RX (Pin 2)

Details Here


5 arrays or one matrix? I am working on a project where i need to store as fast I can following :

1 - Acceleration on X

2 - Acceleration on Y

3 - Acceleration on Z

4 - timestamp

5 - A value from some other sensor

Because I need to get these as fast as I can I am thinking to not do any calculation while acquire values and just store them for 30 -60 seconds and then when the "test" is complete to compute calculations.
My question is if will be better to create 5 arrays and put these values there or create a matrix and store values there.
I need these values to be stored like they are "connected"
e.g. on reading 1 i get 5 values and put them on array[0] , then on reading 1 and so on
Also an important thing to mention, this will run on a esp32.

Thank you

I fully agree with Edgar Bonet.

My opinion is keeping a 'matrix' is better, or actually one array (of structs), where each array elements stores all information for one measurement (which is stored inside one struct). This has some benefits:

Data of one measurement is consecutive in memory, so you can easily transfer it (to some external memory or sending it). It's exact one struct (and you can use sizeof(struct_item) to know how many bytes you have to transfer.
It's good practice in general to keep information together, creating 5 always-equal length arrays seems strange.
If for some reason you want to make a single array dynamic or change it to a ring buffer for example, you can easily add/remove items (instead of dynamically changing 5 arrays).
Locality of change (see comments of Kwasmich/DuncanC)

There is also one benefit about having separate arrays (where each array stores one type of information, like an acceleration or timestamp: when you have a function (especially in another class) that only needs one of them, you can specifically send that array (or pointer/reference), so the other information is hidden from that function.