Bootloader only works once with usb to serial module When programming the Pro Mini using this USB-to-serial adapter the boot loader only works once. After the first programming the programmer is out of sync or not responding.

To be able to program the Pro Mini again I have to burn the bootloader using my Uno as an ISP.

Programming the Pro Mini through an Uno does not present the same problem.

Are the lock bits not being set properly or somehow overridden?

The module I had does not have a DTR signal. I mistook the RTS for DTR. Ordering correct module.


seeeduino can-bus shield v2: can't read can bus and write on SD card I'm using a seeeduino V4.0 and a CAN-BUS shield v2.0 with industrial grade SD card.
I'm using the default library given by the wiki of seeed.
I've simulate a can bus with two mcp2515. I can read it without trouble and everything is fine.
I can write/read on the SD card with the exemple given in the SD library.
But when I use this example, the can bus and SD card start without error. The can bus read normally and show the can bus data. But when I read the SD card, the file is created but completly empty.
I've tried to modify to write on a .txt instead of .csv and when I try a
myFile = SD.open("test.txt", FILE_WRITE);
if (myFile)
{
  ...
}
else
{
  Serial.println("error: file not reachable");
}

The "myFile" return false.
ps: I don't ask a lot of question here. Sorry for bad formating my question.

Despite the "the library example must be correct, It's work for other people before you", I'm not sure a lot of people make it works.
I've seen that even when the mcp2551 don't receive anything on can bus, the SPI bus is saturated by the mcp2551.
The solution was to use a simplest library make for 8MHz cristal chip. Modify it to works with standard 16MHz and use the interrupt pin (pin 2 on board) as interrupt.
If anybody got the same issue, just post a comment here and I'll do a better and more complete response.
Thank you very much @Timemage for your help


Connect two Arduinos using I²C (wiring) Altough having found a lot of documentation concerning wiring of I²C buses, I'm still not sure about the following question:

If both devices use separate power sources, is it a good idea to connect VCC/GND of those two devices?

I have two lines for SCL and SDA, connected to SCL/SDA pins on both devices A and B. The master device's VCC is connected to both lines using a pull-up resistor. Now as far as I understood, VCC/GND of the two devices should not be disconnected but I'm afraid I'd damage something if I'd connect them. As two separate power sources will never provide exactly the same voltage that would result in high currents, won't it? Or should I just connect them using some resistor to avoid high currents but provide the same voltage level?

The VCC lines aren't directly connected - you just have a shared data line with some voltage on it, which is always lower than VCC because of the resistor. Each device "talks" to the I2C bus by briefly connecting those lines to GND, which is common between both devices. Current is limited by the pull-up resistor, so it never gets too high. This makes it safe to directly link devices running at slightly different voltages.


Conditions with GSM module SIM900 doesn't execute I'm executing this code to control a LED with GSM SIM900 message but there are two problems. First, it receives messages sometimes and some times doesn't. The second is that it doesn't execute the if conditions that are on the GSM message when received.

Is there a problem with my GSM module? Can any one help?

#include <SoftwareSerial.h>
SoftwareSerial gsm(9,10);
String msg;
const int LED = 13;

void setup() {
  gsm.begin(9600);
  Serial.begin(9600);
  Serial.println("PUMP CONTROL");
  Serial.println("t : to receive text");
  delay(1000);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
}

void loop() {
  if (Serial.available()>0)
  switch(Serial.read())
  {
    case 't':
    showSMS();
    break;
  }

  while(gsm.available() > 0)
  {
    Serial.write(gsm.read());
  }
  if ( msg == "ON")
  {
    Serial.println("ON");
    digitalWrite(LED, HIGH);
     Serial.println("ON1");
    delay(1000);
  } else if (msg == "OFF")
  {
    digitalWrite(LED, LOW);
    delay(1000);
  }
  if(msg != "") msg = "";
}

void showSMS()
{
 gsm.print("AT+CMGF=1\r");
 gsm.print("AT+CNMI=2,2,0,0,0\r");
 delay(1000);
 msg = "";
 while(gsm.available() > 0)
 {
  msg += gsm.read();
 }
 Serial.println(msg);
}

I’ve solved the condition problems by making the condition with the ASCII code of ON and OFF.

I replaced:

if ( msg == “ON”)

with

if(msg.indexOf("ON")>=0)

and replaced:

else if (msg == "OFF")

with

if(msg.indexOf("OFF")>=0)


How can I concatenate these two values as a string? I've tried all the supposed solutions for the exact error, pasted into google, that I could find on every forum including this one and no matter the alleged solution I will either get the error about unsigned int to char*, the error below, or invalid pointers.

Why is this platform so completely unfriendly in data type conversion? It's almost as if the creator/s never wanted any data types to be able convert.

Here's my code that is apparently useless:

  char* DeviceName = "Device-" +  ESP.getChipId();
  wifiManager.autoConnect(DeviceName);

Error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
   char* DeviceName = "Device-" +  ESP.getChipId();

Then I tried to use the pointers, but I have no idea what I'm doing and I keep getting invalid pointer errors, and/or invalid conversion errors.

You can use the c function sprintf(, , ...)
The char array has to be big enough to hold your text plus a null to terminate the string.

#include <Arduino.h>

void setup() {
  Serial.begin(115200);
  delay(1000);
  char out[20];
  sprintf(out, "Device-%08X",ESP.getChipId()); // %08X\n formats the hex and pads with 0s.

  Serial.println(out);
}

void loop() {}

Output:

Device-005D4D9D


Shift registers. What, how and why? I'm making a project and I'm using multiple 1 digit 7 segment displays. I haven't plugged them all on my arduino because currently I'm just testing. The problem is on the I/O ports. Obviously I need to use shift registers and since it's my first time ever using them I need to know more about them. After googling, I found that the specific model I bought outputs 8 pins and you can stack up to 8 in series. So lets do the math. 8 shift register x 8 pins each SR = 64 new pins It seems cool but assuming I'm using 28 displays let's do the math again.
28 displays, each display has 8 pins (8 for segments and 2 as common cathode)
28 x 8 = 224 required pins.
Is is possible to expand the I/O pins by 224 pins? How many shift registers can I stack together? Also which is better, the single digit display or the 4 digit display?

You can chain as many shift registers as you want.

Most commonly, these displays are multiplexed. Only one digit is lit at a time, cycling though all the digits fast enough, so the eye can't tell. This is however not very good practice for 28 digits, as the brightness will become 1/28th (though you could create groups of digits, and multiplex those groups separately).

There are specialized chips that do this multiplexing for you. E.g. the Max7219. This chip can multiplex 8 digits, with 8 segments. So you'd need 4 of these to light up 28 digits.


Using RTC DS3231 + Arduino UNO to calculate time lapsed I am a beginner with no coding background.
I am trying to figure out an alarm that tells people how long they have been sitting on their chair.
The concept is very simple when the person would sit in his chair it will trigger an event ( maybe a button press) which should trigger the counting of time. if the time exceeds a limit (let's say an hour) a buzzer will go off. The only way to stop the buzzer is to stay away from the chair for let's say a minute.
I don't know how to start writing this code, especially how do I make this time counter start with this sitting action ( which might press a button).
Its for my class project so any help is highly appriciated.

One idea would be to use force/pressure sensor on chair. You have to find what the sensor outputs when an average person sits on it and calibrate the values accordingly in code. Finally you have to a set threshold value for it. Now if somebody sits on it and if that threshold is exceeded, it means somebody sat on it. So you can now trigger your rtc module or maybe you can use special peripherals called timers , which are inside arduino itself. Both can be used to keep track of time. Tutorials are available for both timers, and ds3231- arduino interfacing. You can easily code. Good luck :-)


Connect Multiple L293D Motor Controllers to Arduino I would like to connect 3 L293D Motor controllers to an Arduino Uno with the hopes of powering 6 different dc motors. I was just wondering how to wire this being that one motor controller (which allows for 2 dc motors to be controlled) already takes up most of the pins on the Arduino, thanks.

Below is the wiring diagram for how I am hooking up 1 L293D motor controllers to the Arduino.

The suggestion of using an Adafruit Motor Shield V2 for Arduino seems fairly good, although that particular shield controls only four DC motors at once.  That shield has a dedicated PWM driver chip on it, which removes the overhead of motor and speed control from the MCU.  That might allow you to drive four motors via the shield, and two via wires from the Arduino; or, stack two motor shields on the Uno.

If you definitely want to drive six motors from the Arduino, you may need to add a couple of control chips.  You could add a 74HCT04 hex inverter and a 74LS595, to create inverted drive signals and enable signals.  For example, the first PWM drive would go to L293 pin 1A and to '04 pin 1A; the first '04 output, 1Y, would drive L293 pin 2A.  One of the '595 outputs would go to L293 pin 1,2EN.

Alternately, you could use two '595s, with outputs to control L293 pins 2A; 4A; 1,2EN; and 3,4EN on each of three L293's.  The six PWM outputs from the Uno would go to 1A and 3A on the several L293's.  Using motor shields probably is a better idea, however.


Arduino Nano v3: is it possible to PCM + AltSoftSerial? I wonder is it possible to change PCM.h 's lib use of 16-bit timer1 to another 8-bit?
Now I'm getting

libraries\AltSoftSerial\AltSoftSerial.cpp.o (symbol from plugin): In function `AltSoftSerial::read()':

(.text+0x0): multiple definition of `__vector_11'

libraries\PCM\PCM.c.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1

when compiling

#include <PCM.h>
#include <AltSoftSerial.h>

An attempt to avoid XY problem: make AltSoftSerial work alongside with PCM-alike library on Arduino Nano v3 without SD.

I'm poorly familiar with timers and interrupts, so I'll be very grateful for any advice and suggestion!

It is not easy to make PCM sounds with the Arduino Uno or Nano. A few libraries can do that, but they use two timers: Timer1 and Timer2. Timer0 is already in use by Arduino. When using those libraries, the Arduino Nano is almost completely occupied to make sounds.

A software serial port also requires a lot from the Arduino Nano. The AltSoftSerial uses Timer1.

Those two will never work together. It is not possible.
For what do you need the serial port ?
Could that be done in a different way ?

The normal SoftwareSerial does not use a timer, but because it also occupies the Arduino Nano a lot, using SoftwareSerial together with a PCM sound at the same time will not work. Perhaps if you carefully design the sketch and never use them at the same time, it might work. I doubt if it will be reliable.

A better option is to swap the Arduino Nano for an Arduino Micro. Then you have a extra hardware serial port and you don't need the AltSoftSerial anymore. The library to make PCM sounds has to be compatible with the Arduino Micro. I suppose that not every PCM library is compatible.

The best option is to use a MP3 shield. Then you can send a command to play a MP3 sound. If you use a MP3 shield with a Arduino Micro or Arduino Leonardo or Arduino Mega 2560 or Arduino Zero or Arduino Due, then you have a extra hardware serial port and you don't need libraries that occupy the most of the Arduino board, and your sketch will be a normal sketch that does normal things.


Code runs, then doesn't run after I add some routine code I am programming an ESP8266-01.

I have this code which I am using to operate an on-off switch, which is being used as an override switch for when the relay is turned on and off over the internet:

void loop() {

  // Connect to the cloud
  rest.handle(client);

  // put your main code here, to run repeatedly:
  int read3 = digitalRead(0);

  Serial.print(read3);
  Serial.println(" input (1 is off)");

  if(read3 == 0) {
    if(pressed2) {
      Serial.println("in on");
      digitalWrite(2, 1);
      pressed = true;
      pressed2 = false;
    }
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
      pressed2 = true;
    }
  }
}

The above code never starts to run (nothing gets output on the serial) and the relay turns on. The thing is, this code works:

void loop() {

  // Connect to the cloud
  rest.handle(client);

  // put your main code here, to run repeatedly:
  int read3 = digitalRead(0);

  Serial.print(read3);
  Serial.println(" input (1 is off)");

  if(read3 == 0) {
    Serial.println("in on");
    digitalWrite(2, 1);
    pressed = true;
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
    }
  }
}

Basically the way the code is set up, it is handling things so that the pin doesn't get read after the instance first instance that it is read (this is what the bool pressed is helping to do).

Why doesn't the first version work?

UPDATE

Whole working sketch:

/*
  This a simple example of the aREST Library for the ESP8266 WiFi chip.
  This example illustrate the cloud part of aREST that makes the board accessible from anywhere
  See the README file for more details.

  Written in 2015 by Marco Schwartz under a GPL license.
*/

// Import required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <aREST.h>

// Clients
WiFiClient espClient;
PubSubClient client(espClient);

// Create aREST instance
aREST rest = aREST(client);

// Unique ID to identify the device for cloud.arest.io
char* device_id = "ew1zard";

// WiFi parameters
const char* ssid = "MaisonBlanche";
const char* password = "7932gLBw";

bool pressed = true;

// Functions
void callback(char* topic, byte* payload, unsigned int length);

void setup(void)
{
  // Set input / output pin
  pinMode(0, INPUT);
  pinMode(2, OUTPUT);

  // Start Serial
  Serial.begin(115200);

  // Set callback
  client.setCallback(callback);

  // Give name & ID to the device (ID should be 6 characters long)
  rest.set_id(device_id);
  rest.set_name("esp8266");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Set output topic
  char* out_topic = rest.get_topic();
}

void loop() {

  // Connect to the cloud
  rest.handle(client);

  // put your main code here, to run repeatedly:
  int read3 = digitalRead(0);

  Serial.print(read3);
  Serial.println(" input (1 is off)");

  if(read3 == 0) {
    Serial.println("in on");
    digitalWrite(2, 1);
    pressed = true;
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
    }
  }
}

// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("request from interwebs: ");
  Serial.println(topic);
  rest.handle_callback(client, topic, payload, length);

}

I used this - it does the same thing basically, just moved where the bool variables were.

if(read3 == 0) {
    if(pressed2) {
      Serial.println("in on");
      digitalWrite(2, 1);
      pressed2 = false;
    }
    pressed = true;
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
    }
    pressed2 = true;
  }


Printing Time to Serial Port I am reading sensory data that comes from the digital inputs(two DHT11 Humidity sensors using adafruit library.) and I would like to add a hh:mm:ss real time counts next to them. I try to use the time.h library but could not understand how to worked it in that way.

My code is;

#include "DHT.h"

#define DHT1PIN 4
#define DHT2PIN 7

#define DHT1TYPE DHT11
#define DHT2TYPE DHT11

DHT dht1(DHT1PIN, DHT1TYPE);
DHT dht2(DHT2PIN, DHT2TYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("Humidity sensors DHT11 tests!");

  dht1.begin();
  dht2.begin();
}

void loop() {

  delay(2000);

  float h1 = dht1.readHumidity();
  float t1 = dht1.readTemperature();
  float h2 = dht2.readHumidity();
  float t2 = dht2.readTemperature();

  if (isnan(t1) || isnan(h1)) {
    Serial.println("Failed to read from DHT #1");
  } else {
    Serial.print(h1); Serial.print(" \t");
  }

  if (isnan(t2) || isnan(h2)) {
    Serial.println("Failed to read from DHT #2");
  } else {
    Serial.print(h2);
    Serial.print(" \t");
  }
  Serial.println();
}

and my serial port out is;

and I want it to be like that;

Any help will appreciated.

I solved the problem by using millis() function. And now I ca get results like these;

My code is;

#include <Sensirion.h>
#include "DHT.h"
unsigned long time;

#define DHT1PIN 4
#define DHT2PIN 7

#define DHT1TYPE DHT11
#define DHT2TYPE DHT11

DHT dht1(DHT1PIN, DHT1TYPE);
DHT dht2(DHT2PIN, DHT2TYPE);

const uint8_t dataPin =  9;              // SHT serial data
const uint8_t sclkPin =  8;              // SHT serial clock
const uint8_t ledPin  = 13;              // Arduino built-in LED
const uint32_t TRHSTEP   = 1000UL;       // Sensor query period
const uint32_t BLINKSTEP =  250UL;       // LED blink period

Sensirion sht = Sensirion(dataPin, sclkPin);

uint16_t rawData;
float temperature;
float humidity;
float dewpoint;

byte ledState = 0;
byte measActive = false;
byte measType = TEMP;

unsigned long trhMillis = 0;             // Time interval tracking
unsigned long blinkMillis = 0;

void setup() {
  dht1.begin();
  dht2.begin();
  Serial.begin(9600);
  Serial.println("In.(%) In.Tem(*C) Out.(%) Time");
  pinMode(ledPin, OUTPUT);
  delay(15);                           // Wait >= 11 ms before first cmd
  // Demonstrate blocking calls
  sht.measTemp(&rawData);              // sht.meas(TEMP, &rawData, BLOCK)
  temperature = sht.calcTemp(rawData);
  sht.measHumi(&rawData);              // sht.meas(HUMI, &rawData, BLOCK)
  humidity = sht.calcHumi(rawData, temperature);
  dewpoint = sht.calcDewpoint(humidity, temperature);
  logData();
}

void loop() {

  unsigned long curMillis = millis();          // Get current time

  // Rapidly blink LED.  Blocking calls take too long to allow this.
  if (curMillis - blinkMillis >= BLINKSTEP) {  // Time to toggle the LED state?
    ledState ^= 1;
    digitalWrite(ledPin, ledState);
    blinkMillis = curMillis;
  }

  // Demonstrate non-blocking calls
  if (curMillis - trhMillis >= TRHSTEP) {      // Time for new measurements?
    measActive = true;
    measType = TEMP;
    sht.meas(TEMP, &rawData, NONBLOCK);      // Start temp measurement
    trhMillis = curMillis;
  }
  if (measActive && sht.measRdy()) {           // Note: no error checking
    if (measType == TEMP) {                  // Process temp or humi?
      measType = HUMI;
      temperature = sht.calcTemp(rawData); // Convert raw sensor data
      sht.meas(HUMI, &rawData, NONBLOCK);  // Start humidity measurement

      float h2 = dht2.readHumidity();
      float t2 = dht2.readTemperature();

      Serial.print(humidity);
      Serial.print(" \t");
      Serial.print(temperature);
      Serial.print(" \t");

      if (isnan(t2) || isnan(h2)) {
        Serial.println("Failed to read from DHT #1");
      } else {
        Serial.print(h2);
        Serial.print(" \t");

        //time = millis();
        //prints time since program started
        Serial.println(curMillis);
      }
      Serial.println();
    }
    else {
      measActive = false;
      humidity = sht.calcHumi(rawData, temperature); // Convert raw sensor data
      dewpoint = sht.calcDewpoint(humidity, temperature);
      logData();
    }
  }
}

void logData() {
}

But the difference is that I am using SHT75 instead of another DHT11 so I am simultaneously acquiring data from the both of them. Thanks for everyone!


Where Can I Find a 12v Solder-less Breadboard Power Supply? I am trying to find a 12v input and 12v output breadboard power supply but I can't find one. I am making an arduino-controlled lock but the Arduino cannot power the lock strike by itself so I need to use a seperate power supply. The link to make things clearer:
http://www.instructables.com/id/Arduino-RFID-Door-Lock/#step0

There is nothing special about a "breadboard power adapter" that isn't served by a normal regulated supply. Simply use wires or a barrel jack or some other connector to connect any regulated supply to the breadboard as desired.


Difficulties programming Arduino uno for 24 hour cycle I am trying to program my Arduino Uno board for a 24 hour cycle.
I have the Arduino board and two relays.
The aim is; every 24 hours relay 1 has to switch on for 5 seconds, and 1 second later relay 2 has to switch on for 15 seconds.
I have a sketch for a 12 hour cycle, and that works fine, but when I try for a 24 hour cycle, by changing the const unsigned int totalTime from 43200 seconds to 86400 seconds, everything goes wrong.

24 hour sketch - what is wrong?

//turn relays on and off at certain times.
//when the digital output pin is HIGH, then the relay is off.
//when the digital output pin is LOW, then the relay is on.

enum actioEnum {
  RELAY1_ON,
  RELAY1_OFF,
  RELAY2_ON,
  RELAY2_OFF,
};

struct tableStruct{
  unsigned int time;
  actionEnum action;
}
const table [] = {
  {0,RELAY1_ON},
  {5,RELAY1_OFF},
  // remaining 86395 for a total of 86400.
  {0,RELAY2_OFF}, // not needed, it is already off.
  {6,RELAY2_ON},
  {6+15,RELAY2_OFF},
  // remaining 86379 for a total of 86400.
};

const unsigned int totalTime = 86400; // total amount for sequence
unsigned int seconds;

unsigned long previousMillis;
const unsigned long interval = 1000; // 1000 ms; // 1000 ms is one second

const int relay1Pin = 2;
const int relay2Pin = 3;

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

  // the relay is off when the pin is high.
  // turn output high before setting the pinMode.
  // then the output changes from a floating pin to high,
  // and the relays will not be activated.
  digitalWrite (relay1Pin, HIGH);
  pinMode (relay1Pin, OUTPUT);
  digitalWrite (relay2Pin, HIGH);
  pinMode (relay2Pin, OUTPUT);
}

void loop () {
  // a one second timer with millis
  if (millis() - previousMillis >= interval) {
    previousMillis += interval;
    // scan table
    for ( int i = 0; i < int (sizeof(table) / sizeof (tableStruct)); i++) {
      if (table [i] . time == seconds) {
        switch (table [i] . action) {
          case RELAY1_ON:
            Serial.println("Relay 1 on");
            digitalWrite (relay1Pin, LOW); // low is relay on.
            break;
          case RELAY1_OFF:
            Serial.println("Relay 1 off");
            digitalWrite (relay1Pin, HIGH); // high is relay off.
            break;
          case RELAY2_ON:
            Serial.println("Relay 2 on");
            digitalWrite (relay2Pin, LOW); // low is relay on.
            break;
          case RELAY2_OFF:
            Serial.println ("Relay 2 off");
            digitalWrite (relay2Pin, HIGH); // high is relay off.
            break;
          default:
            Serial.println ("Error, a bug in the scketch");
        }
      }
    }
    seconds++;
    if (seconds >= totalTime) {
      seconds = 0;
    }
  }
}

On the Uno unsigned int is a 16 bit number. That means, that it can hold values between (and including) 0 and 65535. If you try to write a bigger value to this variable, it will cut of the higher bits, so that the rest fits into 16 bits. That gives you a totally different value, which is significantly small than 24h.

The solution is to use a bigger variable type for totalTime.
 You can use unsigned long, which has 32 bits and can hold way bigger values ( 0 to 4,294,967,295 (2^32 - 1)). That should be plenty enough for all your cases.


Atmega2560V, trying to burn bootloaders of MegaCore I am trying to burn MegaCore bootloaders to it, I have setup my custom PCB  with Atmega2560V-8AU and 8Mhz Crystal + Load Caps all assembled on using PCBA process.
I am trying to burn MegaCore bootlaoders to it, I am using Arduino UNO as ISP Programmer. My connections are all correct, It shows different Device Signatures (see below) whenever I hit Burn Bootloaders....

  0x0000ff
  0x00003f
  0x0000ff
  0x00ff00
  0x001000
  0xff0000
  0xfc0000
  0x00fe00

This is complete output with different Device Signatures

  Arduino: 1.8.3 (Windows 10), Board: "ATmega2560, Arduino MEGA pinout,
  2.7v, Disabled (default), 8 MHz external"

  C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude
  -CC:\Users\mudas\OneDrive\Documents\Arduino\hardware\MegaCore-avr-100-pin\avr/avrdude.conf
  -v -patmega2560 -cstk500v1 -PCOM4 -b19200 -e -Ulock:w:0x3f:m -Uefuse:w:0xfd:m -Uhfuse:w:0xd6:m -Ulfuse:w:0xf7:m

  avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
           Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
           Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Users\mudas\OneDrive\Documents\Arduino\hardware\MegaCore-avr-100-pin\avr/avrdude.conf"

     Using Port                    : COM4
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega2560
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
       flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

  avrdude: AVR device initialized and ready to accept instructions

  Error while burning bootloader. Reading |

  ############################################ | 100% 0.02s

  avrdude: Device signature = 0x00fe00 avrdude: Expected signature for
  ATmega2560 is 1E 98 01
           Double check chip, or use -F to override this check.

  avrdude done.  Thank you.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
What should be the problem.??? How to solve this.?

I removed 8Mhz from board and followed this instructions LINK, and burnt bootloaders using -F override check, then i returned 8Mhz oscillator to Atmega2560V and see device signature and it's automatically appears 0x1e9801 rather than 0x1e9803


"write" function in sd card is not working I have recently started working with arduino UNO and the "write" function in sd Card library is not working. Below is my code. I have tried with "println" which is working fine. Any help regarding this is welcome.

void loop()
{
     byte b=10;
     File dataFile = SD.open("datalog.txt", FILE_WRITE);
    if (dataFile)
    {
        dataFile.write(b);
     }
}

The problem is that print() and write() behave differently when you give them numerical data, such as a byte.

When you pass your byte to print(), it converts it to text which is convenient for humans to read. For example:

byte b = 10;
dataFile.print(b);

This will result in the following ASCII characters being written to the file:

10

That's actually two bytes: one byte with the value 49, which represents ASCII character 1, followed by a byte with the value 48 representing character 0.

However, write() does not convert numbers into text. It writes them in their raw binary form. For example:

byte b = 10;
dataFile.write(b);

When you do this, it doesn't write a "1" and a "0" to the file. It literally writes a binary byte with the value 10. When you try to open this as a text file, your computer interprets that byte as a single ASCII character. It so happens that ASCII value 10 is the newline character, meaning your file basically contains a blank line.

For comparison, try this instead:

byte b = 65;
dataFile.write(b);

ASCII value 65 corresponds to the letter A (uppercase), so that's what you should see in the file.

The write() functions are useful for writing raw data to file in the most efficient form for another machine to read (as opposed to being human-readable). This is why they allow you to write arrays -- it acts like one big block of raw data with a fixed format.

In your case, print() is more appropriate. That means for outputting arrays of numbers, you will need to use loops. That functionality isn't built-in to the print() functions because different projects might need different formatting. For example, some people might want one number per line, whereas others might want numbers separated by commas, and so on.


Pair of nRF24L01s ping/pong example sketch works, but using my own code fails after first successful transmit I have a pair of nRF24L01s connected to a pair of Arduino Unos and I'm using the RF24 library from here: RF24 library. When I run the pingpair example sketch, the radios transmit and receive back and forth just fine. So I tried to program my own very simple example but I'm running into a problem where the first message transmits successfully (and is received successfully), however, subsequent messages fail to send. The call to radio.write() returns false.

I'm using the following code on the 'sender':

RF24 radio(9,10);
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
uint8_t payload[1];

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setRetries(15, 15);
  radio.setPayloadSize(1);
  radio.openWritingPipe(pipes[0]);
}

void loop() {
  payload[0] = 1;
  bool ok = radio.write(payload, 1);
  Serial.println("Status: " + (String) ok);
  delay(200);
}

And the following on the 'receiver':

RF24 radio(9,10);
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
uint8_t payload[1];

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setRetries(15, 15);
  radio.setPayloadSize(1);
  radio.openReadingPipe(1, pipes[0]);
  radio.startListening();
  Serial.println("Listening: " );
}

void loop() {
  if (radio.available()) {
    bool done = false;
    while (!done) {
      done = radio.read(payload, 1);
      Serial.println("Got payload: " + (String) payload[0]);
    }
  }
}

I'm guessing the problem has to be with my code because the example sketches work, but I can't figure out what the problem is. Again to summarize, when I reset the Arduino, the first call to radio.write() returns true and the message is transmitted. After that, subsequent calls to radio.write() return false.

Also note that I did try adding a 10uF capacitor across +3.3V and Ground but it did not help.

Thanks for any help.

Comparing your rx against the example, i would suggest not having the while done statement. You could also throw in a few serial.write debug lines in both sketches, to log different parts of the code, to find where its getting stuck.


Are my arrays stored in sram or in Flash? I have the following memory allocation:

unsigned char g1[]={
  0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ....0x00 ,0x00 ,0x00 ,0x00 ,0x00 };
g2[]={
  0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ....0x00 ,0x00 ,0x00 ,0x00 ,0x00 };
...

 unsigned char* index[10] = {g1,g2,g3,g4,g5,g6,g7,g8,g9,g0};

This is accessed in the following way:

unsigned char* getMatch(int input){
  return index[input];
}

This is then futher acces using the method of

unsigned char store[1024]
unsigned char* temp = getMatch(n);
for(int i=0;i <50;i++){
 store[i]=temp[i];
}

and store is then modified and send to an external device.

As my program is randomly failing I think it might be running low on SRAM and was wondering if there is any way to force this memory to be placed in flash. Anybody got an idea?

It's stored in both the FLASH and SRAM because it's initialized array. To store in FLASH only you need use PROGMEM attribute.

const unsigned PROGMEM char g1[]= ...

You cannot access directly but using memcpy_P() function.


ESP8266 Switching firmware on the fly Can you help me out to understand if this is possible with ESP8266 / 32 ?

I have a main binary that i upload to the chip, let's call it A - that's done from arduino.

A starts to work, but communicates every couple of minutes with central server polling for a task.

If there is a task - let's call it B

A downloads it and stores it on SPIFFS.

Now what should happen is that A uploads it, reboots and B starts to work.

When B finishes it loads up again A and the circle closes - this process goes on forever.

Questions:

1) Is it possible that a stored on SPIFFS binary file can be uploaded to the chip? Like OTA does via www.

2) Can i somehow store A onto the SPIFFS, so that when B finishes i reupload A ?

Thanks for any input into this

The esp8266 Arduino package has 3 libraries for firmware update.

ArduinoOTA for upload from Arduino IDE
ESP8266HTTPUpdateServer for upload with web browser
ESP8266httpUpdate library to check a web server for new version of the
firmware


What good designs are available for Geiger counters using an Arduino? Are there any good circuit designs for Geiger-counter projects using an Arduino?

If so, what Geiger-Muller tubes should I choose to detect different types of radiation?

There are a few good, open-source, designs for Geiger counters using cheap G-M tubes and Arduino boards out there. Which one is best for you depends on what you want to achieve, so let's start by taking a look at what you might want to detect.

What are these "types" of radiation?

(source: Wikipedia)
Alpha radiation: basically consists of helium-4 nuclei (i.e. two protons and two neutrons). These interact with matter strongly because they are relatively heavy and carry a positive charge. However, because of their mass they will normally only penetrate a few centimetres of air. Alpha particles can be stopped in their tracks by a single sheet of paper.
You may not realise it, but the sensor in most smoke detectors uses a very small amount (~0.2μg) of Americium -  241Am.

Beta radiation: consists of highly energetic electrons. Because these particles are relatively light, they can penetrate somewhat further than Alpha particles. Even so, beta radiation can be stopped by a thin sheet of aluminium.
The big risk to human health from alpha- and beta-emitters is when they are ingested or inhaled. In these cases, the particles are brought into close contact with sensitive live tissue where the ionising radiation has the potential to cause various types of cancers.
Gamma radiation: is electromagnetic radiation having a higher frequency and shorter wavelength than X-rays.

One way to think of gamma-radiation is like a kind of "super X-ray". Gamma rays can pass through virtually anything. To build an effective shield, you need to have either very thick walls or a shield made from something with a high atomic weight, such as lead.
Gamma rays are produced naturally by the sun and stars - this is the source of what we call "cosmic radiation".

So which tubes should you choose?
Once you have decided what types of radiation you want your Geiger counter to detect the next step is choosing the tube. In general, they are all high-voltage tubes, typically operating at ~ 400V.
At the moment, the cheapest available tubes are probably the Russian SI-3BG Geiger Muller tubes, which can be picked up on eBay for about £5 GB. These are not very sensitive, but I've found they do work OK for beta and gamma radiation. However, it doesn't detect alpha radiation (which, as mentioned earlier, is what is emitted by the source in the sensor in many smoke detectors!)
One thing to watch out for is that these tubes are all different sizes, ranging from about 20mm long to more than 200mm. This matters. If you are going to design or buy a PCB for your project, just check that it has been designed to fit the sensor that you intend to use.
The following table lists the most popular G-M tubes, together with their main characteristics:

Follow the links below for further data on each tube:

SBM-20
SBM-21
SI-1G
SBT-9
SI-3BG
LND-712
LND-7124
LND-7224
J408γ
J305β
J306β

Your choice of tube is going to be determined by your budget, the types of radiation you want to detect and the sensitivity you want to achieve with your G-M counter.

Circuit designs
OK, so now we understand the radiation types, and we've chosen our tube, what Geiger counter designs are out there that use the Arduino.
(disclaimer: I have no connection with any of the companies mentioned in this answer)
Well, it turns out there are a few good designs out there (Google is your friend here), but one that does stand out from the pack (IMHO) is the Geiger Counter - Radiation Sensor Board for Arduino and Raspberry Pi from Cooking Hacks.
This is an open hardware design, and the code can be downloaded on a GPL licence.
It's a relatively simple design, and has a kit available pretty much off-the-shelf. Software can be downloaded for the Arduino and/or the Raspberry Pi. If you decide to buy the kit, they assure us that the shield/hat has been tested with the Arduino Uno and all models of the R-Pi.
Alternatively, you can just download the circuit diagram on the link above and design your own PCB (I don't think they offer the Gerber or Eagle files to download).
It is worth mentioning that the tutorial page also includes all the lovely useful background theory you'll need to understand how Geiger counters work, and how to get the most out of it.

Final thoughts. If you were thinking of building a Geiger counter without using an Arduino (Yes, yes, I know. But there may be some strange people out there who want to go this route!), there are still some nice designs out there you can play with.
The Geiger counter from MightyOhm is also open-source and uses the SBM-20 Geiger-Muller tube. Again, it is available as a kit, but if you prefer the DIY route, the design files are available to download.
Having looked at it, adapting this design to interface with an Arduino would probably also be relatively straightforward ...
If you are on a really tight budget there is a $15 Geiger counter on Hackaday. This uses the Russian SI-3BG G-M tube (discussed above) and a modified power-supply from a disposable camera.
I built one of these with a friend who was just starting out studying electronics and wanted to have a go at this project. I can confirm that it works, but that $15 price-tag is very optimistic.
(Having built this one, my friend decided that her next project would be to design a better one with greater sensitivity and which could detect alpha-, beta- and gamma-radiation and which incorporated an Arduino Uno. In hindsight, I should probably have mentioned the design from Cooking Hacks ..!).


MKR WIFI 1010 Providing 3.3V to breadboard The Arduino MKR WIFI 1010 product page says "The microcontroller on the MKR WIFI 1010 runs at 3.3V, which means that you must never apply more than 3.3V to its Digital and Analog pins. Care must be taken when connecting sensors and actuators to assure that this limit of 3.3V is never exceeded. Connecting higher voltage signals, like the 5V commonly used with the other Arduino boards, will damage the MKR WIFI 1010."

and yet it only has a 5V pin. I have a sensor that requires a 3.3V pin so I'm guessing my only option is to use a Logic Level Converter.

My question is if the MKR Digital and Analog pins can only take 3.3V, why is there only a 5V pin instead of a 3.3V pin to connect to a breadboard?

In short: VCC = 3.3V

The Arduino MKR WiFi 1010 board documentation is not complete. Well, at least they have the warning that the processor is running at 3.3V and the voltage levels of the pins should never be above 3.3V.

The page of the Arduino MKR ZERO has more information in the "documentation" tab. The VIN pin is the 5V power input, the 5V pin is unregulated 5V output (when the board is powered by USB or the VIN pin) and VCC is the regulated 3.3V output.

The term "VCC" means that it is the voltage at which the processor is running. Since it is a 3.3V Arduino board, it is the 3.3V voltage pin. That 3.3V should be used to power sensors. The "Tech Specs" tab at the MKR ZERO tells that it can supply up to 600 mA. That is the same for the MKR WiFi 1010, because the same AP2112K-3.3 voltage regulator is used.


Myoware reading multiple fingers? So I have recently been trying to use the Myoware Muscle sensor to control an 3d printed arm, but it is only able to read the muscle of the entire arm. Is there anyway i could make the Myoware sensor read different fingers at the same time?

Our MyoWare sensor is a single channel EMG sensor and should only be used to detect a single muscle at a time. BUT, if you have 5 sensors, then you can indeed use them to measure each finger's flexion or extension individually. It would take 10 sensors to do both flexion and extension of all your fingers.

However, keep in mind that there are many muscle groups on top of each other in the forearm (e.g. finger muscles, wrist muscles, forearm rotation muscles) and the MyoWare uses surface electrodes. The sensor will detect the activity of any muscle(s) that get activated under the area of the electrodes and you could get a lot of cross-talk between these muscles. For example, the muscles that control your wrist are under the muscles that control your fingers. Any activation of your wrist muscles when trying to measure the finger muscles would cause the sensor to falsely register activity for your finger muscles.

If you are thinking of using it to detect finger position, I would advise using a flex sensor or something similar than a muscle sensor. Muscle sensor sensors are usually used to detect force or as an on/off switch given a threshold value to activate the switch.


Arduino Mega Clone CH340G Capacitor Values I'm making my own Arduino Mega board with ATmega2560-16AU and CH340G. Jump to the end of the post to find the real question.
I have already ordered a PCB before and it didn't work when I soldered everything in place. I have already asked why that board didn't work on another post here: Programming custom Arduino Mega with Arduino Uno
But I was not satisfied with the answers and started suspecting whether or not the capacitor values were right on my board.
I'm trying to make my own version of RobotDyn's Arduino Mega 2560 Pro so I tried taking the already programmed ch340g and soldering it on my own board and still failed. When I put a previously not programmed ch340g on the RobotDyn board and programmed it using Arduino UNO (Arduino as ISP) the board would work.
So now I ordered a new PCB but haven't ordered any of the passive components yet.
If any of you could tell me where I could find the values from the schematic below I would really appreciate that.
https://robotdyn.com/pub/media/0G-00005641==MEGA-PRO-CH340GATmega2560/DOCS/Schematic==0G-00005641==MEGA-PRO-CH340GATmega2560.pdf

The values can be easy found for generic CH340g and ATmega2560 implementations:
C1,C2 = 100nF, C3,C4 = 22pf but depends on the crystal you use, all others excepting C12 are decoupling capacitors.
C12 has no sense where it's placed, it seems that the schematic is a bad combination of schematics, this capacitor should reset the board at power on but it breaks the reset pulse from CH340g so you cannot program the board without pressing manually the reset pushbutton. Don't place C12 at all.
Also place a short instead of R5 and R6 that are not in the CH340g manual (there is a special mention to connect the pins straight to USB bus), remove R8, is not needed for the same reason, R3 makes no sense, don't place-it.
R2,R4 = 1K, R7,R9 = 10K, R10,R11,R12,R13 = 1K, R14 = 10K , R15 = 1M.
Y1 = 12Mhz, Y2 = 16Mhz
A 22 ohm resistor is missing in your schematic between Y2 XTAL1 and ATMEGA XTAL2 but I don't think it's important.
I hope I didn't missed something
The bare minimum is to remove c12 and maybe R3 and check the values you used for R2, R4 against the above values.
If something would be wrong with CH340g the USB connection would fail but I see no mention about that in your post.


U8glib Code Help - Simple text display with new line I havent coded in C++ for about 10 years and need to relearn,  in the meantime, i have a project that i would like to get working.

I have a sensor which i store uint16_t variables.  I would like to have my loop print my variable at the bottom with some text for the unit, example  "Deg F: (variable)"  and then shift up one line for the next reading.

Im having a lot of trouble with this.  The U8glib example "console" functions almost exactly how i want my code to work,  i simply cannot figure it out.  Ive been experimenting and reading documentation for a week and cannot get it to work.  I can get it to print on top of the old data but I cannot seem to figure out how to shift the line and keep the older data.  im using a SSD1306 128x64 I²C Oled with Arduino uno re.

Thanks.

First, u8glib is no longer maintained. It has moved to u8g2.  There is a u8x8 mode that is much like the u8glib code, in that it is text-only, and uses fonts that fit in an 8x8-pixel box, though there are multiple fonts to choose from.

Second, u8g2 does not have an automatic scrolling mode, so the Console example you mention keeps a buffer (an array of strings, with one element per possible text-row on the display) of the "history". Each time it adds a line to the console, this example copies every line to the one closer to the top of the display, and then copies the new line to the last row (the bottom of the display.)

Go and do likewise. If you show your coding attempt, you will get better answers.


Are there any good and maintained libraries for using DS2482 I2C to 1-Wire bridge? The DS2482-100 and DS2482-800 are I2C to 1-Wire bridges which are useful for driving complex 1-Wire networks.

These are natively supported by a number of packages in Linux so you can interface easily with them on a Raspberry Pi.

I was surprised to find there is not an obvious library for accessing them on an Arduino however.

I have found the following:

An Arduino library - has some quirks and not-maintained.
Part of AVR-Liberty - less quirks, not sure if maintained, not "Arduino" as
such, more AVR.

It is helpful to be able to rely on maintained libraries to deal with any changes to the Arduino environment.

Arduino libraries are often easier to use than ones designed for AVR in general, which means more people are able to use the software.

Is there a better library available?

I believe the library linked by Cybergibbons has a bug in

uint8_t OneWire::wireSearch(uint8_t *address)

A discrepancy at i = 0 (bit zero in this library, id_bit_number = 1 in a Maxim example) only follows the direction = 1 path and fails to find ROM addresses where bit zero = 0 (i.e. even family codes are missed when mixed devices, some with even and others with odd family codes, are present on the 1-wire bus).

A fix I have just implemented and appears to work is to modify the library to declare searchLastDiscrepancy and last_zero as int8_t (not uint8_t), initialise/reset them to -1 (not zero) and, near the end of the method

    if (!last_zero)
            searchLastDeviceFlag = 1;

becomes

    if (last_zero == -1)
            searchLastDeviceFlag = 1;

I hope that helps.


How to execute operation once till a condition then restart it from start I am making a project using IR sensor,servomotor and Push button.
I am not able write code for the logic as stated:
it will execute the operation when it reads the digital value of IR high and rotates the servomotor till a threshold and then rotates the servo reverse  on using push button.It will perform no actions till the push button is used altough IR sensor is reading value.Then it will again perform the same action after push button is used.

My suggestion is, even if it seems to be a simple example, to start with an analysis of what you really want to achieve. In this example I would try to start with an state diagramm. With this you could clarify simple questions, e.g. what happens if the IR goes low while the motor is turning. In my draft, the motor would keep running, but maybe the IR is for safety reason and you want to stop motor if something approaches. If that is your intention, you can easy add aditional transitions at all states to return to state 00.

Such an approach helps you in creating code easy to maintain and change to new requirements

After having your state diagramm finished it is often easy to start programming with switch/case sturctures for first learning experiences.

Switch(state) {
  case 00:
  // if IR set state = 10;
  break;
  case 10:
  // if button was pressed set state = 11
  break;
  case 11:
  // turn motor
  // if treshold set state = 12
  break;
.
.
.

}


How do I set a variable so that after a condition is met the loop ignores input? I have a analog inputs to my Uno that I am cleaning up and using to keep a digital pin high until the output drops to zero. At this point I want to stop reading that input because it may come back up after being low for a short time.
Is there any way to set a variable that can be triggered by that first zero that prevents the loop from sending the digital pin high from then on?
Like a latch of some sort, or could I use an interrupt somehow?

You've already described what you need to do.  Just set a boolean variable.  It really couldn't be easier.

boolean runThisPart = true;

void loop() {

  if(runThisPart) {
     // this part only runs if runThisPart is true
     //  if something happens and you don't want
     //  to run this part anymore then
     if(some-condition){
        runThisPart = false;
     }
  }
  //  The rest of your code can also set runThisPart
  //  to true or false to turn that section on or off.
}


How to reset arduino Mega 2560 code automatically? I am working on the temperature project using arduino to collect temperature. But sometimes arduino hang there so I have to unplug cord and plug it back in to restart the arduino. I do not when it is going to hang up again. So I decide to do some research on the internet but no luck for that. Here is the article I read about resetting arduino code with watchdog timer library.(unfortunately, it only work for arduino uno) If someone has any idea how to reset arduino mega 2560 code. Please help !!

avr-libc already has the appropriate functions created for you. Just include <avr/wdt.h>.

Sample usage

#include <avr/wdt.h>

void setup()
{
   wdt_enable(WDTO_8S);
   ...
}

void loop()
{
   wdt_reset();// make sure this gets called at least once every 8 seconds!
   ...
}


warning: variable 'b' set but not used I got the following error:

warning: variable 'b' set but not used.

I think I do a really small thing wrong but I can't figure out what it is.

#define array_size(array) ((int)(sizeof(array) / sizeof((array)[0])))

typedef struct Boid {
  unsigned long start_animate_time;
} Boid;

Boid boids[4];

Boid create_boid() {
  unsigned long start_animate_time = 0L;
  Boid b = {start_animate_time};
  return b;
}

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

  boids[0] = create_boid();
  boids[1] = create_boid();
  boids[2] = create_boid();
  boids[3] = create_boid();

  for (int i = 0; i < array_size(boids); i++) {
    Boid b = boids[i]; // <<<<<<<<<<<<< this line!
    b.start_animate_time = 456;
  }

  for (int i = 0; i < array_size(boids); i++) {
    Boid b = boids[i];
    Serial.println(b.start_animate_time); // BUG always 0
  }
}

void loop() {

}

  flock_01_ino_debug.ino:28:10: warning: variable 'b' set but not used
  [-Wunused-but-set-variable]
       Boid b = boids[i];
            ^

C++ is not Java. You can't just assign structs like that - it copies them (if anything).

Boid b = boids[I]; // <<<<<<<<<<<<< this line!
b.start_animate_time = 456;

Instead just access the array slice directly:

boids[i].start_animate_time = 456;

And later on as well:

Serial.println(boids[i].start_animate_time);

Basically, you create a "Boid" variable called "b", copy the content of boids[i] to it, set a value in that variable, and then throw it away. Hence the "not used". If you want to reference a specific array slice as a separate variable either get a pointer to it:

Boid *b = &boids[i];
b->start_animate_time = 456;

Or use a reference:

Boid &b = boids[i];
b.start_animate_time = 456;

Of the two I prefer using a pointer, but I come from a C background and understand pointers, but it took me many years of trial and error to get to that point...


Monitoring multi analog ports with ACS712 current sensors Making a Auto Blast Gate for dust collection in my wood shop. Arduino Nano using ACS712's to detect when tool is in use.  Using DRV8825 to drive a single Stepper motor that will spin a disk to line up blast gate for the tool in use. Code works as expected with one sensor coded but I can't figure out how to make it work with additional sensor coded in.
Not sure if this is the way the question shows up,  Thanks

/*This one is atarting to work.   When tool is turn on the ACS712 detects it and the stepper moves 90 deg/steps.

When the tool is turned off it remains in position which is desireable as I would use the same tool multiable times in a row.
Need to add sensor A1 and assign different steps to it.
Can I declare the values of each sensor 1 time to be used whenever that analog port read > current Threshold?
Can I have a statement that will check all the analogs and act on the one that is >current Threshold?
Need for the stepper to only move if a different sensor (than the previous analog#) is > current Threshold?
IF/Else
*/

#include <Arduino.h>
#include "BasicStepperDriver.h"
#include "DRV8825.h"

#define MOTOR_STEPS 360 // Motor steps per revolution. Most steppers are 200 steps or 1.8 degrees/step
#define RPM 200
#define MICROSTEPS 1    // Since microstepping is set externally, make sure this matches the selected mode
                        // If it doesn't, the motor will move at a different RPM than chosen
                        // 1=full step, 2=half step etc.
#define DIR 2           // All the wires needed for full functionality
#define STEP 3
#define ENABLE 4        // 2-wire basic config, microstepping is hardwired on the driver
BasicStepperDriver stepper(MOTOR_STEPS, DIR, STEP, ENABLE);

#define CURRENT_SENSOR_PIN A0 // Current sensor is connected to analog pin A0

#define CURRENT_THRESHOLD 570 // The analog value above which the relay shall be triggered
#define CURRENT_SAMPLE_PERIOD 500 // The number of milliseconds to sample the current reading

int analogValue = 0; // Stores ADC values read in from the current sensor
unsigned long stopwatch = 0; // Used to keep track of elapsed time

void setup() {
  Serial.begin(9600);
  pinMode(DIR, OUTPUT);
  pinMode(STEP, OUTPUT);
  pinMode(ENABLE, OUTPUT);
 // pinMode (A0, INPUT);

    stepper.begin(RPM, MICROSTEPS);
    stepper.setEnableActiveState(LOW);
  }

void loop() {
    analogValue = 0; // Initialize analogValue to a known state
    stopwatch = millis(); // Store a snapshot of the current time since the program started executing

    // Collect the max ADC value from the current sensor for the predetermined sample period
    while (millis() - stopwatch < CURRENT_SAMPLE_PERIOD) {
      analogValue = max(analogValue, analogRead(CURRENT_SENSOR_PIN));
      Serial.println(analogValue);
    }

    // If the max ADC value from the current sensor exceeds the threshold, set the state to LOW
    if (analogValue > CURRENT_THRESHOLD) {
      stepper.enable();  //  energize coils - the motor will hold position
      stepper.rotate(90);  //Moving motor using the degree notation in ()

   }
    while(analogValue > CURRENT_THRESHOLD)
      stepper.disable();  // pause and allow the motor to be moved by hand
}
// need to return to top of loop

First: As written in the comments, your current code will only work once. After the first reaching of the threshold it will permanently stay in the last while loop, since analogValue can never change in there (you don't assign a new value to it). Thus this part should be removed.

To extend your code for multiple sensors, you can organize all the relevant data into arrays, so that you can loop over them. First we define an array of the used analog input pins (together with a define for the array size, so that we can later easily loop over the array and still be able to easily add further sensors):

#define SENSOR_N    2
uint8_t sensor_pins[SENSOR_N] = {A0, A1};

Then we are defining similar arrays for the thresholds and stepper positions:

uint16_t sensor_thresholds[SENSOR_N] = {570, 400};
uint8_t stepper_positions[SENSOR_N] = {90, 180};

Now in the loop() function we can surround the measurement and stepper code into a loop over the arrays. Where you used defines before, we are now using the array elements of the corresponding index:

for(uint8_t i=0;i<SENSOR_N;i++){
    analogValue = 0; // Initialize analogValue to a known state
    stopwatch = millis(); // Store a snapshot of the current time since the program started executing

    // Collect the max ADC value from the current sensor for the predetermined sample period
    while (millis() - stopwatch < CURRENT_SAMPLE_PERIOD) {
        analogValue = max(analogValue, analogRead(sensor_pins[i]));
        Serial.println(analogValue);
    }

    // If the max ADC value from the current sensor exceeds the threshold, set the state to LOW
    if (analogValue > sensor_thresholds[i]) {
        stepper.enable();  //  energize coils - the motor will hold position
        stepper.rotate(stepper_positions[i]);  //Moving motor using the degree notation in ()
    }
}

Now you still have 2 things to consider:

Depending of the number of sensors, your code currently can take rather long. With lets say 6 sensor, you are measuring for 3s in total at the worst case (when the last machine is turned on). You might want to reduce your measurement duration (500ms is rather long).
You need to add code for defining, what happens, when you turn multiple machines on at the same time. Currently that would lead to the stepper motor going back and forth; surely not what you want. The easiest thing would be to only consider the first sensor, that reaches the threshold, which then gets to set the position ("first" not in chronological sense, but in the order of the pin in the sensor_pins array). You can reach that with a break; command at the end of the threshold if condition.

Notes:

The arrays hold, what they say. sensor_thresholds holds all the thresholds. In my example 570 is the threshold of the first sensor and 400 is the threshold of the second sensor. 90 in stepper_positions is the position of the stepper for the first sensor. 180 is the position for the second sensor.
I used 2 sensors in my example. You can extend that yourself by setting the define SENSOR_N to the number of sensors and adding elements for every sensor into the arrays.
uint8_t and uint16_t are unsigned integer types with the mentioned number of bits: uint8_t has 8 bits (1 byte), uint16_t has 16 bits (2 bytes). uint8_t is the same as unsigned char or byte. uint16_t is the same as unsigned int on the Uno/Nano. I used these types, because it is a good practice to use types, that have the same size on every platform. When changing to a different platform, types like unsigned int might have a different size, like being a 32 bit unsigned integer instead of a 16 bit one. As that might break code, that relies on the specific size of the type, I try to always use types with the same size on all platforms. These types have always the same pattern. There are also: uint32_t, int16_t (signed integer) or int8_t.
I've chosen the type sizes according to the expected values. Pin numbers are typically 8bit/1 byte. That is sufficient. The thresholds are above 255, thus 8 bits are not enough, so I chose a 16 bit integer. Depending on the stepper positions, that you need, you might want to change it's type also to uint16_t.


a mega 2650 power supply mystery Something happened to my mega2650 as I was experimenting the other day.  It no longer turned on when powering from the 2.1mm jack or from Vin, regardless of the voltage applied.  A plastic bubble had formed on the 5V regulator, I assumed I had shorted something and fried it.  If I applied 5V to the 5V pin everything worked fine.  It also works fine when powered from USB.  So I replaced the 5V regulator with a NCP1117 version.  But I have the same situation.  If I apply voltage directly to the 5V regulator input pin I get 5V on the output pin and everything is fine.  I tested up to 12V and it is dead on at 5V.  I also checked the PNP switching transistor, and found it was working correctly.  As far as I can tell, the only thing remaining is that the trace is severed somewhere between just after the Vin pin and the 5V regulator, maybe the regulator input is not soldered well to the trace?  But this was one of the better solder joints I made, so I thought.  Any other ideas as to the root cause?

Thanks

You obviously have some form of DMM or volt meter at your disposal, since you know the voltages around the regulator.

Some places you should, therefore, probe for voltages, and what voltages you should expect.  With the barrel jack connected and powered up, and assuming a 12V supply, you should expect:

At the rear of the socket: 12V
At the socket side of the M7 diode: 12V
At the header side of the M7 diode: 11.4V
At the right-hand (VIN) pin of the regulator: 11.4V
On the tab of the regulator: 5V

If you find any of those are wrong then the component that comes before it may well be faulty.


Error initializer-string for array of chars is too long using ESP32 Webserver i tried to use an asynchronic webserver for a new project with friends using this tutorial.
We want to run an FFT while also changing some settings via the webserver. Since the tutorial only put code in the setup() i thought it would be good for performance.
When i just copy paste the code it works pretty ok, but then i wanted to change everything into classes like a good boy. Now i get this error:
 In file included from sketch\webserver.cpp:2:0:
webserver.h:36:29: error: initializer-string for array of chars is too long [-fpermissive]
   const char index_html[] = R"rawliteral(

sketch\webserver.cpp: In constructor 'webserver::webserver()':
webserver.cpp:4:22: error: initializer-string for array of chars is too long [-fpermissive]
 webserver::webserver() {

I tried to search for a solution, but all the other problems with this type of error, didnt seem to fit with my problem.
This is the header file where the char string is declared
#ifndef webserver_h
#define webserver_h

#include "Arduino.h"
#include "ESPAsyncWebServer.h"
#include "AsyncTCP.h"
#include <WiFi.h>

class webserver {

  private:
  // Insert Private Variables And Functions

   // Replace with your network credentials
  const char* ssid     = "ESP32-Todesstern";
  const char* password = "CaptainHook";

  const char* PARAM_INPUT_1 = "input1";
  const char* PARAM_INPUT_2 = "input2";
  const char* PARAM_INPUT_3 = "input3";

  // Set web server port number to 80
  AsyncWebServer server(int port);

  // Variable to store the HTTP request
  String header;

  IPAddress IP;
  //WiFiClient client;

  public:
  //Insert Public Variables and Functions
  webserver();

  String music_state;

  const char index_html[] PROGMEM = R"rawliteral(
  <!DOCTYPE HTML>
    <title>ESP Input Form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <form action="/get">
      input1: <input type="text" name="input1">
      <input type="submit" value="Submit">
    </form>

    <form action="/get">
      input2: <input type="text" name="input2">
      <input type="submit" value="Submit">
    </form>

    <form action="/get">
      input3: <input type="text" name="input3">
      <input type="submit" value="Submit">
    </form>

  )rawliteral";

  void setup_server(AsyncWebServer server);

  void notFound(AsyncWebServerRequest *request);

};

#endif

Thanks for the Help,
Xenoshell

Please check the readme: https://github.com/me-no-dev/ESPAsyncWebServer#send-large-webpage-from-progmem
You probably have to declare it in progmem without rawliteral.
const char index_html[] PROGMEM = "..."; // large char array, tested with 14k request->send_P(200, "text/html", index_html);


Incompatible types in assignment of 'uint8_t {aka unsigned char}' to 'uint8_t [1] {aka unsigned char [1]}' I'm trying to send custom data. But it doesn't seem to work. I can't find a way to parse my string to a unit8_t. I tried to follow other people's solutions but they don't seem to work for me.

// Declaration
uint8_t myData[] = "";

void loop(){
    myData = *(uint8_t*)atoi("custom string".c_str());
}

This is the error message that I keep getting:
Incompatible types in assignment of uint8_t {aka unsigned char}' to 'uint8_t [1] {aka unsigned char [1]} .

atoi is for converting a textual representation of a number ("123" for example) into an actual integer.

The c_str() function gives you a pointer to the internal buffer of the String (assuming you actually have a String) which is no different to a uint8_t[] or uint8_t * (other than the signedness).

Without knowing exactly what the destination function for this buffer requires it's very hard to help you, but you may want something like:

LoRaWan.send((uint8_t *)myString.c_str(), myString.length());

If you need to copy the data into a fixed length buffer then you need to first create a buffer of that actual size - then copy the string data into it:

// Create a buffer of 32 bytes
uint8_t myBuffer[32];
// Copy at most 32 bytes, but no more than there actually is, into the buffer
memcpy(myBuffer, myString.c_str(), min(myString.length(), 32));


Blueduino Rev2 service UUID for web bluetooth I have a Blueduino Rev2 board that I would like to have communicating with a web app (running the chrome bluetooth software) but I'm having trouble sorting out the service UUIDs that the web bluetooth library requires.

According to the wiki, it uses the service UUID 0xFFF0, write characteristic UUID 0xFFF1 and read characteristic UUID 0xFFF2 (source) but when I scan for the device through the web app filtering for that service UUID it doesn't appear, but does when I remove the service UUID filter.

Code used to scan for the blueduino:

navigator.bluetooth.requestDevice({
    filters: [{
        name: 'ZeroBeacon',
        services: [0xFFF0]
    }]
})

Does anyone know what the UUIDs are that I should be using? The documentation is quite unclear and lacking.

If the 0xFFF0 Bluetooth Service is not advertised by the Blueduino Rev2 board, you should not include it in the "services" key. It should be in "optionalServices. See https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web#request_bluetooth_devices

I think your code should look like:

navigator.bluetooth.requestDevice({
  filters: [{ name: 'ZeroBeacon' }],
  optionalServices: [0xFFF0]
});


How do I connect Arduino to RS232 via USB? I have a device that takes commands in the form of RS232 communication. I've connected the Arduino's USB port, through an adapter, to the device's 9-pin serial port, but no communication has happened.

The full chain of adapters is a printer cable (which would connect the Arduino to a computer), a female-to-female usb adapter, and a Sabrent USB to serial adapter.

I made sure the communication wasn't happening using the code while (!Serial) and blinked an LED in a certain pattern.

Is there something I'm missing? How do you get the devices to communicate?

This is effectively not workable.  USB is not a peer-to-peer standard, but a host/device one.  Both your Arduino and the USB-serial converter are intended to be devices, so they cannot communicate.  While it would be possible to use another microcontroller acting as a host to bridge to serial that would be pointless, as the actually central problem of RS232 vs. logic level serial would still need to be solved.

Instead, what you want is an inverting serial level shifter - essentially a board with an IC like a MAX232 or one its many successors.  You would either connect this to arbitrary digital pins of the Arduino and use a Software Serial instance, or decide that it is okay to block usage of the USB port by a computer while this is being operated, in which case you could connect it to the D0 & D1 pins used by the on-board USB interface (there are typically resistors in between the chips on the board to support this overriding).

Ironically, in a way what you want is one of the original Arduino boards that had a serial level shifter and 9-pin connector in place of the USB chip and USB connector of modern boards.  But then, you probably want something with an ATMega328p rather than the earlier, more primitive ATmega chips used on the original boards.  If you can still find a board of the original design, upgrading the chip may be an option, or it may be that your task is simple enough not to require it.

There have been many other non-Arduino embedded controller boards released with native RS232 ports as well, especially those dating from around a decade ago might give a good combination of fairly modern capability with not yet having abandoned RS232 in favor of USB.


Rounding up and Down My arduino is meisuring the tempature and gives values like: 28.58 Degrees Celcius. I would like to round this up to one decimal. I could make the variable one shorter by cutting the "8" off which would desplay 28.5.
Yet this feels a bit like cheating as it mathimatical not correct. Does anyone know how to round up/down. Which would show my tempature as 28.6.

Extra advice needed. I am sending the tempature by Serial to my RPi which has a python code running. Would you suggest doing the rounding in the Arduino code or in The Python code.

Thanks in Advance!

As far as I know, the Serial.print (or println) does rounding up and down. All you have to do is take a float variable and do Serial.print( value, 1);

Without extra parameter, the default is choosen, which is 2 decimal digits: Serial.print( value, 2);

Why do you want to shorten the bytes over the Serial ? You can just as well send two decimal digits and process the value in Python.


Arduino IDE upload error I've recently been trying to make program using IRremote(library) in my Arduino IDE(v1.8.9), but whenever I hit the upload button this error message is returned

  Sketch uses 7514 bytes (23%) of program storage space. Maximum is
  32256 bytes. Global variables use 415 bytes (20%) of dynamic memory,
  leaving 1633 bytes for local variables. Maximum is 2048 bytes.

  avrdude: verification error, first mismatch at byte 0x0002

  0x5d != 0x62 avrdude: verification error; content mismatch

  avrdude: verification error; content mismatch

I'm using Arduino UNO R3

This is the code I'm trying to run

    #include <IRremote.h>
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
  if (irrecv.decode(&results))
    {
     Serial.println(results.value, HEX);
     irrecv.resume(); // Receive the next value
    }
}

Also, every other code(not using the IRremote library) uploads just fine without any errors.

There can be power/connection problem or somehow the bootloader has been damaged.
So

Check power
Check Connection

If there no problem found, then by using usbasp, avrisp, usbtinyisp, etc reflash the bootloader. I hope your problem will be solved.


Using PortB as a sink, not working Out of ideas here, i try using PB0-3 as sinks for a LED matrix and the pins just won't sink.

My test code:

void setup() {
  //bitClear(SPCR, 6);
  pinMode(PD5, OUTPUT);

  pinMode(PB0, OUTPUT);
  pinMode(PB1, OUTPUT);
  pinMode(PB2, OUTPUT);
  pinMode(PB3, OUTPUT);

  digitalWrite(PB0, LOW);
  digitalWrite(PB1, LOW);
  digitalWrite(PB2, LOW);
  digitalWrite(PB3, LOW);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(PD5, HIGH);
  delay(1000);
  digitalWrite(PD5, LOW);
  delay(1000);
}

(Using bog standard Blink as a starting point for tests)

My controller is an ATMega328P programmed using USBaspLoader on my own PCB.

If i connect the physical pin that should be sinking with a piece of wire to ground the LED starts blinking, so the "sending" part seems to work but the "receiving" part doesn't.
As you can see i tried manually disabling the SPI port, no luck either.
I tried different controllers, among them a good old ATMega8-16, nothing seems to work.
I even breadboarded a test circuit but no luck, PortB wont sink.

PB3 etc don't refer to Arduino pins. Instead they refer to the bits in the internal registers.

To use digitalWrite() etc you must use Arduino pins not internal register bit numbers.

The pin to port/bit mapping is defined by what board you have selected, and if you want to look it up you should examine the pins_arduino.h file for your selected board.


RFID + LCD + Arduino Mega 2560 = RFID not printing correctly My Arduino Mega isn't printing the RFID card's tag it simply prints the card's 2 digits at a time but deletes the previous prints. Can I get help with this?

#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#include <LiquidCrystal.h>

Servo myservo;  //creates servo to control

const int rs = 26, en = 27, d4 = 28, d5 = 29, d6 = 31, d7 = 30;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int R=3;
int G=8;
int B=6;

void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Approximate your card to the reader...");
  lcd.print("Place your card");
  lcd.setCursor(0, 1);
  lcd.print("Near reader");
  lcd.setCursor(0, 0);
  myservo.attach(7);//attatches servo to pin 7
  myservo.write(179);
}

void loop() {
  analogWrite(B, 255);
  // Look for new cards
  if (!mfrc522.PICC_IsNewCardPresent()) {
    return;
  }
  // Select one of the cards
  if (!mfrc522.PICC_ReadCardSerial()) {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  byte letter;
  String content= "";
  for (byte i = 0; i < mfrc522.uid.size; i++) {
     lcd.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     lcd.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
     lcd.setCursor(0, 0);
  }
  delay(1000);
  lcd.clear();
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "4F 60 3C D9") {
    //change here the UID of the card/cards that you want to give access
    Serial.println("Authorized access");
    lcd.print("Authorized");
    analogWrite(B, 0);
    tone(4, 900, 100);
    lcd.clear();
    Serial.println("Unlocking...");
    lcd.print("Unlocking...");
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    delay(1000);
    myservo.write(100);
    delay(15);
    Serial.println("Unlocked");
    lcd.print("Unlocked");
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 255);
    delay(5000);
    Serial.println("Relocking...");
    lcd.print("Relocking...");
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    delay(1000);
    myservo.write(179);
    delay(15);
    Serial.println("Locked");
    lcd.print("Locked");
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 0);
    delay(100);
  } else {
    Serial.println("Checking Card");
    lcd.print("Checking Card");
    lcd.setCursor(0, 1);
    delay(100);
    lcd.clear();
    Serial.println("Access denied");
    lcd.print("Access denied");
    analogWrite(B, 0);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(100);
  }
 lcd.clear();
 Serial.println("Ready");
 lcd.print("Ready");
}

OK i fixed it. It is now this :

#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#include <LiquidCrystal.h>

Servo myservo;  //creates servo to control

const int rs = 44, en = 45, d4 = 46, d5 = 47, d6 = 49, d7 = 48;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int R=3;
int G=8;
int B=6;

void setup()
{
  lcd.begin(16, 2);
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Place your card near reader");
  lcd.print("Place your card");
  lcd.setCursor(0, 1);
  lcd.print("Near reader");
  lcd.setCursor(0, 0);
  myservo.attach(7);//attatches servo to pin 7
  myservo.write(179);
}
void loop()
{
  analogWrite(B, 255);
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  lcd.clear();
  Serial.print("UID tag :");
  lcd.print("ID:");
  byte letter;
  String content= "";
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     lcd.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     lcd.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "4F 60 3C D9") //change here the UID of the card/cards that you want to give access
  {
    delay(5000);
    lcd.clear();
    Serial.println("Scanning Database");
    lcd.print("Scanning");
    lcd.setCursor(0, 1);
    lcd.print("Database");
    lcd.setCursor(0, 0);
    delay(5000);
    lcd.clear();
    Serial.println("Authorized access");
     lcd.print("Authorized");
    analogWrite(B, 0);
    tone(4, 900, 100);
    lcd.clear();
    Serial.println("Unlocking...");
    lcd.print("Unlocking...");
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    delay(1000);
    myservo.write(100);
    delay(15);
    Serial.println("Unlocked");
    lcd.print("Unlocked");
    delay(5000);
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 255);
    Serial.println("Relocking...");
    lcd.print("Relocking...");
    delay(1000);
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    myservo.write(179);
    delay(15);
    Serial.println("Locked");
    lcd.print("Locked");
    delay(100);
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 0);
  }else{
    delay(1000);
    lcd.clear();
    Serial.println("Scanning Database");
    lcd.print("Scanning Databas");
    delay(5000);
    lcd.clear();
    Serial.println("Access denied");
    lcd.print("Access denied");
    analogWrite(B, 0);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(100);
  }
 lcd.clear();
 Serial.println("Ready");
 lcd.print("Ready");
}

had to remove the lcd.setCursor(0, 1);
from line 57.


Homodyne detection for arduino In your code https://gist.github.com/edgar-bonet/0b03735d70366bc05fc6 for homodyne detection, is there a way to make the frequency detected a range of frequencies? For example detecting between 3kHz and 4kHz?
Thanks in advance!

It may be possible to modify that program in order to get such a large
frequency range:

change the local oscillator frequency to 3.5 kHz
drastically shorten the filter's time constant in order to get a
wider passband

However, the homodyne detection scheme is best suited for building very
narrow band filters. In your case, the upper limit you want is quite
close to the Nyquist frequency (4,808 Hz), so I suggest you use a
high-pass, rather than a band-pass filter. The simplest high-pass you
can get is a numerical derivative:

y[n] = x[n] − x[n−1]

The gain of this filter is 2×sin(π×f/fsamp), so you get the
−3 dB cutoff at fsamp/4 ≈ 2,404 Hz. If you need
something better, you may want to try a higher order filter. But then
you get deep into the territory of digital filter design, which can be
tricky, especially if you have no experience with the z-transform or you
want to implement the filter in fixed point.

Edit: If you really want a bandpass, the simplest I can think of is
this two-pole filter:

y[n] = 0.360 x[n] − 0.885 y[n−1] − 0.552 y[n−2]

It will give you a maximum gain of roughly 1 at about
3.43 kHz, and −3 dB cutoffs at 3 and 4 kHz. A
straightforward floating point implementation would be:

float filter(float x)
{
    static float y1, y2;
    float y = 0.360 * x - 0.885 * y1 - 0.552 * y2;
    y2 = y1;
    y1 = y;
    return y;
}

You should convert this to fixed point if you want to use it, otherwise
I doubt your Arduino will have the processing power to run every sample
through it. Below is a plot of this filter's gain, compared with the
simple derivative, which I divided by 2 in order to normalize its
gain:

Note that the gain gets flat as you approach the Nyquist frequency, and
stays relatively high (above −5.4 dB).


expected primary-expression before ',' token ...problem this the problem---expected primary-expression before ',' token

#define motor

void setup() {
 pinMode(8,OUTPUT);
}

void loop()
{
  digitalWrite(motor,HIGH);
  // put your main code here, to run repeatedly:

}

Assuming that your motor is connected to pin 8, and you want to set that signal high, you have to define it:

#define motor 8

void setup() {
   pinMode(8, OUTPUT);
}

void loop()
{
  digitalWrite(motor, HIGH);
  // put your main code here, to run repeatedly:
}

Since you use it also in setup, also replace it there:

#define motor 8

void setup() {
   pinMode(motor, OUTPUT);
}

void loop()
{
  digitalWrite(motor, HIGH);
  // put your main code here, to run repeatedly:
}

Beyond that, MOTOR_PIN is a better name, since it is a pin you refer to, not the motor itself. Also it is a convention that defines are written with capitals, so you get:

#define MOTOR_PIN 8

void setup() {
   pinMode(MOTOR_PIN, OUTPUT);
}

void loop()
{
  digitalWrite(MOTOR_PIN, HIGH);
  // put your main code here, to run repeatedly:
}


How can I create a power rail on my Arduino shield? I have an Arduino that has 4 devices within an enclosure.  Each of the 4 devices needs 5 V and GND.  I have a shield with lots of unused pins (see photo).  I'd like to "bridge" one row of the pins to create a power rail, and I'd like to bridge another row to create a ground rail.

I think most people are using an external breadboard for this.  Also, I see that there is a shield that has power rails, but I don't have room for it.  I'm looking for a female header, or another way to bridge these unused pins.

Note: I'm not asking about wiring voltage in parallel or amperage consumption.

Just bridge them.  Wire in your +5V connections then join them together on the back with lots of solder.  Maybe with a strand of 0.6mm single core wire along it for extra ruggedness.


Format Integer in Arduino How to format an integer as 3 digit string? If I give 3 formated string should be 003

printf("%03d\n", 3); // output: 003

This doesn't work in Arduino.

The standard C function printf print to stdout. Arduino doesn't has a stdout. You can print to Serial, but must prepare/format the string first.

Instead of printf, use snprintf. It prints to a char array, which you later can use with Serial.print, or whatever other function that take a string.

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

  char buffer[4];
  snprintf(buffer,sizeof(buffer), "%03d", 3);
  Serial.println(buffer);
}

void loop() {

}

Note: all the comments apply to this answers.


Sending JSON message to web api via post. Why does HTTP 1.0 versus 1.1 make a difference? I am sending a message to a web api call every xx seconds. I could not get it to work at all until I changed the header from HTTP 1.1 which is what I was using to HTTP 1.0. Then, it started working. Why would this affect things where I could not post and now I can?

This is what it was when it wasn't working:

client.println("POST /BoxLevel/api/BoxMeasurement HTTP/1.1");

And the change that fixed it:

client.println("POST /BoxLevel/api/BoxMeasurement HTTP/1.0");

Thanks!

HTTP/1.1 requires you to provide the host name of the server. And it will keep the connection open for some time unless you explicitly opt out of this. Thus, the equivalent of the basic HTTP/1.0 request in HTTP/1.1 language is

POST /the_uri HTTP/1.1
Host: foo.example.com
Connection: close


Hall Effect Sensor for POV Project I'm making a POV project and need to count the RPM of the DC Motor.

I purchased a Hall Effect Sensor and it seems to work perfectly at slow speeds, however once the motor speeds up, the sensor doesn't pick up the magnet at all.

The datasheet for the sensor is at:
http://cdn.shopify.com/s/files/1/0045/8932/files/AH180.pdf?100744

This is one of my first projects and I'm not sure what I should be looking for on the datasheet.

The sensor came as part of this product:
http://www.freetronics.com.au/pages/hall-effect-magnetic-and-proximity-sensor-module-quickstart-guide#.VZ0Zs_meDGc

There doesn't seem to be a problem with the code:

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

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

void loop()
{
  digitalWrite(pin, state);
  Serial.println(tcnt);

}

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

Thanks!

From the datasheet of the hall effect sensor, the thing is only checking for 125usec in every 125msec - so if your magnet whizzes by in <100msec it will miss it.

Obviously you haven't stated the speed your magnet passes your sensor, but as it's only active 0.1% of the time, this seems the likely reason to miss.

Can you put it nearer the shaft/axle ?


Controling L298n with interrupts I'm working on my first arduino project, Sumo Robot, therefore i dont know much about programming yet.  We are supposed to use two IR sensors one on the front of the robot other on its back to avoid crossing the black line of the arena.
I wrote this simple code to control the motors.
But i have been  asked to use interrupts to raise the efficiency of my code.

So do you guys have an idea of how i can use interrupts with the L298n motor driver to move my dc motors forward and backward.

Here is my code

int fIR=7;
int bIR=8;
int fIR_value;
int bIR_value;
const int trigPin = 9;
const int echoPin = 11;

long duration;
int distance;

int IN1 = 4;
int IN2 = 5;
int IN3 = 6;
int IN4 = 12;

void setup() {
  Serial.begin(9600);
  pinMode(fIR,INPUT);
  pinMode(fIR,INPUT);
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
  pinMode(IN1,OUTPUT);
  pinMode(IN2,OUTPUT);
  pinMode(IN3,OUTPUT);
  pinMode(IN4,OUTPUT);

}

void loop() {

  fIR_value = digitalRead(fIR);
  Serial.print("Front IR:");
  Serial.print(fIR_value);
  Serial.print(" , ");

  bIR_value = digitalRead(bIR);
  Serial.print("Back IR:");
  Serial.print(bIR_value);
  Serial.print(" , ");

  digitalWrite(trigPin, LOW);
  delayMicroseconds(10);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration*0.034/2;
  Serial.print("Distance: ");
  Serial.println(distance);
  delay (500);

  if(distance<30&&fIR_value==HIGH&&bIR_value==LOW){
    STOP();
    delay(50);
    BACKWARD();
//    Serial.print("1");
  }
  else if(distance<30&&fIR_value==LOW&&bIR_value==HIGH){
    STOP();
    delay(50);
    FORWARD();
//    Serial.print("2");

  }
  else if(distance<30&&fIR_value==LOW&&bIR_value==LOW){
    STOP();
    delay(50);
    FORWARD();
//    Serial.print("3");

  }
    else if(distance>30&&fIR_value==LOW&&bIR_value==LOW){
    STOP();
    delay(50);
    ROTATE();
//    Serial.print("4");

  }
   else if(distance>30&&fIR_value==HIGH&&bIR_value==LOW){
    STOP();
    delay(50);
    BACKWARD();
//    Serial.print("5");

  }
   else if(distance>30&&fIR_value==LOW&&bIR_value==HIGH){
    STOP();
    delay(50);
    FORWARD();
//    Serial.print("6");

  }
}

void FORWARD(){

  digitalWrite(IN1,200);
  digitalWrite(IN2,0);
  digitalWrite(IN3,0);
  digitalWrite(IN4,200);
}
void BACKWARD(){

  digitalWrite(IN1,0);
  digitalWrite(IN2,200);
  digitalWrite(IN3,200);
  digitalWrite(IN4,0);
}
void ROTATE(){

  digitalWrite(IN1,200);
  digitalWrite(IN2,0);
  digitalWrite(IN3,200);
  digitalWrite(IN4,0);
}
void STOP(){

  digitalWrite(IN1,0);
  digitalWrite(IN2,0);
  digitalWrite(IN3,0);
  digitalWrite(IN4,0);
}

As jsotola already suggested in the comments, using interrupts for driving the motors does not make sense. With a L298N you simply set the outputs and then leave them alone until you think they should stop.

Instead you could use interrupts for your sensors.

Though I would argue, that using interrupts would not be really necessary, when you implement your code the right way, means non-blocking. You use a lot of delay() calls. where the Arduino does not do anything, just twiddling thumbs. Instead you could use the principle from the BlinkWithoutDelay example, that comes with the Arduino IDE, to write the code non-blocking. In that case every bit of code would only do something, if it needs to, and otherwise return fast. That would make your code run way faster. You would also need to set a lower timeout for the pulseIn() function, as it's standard timeout is 1s (ultrasonic sensors like you are using one normally can only sense up to 3m, would would correspond to 20ms max pulse duration, if I'm doing the math correctly).

If using interrupts is a mandatory part of your excercise, you can decide, where to use interrupts:

The simplest way would be for the IR sensors. You could use the attachInterrupt() function to set up an Interrupt Service Routine (ISR) for the corresponding pin. If you want the interrupt to trigger, when the IR sensors go HIGH, you can use RISING, otherwise you can use FALLING. Keep in mind, that ISRs should be as small and fast as possible. You cannot use delay() there. Normally one would only set simple (1 byte) variables in the ISR, and then react with longer actions in the main code by checking these variables. You have you set every variable, that can be changed in an ISR, as volatile:

volatile byte flag;

For the ultrasonic sensor, you have more than one way to go. I will outline 2 ways. For both of them you need to either directly manipulate the Special Function Registers of the microcontroller, or find a library, that does that for you (don't know, if such libraries exist, but you can search for them):

You could use the Pin Change Interrupt. It triggers everytime, when a pin from a full pin port (group of up to 8 pins) changes it's state. You can mask away unused pins, so that they will not influence the interrupt. In the ISR you can check the state of the pin. If it is high, the start of the pulse just happened. Save a timestamp of that moment with the micros() function. The next ISR (where the pin will be LOW) will mark the end of the pulse. Now you can calculate the time difference between the timestamp and the current micros() value. You should use a 1-byte variable as flag, to trigger the processing the the pulse duration in the main function (or, if you want to directly use the time difference variable, you need to turn of the interrupt, while you are using the variable).
If you want to show off, you could use a hardware Timer in Input Capture mode (this is the more complex, then the other possibilities). The timer is a counter, that is connected to the system clock (through a prescaler, where you can change the count frequency in a coarse way). The timer starts and when the Input Capture pin ICP1 (in case of Timer1) changes it's state, the current value of the timer will be saved in an extra register and an interrupt is fired. This timer value is like a timestamp. If you record the timestamps for the rising and the falling edge of the pulse, you can take the difference and calculate the time difference/distance from this. This part works similar to the first way above. The notes about interrupts also apply here.