SMS Receiving problem - Arduino Uno and SIM900A GSM Module My intention is to control an LED according to the content of the SMS received. For example, if the SMS is "ON", turn on the LED and if it is "OFF", turn it off. I referred many sites and got the below code.
The digital pins 9 and 10 are used instead of Rx and Tx to avoid the code uploading problem.

(I have kept the different versions of AT commands commented in the code because I'm not sure which one is correct. With the current one, I'm able to get some kind of output which I've mentioned after the code.)

#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 10);

char msg;
void setup()
{
  Serial.begin(9600);
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  delay(1000);
  //mySerial.print("AT+CMGF=1r"); // set SMS mode to text
  mySerial.print("AT+CMGF=1\r");  // set SMS mode to text

  delay(100);
  //mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
  //mySerial.print("AT+CNMI=2,2,0,0,0r");

  mySerial.print("AT+CNMI=1,2,0,0,0\r"); // AT Command to receive a live SMS
  delay(100);
  Serial.println("Ready");
}

void loop()
{
  if (mySerial.available()>0)
  {
    msg=mySerial.read();
    Serial.print(msg);
  }
}

This is the output I'm getting..

Ready
AT+CMGF=1
AT+CNMI=1,2,0,0,0

OK

+CMTI: "SM",31

+CMTI: "SM",32

+CMTI: "SM",33

+CMTI: "SM",34

The issue is, I'm not able to retrieve the message content. What I'm getting is

"+CMTI: "SM",31"

"+CMTI: "SM",32"

and the number keeps on incrementing. (33, 34 and so on).

I do understand that I have to parse the message to get the exact content, but here I'm not getting the content at all. What exactly should I do to get the SMS content? Could anybody help me to solve this?

One more thing, the GSM module I'm using is a SIM900A type (from elementzonline.com). It's not a shield type, so I've made connections using wires; the Rx, Tx connections and the ground one.

(Sorry for the bad explanation, I'm a complete noob in Arduino, a hobbyist.)

Thanks in advance.

Instead of using At commands use the GSM library of Arduino it easier to understand and implement.
the code to recieve SMS

    #include <GSM.h>

    // PIN Number for the SIM
    #define PINNUMBER "" //sim pin incase the sim is kept locked

    // initialize the library instances
    GSM gsmAccess;
    GSM_SMS sms;

    // Array to hold the number a SMS is retreived from
    char senderNumber[20];

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

      Serial.println("SMS Messages Receiver");

      // connection state
      boolean notConnected = true;

      // Start GSM connection
      while (notConnected) {
        if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
          notConnected = false;
        } else {
          Serial.println("Not connected");
          delay(1000);
        }
      }

      Serial.println("GSM initialized");
      Serial.println("Waiting for messages");
    }

    void loop() {
      char c;

      // If there are any SMSs available()
      if (sms.available()) {
        Serial.println("Message received from:");

        // Get remote number
        sms.remoteNumber(senderNumber, 20);
        Serial.println(senderNumber);

        // An example of message disposal
        // Any messages starting with # should be discarded
        if (sms.peek() == '#') {
          Serial.println("Discarded SMS");
          sms.flush();
        }

        // Read message bytes and print them
        while (c = sms.read()) {
          Serial.print(c);
        }

        Serial.println("\nEND OF MESSAGE");

        // Delete message from modem memory
        sms.flush();
        Serial.println("MESSAGE DELETED");
      }

      delay(1000);

    }


How to detect the absence of an RFID tag? I have installed an MFRC522 RFID reader in my house. The main use so far is to tell the house I've arrived using an RFID keychain, by leaving it in the key holder.

I would also like for the house to detect when I'm gone, and I was thinking that, if I can detect when a tag is present, I should also be able to detect when it is not.
However, this poses some challenges like the following:

Should I be constantly reading the tag until it disappears from range? (when I take it from the key holder).
What if I have more than one RFID Keychain/Tag in the range of the reader? (because there could be other keychains in the same key holder). Would I get multiple readings or could one tag interfere with another in some way?

I realize that maybe this is not the typical RFID scenario when the tag is scanned and then moved away from the reader. I've been searching about "RFID tag absence detection" but I've only found what seemed to me like very theoretical papers.

Do you have any advice or experience in implementing something like this?

Thanks!

I don't think it is particularly practical, unless you make your own RFID scanner. The off-the-shelf ones generally only respond once when a particular card is in range, so you can't even detect if the card is left next the reader, or not.

Also, as the range is usually quite limited (a few cm) I don't see how it could tell the difference between you being out of the house, or taking a bath.

What might work better would be to have an active transmitter (eg. a nrf24l01) in your pocket, which every minute or so sent a "I'm home!" message to a central place. The absence of such a message after 10 minutes could indicate you are out.

The other approach would be to "check out" with your RFID scanner. I did an RFID event management system a little while back. You use a special "admin" card to indicate that a person was leaving an event for a while (a pass-out). You could do that, or have a button by the door, which you press. The "I am leaving" button.


Can't flash ESP 32 Wroom I have a new ESP32 Wroom attached to my USB and it shows up in the settings on my mac:

I do have another ESP thing from sparkfun which I can access via  /dev/cu.usbserial-DN02N1D8. This device I can flash without problems or read its mac address using esptool.py.

Connecting........_____....._____....._____....._____....._____....._____....._____

So I wonder how I can flash the ESP32.

Update: Added a picture of my board.

I did fix the problem now.

My mac has USB-C and I was using a single USB-C to USB Dongle. And the serial port never showed up on my mac:

crw-rw-rw-  1 root  wheel   18,   5 Mar  8 10:53 /dev/cu.Bluetooth-Incoming-Port
crw-rw-rw-  1 root  wheel   18,   7 Mar  8 10:53 /dev/cu.Heinz-WirelessiAP
crw-rw-rw-  1 root  wheel   18,   3 Mar  8 10:53 /dev/cu.MALS
crw-rw-rw-  1 root  wheel   18,   1 Mar  8 11:02 /dev/cu.SOC

As soon as I used the Satechi USB Dock the Silicon Labs USB to UART port showed up in the list:

[...]
crw-rw-rw-  1 root  wheel   18,  13 Mar  8 11:04 /dev/cu.SLAB_USBtoUART

I can now communicate with the ESP32:

esptool.py --port /dev/cu.SLAB_USBtoUART read_mac

esptool.py v2.6
Serial port /dev/cu.SLAB_USBtoUART
Connecting........___
Detecting chip type... ESP32
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
MAC: XXXXXXXXX
Uploading stub...
Running stub...
Stub running...
MAC: XXXXXXX
Hard resetting via RTS pin...

Please note that if you'll need the Drivers for the USB to Serial Chip from Silabs.

If you do not see the device showing up you'll need to load the kernel extension:

sudo kextload /Library/Extensions/SiLabsUSBDriver.kext/

After this you might to confirm the extension in the Privacy section of the mac settings. See this forum post for reference.


Building mocoLUFA under OSX & Linux I am attempting to build mocoLUFA under OS X el Capitan 10.11.6.

[Editor: mocoLUFA (MIDI firmware for Arduino Uno)]

I am using the specified LUFA version (LUFA101122) and I have tried building with both brew avr-gcc and also Crosspack-AVR.

The problem I am facing isn't with the build or the install. It's just that as soon as I install the hex file, I get no midi messages at all.

What does work - the OSX machine recognises the MIDI device and the MIDI device appears in DAW's, however MIDI Monitor registers no messages at all.

I have tried downloading a custom-built mocoLUFA and I am able to install this and it works fine. I see midi messages coming across from my sketch.

Crosspack-AVR installs avr-gcc 4.8.1.

My question is - what is the correct build environment in order to achieve a working mocoLUFA under OSX? I have tried both mocoLUFA and dualMoco and I get the same result with each.

My purpose for this is to modify mocoLUFA so that it can support sending MTC over USB. At present, it appears that mocoLUFA does not support System Common messages.

UPDATE: Built fresh Ubuntu VM. Installed avr-gcc, avr-libc, LUFA-100807 and mocoulfa. Same result. hex builds fine, no response from the atmega16u2. TX light flashing, sketch on the 2560 running, but no midi messages down the usb cable.

This is Franco, from Yaeltex, the guys who put up that site for custom MocoLUFA compiling.

Our site works on an Ubuntu server, and the build environment can be seen at the bottom of the site, which is as follows:

Ubuntu Server Setup

avr-gcc: avr-gcc (GCC) 4.9.2
avrdude: Version 6.3, compiled on Mar 15 2016 at 21:26:45
LUFA: 100807
dualMocoLUFA: custom Yaeltex based on 2013/09/22

On the other hand, I use Windows 10 to build locally in my computer, and I have a similar setup with sligthly older versions of avr-gcc and avrdude:

Windows 10 Server Setup

avr-gcc: avr-gcc (GCC) 4.3.3
avrdude: Version 5.10, compiled on Mar 15 2016 at 21:26:45
LUFA: 100807
dualMocoLUFA: custom Yaeltex based on 2013/09/22

Here is a link to the fork we made to mocoLUFA, it has minor changes, that were very useful to us and our hardware.

Regarding your problem, I am really lost on the cause of it, but we can start with some questions to get closer to a solution.

What kind of MIDI messages are you trying to send/receive?
Can you share the code you are using?
Are you using Arduino MIDI Library (Last version is v4.3.1)?
If not, are you sure you are using 31.250 bps as baud rate?
Do you have something else connected to TX or RX lines in your circuit?

Let's start with these. Cheers!


Arduino Yun Analog Read Problem I am having some major issues with my Arduino Yun.

When attempting to read a value from the analog pins, the Yun is giving me incorrect constant values.

I have attached everything to a common ground, and I am supplying 3.3 volts to the A0 pin on the Yun.

The weird thing is, the pins all give constant values in ascending order, no matter what is connected to them, or if nothing is connected at all.

A0 - 18
A1 - 19
A2 - 20
A3 - 21
A4 - 22
A5 - 23

The code I am running is a very simple script.

float i;

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

void loop() {
  i = A0;
  Serial.println(i);
  delay(1000);
}

You are not reading from any analog pins. You are just printing out the digital pin number of the analog pin.

Look at some basic examples on how to read analog values.

/*
  AnalogReadSerial
  Reads an analog input on pin 0, prints the result to the serial monitor.
  Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  This example code is in the public domain.
*/

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}


how to send large strings (> 100 characters) from arduino serial monitor I am a newbie to arduino programming. I wish to send big strings which are in range of 100 to 1000 characters to my arduino uno. I saw that arduino cannot read more than 63 characters at a time.

The strings can be received in parts (~40 characters) which will be processed by my program and few minutes later they will get deleted. Then another ~40 characters will be received and the process continues till all the characters are received.

Can you please help me with this. If the question is not clear, you're free to ask in the comments. Thanks in advance :-)

I saw that arduino cannot read more than 63 characters at a time.

Not strictly true. The Arduino core HardwareSerial library has a 64 byte buffer, so it can only buffer up to 64 characters. If your sketch is reading the characters from the buffer whilst you are sending the characters from your PC then that limit is irrelevant. As long as you are reading the characters as fast as they are coming in.

Serial is actually quite slow (on the scale of things) and unless you're doing silly things like using delay() or long blocking loops, then reading the data fast enough is not that big a problem.  If you do need more time the simplest way is just to slow down the serial data somewhat - i.e., use a lower baud rate. The slower you send the data the longer you get between each character arrives to do things.

For strings the size you are on about you are probably best off processing the data on the fly rather than storing it all then post-processing it - simply because the Arduino doesn't have much RAM, so storing large strings isn't always an option.


DS3231 rtc.begin() always returning false I am using Arduino UNO with a RTC DS3231 module.
I have connected SDA & SCL pins of RTC DS3231 with Arduino SDA & SCL pins near AREF pin.
RTC module is having attached battery also.
My code is as below :
#include <RTClib.h>
#include <Wire.h>
RTC_DS3231 rtc;

char daysOfTheWeek[7][12] = {
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
};

void setup() {
  Serial.begin(9600);
  Wire.begin();
  delay(3000);
  //rtc.begin();
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
       // Following line sets the RTC with an explicit date & time
    // for example to set January 27 2017 at 12:56 you would call:
    // rtc.adjust(DateTime(2017, 1, 27, 12, 56, 0));
  }
}

void loop() {
  DateTime now = rtc.now();
  Serial.println("Current Date & Time: ");
    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.println("Unix Time: ");
    Serial.print("elapsed ");
    Serial.print(now.unixtime());
    Serial.print(" seconds/");
    Serial.print(now.unixtime() / 86400L);
    Serial.println(" days since 1/1/1970");

    // calculate a date which is 7 days & 30 seconds into the future
    DateTime future (now + TimeSpan(7,0,0,30));

    Serial.println("Future Date & Time (Now + 7days & 30s): ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();

    Serial.println();
    delay(1000);

}

While running the above command and opening the Serial Monitor, I always get following output:
Couldn't find RTC

Can anyone help me to correct this problem.

No fault is there in code. Rather, it was an faulty connection which prevented RTC module from working. Now, after restoration, the RTC module is working fine.


Can't get software serial to work So I have two Arduinos (Arduino Nano) and I'm trying to get them to communicate via SoftwareSerial.  I have the 'sending' Arduino's D10 pin connected to the 'recieving' Arduino's D11 pin, and vice versa.  On my sending Arduino, I have the following code:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);

void setup() {
  pinMode(2, OUTPUT);
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.isListening()){
    digitalWrite(2, HIGH);
  }
  mySerial.write(5);
}

and on my receiving Arduino, I have:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(11, 10);

void setup() {
  pinMode(2, OUTPUT);

  Serial.begin(9600);

  mySerial.begin(9600);
}

void loop() {
  mySerial.listen();
  if (mySerial.available()>0) {
    digitalWrite(2, HIGH);
    char inByte = mySerial.read();
    Serial.write(inByte);
  }
  digitalWrite(2, LOW);
}

(with D2 being hooked up to an LED for both).

I can't get it to read anything.  Nothing seems to be available for the receiving Arduino (the LED is off).  What am I doing wrong?

Sender:

SoftwareSerial mySerial(10, 11);  // Rx, Tx

Receiver:

SoftwareSerial mySerial(11, 10);  // Rx, Tx

  I have the 'sending' Arduino's D10 pin connected to the 'receiving' Arduino's D11 pin, and vice versa.

So you have the sending Arduino's Rx connected to the receiving Arduino's Rx. Therefore it won't work. You need to connect Rx to Tx.

  mySerial.listen();

You don't need that in this simple example.


Arduino Uno Wire Transmission Issues I am developing code to run a word clock and have noticed a slight problem. I am using a DS3231 to keep time, and using the Wire library to communicate with it. I ping the DS3231 every second to get the time and check a few other things. This is all working fine except when the clock loses power. It seems that occasionally upon loss of power to the Arduino, the time that that the DS3231 reports when it regains power, is incorrect.

My thought is that the power is getting cut in the middle of various Wire.read() commands and this is causing the chip to mess up and reset its own time, but I am not sure. The DS3231 has a battery backup attached to it, and that battery has only been plugged in for a month or two, so I don't imagine that is the problem.

I am wondering if anyone has an idea how I can deal with this potential problem, or if there is some way I can clear the Wire library before it starts up again.

I have put some sample code below to give an idea of what I am doing. There is of course much more code, but this is the only relevant part.

#include "Wire.h"
#define kClockAddress 0x68

void readDS3231time(byte * second, byte * minute, byte * hour, byte * dayOfWeek, byte * dayOfMonth, byte * month, byte * year) {
  Wire.beginTransmission(kClockAddress);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(kClockAddress, 7); // request seven bytes of data from DS3231 starting from register 00h
  *second = bcdToDec(Wire.read() & 0x7f);
  *minute = bcdToDec(Wire.read());
  *hour = bcdToDec(Wire.read() & 0x3f);
  *dayOfWeek = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month = bcdToDec(Wire.read());
  *year = bcdToDec(Wire.read());
}

void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte dayOfMonth, byte month, byte year) { // sets time and date data to DS3231
  Wire.beginTransmission(kClockAddress);
  Wire.write(0); // set next input to start at the seconds register
  Wire.write(decToBcd(second)); // set seconds
  Wire.write(decToBcd(minute)); // set minutes
  Wire.write(decToBcd(hour)); // set hours
  Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
  Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
  Wire.write(decToBcd(month)); // set month
  Wire.write(decToBcd(year)); // set year (0 to 99)
  Wire.endTransmission();
}

void setup() {
  // put your setup code here, to run once:
  Wire.begin()
   // DS3231 seconds, minutes, hours, day, date, month, year
   //setDS3231time(0, 36, 10, 2, 21, 12, 15);
}

void loop() {
  // put your main code here, to run repeatedly:
  byte second, minute, hour, dayOfWeek, dayOfMonth, month, year; // retrieve data from DS3231
  readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
  delay(1000);
}

Wire.requestFrom(kClockAddress, 7); // request seven bytes of data

Just because you request 7 bytes doesn't necessarily mean you get them. I suggest before reading the date and time you set all those variables to something invalid (like 0xFF). Then after reading, if you get 0xFF in any of them, ignore the entire lot.

  we are sending a start bit again, when we never sent a stop bit previosuly. ... Does this sound reasonable

Not really, because I2C doesn't have start and stop bits, it has start condition and stop condition which are specific changes to SDA and SCL which don't happen at any other times. See I2C for a description. I would be checking the data for validity, as I said. There is no other way of knowing for sure that a transmission wasn't interrupted. If you request 7 bytes of data, the library tells you that you got 7, even if you did not. However if it cannot even find the target device, it returns 0 as the number of bytes (you aren't testing for that anyway).

The very least you should do is test for a valid connection, eg.

if (Wire.requestFrom(kClockAddress, 7) == 7)
  {
  // read the data
  }

That at least confirms that the clock chip responded in some way. Not checking error returns from function calls, where documented, is not wise.

Similarly when you send your command.

  Wire.endTransmission();

That should be:

if (Wire.endTransmission() != 0)
  {
  // handle error here
  return;
  }

You have no tests in your code for either the sending or receiving to be working. And then you are unconditionally using the resulting time values. That's like opening a file, and reading it, without checking if the file exists.


Sending information via USB/Serialport Am I able to send instruction from my computer, from another compiler, via the Arduino USB port?

To put this in context, I'm doing some vision processing on my computer, with Visual Studio, and I want to send some motor output via USB for the Arduino to execute.

I imagine Code Gorilla's given you the proper, specific answer you needed. I simply wanted to address your first (more general) ask,

  Am I able to send instruction from my computer, from another compiler, via the Arduino USB port?

... and mention some other ways I've done this before. As long the Arduino's listening to the serial port for some specific (or any) input coming in, you can use whatever you'd like to send a message to the COM port your Arduino's using.

You absolutely are not hemmed into using solely the Arduino IDE (or it's serial monitor) for serial communication.

For instance, I wrote a Python script that communicated with an Arduino R3 (Rx/Tx) via the COM port it was assigned via the PySerial library - before coming to Python, I'd been doing this through a MS Visual C# WPF that was connected to the COM port and communicating with the Arduino (Rx/Tx) (you might need to adjust baud rates here or there, if I recall). Just to give you some ideas.


How do I burn the bootloader? I was instructed to "burn the bootloader" to my Arduino to fix an error I was getting. How can I do this? (And what exactly is the bootloader?)

The bootloader is a small program that is (almost) always on an Arduino. It manages uploading and starting the sketches you make, and blinks the pin 13 LED whenever the board resets.

To burn the bootloader:

Obtain an AVR ISP, USBtinyISP, ParallelProgrammer, or similar; or use another Arduino board. This will be your ISP.
Unless otherwise instructed, connect the ISP to the ICSP pins on your board.
Power your board with either a USB cable or an external power supply.
Open up the Arduino IDE.
Make sure you selected the correct board that you are burning to at Tools ► Board ► in the IDE. Double-check this even if you could upload programs correctly; uploading doesn't always require the right board.
Select the appropriate programmer at Tools ► Programmer ►.
Click Tools ► Burn Bootloader, and wait. It shouldn't take more than a minute, and often takes only a few seconds.

Sources:

http://arduino.cc/en/Hacking/Bootloader
http://arduino.cc/en/Guide/Environment


Menu system without libraries I was wondering if there are a way to do a menu system for arduino UNO using buttons and without libraries.

I tried to do it by myself but the code was too long and heavy.

I don't want full code, just a pseudo-code idea and how does it works.

I know there are libraries that to this, but I want to practise C++.

Thanks!

Interactive menus are certainly not a "simple" task. That is why people use libraries.

Whatever you try you will end up with complex code - either long winded with lots of duplication, or somewhat cryptic with lots of pointers, arrays, and structures. Not an easy task for a beginner in C++.

How I would set about it would involve the following things:

A structure that defines a menu entry, including pointers to one of: sub-menu array, numeric variable (including max/min limits), option array, function to execute.
Arrays of the above structure to define each menu
Array or linked list of "breadcrumbs" through the menu to track where you are and go back up properly
Functions to display and navigate the menu arrays on an LCD.

All of that uses fairly advanced C coding techniques, especially when it comes to managing all the pointers, etc.

The "simpler", though more long winded way, would be to write individual functions for each menu and sub-menu, but that would make your program incredibly long and prone to have errors when duplicating (copy/paste) code.


NeoICSerial and SPI on the Uno - pin 10 The NeoICSerial documentation contains a table that states for the Uno:

Transmit: 9
Receive: 8
PWM Unusable: 10

Pin 8 and 9 are used for the serial connection. Pin 10 is part of the pins for the SPI on the Uno. Does this mean SPI connections can't be used together with NeoICSerial or is this specific for using pin 10 for PWM?

The "Unusable 10" is explained in AltSoftSerial library

  The "Unusable PWM" pins can be used normally, with digitalRead() or
  digitalWrite(), but their PWM function controlled by analogWrite()
  will not work properly, because AltSoftSerial uses the timer which
  controls that pin's PWM feature.

Pin 10 on Uno is SPI slave select if the Uno is SPI slave (then it is an INPUT).

If the Uno is SPI master, this pin must be set as OUTPUT. For this reason it is usual to use pin 10 as slave select for the (first) SPI slave. SPI shields have this pin hardwired as slave select for the (first) SPI device on the shield.


Arduino Mega 2560 as ISP for ATTINY2313 / ATMEGA328P I have posted this on the Arduino forum also, but I give it more chance if posted here also.

I've been trying to use my Arduino Mega as an ISP for programming two different ATMEGA328P's and a ATINY2313, but I just don't succeed.

I am running the Arduino IDE (version 1.5.8 ) on windows 7. I've been using these http://www.instructables.com/id/How-to-use-Arduino-Mega-2560-as-Arduino-isp/ http://www.instructables.com/id/Arduino-ATtiny2313-Programming-Shield/ instructables for help. The circuit are built on a breadboard. On my Arduino Mega is use the pins reset: 53, MOSI: 51, MISO: 50, SCK: 52.

First I upload the arduino as ISP sketch on my Mega. There are LEDs on the programming, error and heartbeat outputs, the heardbeat is pounding. I then select the according board from the boards list (the ATINY2313 1MHz from the instructable for the ATTINY and either the Arduino UNO or the Arduino Duelimanove for the ATMEGA328P) and after that the programmer árduino as ISP'. When uploading the Blink sketch I get errors like:

avrdude: Yikes! Invalid device signature
avrdude: stk500_getsync(): not in sync: resp=0x00
avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x51
I have tried things like capacitors/resistors between the reset and the ground or between the reset and the +5V, but nothing different. I have searched for help on the internet and alot of people have problems with it, but no clear or working answers. I have been looking at the MegaISP guide form Arduino, but this is not very clear to me.

I have no idea where to start anymore. Does anybody have an idea what I can try or where to start searching for answers?

I appriciate all the help I can get!

This worked for me dude :)

See this:

http://www.instructables.com/id/Bootloading-ATmega328-with-Arduino-Mega2560/?ALLSTEPS


How to use Arduino Nano with Arduino Uno I am using an Arduino Uno and have used up all it's pins so I have plugged up a Nano to a couple of the Uno's pins and using the Uno's 5v and ground to power the Nano. Is this ok?

It's been working fine until recently. My Uno will no longer allow me to upload code but everything still powers fine and runs on the existing code I had uploaded before. The reset button on the Uno does not work so I assume it's bricked, but it does still operate fine on the code it has, as I said.

Anyway, my question, is it ok to run the Nano like this? Is it using too much of the Uno's current... because the Nano's pins are also all being used. I'm no good at regulating current and just want to make sure that the Nano isn't eating up a bunch of current from the Uno by lighting it's LED's and it's other operations.

try to connect uno and nano with I2C or serial, with I2C it connected to SCA/SDL pin (analog 4/5) or with serial it connected to tx rx. Make sure you use a pull up resistor. From the main site of arduino there's a tutorial in there but forgot to set up a pull up resistor.


Arduino Uno R3 not working with Cytron shield GPS 53 My project is to find latitude and longitude of certain places. I am using an Arduino Uno R3 with a Cytron GPS 53 shield to get the position of places but, my device cannot run because COM4 already in use. How to fix this error?

Your GPS board supports sending the data to the USB socket on the Arduino, sending it to pins 0 and 1, or sending it to a Software Serial port.  The first two options are going to confuse the output you are getting from the Arduino, so you should probably use the Software Serial option (read the manual on how to do that).

The data that you receive on the Arduino from the software serial port will need forwarding to the USB serial port that your PC is connected to, you will have to right a program to do this, but its not a difficult program and I'm sure there are examples out there.

If you want to make this mobile, you will need a battery to power the kit and an LCD display to show your results (get one with an I2C 'backpack' it will be easier to program).

Hopefully that should give you a start.


How to call an interrupt when any one of the 12 defined digital inputs go high? I'm using an Arduino Mega 2560 board. I need to sense 12 digital pins (pins 36-47) coming from another board continuously and display power when they are low.

When any of the 12 pins go HIGH, an interrupt must be created. In the ISR part, I'll be making one new digital pin (PIN 35) go HIGH (this is initialized as low in setup function).

To reset from interrupt, I need to press the "#" key in the keypad. This should make PIN 35 go low again and program should function normally again.

This is my code without using Interrupt.

#include "LiquidCrystal.h"
#include <Keypad.h>

// initialize the library by providing the nuber of pins to it
LiquidCrystal lcd(8,9,4,5,6,7);
 const byte ROWS = 4; // four rows
const byte COLS = 3; // three columns
char keys[ROWS][COLS] = {
 {'1','2','3'},
 {'4','5','6'},
 {'7','8','9'},
 {'*','0','#'}
};
byte rowPins[ROWS] = {22, 24, 26, 28}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {30, 32, 34};     //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
float fwd_voltage = 0.0,rev_voltage = 0.0;
float fpower,rpower;
int sensorValue=0;

void setup() {
  int i;
  for (i=36;i<48;i++) {
    pinMode(i,INPUT);
  }
  pinMode (35, OUTPUT);
  digitalWrite(35,LOW);
}

void reset () {
  while(1) {
    lcd.begin(16,2);
    lcd.setCursor(0,0);
    lcd.print("press # to reset");
    char key = keypad.getKey();
    if (key=='#') {
      digitalWrite(35, LOW);
      break;
    }
  }
}

void process(int pin, char* text) {
  if (digitalRead(pin) == HIGH && digitalRead(35)==LOW) {
    // Use HIGH instead of 1
    lcd.print(text);
    digitalWrite(35, HIGH);
    reset ();
  } else {
    int analog_value = analogRead(A0);//reading forward voltage
    int analog_valuer = analogRead(A1);//reading reverse voltage
    fwd_voltage = (analog_value * 5.0) / 1024.0;
    rev_voltage = (analog_valuer * 5.0) / 1024.0;
    fpower =  ((fwd_voltage)*(fwd_voltage)*10000);
    rpower = ((rev_voltage)*(rev_voltage)*10000);
    lcd.setCursor(0,1);
    lcd.print("REV= ");
    lcd.print(rpower);
    lcd.print("W");
    delay(500);
    lcd.setCursor(0, 0);
    lcd.print("FWD= ");
    lcd.print(fpower);
    lcd.print("W");
    delay(500);
  }
}

void loop() {
  lcd.begin(16,2);
  // set cursor position to start of first line on the LCD
  lcd.setCursor(0,0);
  process(36, "vswr");
  process(37, "thermal");
  process(38, "overdrive");
  process(39, "A1-B1 fault");
  process(40, "A1-B2 fault");
  process(41, "A1-B3 fault");
  process(42, "A1-B4 fault");
  process(43, "A2-B1 fault");
  process(44, "A2-B2 fault");
  process(45, "A2-B3 fault");
  process(46, "A2-B4 fault");
  process(47, "driver fault");
}

How do I modify the program to add an interrupt so that my board works faster and efficiently? BTW I'm new to programming so there might be some mistakes in the program and also I didn't write the program small and efficient.

The interrupt service routine should consist of this part of the above program:

lcd.print(text);
digitalWrite(35, HIGH);
reset ();

My interrupt should detect this part of the program.

if (digitalRead(pin) == HIGH && digitalRead(35)==LOW)

You are kind of unlucky. The ATmega2560 MCU has 32 pins capable of
generating interrupts (counting the INTn and PCINTn, not sure all of
them are routed to board headers), but none of the pins you have chosen
is interrupt-capable.

I suggest you combine your 12 signals, using external logic, into a
single interrupt signal. You would then, in the ISR, sort out which
individual signal triggered the interrupt. A pair of 74HC4075 chips
should be enough to OR together the 12 inputs.


Bidirectional communication between Arduino and Raspberry Pi over USB possible? Is it possible to have bidirectional communication betweeen an Arduino Uno Rev 3 and a Raspberry Pi Modell B+ running Rasbian? They're connected ofer USB, and it would be good if I could use Python on the Pi.

Yes.  The Arduino Uno implements a serial protocol inside the USB signal using hardware.  This is how it is built.  The Linux side is a bit more complex as there are many USB protocols.  Here is a howto which talks about the Linux side of the Arduino / Linux connection.

To be clear, Rasbian is a derivative of Linux.


Arduino Uno with Adafruit CC3000 I am using Arduino Uno with Adafruit CC3000 wifi shield to connect to the internet and get data for Arduino. Everything works fine but I can't figure out how to use HttpClient library. The code is:

#include <Adafruit_CC3000.h>
#include <SPI.h>
#include "utility/debug.h"
#include "utility/socket.h"
#include <HttpClient.h>

#define ADAFRUIT_CC3000_IRQ   3
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,    ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIVIDER);

#define WLAN_SSID       "ssid"
#define WLAN_PASS       "pwd"
#define WLAN_SECURITY   WLAN_SEC_WPA2

void setConnection(){

     Serial.println("Initializing...");
     if (!cc3000.begin())
     {
       Serial.println("Couldn't begin()! Check your wiring?");
       while(1);
     }
     Serial.print("Attempting to connect to ");
     Serial.println(WLAN_SSID);
     if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
       Serial.println("Failed!");
       while(1);
     }
     Serial.println("Connected!");
     Serial.println(F("Request DHCP"));
     while (!cc3000.checkDHCP())
      {
          delay(100);
       }
     Serial.println(F("DHCP success!!"));
 }

void dweet(){

  int ctr=0;
  char buff[100];
  int x=0;
  const char* host = "https://dweet.io/get/latest/dweet/for/dunebot";

  Serial.println(F("Initializing dweet client ..."));
  HttpClient client;
  client.get(host);
  Serial.println(F("Client Connected !"));

  while (client.available()) {
    char c = client.read();
    Serial.write(c);
    delay(100);
  }

void setup(){

     Serial.begin(115200);
     while(!Serial);
     Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);
     setConnection();

}

void loop(){
dweet();
}

If all worked fine then I should have got a json string which is:

{"this":"succeeded","by":"getting","the":"dweets","with":[{"thing":"dunebot","created":"2018-05-12T13:27:56.106Z","content":{"0001":""}}]}

When I run the code, Arduino connects to the wifi network but afterwards when I observe the Serial monitor all I get are garbage values.

I need a way to read the key 0001 from the json string. Any help would be appreciated.Thanks.

The HttpClient object must be instantiated with a Client object which will handle the underlying connection. Source:

  Requires a networking hardware and a library that provides transport specific Client instance, such as:

Refer to the following code:

https://github.com/arduino-libraries/ArduinoHttpClient/blob/master/examples/DweetGet/DweetGet.ino
https://github.com/adafruit/Adafruit_CC3000_Library/blob/master/Adafruit_CC3000.h#L86
https://github.com/arduino-libraries/ArduinoHttpClient/blob/master/src/HttpClient.h#L51

In the above example, it is done like

WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);

Which means that for your code, you might want to pull out client as global object and instantiate it as:

Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,    ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIVIDER);
/* Create new Adafruit_CC3000_Client object */
Adafruit_CC3000_Client cc3000_client;
/* Feed this into the client */
HttpClient client (cc3000_client, "dweet.io", 80);

You should also use the example code to see how to print the response after executing client.get():

  // read the status code and body of the response
  statusCode = client.responseStatusCode();
  response = client.responseBody();
  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);

The example code is pretty much example what you want, you just have to give it a Adafruit_CC3000_Client as the Client.

Full code:

#include <Arduino.h>
#include <Adafruit_CC3000.h>
#include <SPI.h>
#include "utility/debug.h"
#include "utility/socket.h"
#include <HttpClient.h>

#define ADAFRUIT_CC3000_IRQ   3
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,    ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIVIDER);
/* Create new Adafruit_CC3000_Client object */
Adafruit_CC3000_Client cc3000_client;
/* Feed this into the client */
HttpClient client (cc3000_client, "dweet.io", 80);

#define WLAN_SSID       "ssid"
#define WLAN_PASS       "pwd"
#define WLAN_SECURITY   WLAN_SEC_WPA2

int statusCode = 0;
String response;

void setConnection(){

    Serial.println("Initializing...");
    if (!cc3000.begin())
    {
        Serial.println("Couldn't begin()! Check your wiring?");
        while(1);
    }
    Serial.print("Attempting to connect to ");
    Serial.println(WLAN_SSID);
    if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println("Failed!");
        while(1);
    }
    Serial.println("Connected!");
    Serial.println(F("Request DHCP"));
    while (!cc3000.checkDHCP())
    {
        delay(100);
    }
    Serial.println(F("DHCP success!!"));
}

void dweet(){

    int ctr=0;
    char buff[100];
    int x=0;
    const char* host = "https://dweet.io/get/latest/dweet/for/dunebot";

    Serial.println(F("Initializing dweet client ..."));

    client.get(host);
    Serial.println(F("Client Connected !"));

    // read the status code and body of the response
    statusCode = client.responseStatusCode();
    response = client.responseBody();
    Serial.print("Status code: ");
    Serial.println(statusCode);
    Serial.print("Response: ");
    Serial.println(response);

    /*
    Typical response is:
    {"this":"succeeded",
    "by":"getting",
    "the":"dweets",
    "with":[{"thing":"my-thing-name",
      "created":"2016-02-16T05:10:36.589Z",
      "content":{"sensorValue":456}}]}
    You want "content": numberValue
    */
    // now parse the response looking for "content":
    int labelStart = response.indexOf("content\":");
    // find the first { after "content":
    int contentStart = response.indexOf("{", labelStart);
    // find the following } and get what's between the braces:
    int contentEnd = response.indexOf("}", labelStart);
    String content = response.substring(contentStart + 1, contentEnd);
    Serial.println(content);

    //There was a missing brace here. Was the code cut off?!
}

void setup(){
    Serial.begin(115200);
    while(!Serial);
    Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);
    setConnection();
}

void loop() {
    dweet();
}


Arduino Wifi Rev2, bug when reading PWM duty cycle value on pin 6 I am trying to read the PWM duty cycle set for pin 6 on the Arduino Wifi Rev2.
By default, the timer used is TCB0, used in 8-bit PWM mode. The 16-bit Compare channel CCMP is used as two 8-bit registers, the lowest byte CCMPL is for the period, while the highest byte CCMPH is for the duty cycle.
However, something weird happens when I try to read the Compare channel register, the value of CCMPH is unexpecteadly copied into CCMPL.

// PWM on pin 6, timer TCB0
//TCB_t* timer_B0 = (TCB_t *)&TCB0; // pointer on timer structure

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

void loop() {
  setPWMValueOnPin6(20);
  setPWMValueOnPin6(40);
  setPWMValueOnPin6(60);
  setPWMValueOnPin6(80);
}

void printCompareChannelValues()
{
  Serial.print("Compare channel = ");
  unsigned int r = TCB0_CCMP;
  //byte r = timer_B0->CCMP;
  Serial.println(r);

  Serial.print("Compare channel L = ");
  byte l = TCB0_CCMPL;
  //byte l = timer_B0->CCMPL;
  Serial.println(l);

  Serial.print("Compare channel H = ");
  byte h = TCB0_CCMPH;
  //byte h = timer_B0->CCMPH;
  Serial.println(h);
}

void setPWMValueOnPin6(byte value)
{
  analogWrite(6, value);
  printCompareChannelValues();
  delay(2000);
}

Here is the serial monitor output:
Compare channel = 5375
Compare channel L = 255
Compare channel H = 20
Compare channel = 10260
Compare channel L = 20
Compare channel H = 40
Compare channel = 15400
Compare channel L = 40
Compare channel H = 60
Compare channel = 20540
Compare channel L = 60
Compare channel H = 80
Compare channel = 5200
Compare channel L = 80
Compare channel H = 20
Compare channel = 10260
Compare channel L = 20
Compare channel H = 40
Compare channel = 15400
Compare channel L = 40
Compare channel H = 60
Compare channel = 20540
Compare channel L = 60
Compare channel H = 80
Compare channel = 5200
Compare channel L = 80
Compare channel H = 20

Problem occurs even when removing the serial functions (by watching at a led intensity on pin 6).
The same behavior occurs on pin 3 (timer TCB1).
Does someone has any idea what is going on? Thanks for your help.

Arguable bug location
The problem appears to be here in the analogWrite() code:
    timer_B->CCMPH = val;

I suppose it could be argued that you're using the timer in an way unintended
by the Arduino megaavr core, but I think it's reasonable to consider this as
a bug that should be fixed in the core.
16-bit hardware register access and analogWrite() internals
According to the "Accessing 16-Bit Registers" of the ATMega4809 datasheet (among others no doubt):

The AVR data bus has a width of eight bits, and so accessing 16-bit registers requires atomic operations. These
registers must be byte accessed using two read or write operations. 16-bit registers are connected to the 8-bit bus
and a temporary register using a 16-bit bus.
For a write operation, the low byte of the 16-bit register must be written before the high byte. The low byte is then
written into the temporary register. When the high byte of the 16-bit register is written, the temporary register is
copied into the low byte of the 16-bit register in the same clock cycle.
For a read operation, the low byte of the 16-bit register must be read before the high byte. When the low byte register
is read by the CPU, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as
the low byte is read. The high byte will now be read from the temporary register.
This ensures that the low and high bytes of 16-bit registers are always accessed simultaneously when reading or
writing the register.
Interrupts can corrupt the timed sequence if an interrupt is triggered and accesses the same 16-bit register during an
atomic 16-bit read/write operation. To prevent this, interrupts can be disabled when writing or reading 16-bit registers.
The temporary registers can be read and written directly from user software.

So in effect, timer_B->CCMPH = val; is not just writing the real CCMPH hardware register, it is also writing the real CCMPL register with whatever is in this anonymous temporary register that was filled by either the last read or write operation.
So here's what's happening in your code:

You execute byte l = TCB0_CCMPL; in printCompareChannelValues() which both reads TCB0_CCMPL and loads the temporary register with the real CCMPH register's value, which as you'll see is important.

You execute byte h = TCB0_CCMPH; which is reading the temporary register rather than the real CCMPH hardware register from which the temporary register was loaded in your read from TCB0_CCMPL above.  Note: technically this statement doesn't play a role in problem.  I'm mentioning it only to drive home the behaviour of the temporary register.

You exit printCompareChannelValues() and exit-and-reenter setPWMValueOnPin6() which calls analogWrite() which inside runs timer_B->CCMPH = val;,
which stores val in the real CCMPH with and stores the temporary register (containing the previous CCMPH value) into the real CCMPL.

So yeah, on each time through the previous CCMPH becomes the new CCMPL value.
Patching the core
Arguably what the core should contain, instead of  timer_B->CCMPH = val;, is something like:
{
    const uint8_t saved_SREG = SREG;
    cli();

    uint16_t temp  = timer_B->CCMP;
    temp          &= 0xFF;
    temp          |= (uint16_t)val << 8;
    timer_B->CCMP  = temp;

    SREG = saved_SREG;
}

Here we're doing full 16-bit register reads.  The load from CCMP reads the CCMPL first which primes the temporary register with the real CCMPH. Then the second half of the load from CCMP tries to read CCMPH, but is really  reading the temporary register correctly containing CCMPH's value.  And now there are no unpleasant surprises when this plays out in reverse.
The statement that assigns CCMP writes the CCMPL (really the temp register) then writes to the real CCMPH and simultaneously commits the temp register to the real CCMPL.
You can patch the above snipped over the timer_B->CCMPH = val; in your PATH-TO-ARDUINO15-DIRECTORY/packages/arduino/hardware/megaavr/CORE-VERSION/cores/arduino/wiring_analog.c
I have not spent a pile of time thinking about that patch, so use a bit of caution.  I may well have forgotten something important.
Priming the temporary register instead
If you don't want to mess with the core or you can't for some reason or another, a ugly hack would be to turn your simple analogWrite(6, value); call into something like the following:
{
  const uint8_t saved_SREG = SREG; cli();
  TCB0_CCMPL = TCB0_CCMPL;
  analogWrite(6, value);
  SREG = saved_SREG;
}

Besides turning off interrupt and then restoring them, the only thing happening here is this somewhat ridiculous looking statement:
TCB0_CCMPL = TCB0_CCMPL;
All this is doing is priming the temporary register for you.  On the right-hand side of the assignment we read the real CCMPL register.  This is also loading the temporary register with the real CCMPH, but we don't care about that.  Then on the left-hand side of the assignment, we attempt to write into CCMPL, but what we're in fact doing is writing to the temporary register.  And now your temporary register has the correct CCMPL value for when you run the timer_B->CCMPH = val; in the original analogWrite() code.
So, I suppose if you want to do this and you're unable/unwilling to modify your core, you could do this, potentially wrapping with an #if #else based on the Arduino megaavr core version, should they update the core in the future with patch given above or something equivalent.
Core patch using the same priming technique
The same priming technique could be applied inside the patch as follows.  This is maybe more confusing but slightly more efficient than the comparatively normal looking first patch.
{
    const uint8_t saved_SREG = SREG; cli();
    timer_B->CCMPL = timer_B->CCMPL; // Prime temporary register
    timer_B->CCMPH = val;
    SREG = saved_SREG;
}


Is there a more elegant way to check highest / lowest sample data? N00b question,

Is there a better way for readability / elegance / DRY etc to check various sensor values for high/low record value?  This code works, but looks like the long way round.

  void checkRecord() {

if ( temp.current > temp.high) {
  temp.high = temp.current;
}

if ( temp.current < temp.low) {
  temp.low = temp.current;
}

if ( pressure.current > pressure.high) {
  pressure.high = pressure.current;
}

if ( pressure.current < pressure.low) {
  pressure.low = pressure.current;
}
if ( humidity.current > humidity.high) {
  humidity.high = humidity.current;
}

if ( humidity.current < humidity.low) {
  humidity.low = humidity.current;
}

if ( rainfall.current > rainfall.high) {
  rainfall.high = rainfall.current;
}

if ( rainfall.current < rainfall.low) {
  rainfall.low = rainfall.current;
}
if ( altitude.current > altitude.high) {
  altitude.high = altitude.current;
}

if ( altitude.current < altitude.low) {
  altitude.low = altitude.current;
}
}

Thanks!

This is a variation on the struct idea with an object-oriented flavor.

If you put the current, low and high values of any sensor inside a
struct, you could also morph this struct into a class and give it
an update() method that, in addition to updating the current value,
keeps the low and high updated:

class LowHigh
{
public:
    LowHigh() : current(0), low(INFINITY), high(-INFINITY) {}
    void update(float value) {
        current = value;
        if (current < low)
            low = current;
        if (current > high)
            high = current;
    }
    float get_low() { return low; }
    float get_high() { return high; }
private:
    float current, low, high;
};

I am assuming float data here, you may have to adapt to whatever type
is appropriate for your sensors.

You would use the class as this:

LowHigh temp, pressure, humidity, rainfall, altitude;

void loop()
{
    temp.update(temp_sensor.get_reading());
    pressure.update(pressure_sensor.get_reading());
    humidity.update(humidity_sensor.get_reading());
    // ...
}


Az Delivery ESP32 DevKitC V2 PIN names/number i wonder where to find out the PIN names for the Az Delivery ESP32 DevKitC V2.
There is a pin out graphic, but it does not say how the Pin addresses are:
https://cdn.shopify.com/s/files/1/1509/1638/files/ESP_-_32_NodeMCU_Developmentboard_Pinout_Diagram.jpg?4479111012146266271
I thought maybe it's just the number of the GPIOs but that's wrong. In the first example script only PIN 1 was named as the address for the board intern LED.

ESP32 boards don't use "names" for their IO pins. There is a direct 1:1 mapping between the internal "GPIO" number and the pin number.
To do something with pin G21 on the board you use pin number 21. To do something with pin G14 you use pin number 14.
By all accounts that board differs from other ESP32 devkits in that the LED is on GPIO1 rather than the normal GPIO0 that all the other boards use. I suspect that this is the source of your confusion.


New UNO, BLINK not working Finally got around to playing with my uno today for the first time. ( It's a branded sunfounder UNO R3)

First project. Simple blink. Using arduino 1.6.3, Windows 8.1 It is hooked up correctly.

void setup() {
   // initialize digital pin 13 as an output.
   pinMode(9, OUTPUT);
}

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

What I get is a fast blinking LED. I've tried multiple values and it doesn't change. No error on upload.
I've commented out everything except the digitalWrite(9, HIGH); and I get a fast blink.

I tried:

void loop() {
   digitalWrite(9, LOW);
   delay(5000);
   digitalWrite(9, HIGH);   // turn the LED on (HIGH is the voltage level)
}

And I get nothing, it doesn't even turn on.

Same if I remove the first digitalWrite();

So, I'm already a little lost here. I did a but of google searching tried adding a serial 9600 line, and a few other things. Nada.

Added as new answer because comments limit was reached
Doesn't really matter which programmer you set because in this instance you're not actually burning the bootloader just setting the fuses (to those already stored in boards.txt for the Uno) but 'Using Arduino as ISP' is the nearest to what you're doing


How would i capture and split serial data? How would i capture the following serial data, and split it into parts?
<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>

the parts i need from this is
Alarm - This is a state. i.e Alarm, Idle, Paused, Working
MPos: - This is a series of positions X,Y,Z
WPos: - This is a series of positions X,Y,Z

What i want to do is capture the string from serial (See above for formatting)
Then display the information on the LCD.

i.e.
X: 0.000  Y:0.000
Z: 0.000  Idle

I've managed to figure out how to do all the LCD display stuff, and send commands to the serial, but it appears there are so many variations on how to split the data up, that i't really confusing to me, as well, almost all of the examples i find use loop to do this, but i would like to have this done in a function, that way i can display this info only when needed, not constantly, as i'll be useing the LCD for a menu system.

This string is actually fairly easy to split up, because everything is separated by commas nice and regularly.

Assuming you have the string in a char array (aka a C string) and not a String object (I and most other programmers abhor the String class) you can use the function strtok() to split the string up into parts.

So you have the string:

char string[] = "<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>";

The function strtok() takes, on its first call, the string you want to split and the delimiter that you want to split on.  It returns a pointer to the chunk:

char *alarm = strtok(string, ",");

alarm now contains <Alarm and strtok() moves its internal pointer to point at the next character, so it sees the string as MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>

With the next and subsequent calls to strtok() you don't give it the string, or it will reset its internal pointer.  You just pass it NULL and it gives you the next block:

char *mposX = strtok(NULL, ",");
char *mposY = strtok(NULL, ",");
char *mposZ = strtok(NULL, ",");
char *wposX = strtok(NULL, ",");
char *wposY = strtok(NULL, ",");
char *wposZ = strtok(NULL, ">");

Note that I changed the delimiter on the last one to > so it chops off that extra character that we don't want (and there is no , after the last part).

So now you have 7 variables that point to chunks of the string, which has internally been chopped up and modified into individual substrings:

*alarm = "<Alarm";
*mposX = "MPos:0.000";
*mposY = "0.000";
*mposZ = "0.000";
*wposX = "WPos:0.000";
*wposY = "0.000";
*wposZ = "0.000";

So now we can clean up the three entries that have extra stuff in them, and that is a simple as adding an offset value to the pointers we have:

alarm += 1;
mposX += 5;
wposX += 5;

Our list of pointers now looks like this:

*alarm = "Alarm";
*mposX = "0.000";
*mposY = "0.000";
*mposZ = "0.000";
*wposX = "0.000";
*wposY = "0.000";
*wposZ = "0.000";

The position variables can now be passed through strtod() to convert them to float values:

float mx = strtod(mposX, NULL);
float my = strtod(mposY, NULL);
float mz = strtod(mposZ, NULL);
float wx = strtod(wposX, NULL);
float wy = strtod(wposY, NULL);
float wz = strtod(wposZ, NULL);

You can do different things depending on the content of the *alarm string by using strcmp():

if (strcmp(alarm, "Busy") == 0) {
    // Something to do when Busy
}

etc.

Or you can just use it to print the content to the LCD.


Can the Arduino Eclipse plugin use the libraries installed by the Arduino IDE? In Arduino Eclipse (v3, nightly build) I have not been able to load 'foreign' libraries, those written by me or someone else, so they are not among the available choices in the include-library dialogs.

I've tried adding them to a project as well as adding them as an available library resource using the built-in dialogs for doing so, but I don't see a way to select a library that isn't already included in those dialogs.

My ideal case would be a way for the Arduino Eclipse plugin to use the same boards and libraries as I use in my Arduino IDE installation, so that:

An upgrade to the Arduino IDE would simultaneously upgrade the core libraries in Eclipse;
An optional library would need installing in only one place;
Modifying an optional library would only need to be done once, in one place.

The goal, as in an earlier question of mine, is to seamlessly permit using either IDE to advance a project. However, I'd be grateful to be able to add to my Eclipse installation any library of my choosing.

I fear that what you want is not 100% possible.
For libraries I am 100% sure it will work but the problem is the platforms.
UPDATE arduino IDE (no longer)? decompresses libraries and as such the libraries are unusable in Sloeber.

Lets start with the Libraries
What you do is:
In arduino eclipse ide remove all libraries from the library manager.

In windows->preferences->arduino->"private libraries path" add the libraries folder in the arduino IDE install and add the libraries folder in the arduino15 folder maintained by the library manager.
It is important to point to the parent folder containing the libraries. All subfolders are assumed to be libraries.

Then the boards
The problem here is that the boardsmanager adds environment variables to link boards to tools. You may have read remarks about A.RUNTIME.TOOLS.AVR-GCC.PATH and A.RUNTIME.TOOLS.AVRDUDE.PATH not being defined. Well it is the boardsmanager that maintains these based on json file content.
If you can limit yourself to 1 version of AVR, SAM, AVRDUDE, BSON,... tool chain you can "make it work" as follows:
Step 1: Keep as little boards as possible installed. You have to keep at least 1 or the plugin will reinstall the AVR boards of Arduino when started.
Step 2: In windows->preferences->arduino->"private hardware path" add the hardware folder in the arduino IDE install and add the packages folder in the arduino15 folder maintained by the Arduino IDE boards manager.
Step 3: Recreate the project in eclipse as described in your other question.
Step 4: If the build fails modify the [eclipse installation]/arduinoPlugin/post and pre processing files to try to get it to work.
Step 5: in project properties->Arduino select apply and OK (this will take your changes in step 4 into account)
Step 6: Goto Step 4

Good luck
Jantje


Generate particular pulse using Arduino How can I generate this pulse with an Arduino Micro?

Is it necessary an external component?

Take two 10K or so resistors:

    +5V
     |
    10K
     |
Pin2-+---> output
     |
    10K
     |
    GND

The following program does the trick:

const uint8_t kPin = 2;
const uint32_t kDelay = 10;  // 100Hz

void setup() {
}

void loop() {
  pinMode(kPin, OUTPUT);
  digitalWrite(kPin, HIGH);
  delay(kDelay);

  pinMode(kPin, INPUT);
  delay(kDelay);

  pinMode(kPin, OUTPUT);
  digitalWrite(kPin, LOW);
  delay(kDelay);

  pinMode(kPin, INPUT);
  delay(kDelay);
}

When Pin2 (or any other pin for that matter) is set as INPUT, it is in high-impedance state (theoretically), so effectively you have a voltage divider giving you 1/2 Vcc. When it is set as OUTPUT, and now assuming that its output impedance is << 10KΩ, it drives the output to either +5V or 0V.


Set PWM frequency to 25 kHz I currently can set four PWM pins to around 31 kHz with the following code:

void setup()
{
    TCCR1B = TCCR1B & B11111000 | B00000001; // Set PWM frequency for D9 & D10:
    pinMode(pwmPin9, OUTPUT); // Sets the pin as output
    pinMode(pwmPin10, OUTPUT); // Sets the pin as output

    TCCR2B = TCCR2B & B11111000 | B00000001; // Set PWM for D3 & D11
    pinMode(pwmPin3, OUTPUT); // Sets the pin as output
    pinMode(pwmPin11, OUTPUT); // Sets the pin as output
}

I found this setup somewhere, but I don't know how I can set these four PWM pins to around 25 kHz instead. How is that possible?

You can configure Timer 1 to cycle at 25 kHz in phase correct PWM mode, and use it's two outputs on pins 9 and 10 like so:

// PWM output @ 25 kHz, only on pins 9 and 10.
// Output value should be between 0 and 320, inclusive.
void analogWrite25k(int pin, int value)
{
    switch (pin) {
        case 9:
            OCR1A = value;
            break;
        case 10:
            OCR1B = value;
            break;
        default:
            // no other pin will work
            break;
    }
}

void setup()
{
    // Configure Timer 1 for PWM @ 25 kHz.
    TCCR1A = 0;           // undo the configuration done by...
    TCCR1B = 0;           // ...the Arduino core library
    TCNT1  = 0;           // reset timer
    TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
           | _BV(COM1B1)  // same on ch; B
           | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
    TCCR1B = _BV(WGM13)   // ditto
           | _BV(CS10);   // prescaler = 1
    ICR1   = 320;         // TOP = 320

    // Set the PWM pins as output.
    pinMode( 9, OUTPUT);
    pinMode(10, OUTPUT);
}

void loop()
{
    // Just an example:
    analogWrite25k( 9, 110);
    analogWrite25k(10, 210);
    for (;;) ;  // infinite loop
}

Writing a value of 0 with analogWrite25k() means the pin will be
always LOW, whereas 320 means always HIGH. The regular analogWrite()
should almost work, but it will interpret 255 the same as 320 (i.e.
always HIGH).

This code assumes an Arduino Uno or similar board (ATmega168 or 328 @
16 MHz). The method used here requires a 16-bit timer, and thus it
uses Timer 1 as it's the only one available on the Uno; that's why only
two outputs are available. The method could be adapted to other
AVR-based boards with a 16-bit timer. As Gerben noted, that timer should
have a corresponding ICRx register. There are 4 such timers on the
Arduino Mega, each with 3 outputs.


Transferring OV7670 data with SPI port I bought an OV7670 camera and I would like to use the following code:
https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno

But I wonder whether it is possible to use SPI instead of I2C when I transfer the image data through Arduino to other breakout boards.

I2C is not used to get the pixel data. That is used only to configure the ov7670. You can read the pixel data by reading the IO PORTS and then send the data via SPI.


My brand new LCD screen doesn't display anything, even though there is no code errors? I have a LCD screen, and I wanted to use it with a Simon Says game that I am making. I tried the tutorial on the Arduino website, but it doesn't work. Then I tried another tutorial on Adafruit. On this one, the LCD screen seemed brighter which is good, but it also doesn't work.

What it is supposed to look like:

My code:

#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

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

void loop() {
  lcd.print("Test!");
  delay(500);
  lcd.clear();
  delay(500);
}

I have verified that the wiring is correct on the official version and the Adafruit version, and my screen is brand new from the kit, so what is wrong?

Edit 1:

Let me define "doesn't work." I can turn the potentiometer, but nothing changes. I can't even see white rectangles or even a single pixel on the display. It is blank. Absolutely nothing to see other than the blacklight, which does work.

Edit 2:

Turns out that the diagram was wrong. Needed to move the potentiometer 1 pin to the right, now it works!


How does one set attributes for SD files? How does one set file attributes, e.g., creation date, for a file being created on an SD?

The Arduino SD library, is based on Github: greiman/SdFat, by William Greiman.

From SD Created File Attributes:

  The basic SD.h library doesn't set the attributes. You notice everything has the same creation date? The library doesn't have any way of knowing what the date is.

However, you need to use a callback function. The following information is from file creation date and time in sd card ?:

  Install the SdFat library - there is an example called Timestamp.ino describing in detail how to do it...

// after your rtc is set up and working you code just needs:

void dateTime(uint16_t* date, uint16_t* time) {
  DateTime now = rtc.now();

  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(now.year(), now.month(), now.day());

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}

//put that outside of any functions, before your 'setup'

//Then inside your 'loop' or 'setup'

void loop(void)
{

  //Other code that does stuff

  //put this next line *Right Before* any file open line:
  SdFile::dateTimeCallback(dateTime);
  dataFile = SD.open(datafilename, FILE_WRITE);

  //other code that does stuff

}

There is another way of achieving this, in a sketch without having to convert to SDFat:

  @donald0000 wants the Date Modified field to show an actual time stamp
  when you look at the files present on the card using Windows Explorer.
  As Billy Ho says, the callback function is the way to do it. You can
  indeed use this function with SD.h  if you don't want to convert to
  SDFat. Here is an example of the function in a sketch. Notice the
  timing of when the date modified time stamp is written, it is when
  file.close() writes the actual data to the card.

#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <RTClib.h>

File file;  // test file
const uint8_t SD_CS = 10; // SD chip select
RTC_DS1307 RTC;  // define the Real Time Clock object

 char timestamp[30];

//------------------------------------------------------------------------------
// call back for file timestamps
void dateTime(uint16_t* date, uint16_t* time) {
 DateTime now = RTC.now();
 sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(),now.minute(),now.second(),now.month(),now.day(),now.year()-2000);
 Serial.println("yy");
 Serial.println(timestamp);
 // return date using FAT_DATE macro to format fields
 *date = FAT_DATE(now.year(), now.month(), now.day());

 // return time using FAT_TIME macro to format fields
 *time = FAT_TIME(now.hour(), now.minute(), now.second());
}
//------------------------------------------------------------------------------
void setup() {

 Serial.begin(9600);
 Wire.begin();
 if (!RTC.begin()) {
   Serial.println("RTC failed");
   while(1);
 };
 // set date time callback function
 SdFile::dateTimeCallback(dateTime);

  DateTime now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(),now.minute(),now.second(),now.month(),now.day(),now.year()-2000);
  Serial.println("xx");
  Serial.println(timestamp);

 if (!SD.begin(SD_CS)) {
   Serial.println("SD.begin failed");
   while(1);
 }
 file = SD.open("TEST_SD.TXT", FILE_WRITE);
 file.println("Testing 1,2,3...");

 delay(5000);
 file.close();
 Serial.println("Done");
}
//------------------------------------------------------------------------------
void loop() {}


My Serial plotter isn't working (arduino) I'm trying to upload this code and it works properly but I can't see anything on my serial plotter

const int AnalogIn_Pin0=  A0;
const int AnalogIn_Pin1=A1;
const int Pwmout_PIN=11;
float AnalogIn_Val0=0;
float AnalogIn_Val1=0;
int Pwmout_Val=0;
float Error=0;
float ErrorInteg=0;
float Control=0;
float ControlFilt=0;
float kp=0.2;
float Pole =-10;
float Ki =0.01;
int deltaT=0.01;
int deltaT_ms=(int)deltaT*1000;

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

void loop() {
  AnalogIn_Val0=(float)constrain (analogRead(AnalogIn_Pin0),0,600);
  AnalogIn_Val1=0.97*AnalogIn_Val1+0.03*(float)analogRead(AnalogIn_Pin1);
  Error= (AnalogIn_Val0-AnalogIn_Val1);
  ErrorInteg=ErrorInteg+Error*deltaT;
  ControlFilt=kp*Error+Ki *ErrorInteg;
  Pwmout_Val= constrain (map ((int)ControlFilt,0,1023,0,255),0,220);
 analogWrite (Pwmout_PIN,Pwmout_Val);
 Serial.print(AnalogIn_Val0);
 Serial.print("");
 Serial.print(AnalogIn_Val1);
 Serial.print("");
 Serial.print( Pwmout_Val);
 delay (deltaT_ms);

}

You must have each set of data point (or points) on a separate line and if you are plotting more that one value you need a space or a tab between each value.

So to have 3 lines on your plot, I think you want this:

 Serial.print(AnalogIn_Val0);
 Serial.print(' ');
 Serial.print(AnalogIn_Val1);
 Serial.print(' ');
 Serial.println(Pwmout_Val);

The output in the serial monitor should be something like this:

123 456 789
234 567 901
...


Controlled power-down for automotive application I'm working on an automotive project that uses an Arduino Mega 2560.

What I need is a circuit that allows the unit to sense when the external power feed drops (triggering an interrupt?) so that the software can preserve state to the non-volatile memory and then shut down.

I was thinking some sort of capacitor/battery to run it once the eternal feed drops, but the hardware side of things is not my strong skillset - I'm more of a software kinda person.

Consider a battery backup for low power devices.  This article from allaboutcircuits.com discusses how to build a 12 to 5 volt power supply with its own battery backup.

In your specific case, run a second 12 to 5 volt regulated signal to one of the processor's digital inputs.  When the 12 volts shuts off, the signal to the processor's digital input will go low.  Poll this input and when you see it go low shutdown the processor or put the processor into a deep sleep mode to draw as little current as possible from the back up battery.

The ATmega2560 processor may not be the best chose for this. There are processors that can drop down into the nA range and still wake up periodically to check if they should be powered all the way back up.


Modify On board 4 pin switch to work with Arduino I have a HDMI Switch module which switches Input signals. It has a 4 pin push button to switch inputs. ( - )

I want to modify the button in order to control it with an Arduino. (push via Arduino command) What should i do in order to achieve this ?

I am newbie in Arduino so please excuse my mistakes.

Thanks

Although it looks like 4 pins it's actually 2. You can see that they are connected together in pairs. This is identical to any other tactile switch of the kind used in many Arduino demos and examples.

All you need is some way of connecting the left pair of pins to the right pair of pins (in the underside image). The right pair are ground (you can tell because they are connected to the ground plane - the large copper area), so the input the left pair of pins are connected to must be active-low with a pullup resistor. That makes things simple enough.

If you can share the grounds between the switch circuit and the Arduino then it's possible to do it with just wires. However care must be taken:

Chances are this is a 3.3V based system (there's very few 5V systems around these days - the Arduino is pretty old technology from that perspective), so just setting an output HIGH or LOW and connecting it directly could damage the switch. Instead you need to emulate an open drain output. That means instead of setting a pin to OUTPUT and toggling it between HIGH and LOW to press the button you actually have to toggle the mode of the pin - that is, toggling between INPUT and OUTPUT + LOW.

For instance:

void press() {
    digitalWrite(BUTTON_PIN, LOW);
    pinMode(BUTTON_PIN, OUTPUT);
}

void release() {
    pinMode(BUTTON_PIN, INPUT);
}

You can, if you so choose, turn any GPIO pin into a real open drain output by using it to switch a transistor which in turn switches the button:

simulate this circuit – Schematic created using CircuitLab

Now it's just output a HIGH to turn the transistor ON and short the button, or LOW to turn the transistor OFF.

If you can't / don't want to share the grounds, then you can replace the transistor with an opto-isolator:

simulate this circuit

That is by far the safest option since it completely isolates (galvanic isolation) the Arduino and the switch box.


How to use an Arduino to measure speed of rocket I am not very experienced with Arduino and I am trying to learn it. I was wondering what is the easiest and most effective way to calculate speed and log it every second so to say. This would be mounted in a model rocket to see what speeds it can reach. How would I achieve this?

Would it be hard to send over RF to see it in real time?

Thanks in Advance

You can use an accelerometer or a barometre for measure speed and for RF you can use:

Radio NRF24L01
wifi ESP8266
bluetooth HC-06


Understanding bitwise operations I am wondering what the second line of code does:

int16_t GyX;
GyX=Wire.read()<<8|Wire.read();

Also, how can I write the GyX value to EEPROM?

From what I understand, int16_t is a two-bytes value. The Wire.read() returns a single byte. The <<8 shifts the bits by one byte to the left in order to read the higher order bits, and the last part writes the next wire read (lower order bits). Basically, reads wire twice and stores those values in the int. Is that correct?

For the writing, would

EEPROM.write(addr, GyX >> 8);
EEPROM.write(addr, GyX & 0xff);

do the trick? (First line records the higher order bits, while second records the lower order ones)

GyX=Wire.read()<<8|Wire.read();

This is a bug. It reads two bytes from the I2C bus and builds a 16-bit
number from them. One of the bytes (we don't know which one) will be the
most significant byte of the result. The other byte will be the least
significant byte.

This instruction is likely to work just fine on some particular version
of some particular compiler with some particular compiler options.
Presumably it did work for the author. But you should not expect it to
work consistently across compilers, or even across different versions of
the same compiler.

The proper way to do this is to perform the two reads in different
instructions:

GyX = (uint16_t) Wire.read() << 8;
GyX |= Wire.read();

assuming the bytes come most-significant first.

Edit: added (uint16_t) cast. C.f. this answer.


Arduino Driver can I use only PNP? is it possible to use a normal PNP transistor to drive a motor?
I'm kinda new to this stuff so I want to be on the safe side, so I don't damage my Arduino Uno because of the motor.

I have made a motor driver? https://circuits.io/circuits/2493784-test-1
But I'm not sure if i have done right and I wont break any components.

So does this work without any problems and have I done it right?

I'm not trying to make a H-bridge because I need both PNP and NPN?

EDIT:Picture

When connecting together several circuits that have different supply
voltages, common practice is to make them all have a common negative
supply rail. This is called “common ground”. As explained in Majenko’s
answer, you would need an NPN transistor for that.

If you want to use a PNP instead, then you could forget the common
practice and do everything “backwads”: if you connect together the positive
ends of the power supplies, you will have a “common VCC”
instead of a common ground. Relative to the Arduino ground, your
9 V battery will have one pole at +5 V and the other at
−4 V.

The wiring is the following:

connect the emitter to +5 V (Arduino +5 and battery +)
connect the base to an Arduino output through a resistor
connect the collector to the motor
connect the other end of the motor to the battery −
put a free wheeling diode in parallel with the motor.

Edit: Below is an ASCII art rendering of the circuit. Beware that
the motor is ON when the Arduino output is LOW.

+-----------+
|         5V|-----------------+-------------------+
|           |                 |                   |
|  Arduino  |                 |                   |
|           |    ,-----.  B |< E                 ___ +
|        D13|----|     |----|    PNP              _
+-----------+    `-----'    |\                   ___
                              |C                  _
                              |                  ___
                              +---------+         _
                              |         |        ___ 9 V batt.
                              |         |         _
                             ---        |        ___
                              ^       motor       _
                             / \        |        ___
                             ---        |         _  −
                              |         |         |
                              |         |         |
                              +---------+---------+


Convert ASCII output to human readable form and assign to a variable I'm reading the RFID output and I can print it to the serial monitor as human readable. But what I want is to assign that to a variable. But I'm getting the ASCII. Is there any way to convert it and get to the variable like Serial.write() do.

byte readbackblock[19];

for (int j=0 ; j<16 ; j++)//print the block contents
    {
      Serial.write (readbackblock[j]);
      cardNumber += readbackblock[j];
    }

Serial.print(cardNumber);

Serial output

read block: 1234567890123456

49505152535455565748495051525354

Any help please.

I don't think it is possible.

The Arduino is 8-bit microcontroller, and can't handle integers larger than 32-bit. The maximum value for a unsigned 32-bit integer is 4294967296. This is a smaller number than your readblock, so it wil never fit.

If you want to do this with smaller numbers, you can use these 2 function:

atoi -> convert char array to integer
atol -> convert char array to long integer


SPI Arduino communication I want two Arduino cards to communicate with each other using SPI and move the servo motor with potentiometer as a result. I've done the pre-burning led or the led burning led on the SPI, I am waiting for your help. I will give the code below.

MASTER Arduino code

#include <SPI.h>
/* SPI haberleşmesinde Master olarak görev yapan Arduino kodu */
const int pot=A0;   // Servo kontrol potunu bağlayacağımız analog giriş.
int potdurum=0;
int pos = 0;
const int SSpini = 8;
/* Slave görevindeki Arduino'nun seçilmesi için 8 bumaralı pin SS olarak belirlendi */

void setup()
{
  Serial.begin(9600);
  pinMode(SSpini, OUTPUT);
  /* SS pini çıkış olarak ayarlandı */
  digitalWrite(SSpini, HIGH);
  /* Slave olan Arduino başlangıçta haberleşmeye geçmemesi için SS pini HIGH yapıldı */
  SPI.begin();
  /* SPI haberleşmesi başlatıldı */
}

void loop()
{
  potdurum=analogRead(pot);
  pos= map(potdurum,0,1023,0,180);//Pottan okunan değeri  180e oranlıyoruz.
  veriGonder(pos,SSpini);
}

/* SPI üzerinden veri göndermek için yazılmış fonksiyondur */
void veriGonder(int veri, int SSpini)
{
  digitalWrite(SSpini, LOW);
  /* Diğer Arduino'nun veri dinlemeye başlaması için SS hattını LOW düzeyine çekmeliyiz */
  delay(1);
  /* Kısa bir süre bekleyelim */
  Serial.print("Aci Degeri = ");
  Serial.println(veri);
  delay(15);
  SPI.transfer(veri);
  /* veri karakteri diğer Arduino'ya yollandı
  * Fonksiyon diğer arduino'dan gelen veriyi vermektedir
  * Geri gelen veri LEDDurumu değişkeninde tutulmuştur
  * Bu değişken Seri port üzerinden bilgisayardaki Serial monitöre yollanmıştır
  */
  digitalWrite(SSpini, HIGH);
  /* Haberleşmeyi bitirmek için pin LOW konumuna çekilmiştir */
}

SLAVE Arduino code

#include <Servo.h>
int i = 0;
Servo myservomotor;

void setup()
{
  Serial.begin(115200);
  myservomotor.attach(3);
  pinMode(MISO, OUTPUT);
  pinMode(SS , INPUT);
  /* MISO pini OUTPUT, SS pini INPUT olarak ayarlandı */

  SPCR  |= 0b11000000;
  SPSR  |= 0b00000000;
  /* Slave mod ve interrupt için ayarlamalar yapıldı */

  sei();
  /* Interruptlar çalıştırıldı */
}

void loop()
{
}

/* SPI kesmesi olduğunda çalışacak fonksiyon */
ISR(SPI_STC_vect)
{
  cli();
  /* Interruptlar durdurulmuştur */
  while(!digitalRead(SS))
  {
      SPDR = i;
      i ++;
      if ( i > 255)
        i = 0;
      while(!(SPSR & (1 << SPIF)));
      /* SPI hattında veri aktarımı bitene kadar bekle */
      int gelenVeri;
      gelenVeri = SPDR;
      myservomotor.write(gelenVeri);
      Serial.print("Aci Degeri Slave= ");
      Serial.println(gelenVeri);
      delay(15);

//      if(gelenVeri == 'a'){
//        digitalWrite(SERVO,HIGH);
//      }else if(gelenVeri == 'b'){
//        digitalWrite(SERVO,LOW);
//      }
      /* SPI üzerinden gelen verinin değerine göre LED'in konumu değiştirildi */
  }
  sei();
  /* Interruptlar başlatılmıştır */
}

/* SPI kesmesi olduğunda çalışacak fonksiyon */
ISR(SPI_STC_vect)
{
  cli();
 ...
      Serial.print("Aci Degeri Slave= ");
      Serial.println(gelenVeri);

Don't do serial prints inside an ISR.


SIM7000E Waveshare can't do anything Can someone help me? I'm using a sim7000e from Waveshare. One week ago it was working normally, but now it doesn't work at all; it even can't read the RX-TX communication.
#include <SoftwareSerial.h> //koneksi ke modem

#define TINY_GSM_MODEM_SIM7000
#define TINY_GSM_DEBUG SerialMon
#define BAUD 9600
#define SerialMon Serial

const byte rxpin = 2;
const byte txpin = 3;

SoftwareSerial SerialAT(rxpin, txpin); // RX, TX

That's  my code for connecting to the Arduino. I believe it from my Arduino, but I don't know if something wrong from Arduino.
My 5V (sim7000E) to 5V (arduino mega2560), GND to GND.
Because I'm using Putty on USB for reading my AT-cmd it doesn't and has some trouble.

I'm having similar issues, although it could well be my fault!
I can't see any coding sending AT commands, or waiting for responses in your example.
Try running your TX pin to your RX pin on your Arduino (take the SIM7000e out of the equation completely).  If your code works, then the issue is elsewhere.
I've tried connecting via USB and that seems through a terminal.  I was able to connect to a mobile network using the AT command
AT+CSTT="cmnet"


Control/switching of headphone audio I need to do some simple line control of audio out from a phone, 3.5mm TRS. I would have preferred to use transistors, but the voltage drop on an already fairly weak signal makes it unusable. Also not sure about negative voltage from collector to emitter. Essentially I need to switch the line on/off. How can I do this while not introducing noise or signal loss (K.I.S.S.) - I haven't checked if optocouplers are without voltage drop, but in any case they're probably overkill.
Ask for clarification if needed.

My first thought was what about relays.  I've done a quick search and found this http://www.geofex.com/article_folders/relays/relays_for_switching_audio_signa.htm and this https://electronics.stackexchange.com/questions/110750/is-it-possible-to-turn-an-audio-signal-on-off-using-a-solid-state-relay so maybe it's not such a stupid idea, but like optocouplers it probably is a bit OTT.


Arduino to send sms one time only when a button is pressed The LED_UPDATE() is called in my loop() function, I implemented it (tried anyways),
to send sms as shown in the code such that  only one sms is sent , because as the loop() keeps calling LED_UPDATE(), it's going to keep sending an sms every time (yep you guessed it, very bad for credit :o )

any tips on how I can get around this or what i'm doing wrong in my code would be much appreciated.

p.s. nearly left my mobile phone in the code lol

void LED_UPDATE(int state)
{

int count; // initialized to zero, once program runs it automatically enter state ==1
if (state == 1)
{

    digitalWrite(RED_PIN, LOW);
    digitalWrite(GREEN_PIN, HIGH);
    count=0;
}
else if (state == 2)
{
  count+=1;
  Red_Blink();

  if(count == 1 )
  {
    sms.SendSMS("086XXXXXXX", "PANIC BUTTON PRESSED, Subject needs help!!!");
  }

}

You are resetting count every time you enter the function.

static int count; // initialized to zero, once.

Adding the static statement should initialise the variable once and preserve its value between calls.


How to use an 8x8 LED Matrix? I have a LED Matrix just like this one

but couldn't find the data sheet for it (1855AS)
I asked around in my country and one guy told me to try attaching one side to 5v and the other to GND. Some LEDs worked fine and others didn't light up at all. In the end one if not more got burned.

So I'm here asking if anyone can tell me a way to figure out how it works.
I would appreciate the help!

You could check from where you have bought it. Maybe they have datasheet.
I found one similar, but before you must check if everything is the same and then do testing with power. LuckyLight


Arduino HTTPClient passing string to variable For some reason I can't seem to pass a simple string from one variable to another. Below is my code:

  HTTPClient http; // Declare an object of class HTTPClient
  http.begin(address); // Specify request destination
  int httpCode = http.GET(); // Send the request

  Serial.println("String: " + http.getString());

  String prp = http.getString();
  Serial.println("temp string: " + prp);

It prints out:

  String: < ! DOCTYPE HTML>
  26

  temp string:

Why doesnt my string get correctly passed on to my temporary string variable?

Tom

The getString() method calls writeToStream which is documented write all  message body / payload to Stream. It writes all the data of the http response to he output and doesn't store them internally. The next call has nothing to read because the first call to getString() put everything out.


Powering Infrared and Sonar sensors using BEC I'm new to Arduino. I'm using Arduino Mega 2560 board & MATLAB Simulink-Arduino support package and trying to integrate Maxbotix Sonar and Sharp IR sensor for my class project. When I powered single US sensor from Arduino 5V output, the readings are fine. However, when I tried to power IR sensor in parallel with US sensor, IR readings are fine but US readings fluctuate.

So, I tried powering the sensors using BEC (5V-3A). The readings for both sensors are fluctuating(extremely noisy). From the specification mentioned by manufacturers, Maxbotix US sensor draws 2mA of current, whereas IR sensor averagely draws 20mA. Is there any way to solve this problem?

Thank you.

I've managed to solve the problem. When external power supply is used to power multiple sensors, connect the GND of that supply with that of the Arduino GND input. For more details, refer to the link below.

http://www.thebox.myzen.co.uk/Tutorial/Power_Supplies.html


Is it possible to generate an exact 15 kHz clock pulse using an Arduino? I want to generate a 15 kHz pulse with an Arduino using Timer1, but the problem is that if we want a 15000 Hz clock we need to initialize the timer with 1/15000 seconds or 66.66 microseconds, but we can only pass integers without any decimal precision in the Timer1.initialize(66); function which generates a frequency of 15155 Hz.
So is it possible by any other means to generate an exact 15000 Hz or frequencies between 15000 Hz - 15155 Hz?
#include <TimerOne.h>

void setup() {
  pinMode(9,OUTPUT);
  Timer1.initialize(66);  // Frequency, 100 µs = 10 kHz
  Timer1.pwm(9,255);
}

void loop() {}

You can get pretty close if you program Timer 1 directly (not
through the library), and have it run with the prescaler set to 1.
Ideally, you want the period of the timer in clock cycles to be:
F_CPU / 15 kHz = 16,000 kHz / 15 kHz ≈ 1066.67 CPU cycles
If you round this to the nearest integer, you get
F_CPU / 1,067 = 16,000 kHz / 1,067 ≈ 14.9953 kHz
This is about 0.03% too slow, well within the tolerance of the ceramic
resonator clocking the Uno.
Here is my attempt at this. I have tested it.
constexpr float PWM_FREQUENCY = 15e3;  // 15 kHz
constexpr uint16_t PERIOD = round(F_CPU / PWM_FREQUENCY);

void setup() {
    // Configure Timer 1 for 15 kHz PWM on pin 9 = PB1 = OC1A.
    DDRB  |= _BV(PB1);    // set pin as output
    TCCR1B = 0;           // stop timer
    TCCR1A = _BV(COM1A1)  // non-inverting PWN on OC1A
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS10);   // clock @ F_CPU
    ICR1   = PERIOD - 1;  // period
    OCR1A  = PERIOD / 4;  // duty cycle
}

void loop(){}


Arduino starter kit servo is shaking In the example of the arduino starter kit the point is to use a potenciometer to control a servo.

The code is

angle = map(potVal, 0, 1023, 0, 179);

The output in the serial

potVal: 1023, angle: 179
potVal: 1015, angle: 177
potVal: 1023, angle: 179
potVal: 1016, angle: 177
potVal: 1023, angle: 179
potVal: 1023, angle: 179

I noticed that the servo is shaking like trying to go passing over the 179, when it is suppose to use an angle max 180º (0-179)

What could be the problem?

If the problem is due to jittery pot readings, you may want to smooth the potval data sequence by code like the following, where rawreading stands for what you just read from the potentiometer's input line.

potval = alpha*potval + (1-alpha)*rawreading;

Set alpha to a number (eg 0.8 or 0.9 or 0.95 etc) between 0 and 1.  alpha represents the fraction of the old value that you retain, and  1-alpha represents the fractional influence of the new raw reading.   alpha closer to 1 causes smoother but slower response.

If you prefer integer arithmetic for faster or smaller code, then represent alpha as a ratio of integers.  For example:

potval = (potval*12 + rawreading)/13;

The technique mentioned above is called exponential smoothing or  exponential moving average.


Timer to control 1.5V clock I want to make either an alarm clock or countdown timer whose alarm is loud enough to notice, but soft enough to not wake me up when asleep. My idea is to use the sound of an analog clock that I have - powered by a single AA 1.5V battery. I like this sound. So, I'd like to create an alarm or a timer that can turn on the power to this analog clock for a few minutes at least. Ideally, it would be something I could use daily for a couple hours without replacing the timer/alarm battery too often.

I've looked at these programmable relay timers: http://www.amazon.com/dp/B00P0TZ5CY/ but the voltage seems kindof overkill.

I've also considered an arduino board, but I'd like to be able to set the time on the device without plugging it into a computer.

I'm a developer, so I could do arduino programming if needed, but I don't know much about circuitry & hardware. I've also never done an arduino project, so I'm starting from 101.

Any ideas where I could start? The timer I mentioned above would be perfect if it didn't require 12V power. My knowledge is limited, so maybe that's less of a big deal than I think.

I suggest a simple setup (similar to my temperature and humidity sensor but less complex).

You can run from 3 x AA batteries, and have an RTC clock to keep track of the time. You can use a MOSFET to turn on your analog clock when required.

The processor can be asleep most of the time, using the watchdog timer to wake up and check the time from the RTC. Don't use an Arduino "board" unless you are running from a wall-wart because the voltage regulator, USB interface, and power LED, will consume too much power.


Parse data from sensor without delimeters Im using a variant of Arduino Due embedded on a ARM (Udoo). And I have connected a Medlab SPO2 Pearl 200 sensor to Serial1.

Im just trying to parse input from Serial1 to Serial, in a human-readable format (Hexadecimal).

The protocol is described in this image:

And using this Arduino code I reveice two times the "no finger detected line"

int lineLength = 16;
int spo2read[16];
int readed = 0;
 if (Serial1.available()) {
    int inByte = Serial1.read();
    if (readed < lineLength) {
      spo2read[readed] = inByte;
    }
    readed++;
    if (readed == lineLength) {
      Serial.print("SPO2: ");
      for (int i = 0; i <= lineLength; i++) {
        Serial.print(spo2read[i], HEX);
        Serial.print( delimeter);
      }
      Serial.println("");

      readed = 0;
    }

  }

Output with no finger is:

SPO2: A,FB,2,F9,0,FA,0,FC,A,FB,2,F9,0,FA,0,FC,0,

Buf if I put my finger, all is messed up:

SPO2: 7C,74,6B,62,5A,51,4A,42,3B,34,30,2E,2F,30,31,33,0,
SPO2: 36,38,3B,3E,3D,3C,3C,3B,3B,38,34,2F,2C,2B,2B,29,0,
SPO2: 24,21,1E,1D,1E,1E,1F,20,22,24,26,28,2B,2D,30,32,0,
SPO2: 35,37,39,3C,3E,40,42,44,45,4A,4F,53,55,57,59,5C,0,
SPO2: 5E,60,61,F9,0,FA,0,FC,1A,FB,0,F8,62,62,62,63,0,

Sensor doesn't sends a \n or \r so I don't know exactly how to parse the data

actually I don't think it is all mixed up

as per geometrikal use the markers to parse the data stream

I believe your above sample data started mid-stream during the 0xF8 of the wave form.

F8,...
...,7C,74,6B,62,5A,51,4A,42,3B,34,30,2E,2F,30,31,33,0,36,38,3B,3E,3D,3C,3C,3B,3B,38,34,2F,2C,2B,2B,29,0,24,21,1E,1D,1E,1E,1F,20,22,24,26,28,2B,2D,30,32,0,35,37,39,3C,3E,40,42,44,45,4A,4F,53,55,57,59,5C,0,5E,60,61
F9,0
FA,0
FC,1A
FB,0
F8,62,62,62,63,0,...

I believe reading this as a finite length does not portray the data for easy interpetation. Given that 0xF8 is a variable length protocol.

Where the reparse of your data initially appears to be legitimate parse.

That said I do read the SPO2, Pulse as zero. Where it may be likely the sensor has not finished its reading and auto gain cycles.


Is this the right way of using an RF communication? I have a 433Mhz Superheterodyne receiver and a hand set remote of similar frequency, I'm using the RC-Switch library and I couldn't find a better way than using the "numbers" that I'm receiving like this:

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
  pinMode(13, OUTPUT);
}

void loop() {
  if (mySwitch.getReceivedValue() == 7264305) {
    digitalWrite(13, LOW);
  }
  if (mySwitch.getReceivedValue() == 7264308) {
    digitalWrite(13, HIGH);
  }
  if (mySwitch.getReceivedValue() == 7264306) {
    mySwitch.resetAvailable();
  }
}

Is there any other (better?) way than just using the "numbers" simply like that or everyone are using their remote commands like I'm using?

Credits for this answer are mainly for jsotola (see his remarks above). But I want to show an alternative to the if statements, and a way to get the last 4 bits:

In case you want to check for the least significant bits, use ((mySwitch.getReceivedValue() & 0xFFFFF0)
TO check for the least significant four bits (the data you want to act upon), use ((mySwitch.getReceivedValue() & 0xF)
Use a switch statement instead of the if statement; also in theory (I don't know the code of mySwitch.getReceivedValue() does not need to be executed multiple times.

So you get something like this:

void loop()
{
  unsigned long receivedValue = mySwitch.getReceivedValue(); // Call function only once

  if ((receivedValue & 0xFFFF0) == 0x6ED830)
  {
    // Process action
    switch (receivedValue & 0xF)
    {
    case 0x5:
      digitalWrite(13, LOW);
      break;

    case 0x8:
      digitalWrite(13, HIGH);
      break;

    case 0x6:
      mySwitch.resetAvailable();
      break;

    default: // All other values
      break; // Ignore
  }
}


Beginner here. Which arduino revision should i buy? I have no idea what difference is there between the revisions and how it affects me. I have a pdf and this pic was in there:

My questions

which arduino revision is this?
Does it matter which revision i    buy?

That looks like an UNO R2, the type with DIP micro controller (you can extract it and replace it with another one, in case of problems).
The R3 version is probably the best choice to get started.
You might want one that has a connector where this one has only the 3x2 empty pads on the top left (close to the vertical writing AREF).
Have a look on ebay/aliexpress/amazon. You can find it for as little as $5-$6. Just search for UNOR3, if you elect to buy this type.