text:
If any kind of character gets loaded into a string, what do I use for an end-of-line character?
I have an Arduino project that is converting floats to characters and then transferring those characters via the serial to a Python program. This is a portion of the Arduino code:
#define MEM_LEN (16 * 4 * 4) + 1
uint8_t dataBuf[MEM_LEN];

typedef union {
  float f;
  uint8_t b[4];
} cvt_t;

cvt_t cvt1;

// set up sensor stuff
MLX90621 sensor;
 .
 .
 .

void loop() {
    sensor.measure(); //get new readings from the sensor
    count = 0;
    for(uint8_t y=0;y<4;y++){ //go through all the rows
      for(uint8_t x=0;x<16;x++){ //go through all the columns
        cvt1.f = sensor.getTemperature(y+x*4); // data at position x/y
        dataBuf[count + 0] = cvt1.b[0];
        dataBuf[count + 1] = cvt1.b[1];
        dataBuf[count + 2] = cvt1.b[2];
        dataBuf[count + 3] = cvt1.b[3];
        count += 4;
      }
    }
    dataBuf[MEM_LEN - 1] = '\n'; // not a good delimeter
    Serial.write(dataBuf, MEM_LEN);
}

The problem is that float conversion loads any and all characters into dataBuf, so I don't have a good delimiter or "end-of-line". When the Python program ingests the incoming string, there's nothing to use to know it's received a complete frame. I don't want the Python to just count characters to know when it's received a frame. No good delimiter - what should I do?

Generally the method to ensure binary data is correctly decoded is to have some form of header and then a checksum. While the header may appear in the data the chances of the correct checksum also being randomly in the data at the correct point is fairly slim. The longer the header and checksum the lower the probability of invalid data somehow getting accepted.
The header could be as simple as a 1 or 2 byte fixed pattern or could be a fixed pattern followed by a message ID and a length.
The checksum is normally 16 bits, that means that if the system got out of sync somehow and then header happened to appear in the data before the next real header the invalid data has a 1 in 65,000 chance of being accepted.
Exact probabilities of invalid data being accepted depend upon the packet lengths but assuming random data then for a 16 bit header with a 16 bit checksum and 32 bits of data it's in the region of a 1 in 4 billion chance of allowing incorrect data in. A 32 bit header + 16 bit checksum increases that something like 1 in 100 trillion. At that point you've got more chance of winning every lottery in the world while being simultaneously struck by lightning and a meteor.
Data is rarely truly random, if you can use a header that is less likely to appear in the data then you can improve things further.
Since you only have 4 bytes of data I'll assuming you want to keep things simple and don't want to add a dozen bytes of overhead to each value. A header of 0xff is a good bet, if that was the first byte of a float the value will be in the -10E38 region.
If you use a two byte header the 0xffc0 is a good choice, that would be NaN, an invalid floating point value. Since this means the first two bytes of your data aren't going to match the header this greatly reduces the chance of the header appearing in the data. Your checksum could then be a simple xor of the next for bytes.
So your data packet ends up being:
0x ff c0 <d1> <d2> <d3> <d4> <d1^d2^d3^d4>
One other alternative approach is through the use of escape codes/characters. This is a special value that never appears on it's own in the data. For example let's define our escape character as being 0xFF and the header value as being 0xC0 C0.
In that situation 0xC0 C0 is always the start of a data packet.
If 0xC0 happens to appear in the data we insert the escape character in front of it. Similarly if the escape character happens to appear in the data we insert an extra escape character in front of it.
e.g. for a data value of 0x11 0xC0 22 FF we would send 0xC0 C0 11 FF C0 22 FF FF or <header> <d1> <escape> <d2> <d3> <escape> <d4>
For hopefully obvious reasons whenever possible the header and escape characters should be values that rarely occur in the data.
This approach has the advantage that if designed correctly there is no risk no matter how small of invalid data getting through and (on average) it has a lower overhead in terms of bytes sent, most of the time all you need to add is the 2 byte header. The down side is that inserting and removing the escape characters can get complex and messages are no longer a fixed size, the length depends on the data content. This indeterminacy in message length can potentially cause problems depending upon the application.
To be honest for a single floating point number text may be easier. Binary is more efficient, it's less CPU load and less data to send, but for something as short as a single number the savings aren't normally worth the extra complexity.

Good answer. You could also mention the possibility of escaping bytes in the data stream - maybe an 0xFF or 0xC0 in the data stream must be preceded by an escape character (and escape characters must be doubled up) so there is zero chance you see 0xFF 0xC0 in the data (you'd get, say 0x1B 0xFF 0x1B 0xC0, and every 0x1B by itself becomes 0x1B 0x1B). May make encoding/decoding a little harder, but the data integrity would be more reliable.

@Majenko Good point. I'll add that.

most of the time all you need to add is the 1 byte header. - actually having escape characters relies on always having at least a two byte header - that way the header is the only place where 0xC0 is guaranteed not to be preceded by 0xFF. If you have only one byte header and the final byte of the previous packet is 0xFF it looks like an escaped mid-data byte. You need a two-byte sequence which is 100% guaranteed to be the header because the escape character breaks that sequence up in the data portion.

@Majenko Fixed. Although you could still get away with a one byte header if you made the escape sequence for FF to be something like FF FE. That way FF C0 would only ever be an escape sequence and never data followed by header since no valid data symbol would end in FF. However that means modifying data values rather than just padding them which is getting even messier to implement.

Great answer, and by the way I'm just just sending a single floating point - notice it's in a loop that fills the dataBuf[] array with 256 characters and that gets transmitted.

Framing binary messages is not as simple as choosing a delimiter.
Counting the characters could be an option, but you need some way to
check that your reception has not gotten out of sync. You could for
example send messages that looks like:
struct Message {
    uint32_t magic;
    uint8_t data[MEM_LEN];
    uint16_t crc;
};

Where magic in a magic number, i.e. a random but fixed value that
is very unlikely to happen by accident, and you end the message with a
CRC. On the Python side, you check that both the magic number and
the CRC are OK. If they are not, you have a communication error, but you
can re-synchronize by looking for the next occurrence of the magic
number.
Another option is to choose both a delimiter (say, ASCII 10 = LF =
'\n') and an escape character (say, ASCII 92 = backslash = '\\'). On
the sending side, you prefix by the escape character every accidental
occurrence of either the escape character or the delimiter:
void send_byte(uint8_t c)
{
    if (c == '\\' || c == '\n')
        Serial.write('\\');  // prefix by escape character
    Serial.write(c);
}

and on the Python side you do the reverse operation. The only issue with
this approach is that your messages are not constant size anymore.

Using a version of Pascal strings could work: the first byte of the buffer is the number of characters, the rest of the sequence the bytes.
Or convert the numbers to ASCII strings. Inefficient but you'll have your '\0' delimiter.

Doesn't solve the problem of how to identify the start and end of data in a datastream. In fact it just makes it worse.


text:
Help with my DHT22 sensor and using GET request
For some reason using my DHT22 sensor I keep getting "NaN". I have tried using older versions of the DHT22 sensor library as suggested by a few of my searches, but it still doesn't fix the issue.
Also I can't get it to work with the GET request portion. Any help would be greatly appreciated.
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <ESP8266WiFi.h>
#include <Phant.h>
#include <ESP.h>

#define DHTPIN 2
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "Myyyyyyh";
const char* password = "Ixxxxx1";
const char* host = "script.google.com";

//*****example address
//https://script.google.com/macros/s/AKfycbyNsFc87GQmRP3GnWoTzK6/exec?tag=test&value=8
const String gardenchart = "/macros/s/AKfycbyNnWoTzK6/exec?";
const byte sleeptime = 1;
const byte NUM_FIELDS = 5;
const String fieldNames[NUM_FIELDS] = {"ghumidity", "gtemp", "light", "otemp", "wtemp"};
String fieldData[NUM_FIELDS];

void setup() {
  Serial.begin(115200);
  delay(10);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
  fieldData[0] = 1;
  postdata();
  ESP.deepSleep(sleeptime * 60 * 1000000, WAKE_RF_DEFAULT);
}

void loop() {
  delay(50);
}

void postdata() {
  fieldData[0] = dht.readHumidity();
  fieldData[1] = dht.readTemperature(true);
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect (host, httpPort)) {
    return;
  }
  for (int i=0; i<NUM_FIELDS; i++) {
    client.print("GET ");
    client.print(fieldNames[i]); client.print("&value=");
    client.print(fieldData[i]); client.print(" HTTP/1.1");
    client.println("Host:"); client.print(host);
    Serial.print(fieldNames[i] + fieldData[i]); delay(500);
  }
  client.println("Connection: close");
}

The Adafruit DHT library causes a shortcut on the signal line. That can be a problem for Arduino boards, but it is a big problem for the ESP8266.
Issue: DHT init sequence wrong #48
I don't know what is a bigger problem, the shortcut in the code or Adafruit not fixing it.
Why do you mention the Arduino Uno with a label ?
For the "GET" you should find a good working example.
The DHT22 is not very good. There are better sensors with a normal I2C interface, for example the HTU21D-F or the BME-280. This is about a great test: Hackaday: Humidity Sensor Shootout. The BME-280 is the undisputed winner.

I'll look for a BMW, for the GET request it was working when I was using sparkfun's data hosting.  I am switching to posting to my Google sheet and that's when something isn't working quite right.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
L298N DC Motor Driver Conundrum
I am trying to control a single DC motor using a L298N DC Motor Driver. I have a 12V motor plugged into Out1 and Out2, a 7.4 volt battery wired to the 12v in and common ground, a m/m common ground going from the arduino grnd to the L298N common ground, and I have IN1 and IN2 connected to digital pins 2 and 3. I am powering the Uno with USB. I am also running a m/m wire from the Uno 5v to the L298N (I shouldn't have to) in order to power the L298N

I am using a basic code to test the motor
    int motor1pin1 = 2;
int motor1pin2 = 3;

void setup() {
  // put your setup code here, to run once:
  pinMode(motor1pin1, OUTPUT);
  pinMode(motor1pin2, OUTPUT);

}

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

  delay(1000);

  digitalWrite(motor1pin1, LOW);
  digitalWrite(motor1pin2, HIGH);

  delay(1000);
}

If I wire the 7.4v lipo battery directly to the L298N the red led doesn't go on. It only goes on when I run a 5V wire from the Uno to the L298N. Yet still I get no reaction out of the motor. However if I run a ground from the arduino directly to the out1 or out2, the motor turns in that one direction. Anyone have an idea what I am doing wrong?

I don't see any problem in your wiring and code. The only thing that's not exactly optimal is that the voltage provided by the battery is not just high enough. The L298N's supply voltage is supposed to be at least 2.5V above the logic supply voltage (the logic HIGH level to be precise). That would make 7.5V - you only have 7.4V.
That sounds like a tiny gap, but the battery voltage might drop further under load.
"run a ground from the arduino directly to the out1 or out2" - you should not do that as this can create a short circuit, depending on the state of the EN and IN pins.

According to my datasheet, the L298N only requires that the input voltage be above 6V when the 5V regulated output is being used - otherwise it is 5-35V

It sounds like you don't have the +5V regulator output enabled, which means you DO need the +5V from the UNO.  From the datasheet:  "The module includes an onboard regulator. When enabled by the jumper, +5V is provided as an output.  When disabled, a separate +5V input is required to control the logic level circuitry of this module"

Assuming you have the ENABLE jumper in place to enable motor control, then you should be able to drive the motor full-speed forwards or backwards without the UNO code at all - just use the +5V and GND lines from the UNO as 'logic level probes'.
According to my logic table a LOW (GND) on L1 and a HIGH (+5v) ON L2 will cause a motor connected to OUT1/2 to rotate one way, and reversing the logic on L1/2 will cause it to rotate in the other - at full speed (full speed being whatever the battery supply voltage can provide).
Once you have the motor(s) turning properly, THEN you can add the complexity of trying to control the speed and direction programmatically.  The code you showed does exactly the same as just using the +5 & GND leads as probes - with a 1 second delay between reversals.
Hope this helps
Frank

I agree with @starship15 you need to wire the enable pins as you (supposed the picture Is yours) removed the enable jumpers, so you have to add a wire to your Arduino (for each Out) and activate them programmatically.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Pulse period capture with SAMD21

I need to count the number of pulses in a moving window (e.g. last 60 seconds) using as less CPU time as possible.
The first step is to use TCC to capture pulse period.
The pulses arrive randomly at PB02 and the average frequency is about 20-100 counts per minute.

Attempt
According to datasheet TCC has Period and Pulse-Width (PPW) Capture Action
External pulse(PB02)-->EIC-->Event channel-->Event user(TC)
volatile uint32_t T;
volatile uint32_t count;
void setup() {
  Serial.begin(9600);
  while (!Serial);
  Serial.println("init");
  md_setup();
  // put your setup code here, to run once:

}

void loop() {
  Serial.println(T);
  Serial.println(count);
}

void md_setup() {
  //PM
  REG_PM_APBCMASK |= PM_APBCMASK_EVSYS;
  REG_PM_APBCMASK |= PM_APBCMASK_TCC0;
  Serial.println("PM done");

  //GLCK
  REG_GCLK_GENDIV = GCLK_GENDIV_DIV(8) |
                    GCLK_GENDIV_ID(5);
  while (GCLK->STATUS.bit.SYNCBUSY);
  REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                     GCLK_GENCTRL_GENEN |         // Enable GCLK 5
                     GCLK_GENCTRL_SRC_OSCULP32K |   // Set the clock source to 32K
                     GCLK_GENCTRL_ID(5);          // Set clock source on GCLK 5
  while (GCLK->STATUS.bit.SYNCBUSY);
  REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |
                     GCLK_CLKCTRL_GEN_GCLK5 |
                     GCLK_CLKCTRL_ID_TCC0_TCC1;
  while (GCLK->STATUS.bit.SYNCBUSY);
  Serial.println("GCLK done");

  //PORT
  //REG_PORT_PMUX1 |= PORT_PMUX_PMUXEN;
  //REG_PORT_PINCFG1 |= PORT_PINCFG_PMUXEN;
  REG_PORT_WRCONFIG1 = PORT_WRCONFIG_PINMASK(2) |           //select pin PB02 (EIC02)
                       PORT_WRCONFIG_PMUXEN |               //enable peripheral function
                       PORT_WRCONFIG_INEN |                 //input mode
                       PORT_WRCONFIG_PMUX(0) |              //select peripheral function A
                       PORT_WRCONFIG_WRPMUX |               //Write to PMUX register
                       PORT_WRCONFIG_WRPINCFG |             //Write to PINCFG register
                       (0 << 31);                           //Select lower pins
  Serial.println("PORT done");

  //EIC
  REG_EIC_EVCTRL |= EIC_EVCTRL_EXTINTEO2;                                 // Enable event output on external interrupt 2
  REG_EIC_CONFIG0 |= EIC_CONFIG_SENSE2_RISE;                            // Set event detecting rise
  REG_EIC_INTENCLR = EIC_INTENCLR_EXTINT2;                                // Clear the interrupt flag on channel 2
  REG_EIC_CTRL |= EIC_CTRL_ENABLE;                                        // Enable EIC peripheral
  //while (EIC->STATUS.bit.SYNCBUSY);
  Serial.println("EIC done");

  //EVSYS
  REG_EVSYS_CHANNEL |= EVSYS_CHANNEL_EDGSEL_NO_EVT_OUTPUT |                       //no output
                       EVSYS_CHANNEL_PATH_ASYNCHRONOUS |                          //async path
                       EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_2) |           // Select EIC2
                       EVSYS_CHANNEL_CHANNEL(1);                                  //Channel 1
  REG_EVSYS_USER |=  EVSYS_USER_USER(EVSYS_ID_USER_TCC0_EV_1) |                   //Select USER = TCC0
                     EVSYS_USER_CHANNEL(2);                                       //Select Channel 1 (N+1)
  //REG_EVSYS_CTRL |= CTRL_SWRST;
  Serial.println("EVSYS done");

  //TCC0
  REG_TCC0_CTRLA &= ~TCC_CTRLA_ENABLE;            // Disable TCC0 peripheral
  REG_TCC0_CTRLBCLR |= TCC_CTRLBCLR_DIR;          // Clear DIR bit to count up
  while (TCC0->SYNCBUSY.bit.CTRLB);               // Wait for (write) synchronization
  REG_TCC0_EVCTRL |= TCC_EVCTRL_TCEI0 |           // Enable the TCC event 0 input
                     //TCC_EVCTRL_TCEI1 |         // Enable the TCC event 1 input
                     TCC_EVCTRL_MCEI1 |           // Enable the match or capture channel 1 event input
                     TCC_EVCTRL_MCEI0 |           // Enable the match or capture channel 0 event input
                     TCC_EVCTRL_EVACT1_PPW;       // Select PPW
  REG_TCC0_CTRLA |= TCC_CTRLA_CPTEN1 |              // Enable capture on CC1
                    TCC_CTRLA_CPTEN0 |              // Enable capture on CC0
                    TCC_CTRLA_PRESCALER_DIV1;
  REG_TCC0_INTENSET = TCC_INTENSET_MC1 |            // Enable compare channel 1 (CC1) interrupts
                      TCC_INTENSET_MC0;             // Enable compare channel 0 (CC0) interrupts
  REG_TCC0_CTRLA |= TCC_CTRLA_ENABLE;             // Enable TCC0
  while (TCC0->SYNCBUSY.bit.ENABLE);              // Wait for synchronization

  NVIC_SetPriority(TCC0_IRQn, 0);
  NVIC_EnableIRQ(TCC0_IRQn);
  Serial.println("TCC done");
}

void TCC0_Handler()
{
  count++;
  if (TCC0->INTFLAG.bit.MC0)
  {
    T = TCC0->CC[0].reg;
  }
  if (TCC0->INTFLAG.bit.MC1);
}

Problem

The result (T,count) is always zero.
if while (EIC->STATUS.bit.SYNCBUSY); is uncommitted, the execution will lock up there.

I've been playing around with something very similar; not sure if the code does exactly what you want, but maybe it will help you.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Why NVIC_EnableIRQ handler function only run once?
I have a code that spit out random number when the ISR register is ready:
#define TRNG_KEY  0x524E47
uint8_t lut[10] = {0xF6, 0x12, 0xAE, 0xEC, 0xD8, 0x7C, 0x7E, 0xE0, 0xFE, 0xFC};
uint32_t msk = 0x1FE;

void setup()
{
  Serial.begin(9600);
  PIOC->PIO_PER = msk;
  PIOC->PIO_OER = msk;
  PIOC->PIO_OWDR = ~msk;

  PMC->PMC_PCER1 = PMC_PCER1_PID41;
  TRNG->TRNG_CR = TRNG_CR_ENABLE | TRNG_CR_KEY(TRNG_KEY);
  TRNG->TRNG_IER = 1 << 0;
}

void loop()
{
  if (TRNG->TRNG_ISR == 1) {
  PIOC->PIO_ODSR = lut[REG_TRNG_ODATA % 10];
  }
  delay(500);
}

The code above works. However, when I tried to switch to internal interrupt:
#define TRNG_KEY  0x524E47
uint8_t lut[10] = {0xF6, 0x12, 0xAE, 0xEC, 0xD8, 0x7C, 0x7E, 0xE0, 0xFE, 0xFC};
uint32_t msk = 0x1FE;

void setup()
{
  Serial.begin(9600);
  PIOC->PIO_PER = msk;
  PIOC->PIO_OER = msk;
  PIOC->PIO_OWDR = ~msk;

  PMC->PMC_PCER1 = PMC_PCER1_PID41;
  TRNG->TRNG_CR = TRNG_CR_ENABLE | TRNG_CR_KEY(TRNG_KEY);
  TRNG->TRNG_IER = 1 << 0;

  NVIC_EnableIRQ(TRNG_IRQn);
}

void loop()
{

}

void TRNG_Handler(void) {
  PIOC->PIO_ODSR = lut[REG_TRNG_ODATA % 10];
}

The code only spit out one random number and then freezes, indicating TRNG_Handler(void) was only executed once. I cannot figure out why.
Thanks in Advance !

I presume delay will internally wait on some millisecond variable to be incremented, and that only happens in some timer ISR, that you may be blocking by delaying in the first place. You might want to setup a hardware timer in the needed interval or use a flag inside loop to toggle a boolean "it's okay to update" value every 500ms, that is then reset in the TRNG_Handler.

Hm actually I may be partially wrong. The datasheet says This interrupt is set when a new random value is available and is cleared when the status register is read(TRNG_SR register). The SR is probably a typo and means ISR. Can you try and read the status register the same as in https://github.com/davecheney/trng/blob/master/arduino-due-trng/arduino-due-trng.ino#L16 ?

That delay() was a typo, sorry. It's not in my actual code.

Two things:

Never use delay() inside an ISR. On some systems it may work, but on most it will just block. It's bad practice to have your ISRs run for more time that absolutely needed anyway.
You need to read the status register for the TRNG to clear the interrupt flag. You're doing that in your first code sample with if (TRNG->TRNG_ISR == 1) {.

Isn't if (TRNG->TRNG_ISR = 1) {. an assignment?  TRNG->TRNG_ISR is not read -   1 is assigned to it. I think it is intended to be a comparisson. That's an error in the first example. But the condition was always true, and the generator is fast enough to gnerate a number every 500ms  it seems ;-).

@PeterPaulKiefer You might be right...  The end result would probably be reading the register before writing the changed content back.


text:
Why impedance between I/O pin and ground drops when Arduino is not powered
I have a 4KHz 5V pulsed signal connected to Arduino UNO pin2 (ISR).

When the board is powered, the pulse is attached to ISR rising edge, and is working as intended.

I don't know the output impedance of the pulsed signal, but when the board is not powered, the pulse drops to 2V.

The resistance between pin2 and ground is about 500K when not powered. The resistance is infinite when powered.

The pulsed signal does NOT drop when connected to a 500K resistor.

Question:

What is the cause of the signal drop?
How to prevent it ? (It's not practical to disconnected the signal from Arduino, but I can make sure Arduino is always powered. How to deal with transient situations like reset ?)

Thanks in advance !

you prevent it by not sending a signal into an unpowered arduino ... you should not be doing that in the first place because you can blow out the input protection diodes

The Atmega328p (which is used in the Un[ (and actually all other AVR microcontrollers) has clamping diodes in the input hardware to protect it from overvoltage (above Vcc). When not powered, Vcc is at the same level as ground, so any positive voltage on an input pin is above Vcc. The protection diodes get conductive to protect the input hardware. Note, that the diodes can be fried easily, if a too high current flows through them. You should prevent that.
How to prevent it? By not doing it. You should never provide a voltage on an input of an unpowered chip (like any chip). If you really need to unpower the Arduino, you can prevent the voltage from reaching the input pin with a MOSFET.

I can make sure Arduino is always powered, but Arduino will briefly reset when programming or initiating serial com.

@7E10FC9A reset is not unpowered

Adding a resistor (for example 10kΩ) between the signal and the Arduino pin is a reasonable compromise.

I do that all the time but I also read the data sheet. There is a limit on the amount of current you can inject into a processor pin or in total, that is on the data sheet. Also be aware when you inject current you can cause VCC to go out of specification unless it has enough load to support it. Typically I limit my input current to less than 1mA with a resistor. This also protects me in case I get a negative excursion.  For a 5V system that resistor is 5K or greater, with 10K being very common. The input resistance reading is only good to check if the pin is shorted. It is connected to an active junction of a FET and a few Diodes. The voltage and or polarity of your ohm meter will definitely affect the reading. The resistance that may be there is due to  chip resistance, bonding wire resistance etc. all low in value.


text:
Compile Problem with RFDuino RFD22301
I have the following setup:
- Arduino IDE for Mac 1.8.5
- RFDuino RFD220301
- CP2102 USB to UART connector
- Board set to "RFduino"
- port set correctly (but shouldn't matter as it is a compile error)
- Programmer: AVRISP mkII
When trying to compile an example script using BLE (Such as AdvertisementContinuous) I get the following error
arm-none-eabi-g++: error: /var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_188605/core/syscalls.c.o: No such file or directory
Any ideas?
Here's the -v log:
Arduino: 1.8.5 (Mac OS X), Board: "RFduino"

/Applications/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/julian/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/julian/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/julian/Documents/Arduino/libraries -fqbn=RFduino:RFduino:RFduino -ide-version=10805 -build-path /var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200 -warnings=none -build-cache /var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_cache_722169 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arm-none-eabi-gcc.path=/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1 -verbose /Users/julian/Code/openSleep/embedded/sleepduino/sleepduino.ino
/Applications/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/julian/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/julian/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/julian/Documents/Arduino/libraries -fqbn=RFduino:RFduino:RFduino -ide-version=10805 -build-path /var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200 -warnings=none -build-cache /var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_cache_722169 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arm-none-eabi-gcc.path=/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1 -verbose /Users/julian/Code/openSleep/embedded/sleepduino/sleepduino.ino
Using board 'RFduino' from platform in folder: /Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3
Using core 'arduino' from platform in folder: /Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3
Detecting libraries used...
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin  -w -x c++ -E -CC -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sketch/sleepduino.ino.cpp" -o "/dev/null"
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin  -w -x c++ -E -CC -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sketch/sleepduino.ino.cpp" -o "/dev/null"
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin  -w -x c++ -E -CC -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE/RFduinoBLE.cpp" -o "/dev/null"
Generating function prototypes...
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin  -w -x c++ -E -CC -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sketch/sleepduino.ino.cpp" -o "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/preproc/ctags_target_for_gcc_minus_e.cpp"
"/Applications/Arduino.app/Contents/Java/tools-builder/ctags/5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/preproc/ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin -MMD -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sketch/sleepduino.ino.cpp" -o "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sketch/sleepduino.ino.cpp.o"
Compiling libraries...
Compiling library "RFduinoBLE"
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin -MMD -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE/RFduinoBLE.cpp" -o "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/libraries/RFduinoBLE/RFduinoBLE.cpp.o"
Compiling core...
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -c -g -Os -w -std=gnu++11 -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions -fno-builtin -MMD -mcpu=cortex-m0 -DF_CPU=16000000 -DARDUINO=10805 -mthumb -D__RFduino__ "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/cores/arduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/RFduino/include" "-I/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/system/CMSIS/CMSIS/Include" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino/variant.cpp" -o "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/core/variant.cpp.o"
Using precompiled core
Linking everything together...
"/Users/julian/Library/Arduino15/packages/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-g++" -Wl,--gc-sections --specs=nano.specs -mcpu=cortex-m0 -mthumb -D__RFduino__ "-T/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino/linker_scripts/gcc/RFduino.ld" "-Wl,-Map,/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sleepduino.ino.map" -Wl,--cref -o "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sleepduino.ino.elf" "-L/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200" -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/core/syscalls.c.o" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/sketch/sleepduino.ino.cpp.o" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/libraries/RFduinoBLE/RFduinoBLE.cpp.o" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/core/variant.cpp.o" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino/libRFduinoSystem.a" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino/libRFduino.a" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino/libRFduinoBLE.a" "/Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/variants/RFduino/libRFduinoGZLL.a" "/var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/../arduino_cache_722169/core/core_RFduino_RFduino_RFduino_96c93913732efe419124a59ff97a44c7.a" -Wl,--end-group
arm-none-eabi-g++: error: /var/folders/m6/mfwpb8b13wn4f9fvb4lhx_v40000gp/T/arduino_build_997200/core/syscalls.c.o: No such file or directory
Using library RFduinoBLE in folder: /Users/julian/Library/Arduino15/packages/RFduino/hardware/RFduino/2.3.3/libraries/RFduinoBLE (legacy)
exit status 1
Error compiling for board RFduino.

I cannot reproduce this using 1.8.3. I installed https://github.com/RFduino/RFduino in the board manager and used the https://github.com/RFduino/RFduino/blob/master/libraries/RFduinoBLE/examples/AdvertisementContinuous/AdvertisementContinuous.ino sketch. It compiles fine. Can you go into the Arduino IDE settings and activate verbose output on compiling and edit your question with that log?

So it appears solved: Using Arduino 1.6.13 I don't get the compile error. Must be an incompatibility with the RFduino Board libraries and the 1.8x IDE.


text:
Using Teensy 3.5 (Arduino) to produce USB and Hardware MIDI messages simultaneously. Help?
Currently trying to get a teensy 3.5 to spam a series of notes in a loop over USB and hardware serial, which I am pretty sure it can do.
I have a MIDI circuit set up as per the specifications here:
https://www.pjrc.com/teensy/td_libs_MIDI.html
And currently have it booping a looping grouping of notes through massive embedded in ableton over a 5 PIN DIN circuit feeding into a generic MIDI 5 Pin DIN -> USB converter.
 #include <MIDI.h>

#define HWSerial Serial1
MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
const int channel = 1;

void setup() {

  HWSerial.begin(9600);
  MIDI.begin();
}

void loop() {
  int note;
  for (note=10; note <= 127; note++) {
    MIDI.sendNoteOn(note, 100, channel);
    delay(200);
    MIDI.sendNoteOff(note, 100, channel);
  }
  delay(2000);
}

I am lead to believe that when working with the USB serial output on the teensy you simply refer to the port as 'Serial' and for the others it's 'Serial1', 'Serial2', and so on.
I have tried using serial in place of the arguments within MIDI_CREATE_INSTANCE
and also tried using MIDI_CREATE_DEFAULT_INSTANCE which should do this setup on the default serial port, which I assume is USB? (This worked fine on my arduino mega setup where I was using the 16u2 chip as a serial -> USB midi converter as per this method: https://github.com/ddiakopoulos/hiduino)
I'm just a little stumped as I have managed to get the code to compile using default instance and it appears as a midi device in windows device manager and also in ableton when I set USB Type: Serial + MIDI from arduinos tools dropdown box but does not output any notes :(
Can anyone help me get this working?
I'm currently toying with:
    #include <MIDI.h>

const int channel = 1;

void setup()
{

}

void loop()
{
  int note;
  for (note=20; note <= 63; note++) // Range was changed from 10:127 to save eardrums.
  {
    usbMIDI.sendNoteOn(note, 100, channel);
    delay(200);
    usbMIDI.sendNoteOff(note, 100, channel);
  }
  delay(2000);
}

but get
    C:\Users\Jamie\AppData\Local\Temp\arduino_build_144363/..\arduino_cache_283435\core\core_teensy_avr_teensy35_usb_serialmidi,speed_120,opt_o2std,keys_en-us_4939f5412a75a8560acb0f9e98268f02.a(pins_teensy.c.o): In function `_init_Teensyduino_internal_':

C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3/pins_teensy.c:582: undefined reference to `analog_init'

collect2.exe: error: ld returned 1 exit status

Error compiling for board Teensy 3.5.

and if I try inluding 'usbMIDI' I get
F:\GigaTech\MMMM_Beta_Code\debug\TeensyUSBMIDILoopTest\TeensyUSBMIDILoopTest.ino:1:21: fatal error: usbMIDI.h: No such file or directory

compilation terminated.

Error compiling for board Teensy 3.5.

although midiUSB is definitely installed :S

------------------------------C O N T I N U E D ----------------------------
Ok so I now have a working sketch for both USB and Hardware MIDI comms but I can't seem to get them to work simultaneously.
My code for the hardware is as shown above, and the USB method is below:
 #include <MIDI.h>

MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
const int channel = 1;

void setup() {
  MIDI.begin();
}

void loop() {
  int note;
  for (note=10; note <= 127; note++)
  {
    usbMIDI.sendNoteOn(note, 100, channel);
    delay(200);
    usbMIDI.sendNoteOff(note, 100, channel);
  }
  delay(2000);
}

I sort of assumed it would be possible to do something like this:
 #include <MIDI.h>

#define HWSerial Serial1
MIDI_CREATE_INSTANCE(HardwareSerial, Serial, MIDI); // 5 Pin DIN Out
const int channel = 1;

void setup()
{
  HWSerial.begin(9600);
  MIDI.begin();
}

void loop() {
  int note;
  for (note=20; note <= 63; note++) // Range was changed from 10:127 to save eardrums.
  {
    usbMIDI.sendNoteOn(note, 100, channel);
    MIDI.sendNoteOn(note, 100, channel);
    delay(200);
    usbMIDI.sendNoteOff(note, 100, channel);
    MIDI.sendNoteOff(note, 100, channel);
  }
  delay(2000);
}

But It doesn't seem to work.
The code compiles and uploads just fine, however, ableton only sees MIDI messages coming over the teensy usb port and not through my MIDI receiver.
I wondered if this is because the two are both being routed to my PC via a usb port but this shouldn't be a problem surely.
I have also tried assigning the USB and hardware MIDI sends to different channels but to no avail.
I would love to get these both working simultaneously.

Why are the logs full of mentions of "avr" for a board that does not use any sort of AVR chip???  Is this really bad naming and file locations in a plugin, or is the selected board configuration all mixed up?

Just use usbMidi.
#include <MIDI.h>

MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
const int channel = 1;

void setup() {
  MIDI.begin();
}

void loop() {
  int note;
  for (note=10; note <= 127; note++) {
    MIDI.sendNoteOn(note, 100, channel);
    usbMIDI.sendNoteOn(note, 100, channel);
    delay(200);
    MIDI.sendNoteOff(note, 100, channel);
    usbMIDI.sendNoteOff(note, 100, channel);
  }
  delay(2000);
}

I've been trying to do it this way as that's how I had it working with the arduino mega implementation but I just get this error:
C:\Users\Jamie\AppData\Local\Temp\arduino_build_144363/..\arduino_cache_283435\core\core_teensy_avr_teensy35_usb_serialmidi,speed_120,opt_o2std,keys_en-us_4939f5412a75a8560acb0f9e98268f02.a(pins_teensy.c.o): In function `init_Teensyduino_internal':
C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3/pins_teensy.c:582: undefined reference to `analog_init'
collect2.exe: error: ld returned 1 exit status
Error compiling for board Teensy 3.5.

I'm pretty sure there is a proper way to do this, by opening another port with very similiar implementation to the hardware output code, but cant seem to get it right

The code I posted compiles just fine for me (Arduino 1.8.1, Teensyduino 1.41, Teensy 3.5, USB: Serial+MIDI). This is the proper way. Forget everything about MIDI USB on the Mega, it is completely different from the Teensy.

Strange, I tried a literal copy / paste of that code you posted and get:
C:\Users\Jamie\AppData\Local\Temp\arduino_build_144363/..\arduino_cache_283435\core\core_teensy_avr_teensy35_usb_serialmidi,speed_120,opt_o2std,keys_en-us_4939f5412a75a8560acb0f9e98268f02.a(pins_teensy.c.o): In function `init_Teensyduino_internal':
C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3/pins_teensy.c:582: undefined reference to `analog_init'
collect2.exe: error: ld returned 1 exit status
Error compiling for board Teensy 3.5.

Try reinstalling Teensyduino. It looks like something is wrong with your core files.

Ok I will try it in your environment (With fresh installs of everything) and get back to you.

Yes, this has worked beautifully (Got held up by windows updates), I'll test tomorrow using both methods simultaneously, thanks!

So I managed to get both working sumultaneously!
It seems that no declaration of a MIDI instance is necessary for teensy MIDI over USB, and I had a small error in my code, Said function declaration should read 'Serial1' not 'Serial'.
Working code is below! :)
#include <MIDI.h>

#define HWSerial Serial1
MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI); // 5 Pin DIN Out
const int HWChannel = 2;
const int USBChannel = 1;

void setup()
{
  HWSerial.begin(9600);
  MIDI.begin();
}

void loop() {
  int note;
  for (note=20; note <= 63; note++) // Range was changed from 10:127 to save eardrums.
  {
    usbMIDI.sendNoteOn(note, 100, USBChannel);
    MIDI.sendNoteOn(note, 100, HWChannel);
    delay(200);
    usbMIDI.sendNoteOff(note, 100, USBChannel);
    MIDI.sendNoteOff(note, 100, HWChannel);
  }
  delay(2000);
}


text:
What's going wrong with my EEPROM?
I've been chipping away at a project for a long time now and I've found a serious bug.
Basically the user has an 8x8 grid, and each cell in this grid has a number of properties.
I want to be able to save all of these properties as a 'profile' within the EEPROM, and previously this worked OK but now seems to have a few bugs.
The most prominent of which is that when I save a grid to a profile (Say profile 3), and then load the next profile (profile 4, in this case) the far right column of profile 3 appears in the far left column of profile 4.
LikeWise, saving a filled in grid to profile 1, and then saving an empty grid to profile 2 causes the RIGHT hand column of profile 1 to be cleared.
It used to work great in a previous version but there was completely different hardware in place supporting the GUI making it impossible to load older versions of the code and test how it was working then.
Here is the code where I save / load profiles

#include <EEPROM.h>
#include"EEPROMAnything.h"
const int profileSize = 224; // Actually everything is only half the size you thought (WTF but ok)

void saveProfile(int profileNum)                               // saves the complete current configuration of the system to memory under a profile for later restoration
{
  tft.fillScreen(BGCOL);// Clear the screen.
  tft.setTextSize(2);
  setLine0();
  tft.print("Saving...");
  setLine1();
  tft.print(sizeof(saveConfiguration)/8); // Original
  tft.print(" Bytes");
  setLine2();
  tft.print("please wait");
//  tft.sendBuffer();

  for (int ROMRow = 0; ROMRow< 8; ROMRow++)    // Populate the ROM Structure
  {
    for (int ROMCol = 0; ROMCol < 8; ROMCol++)
    {
      saveConfiguration.ROMcellType[ROMRow][ROMCol]      = cellType[ROMRow][ROMCol];
      saveConfiguration.ROMindexVal[ROMRow][ROMCol]      = indexVal[ROMRow][ROMCol];
      saveConfiguration.ROMMIDIVariable[ROMRow][ROMCol]  = MIDIVariable[ROMRow][ROMCol];
      saveConfiguration.ROMcellChannel[ROMRow][ROMCol]   = cellChannel[ROMRow][ROMCol];
      saveConfiguration.ROMorientation[ROMRow][ROMCol]   = orientation[ROMRow][ROMCol];
      saveConfiguration.ROMfaderGroundX[ROMRow][ROMCol]  = faderGroundX[ROMRow][ROMCol];
      saveConfiguration.ROMfaderGroundY[ROMRow][ROMCol]  = faderGroundY[ROMRow][ROMCol];
    }
  }

  EEPROM_writeAnything((profileNum*profileSize), saveConfiguration);

  delay(500);
  menuState = 1; // Go back to main menu
  menuLocatorY = 0; // Otherwise text will not show on next screen;
  updateScreen();
}
//{EEPROM_writeAnything(profileNum*profileSize, configuration);}

void loadProfile(int profileNum)                              // saves the complete current configuration of the system to memory under a profile for later restoration
{
  tft.fillScreen(BGCOL);// Clear the screen.
  tft.setTextSize(2);
  setLine0();
  tft.print("Loading...");
  setLine1();
  tft.print(sizeof(saveConfiguration)/8);
  tft.print(" Bytes.");
  setLine2();
  tft.print("please wait");

  initGrid(); // Clear any information regarding the current grid. Shouldn't really be neccesary but makes code safer.

  EEPROM_readAnything(profileNum*profileSize,saveConfiguration);
  for (int ROMRow = 0; ROMRow< 8; ROMRow++)    // Populate the ROM Structure
  {
    for (int ROMCol = 0; ROMCol < 8; ROMCol++)
    {
      cellType[ROMRow][ROMCol]      = saveConfiguration.ROMcellType[ROMRow][ROMCol];
      indexVal[ROMRow][ROMCol]      = saveConfiguration.ROMindexVal[ROMRow][ROMCol];
      MIDIVariable[ROMRow][ROMCol]  = saveConfiguration.ROMMIDIVariable[ROMRow][ROMCol];
      cellChannel[ROMRow][ROMCol]   = saveConfiguration.ROMcellChannel[ROMRow][ROMCol];
      orientation[ROMRow][ROMCol]   = saveConfiguration.ROMorientation[ROMRow][ROMCol];
      faderGroundX[ROMRow][ROMCol]  = saveConfiguration.ROMfaderGroundX[ROMRow][ROMCol];
      faderGroundY[ROMRow][ROMCol]  = saveConfiguration.ROMfaderGroundY[ROMRow][ROMCol];

      /*
      if (cellType[ROMRow][ROMCol] == 3)
      {
        customValue = orientation[ROMRow][ROMCol];
        customMessage =   indexVal[ROMRow][ROMCol];
        MIDIVariable[ROMRow][ROMCol] = 0;   // Sets read fader value to 0 initially,   the customvalue variable is used to control physical orientation in this function
        customChannel = cellChannel[ROMRow][ROMCol];    // The MIDI channel the given cell is assigned to
        initType3(ROMRow,ROMCol);
      }
      */

    }
  }

    // Here we go back to the grid view
    delay(500); // Just so user can see message
    menuState = 2; // Go back to Grid View
    menuLocatorX = 0;
    menuLocatorY = 0; // Otherwise text will not show on next screen;
    updateScreen();
}
//{EEPROM_readAnything((profileNum*profileSize), configuration);}

Here is the declaration of the struct I am using
//-------------------------------EEPROM STRUCTURE -------------------------------------------
struct config_t   // I think this will allow EEPROM saving made easy
{
  int ROMcellType[8][8];  // [Row][Column] States the type of input assigned to the cell.  Top left = 0,0 Row, Column    // Celltype 9 will be a reservation cell for the faders.
  int ROMindexVal[8][8];       // States the note value / Command  assigned to the cell
  int ROMMIDIVariable[8][8];   // Used to retain desired velocity / Current value of continuous input.
  int ROMcellChannel[8][8];    // The MIDI channel the given cell is assigned to
  int ROMorientation[8][8]; // Keeps track of the direction of orientation of large modules
  int ROMfaderGroundX[8][8]; // Keeps track of where the 'root' of the fader is
  int ROMfaderGroundY[8][8]; // Keeps track of where the 'root' of the fader is
} saveConfiguration;
//--------------------------------------------------------------------------------------------

IndexVal, cellType, etc are all global variables (I know, I know, global variable bad)
And last of all, the header file with my base level EEPROM functions
#include <EEPROM.h>
#include <Arduino.h>  // for type definitions

template <class T> int EEPROM_writeAnything(int ee, const T& value)
{
    const byte* p = (const byte*)(const void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          EEPROM.write(ee++, *p++);
    return i;
}

template <class T> int EEPROM_readAnything(int ee, T& value)
{
    byte* p = (byte*)(void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          *p++ = EEPROM.read(ee++);
    return i;
}

It's been a while since I wrote this code so I'm a little lost in it myself.
I should probably add that if I save to profile 1, mess around testing the other profiles, then load profile 1 again it's always correct.
Also, the part where it prints sizeof(saveConfiguration) does return 224, and I've also removed the "/8" just to check that there was no rounding error.
If I double the value of profileSize it simple halves the number of profiles I have available by spacing them out by the size of the struct in memory.
Please ignore the (if cellType == 3) section, this is used for a type of object that uses 3 consecutive cells and is a whole can of worms in itself.
For the sake of this test I'm just using celltypes that are modules that use a single cell.
I feel like I really need to make some progress with this soon for the sake of my own mental wellbeing.
Anyone able to help?
Further info for the commenters:
The board I am using is a PJRC teensy 3.5.
The /8 was to display the number of Integers being saved. I think when I originally wrote this code I mistakenly thought that the device was 8 bit, and estimated the profile size to be 448.
I believe the EEPROM is 16 bits wide?

What board are you using? And why do you think you would want to divide the size by 8...?

EEPROMAnything can be replaced by EEPROM.put and EEPROM.get.

I'll add that info. 2 Secs.

Ok so replacing with .put and .get works, but I get the exact same issue.

Depending if you are on an 8 bit or 32 bit Arduino your profile is either 896 or 1792 bytes in size. Not 224. (Why do you think /8 is an option?)
I am guessing that you are on a 32-bit Arduino since 1792/8 = 224.
1792 is more EEPROM than any normal Arduino has, anyway.  Even if you were on an 8-bit Arduino and the profile size was 896 there would only be room for one in the EEPROM.
I think you need to re-think your strategy somewhat to either massively reduce the amount of data you are saving, or change where you are storing the data to.

So the teensy 3.5 is a 32 uController with 4096 bytes of EEPROM.
As it stands, I could probably encode the X and Y position into a single variable as neither value can be > 8.
I am considering including a larger external EEPROM in the final design but for now the first few profiles should still work OK, even if the profile size is worst case scenario, right?
I can save stuff to the other profiles OK but I get the issue where the far right and left columns overwrite the a column inthe  next / last profile respectively

I think the /8 comes from the code originally being written on an arduino mega?

I can see no place ever for a /8 regardless of what the code was written for.  The size is the size. If you try working with an eighth of the size then yes things are going to get messed up.

If you are storing values < 256 then there is no need to use int - it's 4x larger than you need. Use uint8_t.

Yeah good shout, this is definitely an artifact from previously working with a smaller Ucontroller.

Having changed the struct and global vars to uint_8 sizeof returns 448 (which was what I have on my spreadsheet where I planned all of the memory allocation.) We are getting somewhere! :)

Ok so now the bug has changed...
I have completely cleared profile 5,6, and 7 and created a 'cross' with inputs of 2 different types going diagonally from corner to corner.
The remaining 6 free cells in the far right and left columns are set to a different celltype.
when I save this to profile 6 ; Profile 5 is unchanged, but profile 7 has a copy of profile 6 in it, but the 4th column has 6 inputs of a totally different type to the ones used for testing, with the top an bottom cells empty.
What a headache.

This behaviour doesn't occur when saving to any profiles below 6 which is great!

Thanks a lot Majenko, that was very helpful.
I also noticed my system configuration (Different to the grid config and only a few bytes) saving function was set to save at an address that would cause the struct to wrap around in the EEPROM.
Changed this so that rather than starting at 9* profilenum, it starts at 8* profilenum (Its only a few bytes.) This fixed the new bug :)

@GigaJoules Excellent. I'm glad you learned the tools to fix the problem. I don't like it when people demand I spoon feed them the answer ;)


text:
How to run my IDUINO Yun Shields stand-alone?
Experts,
How can I power and communicate with the IDUINO shield stand-alone? In other words, without any additional uC for it to plug into.
Failing in that, can a Nano (cheaper, smaller) be wired to give the Yun what it needs?

Can you paste a link to IDUINO? Or do you mean Arduino?

http://www.geeetech.com/wiki/index.php/Iduino_Yun_Shield

Yes, you can. All you need do is provide it with a regulated 5V supply on the 5V pin and it should power up and boot.
There's not a lot of IO on it though, so connecting to sensors and such would be hard, which is where the Arduino comes in handy. You communicate using the UART, so any microcontroller with a UART can be connected to it.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
In the AnalogRead example, would the thing work if I remove or short the A0 and the ground pin?
What I want to know is that how exactly does analogRead work because I have want to use it with a flex sensor and it has only two pins.I tried to find other examples on the internet, but this is the only example I find.If the middle pin of the 10k potentiometer and a0 pin are shorted or the gnd  pin is removed altogether,then would this thing work?

You did not show us the example which is confusing you.

I moved this to the answer...

I think you are confused because the ADC input measures voltage, not resistance.
To convert from resistance to voltage you need to pull in the opposite direction on the variable resistance with a fixed resistor.  As in the following image from this tutorial.

Hmmm...the image said it all....thank you...


text:
It is possible to carry a pic c code for arduino
Code C for PIC16F887, I want to be able to try this code in ATMEGA328, but I do not know how, I do not know the outputs of the pic, that is, none of the pic I know.
Thank you for helping me. Grateful.
/*
Universidad del Azuay
Microcontroladores
Proyecto Piano
Autores: Juan Pablo León, Santiago Vazques
Tutor: Ing. Kenneth Samuel Palacios Baus
Fecha: 2 de enero de 2015
*/

//Declaración de Funciones
void ndo(); //Nota Do
void sdo(); //Nota Do Sostenido
void nre(); //Nota Re
void sre(); //Nota Re Sostenido
void nmi(); //Nota Mi
void nfa(); //Nota Fa
void sfa(); //Nota Fa Sostenido
void nsol(); //Nota Sol
void ssol(); //Nota Sol Sostenido
void nla();  //Nota La
void sla(); //Nota La Sostenido
void nsi(); //Nota Si
void ndo2(); //Nota Do

//Programa Principal
void main (){
osccon=0x77; //Ocilador de 8bits interno del PIC16f887

TRISC=0XFF; //Puerto C habilitamos como entrada  para las notas normales
PORTC=0;;

TRISB=0XFF; //Puerto B habilitamos como entrada para los sostenidos
PORTB=0;

TRISD=0X00; //Puerto D habilitamos como salida para el sonido del parlante
PORTD=0;

ANSELH = 0x00;
ANSEL=0x00;      // Bits AN6:AN0 como E/S digital.

    while(1){

        PORTB=0xFF;  // 255   11111111
        switch(PORTB)
        {
               case  0b00000001: sdo();  break;  //#Do
               case  0b00000010: sre();  break;  //#Re
               case  0b00000100: sfa();  break;  //#Fa
               case  0b00001000: ssol(); break;  //#Sol
               case  0b00010000: sla();  break;  //#La
        }

        PORTC=0xFF;  // 255   11111111
        switch(PORTC)
        {
               case  0b00000001: ndo();  break;  //Do
               case  0b00000010: nre();  break;  //Re
               case  0b00000100: nmi();  break;  //Mi
               case  0b00001000: nfa();  break;  //Fa
               case  0b00010000: nsol(); break;  //Sol
               case  0b00100000: nla();  break;  //La
               case  0b01000000: nsi();  break;  //Si
               case  0b10000000: ndo2(); break;  //Do
        }
    }

}

void ndo(){      //Do
        PORTD=1;
        delay_us (1911);
        PORTD=0;
        delay_us (1911);
}

void sdo(){      //#Do
        PORTD=1;
        delay_us (1804);
        PORTD=0;
        delay_us (1804);
}

void nre(){     //Re
        PORTD=1;
        delay_us (1702);
        PORTD=0;
        delay_us (1702);
}

void sre(){     //#Re
        PORTD=1;
        delay_us (1607);
        PORTD=0;
        delay_us (1607);
}

void nmi(){     //Mi
        PORTD=1;
        delay_us (1517);
        PORTD=0;
        delay_us (1517);
}

void nfa(){     //Fa
        PORTD=1;
        delay_us (1432);
        PORTD=0;
        delay_us (1432);
}

void sfa(){     //#Fa
        PORTD=1;
        delay_us (1351);
        PORTD=0;
        delay_us (1351);
}

void nsol(){    //Sol
        PORTD=1;
        delay_us (1276);
        PORTD=0;
        delay_us (1276);
}

void ssol(){    //#Sol
        PORTD=1;
        delay_us (1203);
        PORTD=0;
        delay_us (1203);
}
void nla(){     //La
        PORTD=1;
        delay_us (1136);
        PORTD=0;
        delay_us (1136);
}

void sla(){    //#La
        PORTD=1;
        delay_us (1121);
        PORTD=0;
        delay_us (1121);
}

void nsi(){    //Si
        PORTD=1;
        delay_us (1012);
        PORTD=0;
        delay_us (1012);
}

void ndo2(){   //Do
        PORTD=1;
        delay_us (955);
        PORTD=0;
        delay_us (955);
}

Code file taken from this video: https://www.youtube.com/watch?v=2jVZnKjCltw

There are two things you need to learn:

What the instructions in the PIC program mean, and
What the equivalent instructions (or functions for abstracted concepts) are in the Arduino API.

For instance, it looks like you may be making sounds of specific pitches. For that you would replace much of your code with the tone() function.
Reading IO pins would be done with digitalRead(), and pinMode() to set them to INPUT mode.
Basic C constructs like switch, and if() { } else { } etc are the same, but given the abstractions the Arduino API gives you it's probable you'd be using them in different ways anyway.
So in a nutshell: learn what your program is doing, then write the equivalent program for the Arduino.

No, you can not run Microchip PIC16F887 on an Atmel ATMEGA328 directly.  Any code that does useful work likely interfaces with the "outside world" through the processor's inputs and outputs (ADC, GPIO, ect).  It is very unlikely any two processor designs approach interfacing to the outside world in the same way.
The process of recoding software / firmware to run on different processors is called porting.  It is a time consuming and costly process which is repeated over and over again.  Porting is most often done because people or companies want to use the same software / firmware despite changing hardware due to speed increases, size reductions or cost reductions.


text:
Understanding ArduinoJson capacity calculation assistant
I am trying to figure out how ArduinoJson capacity can be calculated, therefore I came by the Assistant web application developed by the developer of the library https://arduinojson.org/v6/assistant/
Here what I do not understand is, why when I use either of the following two JSON strings, the helper shows me the same capacity? I would expect that the longer JSON values will result in a bigger capacity, but this does not seem to be the case.
{
  "wifi": {
    "ssid": "S",
    "password": "P",
    "hostname": "H"
  },
  "administration": {
    "username": "U",
    "password": "P"
  }
}

{
  "wifi": {
    "ssid": "SSSSSSSSSSSSSSSSSSSSSSSSSSS",
    "password": "PPPPPPPPPPPPPPPPPPPPPPPPPP",
    "hostname": "HHHHHHHHHHHHHHHHHHHHHHHHHHHH"
  },
  "administration": {
    "username": "UUUUUUUUUUUUUUUUUUUUUUUUUUUUUU",
    "password": "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP"
  }
}

I am trying to calculate the capacity using the assistant using the following configuration:
ESP8266 / Deserialize / char*
Could you anyone explain this to me? Apparently I understand the "reason" behind the capacity wrong?

That site reports to me different capacities for the two JSON documents. How exactly did you set the configuration?

@EdgarBonet, well sorry I have just realized that the I should have mentioned how I was trying to calculate the capacity. ESP8266/Deserialize/char *

If you look at the details of the numbers reported, you should see:
Data structures     112
Strings             0
Total (minimum)     112
Total (recommended) 128

As you see, there are exactly zero bytes allocated for the strings. This
means that the library does not copy the strings, and instead references
them from the character array you provide as an input.
If you instead configure the library for Stream input, it will have to
store the strings, and the capacity is then very different for these two
documents.

You helped me understanding how the things are calculated here, thank you!. Nevertheless, I found the actual problem, please check my answer.

I found what the real problem is. In the assistant tool, when choosing const char * as the input type, it shows that the size of the string is 0, which is wrong according to the documentation of the library.
https://arduinojson.org/v6/api/json/deserializejson/

// writable input => zero-copy
DeserializationError deserializeJson(JsonDocument& doc, char* input);
// read-only input => duplication
DeserializationError deserializeJson(JsonDocument& doc, const char* input);

The assistant, if I see correctly, does not distinguish between these two cases, and thus gives the wrong capacity for this const case.
Accordingly, in const char * it is not enough to only take the size of the structure, but also we need to consider the data stored in it.
According to the documentation, the reason why const char * cannot be a zero-copy is:

3.9.2 Duplication is required
As we saw in the previous section, in the zero-copy mode, ArduinoJson stores pointers
pointing inside the input buffer. We saw that it has to replace some characters of the
input with null-terminators.
With a read-only input, ArduinoJson cannot do that anymore, so it needs to make copies
of "hip" and "hop". Where do you think the copies would go? In the JsonDocument, of
course!

UPDATE
After reporting this bug (see the link below), it has been quickly fixed!
https://github.com/bblanchon/ArduinoJson/issues/1488

Good catch! Did you consider sending a bug report?

@EdgarBonet Thanks! I already did it https://github.com/bblanchon/ArduinoJson/issues/1488

Well, they fixed it now.


text:
How to assign ESP8266 access point a hostname that can be resolved by the stations?
I want to assign a hostname to a ESP8266 access point, so that the clients can reach a webserver on this access point without caring about the IP address of the AP. How can that be done?
I tried using WiFi.hostname("something"); but that does not work with AP mode. Can this somehow be done?
UPDATE
Using mDNS seems to work in this AP mode too. However, I am still curious to know if this is possible to access the webserver on the AP using the hostname and not mDNS.

I'm unclear on the distinction being drawn here:

the hostname and not mDNS

mDNS, like DNS, and hostname lists are all things a "resolver" would use to map a "hostname" to an IP address.
If you mean "how do I use DNS instead of mDNS?", you'd need to have your ESP8266 running a DNS server.  And for clients to be aware of it you'd probably have to be running a DHCP server as well.
By the way, the examples list for the ESP8266 Arduino package contains a DNSServer/DNSServer example that appears to do exactly this.  I have just tested it.
This is the exact code I ran out of the ESP8266 Arduino github repo at the tag for the version of the ESP8266 Arduino core I tested it on, 2.7.4.

Well, yes, I would like the ESP AP to be able to resolve the hostnames (including its own hostname, and share it with any station requests this hostname). Thank you for pointing out that the examples include DNS server, I did a quick research and found nothing, now after checking again, I found one example. I am gonna give it a try. Thanks!

@MohammedNoureldin, let me know if it doesn't work.

Thank you for your comment, I got it working using DNS server, I will post a short answer  a bit later. Thank you!

@MohammedNoureldin, good to know.


text:
Detect certain characters and if not a consequence
How can I program in Arduino Uno a serial.available that will detect some chars that aren't supposed to belong in a list of options, like this:
void lerRespostaUtilizador(){
  if(Serial.available('s' && 'v' && 'r'){
    Serial.println("Podes visualizar: (s)inais de controlo, (v)ariaveis do sistema e conteudo de (r)egistos.")
  }
  switch(Serial.read()){
    case 's': // Mostrar sinais de controlo
      mostrarSinais();
      Serial.println("Podes visualizar ainda: (v)ariaveis do sistema e conteudo de (r)egistos.");
      Serial.println("");
      break;
    case 'v': // Mostrar variáveis do sistema
      mostrarVariaveis();
      Serial.println("Podes visualizar ainda: (s)inais de controlo e conteudo de (r)egistos.");
      Serial.println("");
      break;
    case 'r': // Mostrar conteúdo de registos
      mostrarRegistos();
      Serial.println("Podes visualizar ainda: (s)inais de controlo e (v)ariaveis do sistema.");
      Serial.println("");
      break;
    }
}

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

Check this Serial.available('s' && 'v' && 'r'). I can guess what you think it means but it does not.

How can I correct it then?

Simply wait for something to read, read the character, and add a default switch section case that catches illegal characters.

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

Yeap, that works perfectly!
But can you explain me how the while works and how is it connected to the default option?


text:
Sparkfun Can-Bus Shield example not working
I recently bought a Sparkfun Can-Bus Shield, and tried the SparkFun_CAN_Demo from here but the program only prints "CAN-Bus Demo" and then does nothing, even when I have it connected into my vehicle's OBD-II port and the key is turned to ON (I can't run the engine because I am in my garage). Any help will be appreciated.

SPI pins are located on different pins in Arduino Mega. You have to wire it correctly with your shield. Some shields uses ICSP (6-pin header) for better compatibility but this one doesn't.
See Arduino SPI Reference for more details (section: Connections)


text:
Supervised inputs for alarm panel
I'm using an Arduino Mega 2560 to make a fire alarm control panel. The control panel takes 50 (inputs) supervised inputs. The normal way as mentioned in the link is to use the analog inputs, which I am short of. Is there any other way to monitor supervised inputs other than using analog inputs?
Thanks in advance for your time – if I’ve missed out anything, over- or under-emphasized a specific point let me know in the comments.

I can think of a number of ways of doing this:

Multiplexing -- Employ a (large) number of analog MUX chips to expand the number of analog inputs you have available. That would get messy very quickly.
External ADC Chips -- Add more real analog inputs over SPI or I2C. For 50 inputs that would be quite a lot of extra chips.
Use Op-Amps -- Each input can be converted into a pair of digital inputs using two op-amps to compare the voltage of the input against two thresholds, which would give you an "active" and a "fault" signal. That would be 100 digital inputs needed (and 100 op-amps, which could be done with 25 quad op-amp chips).
Distributed processing -- Don't try and do it all with one device. Split your system into zones with far less inputs then get the zones to communicate with each other.

Of course, you can combine any of those - you could have analog MUX chips fanning out a number of external ADC chips inputs. You could MUX the inputs to the op-amps. You could have external ADC chips on multiple zone systems. Etc.
Personally, on a system of this size, I would certainly consider distributing the inputs across multiple processors even if they are all in the same physical control unit. However, distributing nodes across the building (it sounds like it's quite a large building for 50 inputs) would reduce the amount of cable needed to implement those inputs, and some industry standard bus snaking its way around the building connecting all the nodes up to a master unit would, if implemented correctly, be robust. CAN is a popular protocol for interconnecting control systems (it's used in modern lifts, and those are life critical... you don't want a lift to fail...) so could be a good choice for this.

@LookAlterno I'd be wary about using WiFi for a fire alarm system...

If I use the method 3, can I use encoders to reduce the number of inputs

Encoders....? Shift registers, sure. Io expanders, yes. Encoders? Makes no sense.


text:
NEO 6M GPS speed

I am doing a project using a NEO 6M GPS with my Arduino LilyPad. I programmed it already, and it's working well except of the speed. I get stuck on fixing this. I wonder why the value is never getting zero although I am not moving to my place.
I need any suggestions/help that would make the speed working accurately.
Thanks.
Here is the code I used:
 #include <SoftwareSerial.h>
 #include <TinyGPS.h>

SoftwareSerial mySerial(4, 3); // RX, TX
TinyGPS gps;

void gpsdump(TinyGPS &gps);
void printFloat(double f, int digits = 2);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  delay(1000);
  Serial.print("Sizeof(gpsobject) = ");
  Serial.println(sizeof(TinyGPS));
  Serial.println();
}

void loop() {
  bool newdata = false;
  unsigned long start = millis();
  // Every 5 seconds we print an update
  while (millis() - start < 5000) {
    if (mySerial.available()) {
      char c = mySerial.read();
      if (gps.encode(c)) {
        newdata = true;
      }
    }
  }
  if (newdata) {
    Serial.println("Acquired Data");
    Serial.println("-------------");
    gpsdump(gps);
    Serial.println("-------------");
    Serial.println();
  }
}

void gpsdump(TinyGPS &gps) {
  long lat, lon;
  float flat, flon;
  unsigned long age, date, time, chars;
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned short sentences, failed;
  gps.get_position(&lat, &lon, &age);
  Serial.print("Lat/Long(10^-5 deg): ");
  Serial.print(lat);
  Serial.print(", ");
  Serial.print(lon);
  Serial.print(" Fix age: ");
  Serial.print(age);
  Serial.println("ms.");
  // On Arduino, GPS characters may be lost during lengthy Serial.print()
  // On Teensy, Serial prints to USB, which has large output buffering and
  // runs very fast, so it's not necessary to worry about missing 4800 baud GPS characters.
  gps.f_get_position(&flat, &flon, &age);
  Serial.print("Lat/Long(float): ");
  printFloat(flat, 5);
  Serial.print(", ");
  printFloat(flon, 5);
  Serial.print(" Fix age: ");
  Serial.print(age);
  Serial.println("ms.");
  gps.get_datetime(&date, &time, &age);
  Serial.print("Date(ddmmyy): ");
  Serial.print(date);
  Serial.print(" Time(hhmmsscc): ");
  Serial.print(time);
  Serial.print(" Fix age: ");
  Serial.print(age);
  Serial.println("ms.");
  Serial.print("Alt(cm): ");
  Serial.print(gps.altitude());
  Serial.print(" Course(10^-2 deg): ");
  Serial.print(gps.course());
  Serial.print(" Speed(10^-2 knots): ");
  Serial.println(gps.speed());
  Serial.print("Alt(float): ");
  printFloat(gps.f_altitude());
  Serial.print(" Course(float): ");
  printFloat(gps.f_course());
  Serial.println();
  Serial.print("Speed(knots): ");
  printFloat(gps.f_speed_knots());
  Serial.print(" (mph): ");
  printFloat(gps.f_speed_mph());
  Serial.print(" (mps): ");
  printFloat(gps.f_speed_mps());
  Serial.print(" (kmph): ");
  printFloat(gps.f_speed_kmph());
  Serial.println();
  gps.stats(&chars, &sentences, &failed);
  Serial.print("Stats: characters: ");
  Serial.print(chars);
  Serial.print(" sentences: ");
  Serial.print(sentences);
  Serial.print(" failed checksum: ");
  Serial.println(failed);
}

void printFloat(double number, int digits) {
  // Handle negative numbers
  if (number < 0.0) {
    Serial.print('-');
    number = -number;
  }
  // Round correctly so that print(1.999, 2) prints as "2.00"
  double rounding = 0.5;
  for (uint8_t i=0; i<digits; ++i)
    rounding /= 10.0;
  number += rounding;
  // Extract the integer part of the number and print it
  unsigned long int_part = (unsigned long)number;
  double remainder = number - (double)int_part;
  Serial.print(int_part);
  // Print the decimal point, but only if there are digits beyond
  if (digits > 0)
    Serial.print(".");
  // Extract digits from the remainder one at a time
  while (digits-- > 0) {
    remainder *= 10.0;
    int toPrint = int(remainder);
    Serial.print(toPrint);
    remainder -= toPrint;
  }
}

NOTE:  The altitude and longitude were already working. It's the speed that I want to fix. I want to see it as "ZERO SPEED" when at a steady state. How can I fix this? Please help me. Thanks!

Code and schematic?

@TisteAndii please see the code I inserted above. Thank you for your reply. :)

What speed do you get when you've been stationary for a minute?

Sometimes, I get 1.01, 0.89, 0.06, 0.3 but I never get zero even when stationary state. That's impossible to get that values even when you are not moving on your place, so I concluded that there is something wrong on it.

Not necessarily. These modules arent perfect nor is the GPS technique they use to determine your speed. There will always be some tiny offset. So if you write code based on this, you will have to account for this offset in the code. E.g. if (gps.speed <= 1) moving = False. You will have to run tests and determine the maximum value you can get from the module, when you arent moving and use that to determine motion or the lack of it.

Just to see if you get better results, you could also try powering the module using the Arduino 5V pin through an LM1117 regulator since the 3.3V pin can only supply 50mA max and the NEO 6M may exceed that (max current is 67mA)

@TisteAndii I'll update you once I have the LM1117.

The speed value is correct, like TisteAndi said.  Your GPS location "wanders" around the same way.  You can simply ignore small speed values.
One problem you may not be aware of yet: the printing isn't really coordinated with the GPS updates.  Sometimes that doesn't matter, but if you want your speed to update every second, you'll need to synchronize the two.  And as noted in the code, you can actually lose GPS data if you print too much.
I wrote a GPS library, called NeoGPS, to fix some of these problems.  They are described in the Troubleshooting section of the online documentation.
Also, SoftwareSerial is very inefficient.  I maintain a more-efficient alternative, NeoSWSerial.  As you add more features to your GPS program, the efficiency will become important.
Here is your program, modified to use NeoGPS and NeoSWSerial, and it uses TisteAndi's suggestion to set the speed to zero:
#include <Arduino.h>
#include "NMEAGPS.h"
#include <NeoSWSerial.h>

NeoSWSerial mySerial(4, 3); // RX, TX//

NMEAGPS     gps;
gps_fix     fix;
uint8_t     GPSupdates = 0;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

  delay(1000);

  Serial.print("Sizeof(gps) = "); Serial.println(sizeof(gps));
  Serial.println();
}

void loop() // run over and over
{
  while (gps.available( mySerial )) {
    fix = gps.read();

    if (fix.valid.speed && (fix.speed_mkn() < 1000)) {
      // Too slow, zero out the speed
      fix.spd.whole = 0;
      fix.spd.frac  = 0;
    }

    GPSupdates++;
  }

  // Print once every 5 seconds
  if (GPSupdates >= 5) {
    Serial.println("Acquired Data");
    Serial.println("-------------");
    gpsdump();
    Serial.println("-------------");
    Serial.println();

    GPSupdates = 0;
  }

}

void gpsdump()
{
  Serial.print("Lat/Long(10^-7 deg): ");
  if (fix.valid.location) {
    Serial.print(fix.lat);
    Serial.print(", ");
    Serial.print(fix.lon);
  }
  Serial.println();

  // GPS characters may be lost during lengthy Serial.print()
  //   See the NeoGPS Troubleshooting section.

  Serial.print("Lat/Long(float): ");
  if (fix.valid.location) {
    Serial.print(fix.latitude(), 5);
    Serial.print(", ");
    Serial.print(fix.longitude(), 5);
  }
  Serial.println();

  Serial.print("Date/Time: ");
  if (fix.valid.date | fix.valid.time)
    Serial << fix.dateTime;
  Serial.println();

  //*
  Serial.print("Date: ");
  if (fix.valid.date) {
    Serial.print(fix.dateTime.month);
    Serial.print("/");
    Serial.print(fix.dateTime.date);
    Serial.print("/");
    Serial.print(fix.dateTime.year);
  }

  if (fix.valid.date | fix.valid.time) {
    Serial.print("  Time: ");
    Serial.print(fix.dateTime.hours);
    Serial.print(":");
    Serial.print(fix.dateTime.minutes);
    Serial.print(":");
    Serial.print(fix.dateTime.seconds);
    Serial.print(".");
    Serial.print(fix.dateTime_cs);
  }
  Serial.println();
  //*/

  Serial.print("Alt(cm): ");
  if (fix.valid.altitude)
    Serial.print(fix.altitude_cm());

  Serial.print(" Course(10^-2 deg): ");
  if (fix.valid.heading)
    Serial.print(fix.heading_cd());

  Serial.print(" Speed(10^-3 knots): ");
  if (fix.valid.speed)
    Serial.print(fix.speed_mkn());
  Serial.println();

  Serial.print("Alt(float): ");
  if (fix.valid.altitude)
    Serial.print(fix.altitude());

  Serial.print(" Course(float): ");
  if (fix.valid.heading)
    Serial.print(fix.heading());
  Serial.println();

  Serial.print("Speed(knots): ");
  if (fix.valid.speed)
    Serial.print(fix.speed());
  Serial.print(" (mph): ");
  if (fix.valid.speed)
    Serial.print(fix.speed_mph());
  Serial.print(" (mps): ");
  if (fix.valid.speed)
    Serial.print(fix.speed_kph()*3600.0/1000.0);
  Serial.print(" (kmph): ");
  if (fix.valid.speed)
    Serial.print(fix.speed_kph());
  Serial.println();

  Serial.print("Stats: characters: ");
  Serial.print(gps.statistics.chars);
  Serial.print(" sentences: ");
  Serial.print(gps.statistics.ok);
  Serial.print(" failed checksum: ");
  Serial.println(gps.statistics.crc_errors);
}

(Notice the increased accuracy of the integer lat/lon!  And you don't need printFloat.)
If you'd like to try it, be sure to follow the NeoGPS Installation instructions.  NeoSWSerial is installed like most Arduino libraries.

Usually, this should be solved by just going outside to get the first fix point. If you still don't manage it, try the U-center software to make sure your GPS is properly working.

have you find installer of the u-center for mac? I kept searching for it but I can't even find one.


text:
How to use voltage divider between ESP8266 (3.3v) and IR proximity sensor (5V)?
I am a software developer and I don't know much about circuits so I need help.
I have an ESP8266 (esp-12) 3.3V and I'm planning to use it with an IR proximity sensor (runs between 4.5-5V). I have 2 AA batteries (3V total) and 4 AA (6V total) power supplies. Also, I have a bunch of 10K Ohm and 330 Ohm resistors.
How can I use a voltage divider to supply sufficient voltage to these components, based on what I have? If it would help, I have a 100uF capacitor and I use a CP2102 to TTL Serial Converter to program. Any help will be appreciated. Thank you in advance.

You want to use a voltage divider to POWER your boards?!?!?!

Yes, i already use esp8266 with 3v (AA batteries ) but now i want to connect it to the sensor which is 5v.

My experience with esp8266 tells me that if you power esp8266 with a 3.3V supply and you provide 5V/0V signal to its pins (either Tx/Rx or pin0,1) nothing's gonna happen. It will work fine.
Based on this experience, i would like to suggest you to

power your esp8266 with 3.3V pin of your TTL converter
power your IR sensor using 5V output pin of your TTL converter
connect signal pin of IR sensor to your esp8266 digital pin. (just
in case esp8266 heats up, disconnect circuit and try using voltage
divided only for this particular connection.

If using those external power supplies don't forget to common GND (or -ive terminal) of those power supplies.

Thank you for the advice. I was thinking of powering the Esp8266 with 3.3V batteries and the sensor with 4 AA batteries 6V(keep in mind this takes up to 5V so i wonder if that would be ok?).And signal wire of the sensor to GPIO12 OR 14 (I am using ESP-12)

you can check that in datasheet of your IR sensor. i.e. What is the maximum voltage you can apply.
you can also connect signal wire to esp8266 GPIO12/14 using voltage divider. that would also be perfectly ok.

Data sheet says maximum absolute rating supply voltage is -0.3 to 7. Recommended Operating supply voltage is 4.5 to 5.5v, so i am not sure if that is ok. If i do voltage divider how many/which resistors should i use , i have 10k and 330 ohm?. Thank you again.

No, you don't need voltage divider now. its perfectly ok. Go ahead and be careful, for things like never fail to surprise you.


text:
Clock frequency VS cycle time
I am considering switching from Arduino Pro Mini 5V 16MHz to Arduino Pro Mini 3.3V 8Mhz for some project because I would like to run it with a 4.5V input power.
Will the switch from 16 to 8Mhz double the cycle time of my loop() function ?
Edit -- adding precision:
My loop function is simple: it's reading a couple of sensors with analogRead and setting a few pins to HIGH or LOW. It does not use delay().
Thanks.

The execution time of your loop() will be slightly longer when the CPU
runs at 8 MHz v.s. 16 MHz, but I don't expect the difference
to be significant. CPU-bound functions, such as digitalWrite(), will
run at half the speed. These functions, however, are quite fast. In
contrast, analogRead() is slow, as it takes roughly 110 µs to
execute, so this is likely where your loop() spends most of its time.
The execution time of analogRead() does not depend significantly on
the CPU speed. This function spends most of its time waiting from the
analog-to-digital converter to do its conversion. When the CPU is
clocked at either 1, 2, 4, 8 or 16 MHz, the Arduino core sets the
ADC prescaler so that the ADC is clocked at 125 kHz.
This means the conversion time will be the same irrespective of the CPU
frequency.
Note: You may just use your Arduino Pro Mini 5V 16MHz. This board is
based on the ATmega328P microcontroller, which is rated for frequencies
up to 20 MHz when the supply voltage is between 4.5 and 5.5 V.
According to the datasheet (see freq-Vcc graph), it should safely
run at 16 MHz for any supply voltage between 3.78 and 5.5 V.

It depends.
The loop function is handled like a while loop. This means, when the loop function finishes, some framework code  is executed (very small) and the loop function is called again etc.
However, there are some calls that do not depend on the clock speed, the best example is the delay function, but also if you made your own check using e.g. millis this will not depend high likely on the clock speed.
Beyond that, there can be peripheral calls which are not related to the clock speed (although internally in libraries timing functions as above are used to manage this), but you don't see them when used from a library.


text:
How can I use Wemos D1's TX pin as OneWire?
I'm building a thermostat control with a Wemos D1 Mini. The ILI9341 display uses almost all the pins, and all I have left are the RX, TX, A0 and D0 pins. However I can't get any valid readings from these pins. According to the various wemos pinouts, I should be able to use RX/TX as onewire pins. As soon as I set the pin to a different one, and replace the wire there, I have correct readings. What am I missing with using these pins?
I'm connecting the display as stated in this arcticle: link
I also found this site which shows that I should be able to set these two pins as IO pins.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <OneWire.h>
#include <DallasTemperature.h>

#ifndef STASSID
#define STASSID "wifiname"
#define STAPSK  "password"
#endif

const char* ssid = STASSID;
const char* password = STAPSK;

ESP8266WebServer server(80);

OneWire oneWire(1);
DallasTemperature sensors(&oneWire);

void handleRoot() {
  sensors.requestTemperatures();
  server.send(200, "text/plain", String(sensors.getTempCByIndex(0)));
}

void setup() {
  pinMode(1, FUNCTION_3);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  server.on("/", handleRoot);
  server.begin();
  sensors.begin();
}

void loop() {
  server.handleClient();
}

The documentation of the Wemos D1 mini states that the IO pins except the D0 pin have one wire functionality. I looked into the official PINout  https://wiki.wemos.cc/products:d1:d1_mini and found that TX and RX are not marked as IO pins. A0 is only marked analog. Your code does not contain any lines for the ILI display so I don't know how you used the other pins. Perhaps you could use the D0 pin instead of one of the others, that would then be free to use for the one wire access.

Yeah, but the same site says, that it has 11 IO pins, and this matches with this pinout diagram: https://www.luisllamas.es/wp-content/uploads/2018/09/pinout-wemos-mini-d1.png I'll update my question with containing the display pinout as well.

I do not trust that pin out diagram very much. They marked the 5V pin as GND. ;-) Seriously: I'm not an Wemos mini expert, so I hardly can argue against the 11 IO-Pin claim. But from the observation you told us, I would say, the RX and TX Pin might be unusable for your purposes. As the mini uses the ESP8266 in it's own context (i.e with an USB to Serial converter) which connects the RX/TX pins to another chip (CP2104 or so), this could/would make the RX/TX pins unusable for purposes other than UART communication. You can find schematics here https://escapequotes.net/wemos-d1-mini-pro/


text:
Connecting Arduino Uno to Arduino Leonardo
I have an RFID shield connected to my Arduino Uno, but I want it to be able to send keystrokes to the computer when I scan the correct card. I have the Uno set up correctly so that when the card is scanned and verified it would send a 1 to the Leonardo. But when I have tried to receive the data using I2C, Leonardo doesn't get it. What could I try next?
This is the master code or the code that is sending the information. (On the Arduino Uno)
// Include the required Wire library for I2C
#include
int x = 0;
void setup() {
  // Start the I2C Bus as Master
  Wire.begin();
}
void loop() {
  Wire.beginTransmission(9); // transmit to device #9
  Wire.write(x);              // sends x
  Wire.endTransmission();    // stop transmitting
  x++; // Increment x
  if (x > 5) x = 0; // `reset x once it gets 6
  delay(500);
}

and this is the slave code (on the Leonardo)
// Include the required Wire library for I2C
#include <Wire.h>
int LED = 13;
int x = 0;
void setup() {
  // Define the LED pin as Output
  pinMode (LED, OUTPUT);
  // Start the I2C Bus as Slave on address 9
  Wire.begin(9);
  // Attach a function to trigger when something is received.
  Wire.onReceive(receiveEvent);
}
void receiveEvent(int bytes) {
  x = Wire.read();    // read one character from the I2C
}
void loop() {
  //If value received is 0 blink LED for 200 ms
  if (x == '0') {
    digitalWrite(LED, HIGH);
    delay(200);
    digitalWrite(LED, LOW);
    delay(200);
  }
  //If value received is 3 blink LED for 400 ms
  if (x == '3') {
    digitalWrite(LED, HIGH);
    delay(400);
    digitalWrite(LED, LOW);
    delay(400);
  }
}

x in slave code needs to be defined volatile, since the callback gets called from an ISR. Have you tried with the I2C scan example, if the Uno actually finds the Leonardo? Also you could print the return value of Wire.endTransmission(). A successfull transmission is marked by a return value of zero. If not successfull, the return value is an error code. Please check the error code, it might show the problem. Have you pullup resistors on both I2C lines?

@chrisl I will try the Wire.endTransmisson(). But how do I define x as volatile?

With the keyword volatile. You can google how to use it. When you can confirm, that it solved your problem, I will write an answer, explaining that.


text:
Uploading to an external Atmega328P with a clone UNO R3 with soldered chip
As a complete newbie, after much looking for the best bargain, I ended up buying one of these UNO R3 clones, without realizing it had the chip soldered on the board. It looks like this:

It works OK for development, but after that I want to get rid of the Arduino board and just use the Atmega with the minimum set of components on the final project.
As far as I understand, two tasks need to be acomplished here:

Program the bootloader on the spare Atmega328P
Upload code to the spare Atmega328P

Acording to this tutorial, I should be able to accomplish 1) with my "Arduino" board and a breadboard, but after that I couldn't upload any programs to that same Atme328P as the original microcontroller from the "UNO R3" should be removed and that can't be done on rip off.
Does anybody know of a method to accomplish 2) with my current setup? I also have one of those USB-to-serial converter (FTDI) boards. According to this other tutorial that can be done using it and some components, but I'd like to avoid that if, let's say, there's some trick like disabling the RX and TX line from the soldered chip by software so the external chip ones could be used instead...

it is unclear what the problem is

You don't need to remove the microcontroller from the board. Just keep it in the reset state by connecting the reset pin to ground. That prevents the microcontroller to disturb the communication with the external atmega

OT, you don't upload source code. You upload the executable that is compiled and linked from your source code.

You don't need to put a bootloader on the spare Atmega328P. The bootloader is a nice convenience for development, as it allows you to upload the program through the serial port. For the final product, if you are OK with using an ISP programmer (e.g. “Arduino as ISP”), the bootloader is not needed. Ditching it will make your sketch start way faster. 2. You don't need to remove the microcontroller from the Uno.

The idea of removing the existing MCU is either so you can replace it with yours, or to use the Arduino purely as a USB to UART adapter. For the latter just connect RESET to GND and it will disable the onboard MCU - it will be just like you have removed it.

Thanks a lot for the comments; they are really helpul. I edited the question acording to the busybee notes and added the missing link to the 2nd tutorial I mentioned. @EdgarBonet, is my link to the 1st tutorial an example of Arduino as ISP?

Yes, the first tutorial uses “Arduino as ISP” for burning a bootloader, then the USB-to-serial converter of the Arduino to burn the actual sketch through the bootloader. What I am saying is that you can forgo the bootloader and use “Arduino as ISP” (or any other ISP programmer, for that matter) to burn the actual sketch.

Thanks anyone for the comments. Very clarifying! So, all in all, the replies to my question and other doubts are:

There's no need to remove the existing MCU; it's enough to connect it's RESET pin to ground (GND), so it prevents from messing with the external Atmega, and
There's no need to have a bootloader on the "final" product, as it's only a convenience when developing which allows to upload the program easily.