text:
Finite loop runs infinitely
To gain better understanding of both Rust and Arduino (Uno), I'm trying to write direct hardware code for Arduino in Rust. Here's a very simple LED blink example, that I've tried to write.
I've made use of one library (crate) called avrd which only provides address mapping for ATMega328P microcontroller.
#![no_std]
#![no_main]
#![feature(asm_experimental_arch)]

use core::{arch::asm, hint::black_box, panic::PanicInfo};

use avrd::atmega328p;

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

#[inline(never)]
fn delay(x: u32) {
    for _ in 0..x {
        unsafe {
            asm!("nop");
        }
    }
}

unsafe fn write_reg(reg: *mut u8, val: u8, mask: u8) {
    let reg_val = reg.read_volatile();
    reg.write_volatile((reg_val & !mask) | (val & mask));
}

#[no_mangle]
extern "C" fn main() -> ! {
    const LED_BUILTIN: u8 = 5;
    unsafe {
        let portB_data_direction = atmega328p::DDRB;
        // set it to output mode
        write_reg(portB_data_direction, 1 << LED_BUILTIN, 1 << LED_BUILTIN);
        let portB = atmega328p::PORTB;
        // switch it on, hopefully..
        loop {
            write_reg(portB, 1 << LED_BUILTIN, 1 << LED_BUILTIN);
            delay(500_0000);
            write_reg(portB, 0, 1 << LED_BUILTIN);
            delay(500_0000);
        }
    }
}

(disassembly for the aforementioned snippet pasted at the end)
Now for some reason, if this delay value is 2 or greater, the LED never stops blinking. I think this delay function might be at fault, since putting the delay(2) above the line of code switching on the LED, makes the LED never switch on. Another bizarre thing, is if I change the code up a bit like so:
#[no_mangle]
extern "C" fn main() -> ! {
    const LED_BUILTIN: u8 = 5;
    unsafe {
        let portB_data_direction = atmega328p::DDRB;
        // set it to output mode
        write_reg(portB_data_direction, 1 << LED_BUILTIN, 1 << LED_BUILTIN);
        let portB = atmega328p::PORTB;
        // switch it on, hopefully..
        let mut i = 0;
        loop {
            while i < 1000000 {
                i += 1;
                write_reg(portB, 1 << LED_BUILTIN, 1 << LED_BUILTIN);
            }
            i = 0;
            while i < 1000000 {
                i += 1;
                write_reg(portB, 0, 1 << LED_BUILTIN);
            }
            i = 0;
        }
    }
}

Then though this time the LED switches on, and switches off, but only once (??!!). The infinite loop becomes finite and runs only once. I'm not sure if the code being generated is wrong or what.
Here's the .cargo/config.toml file:
[build]
target = "atmega328p.json" # Plucked from https://github.com/Rahix/avr-hal/

[unstable]
build-std = ["core"]

[target.'cfg(target_arch = "avr")']
runner = "ravedude uno --baudrate 57600"

The AVR toolchain that Rust is consuming is the same one that comes with Arduino, I haven't installed any separately (mentioning in case that toolchain causes problems on non-C platforms).
Here's the disassembly for the first code snippet (RUSTFLAGS="--emit asm" cargo run --release, not the final linked assembly):
    .text
.set __tmp_reg__, 0
.set __zero_reg__, 1
.set __SREG__, 63
.set __SP_H__, 62
.set __SP_L__, 61
    .file   "arduino_blink.caf25912130a4f-cgu.0"
    .section    .text._ZN13arduino_blink5delay17h9627a982856e7dadE,"ax",@progbits
    .p2align    1
    .type   _ZN13arduino_blink5delay17h9627a982856e7dadE,@function
_ZN13arduino_blink5delay17h9627a982856e7dadE:
    ldi r24, 0
    ldi r25, 0
    ldi r18, 75
    ldi r20, 76
    ldi r21, 0
    movw    r22, r24
.LBB0_1:
    ldi r19, 1
    cpi r24, 64
    cpc r25, r18
    cpc r22, r20
    cpc r23, r21
    brlo    .LBB0_3
    mov r19, r1
.LBB0_3:
    andi    r19, 1
    cpi r19, 0
    breq    .LBB0_5
    subi    r24, 255
    sbci    r25, 255
    sbci    r22, 255
    sbci    r23, 255
    ;APP
    nop
    ;NO_APP
    rjmp    .LBB0_1
.LBB0_5:
    ret
.Lfunc_end0:
    .size   _ZN13arduino_blink5delay17h9627a982856e7dadE, .Lfunc_end0-_ZN13arduino_blink5delay17h9627a982856e7dadE

    .section    .text.main,"ax",@progbits
    .globl  main
    .p2align    1
    .type   main,@function
main:
    sbi 4, 5
.LBB1_1:
    sbi 5, 5
    call    _ZN13arduino_blink5delay17h9627a982856e7dadE
    cbi 5, 5
    call    _ZN13arduino_blink5delay17h9627a982856e7dadE
    rjmp    .LBB1_1
.Lfunc_end1:
    .size   main, .Lfunc_end1-main

And here's the final (linked) disassembly (avr-objdump -d binary-name.elf disassembly.s):
Disassembly of section .text:

00000000 <.text>:
   0:   0c 94 34 00     jmp 0x68    ;  0x68
   4:   0c 94 3e 00     jmp 0x7c    ;  0x7c
   8:   0c 94 3e 00     jmp 0x7c    ;  0x7c
   c:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  10:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  14:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  18:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  1c:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  20:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  24:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  28:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  2c:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  30:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  34:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  38:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  3c:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  40:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  44:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  48:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  4c:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  50:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  54:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  58:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  5c:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  60:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  64:   0c 94 3e 00     jmp 0x7c    ;  0x7c
  68:   11 24           eor r1, r1
  6a:   1f be           out 0x3f, r1    ; 63
  6c:   cf ef           ldi r28, 0xFF   ; 255
  6e:   d8 e0           ldi r29, 0x08   ; 8
  70:   de bf           out 0x3e, r29   ; 62
  72:   cd bf           out 0x3d, r28   ; 61
  74:   0e 94 57 00     call    0xae    ;  0xae
  78:   0c 94 5f 00     jmp 0xbe    ;  0xbe
  7c:   0c 94 00 00     jmp 0   ;  0x0
  80:   80 e0           ldi r24, 0x00   ; 0
  82:   90 e0           ldi r25, 0x00   ; 0
  84:   2b e4           ldi r18, 0x4B   ; 75
  86:   4c e4           ldi r20, 0x4C   ; 76
  88:   50 e0           ldi r21, 0x00   ; 0
  8a:   bc 01           movw    r22, r24
  8c:   31 e0           ldi r19, 0x01   ; 1
  8e:   80 34           cpi r24, 0x40   ; 64
  90:   92 07           cpc r25, r18
  92:   64 07           cpc r22, r20
  94:   75 07           cpc r23, r21
  96:   10 f0           brcs    .+4         ;  0x9c
  98:   31 2d           mov r19, r1
  9a:   31 70           andi    r19, 0x01   ; 1
  9c:   30 30           cpi r19, 0x00   ; 0
  9e:   39 f0           breq    .+14        ;  0xae
  a0:   8f 5f           subi    r24, 0xFF   ; 255
  a2:   9f 4f           sbci    r25, 0xFF   ; 255
  a4:   6f 4f           sbci    r22, 0xFF   ; 255
  a6:   7f 4f           sbci    r23, 0xFF   ; 255
  a8:   00 00           nop
  aa:   f1 cf           rjmp    .-30        ;  0x8e
  ac:   08 95           ret
  ae:   25 9a           sbi 0x04, 5 ; 4
  b0:   2d 9a           sbi 0x05, 5 ; 5
  b2:   0e 94 40 00     call    0x80    ;  0x80
  b6:   2d 98           cbi 0x05, 5 ; 5
  b8:   0e 94 40 00     call    0x80    ;  0x80
  bc:   fa cf           rjmp    .-12        ;  0xb2
  be:   f8 94           cli
  c0:   ff cf           rjmp    .-2         ;  0xc0

EDIT: There is some confusion regarding toolchain and what party could be responsible for this issue. So here's the atmega328p.json file which is responsible for telling the Rust compiler how to compile for this backend (AVR):
src:atmega32p.json
{
    "arch": "avr",
    "atomic-cas": false,
    "cpu": "atmega328p",
    "data-layout": "e-P1-p:16:8-i8:8-i16:8-i32:8-i64:8-f32:8-f64:8-n8-a:8",
    "eh-frame-header": false,
    "exe-suffix": ".elf",
    "late-link-args": {
        "gcc": [
            "-lgcc"
        ]
    },
    "linker": "avr-gcc",
    "llvm-target": "avr-unknown-unknown",
    "max-atomic-width": 8,
    "no-default-libraries": false,
    "pre-link-args": {
        "gcc": [
            "-mmcu=atmega328p"
        ]
    },
    "relocation-model": "static",
    "target-c-int-width": "16",
    "target-pointer-width": "16"
}

From what I understand, everything up until the linking is done by the Rust/LLVM part. Linking is done by avr-gcc. As @EdgarBonet said, looks like the code generated by Rust (in the generated --emit asm) is correct but the final linked output is wrong. Basically I'd like to file this bug and for that I need to understand who to file it to.

Why are you calling loop() inside main?

Because the function signature fn main() -> ! implies the function should never exit. For this, I've put an infinite loop at the end so that this function never returns.

I have no idea how the Rust toolchain works but, judging from the disassembly, it assumes the register r1 is loaded with 0, just like the C/C++ toolchain does. Clearing r1 is the job of the C runtime. Does the Rust toolchain link the C runtime? Could you disassemble the complete program and check that r1 is indeed cleared before calling main?

@EdgarBonet For Linux code it does link into C-RT but I'm pretty sure it wouldn't do that for bare-metal code. Let me check, and add the final linked code.

@EdgarBonet I've added the final linked disassembly. Could you please check? I am quite inept in reading assembly let alone AVR assembly.

Please do not cross-post (your question on StackOverflow). Decide which one to keep and delete the other.

This looks like a bug in the toolchain: an off-by-one error in all
relative jumps. For example, the main loop:
loop {
    write_reg(portB, 1 << LED_BUILTIN, 1 << LED_BUILTIN);
    delay(500_0000);
    write_reg(portB, 0, 1 << LED_BUILTIN);
    delay(500_0000);
}

got translated to this by RUSTFLAGS="--emit asm":
.LBB1_1:
    sbi 5, 5
    call    _ZN13arduino_blink5delay17h9627a982856e7dadE
    cbi 5, 5
    call    _ZN13arduino_blink5delay17h9627a982856e7dadE
    rjmp    .LBB1_1

which looks correct to me. However, on the disassembly of the final
program, it looks like this:
  b0:   2d 9a           sbi  0x05, 5 ;        PORTB |= (1<<5);
  b2:   0e 94 40 00     call 0x80    ; loop:  delay();
  b6:   2d 98           cbi  0x05, 5 ;        PORTB &= ~(1<<5);
  b8:   0e 94 40 00     call 0x80    ;        delay();
  bc:   fa cf           rjmp .-12    ;        goto loop;  // 0xb2

The instruction that turns the LED on is now out of the loop. There are
other similar off-by-one errors within the delay function, on the
instructions brcs, breq and rjmp.
I have no idea how to solve this, other than looking at the bug tracker
of the AVR Rust toolchain.
Edit: The Arduino IDE does not come with a Rust compiler. You are
thus using a separate, presumably experimental, compiler. My guess is
that, unless explicitly asked to --emit asm, this Rust compiler
compiles directly to machine code. It is pretty common nowadays to skip
the assembly language and compile from a high-level language directly to
machine code.
The first assembly snippet was obtained with --emit asm. It is not
really a “disassembly”, but the result of a direct Rust → asm
translation. The second snipped, generated by avr-objdump is a proper
disassembly: the result of a Rust → machine code → asm
translation.
My guess is that the bug lies in the Rust → machine code
translation, which is why it does not affect the --emit asm output.
Relative jumps on AVR are a bit unintuitive: they are relative to the
program counter, which is a CPU register holding the address of the
next instruction in the program. If you incorrectly assume these
jumps are relative to the current instruction, you get precisely the
faulty code of the second snippet.

All the avr-gcc, avr-g++, avr-objcopy, etc. are just symlink'd from Arduino's IDE. I'm not using some other variant of linker/compiler than the one that Arduino uses, so this is pretty weird - especially if the object code seems correct but the linked code seems wrong (which would've happened with the help of some AVR linker).

@zombiesauce: See amended answer.

I was not claiming that Arduino comes with a Rust compiler. Now I'm not exactly sure how Rust compiles to AVR, but it really offloads a lot of architecture-specific compilation to the GCC AVR toolchain. I think it generates MIR (middle intermediate representation) from the pure Rust toolchain, and the rest of the AVR stuff including linking is done via the those avr-gcc, avr-objcopy and the whole shebang. Now, instead of downloading it from Ubuntu's repository, since I already have Arduino; I have instead just exported their PATH. Hence maybe problem is in Rust <-> AVR toolchain interaction.

@zombiesauce: Re “I'm not exactly sure...”: Maybe you could launch the Rust compiler driver in verbose mode in order to see exactly how it interacts with the GCC toolchain. If the compiler proper generates an object file to be linked by avr-gcc, you could check whether this file contains intermediate language or machine code. If it's machine code, you could disassemble it and see whether it has the faulty relative jumps.

Nicely explained, although I wonder how this compiler ever got released if it compiles branches incorrectly. It also seems odd that if it can generate the correct assembler code, that this code is not used in the next step (ie. by the gcc assembler).

@NickGammon Agreed, that feels like an insane blunder. Although, nightly releases are not meant for consumer consumption, they're (supposed to be, but I hadn't experienced it before till now) very unstable.

@EdgarBonet was correct. Turns out there is actually a problem in code generation for AVR in the latest nightly release of Rust compiler. Setting the nightly compiler version to 2023-12-11 (11th Dec, 2023) makes the program work flawlessly.
EDIT: Forgot to mention but I have already filed a bug-report/issue on Rust's GitHub.
EDIT#2: The bug was in LLVM toolchain for AVR (remember, compilation is still done by LLVM). The upstream bug has now been fixed.

At least this gave Edgar Bonet a chance to explain how the code generation works. Very interesting thread.


text:
MEGA 2560: Simple program - One analogWrite turns off the other
I'm using Windows 10, Arduino 1.8.12 (Windows Store 1.8.33.0)
I have an Arduino MEGA 2560 and a red LED connected to pin 4.
#define RED 4
#define GREEN 2

void setup() {
  analogWrite(GREEN,  0);
  analogWrite(RED,  100);
}

void loop() {

}

This code lights up the red LED.

However, when I write 1 to the GREEN pin analogWrite(GREEN,  1), the red LED goes off. I'm expecting the red LED to stay on.

#define RED 4
#define GREEN 2

void setup() {
  analogWrite(GREEN,  1);
  analogWrite(RED,  100);
}

void loop() {

}

The red LED stays on when both written values are the same, e.g.
  analogWrite(GREEN,  25);
  analogWrite(RED,  25);

I also found that adding some "garbage" code at the beginning fixes the issue. I wasn't able to get the garbage into a simpler form without both pins shutting off.

#define RED 4
#define GREEN 2

void setup() {
  // GARBAGE BEGIN ===
  unsigned long t = millis();
  const unsigned long period = 10;
  float progress = float(t % period)/period;
  float r = progress * 0;
  // GARBAGE END ===

  analogWrite(GREEN,  100 + r);
  analogWrite(RED,  50 + r);
}

void loop() {

}

Update: Thanks all for your comments. Setting the pinMode to output did not fix the issue. However, changing the function declaration to __attribute__((optimize("-O0"))) void setup() { fixed the issue. -O1 also works, but -O2 fails.

Do both LEDs have suitable current-limiting resistors?

Actually there is only one LED attached, and it's connected through a 220 Ohm Resistor.

Please, show your circuit schematic.

Wait, what? There's only one LED attached, but when you turn on one of your LEDs the other one turns off? That makes no sense.

@DuncanC it's not that I turn on another LED, it's that I analogWrite to an additional pin and it turns off the LED pin.

do both pins exhibit the same behavior?

@jstola Yes, it seems that doing simultaneous writes will disable both of them.

looks like a bug in the library ... do you have the correct board selected in the arduino IDE? ... does the behavior remain if you insert a command line between the two ... something as simple as a++;

Try before the write pinMode(GREEN, OUTPUT); pinMode(RED, OUTPUT); and give feedback if it worked

@Codebreaker007 I started to post that the OP was missing the calls setting the pins to outputs, but if you look up the docs on analogWrite() it says specifically that you don't have to set the pin to output before using it, which surprised me. It's probably still worth trying a try though.

You should post an answer to your own question. with the solution you found. I would suggest trying calls to pinMode(GREEN, OUTPUT); pinMode(RED, OUTPUT) as Codebreaker suggests, as well as adding a short delay in your setup in place of the "garbage code" you posted.

If you use ArfuinoIDE < 1.6 you have to define pin mode, since then its done in analogWrite.c.If using IDE >=1.8.10 its an optimization problem by the compiler for the Mega try to replace the line void setup() with void setup() attribute((optimize("-O0")));  // also -O1 works the default -Os and -O3,-O4 not

If you look in the source code for analogWrite, one of the first things it does is set the pinMode.

Yes since around 1.6 on as I wrote as we do not know OPs version we have to exclude basic things not everybody is always on the latest version

@Codebreaker007 Setting the optimization level to 0 or 1 fixes the issue (see my update in my post). I'm wondering if you can direct me to an explanation of why this occurs.

However, would you mind to answer your own question, and mark it (later, if you're forced to wait), please? This will help others investigating the same problem, because they can upfront see that your problem is solved.

As you are using using ArduinoIDE >=1.8.10 its an "optimization" problem by the compiler for the Mega try to replace the line
 void setup()

with
 void setup() __attribute__((optimize("-O0")));

// also -O1 works the default -Os and -O3,-O4 not
Actually the problem is not the IDE version but the included AVR boards package version.  You can install any AVR boards package in any IDE with Boards Manager. Last good AVR boards package is 1.6.21. If your compiler (tool chain) shows 7.03 in the output window you  are affected. I have examples where the compiler even optimizies the loop away, which ends in funny results - I dont know wether other boards are also affected but the MEGA is for sure.

Is there a bug report issue opened with Arduino for this? This definitely needs to be fixed!

Yeah more than one the last one https://github.com/arduino/Arduino/issues/9659

This one looks relevant as well https://github.com/arduino/Arduino/issues/9653

source: Stack Exchange

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

sort: votes


text:
NRF24L01+ Getting Started Acknowledge Failed
I have followed numerous guides and tutorials for getting the NRF24L01+ modules working with an Arduino Uno. I have swapped to a genuine Arduino and tried 4 different NRF modules. All without luck.
I am trying to get the most basic example from Simple nRF24L01+ 2.4GHz transceiver demo to work.
Hardware Connections:

Simple TX Test Code:
// SimpleTx - the master or the transmitter

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte slaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

char dataToSend[10] = "Message 0";
char txNum = '0';

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000; // send once per second

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleTx Starting");

    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.setRetries(3,5); // delay, count
    radio.openWritingPipe(slaveAddress);
}

//====================

void loop() {
    currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {
        send();
        prevMillis = millis();
    }
}

//====================

void send() {

    bool rslt;
    radio.stopListening();
    rslt = radio.write( &dataToSend, sizeof(dataToSend) );
        // Always use sizeof() as it gives the size as the number of bytes.
        // For example if dataToSend was an int sizeof() would correctly return 2

    Serial.print("Data Sent ");
    Serial.print(dataToSend);

    if (rslt) {
        Serial.println("  Acknowledge received");
        updateMessage();
    }
    else {
        Serial.println("  Tx failed");
    }
}

//================

void updateMessage() {
        // so you can see that new data is being sent
    txNum += 1;
    if (txNum > '9') {
        txNum = '0';
    }
    dataToSend[8] = txNum;
}

Serial monitor:

Using radio.printDetails( ); returns:

Please let me know what I'm missing.

Can you please upload the unmodified PingPair example and see if that works?

Where is the code for the receiving side? If there is no receiver, the sender won't get an ACK packet back, and you get the TX failed error message.

What is this: uint8_t slaveAddress[5] = {0xF0F0F0F0A1LL, 0XF0F0F0F0B1LL, 0XF0F0F0F0C1LL, 0XF0F0F0F0D1LL, 0XF0F0F0F0E1LL};? How do you expect such large values to fit into uint8_t??? The compiler will interpret this as uint8_t slaveAddress[5] = {0xA1, 0xB1, 0xC1, 0xD1, 0xE1};. Is this what you wanted? I'd guess not. Also, take a look here https://github.com/nRF24/RF24/blob/master/RF24.h#L246 how the address is supposed to be formed.

@AnT I was trying the same as 1 of the answers here: https://arduino.stackexchange.com/questions/65249/nrf24l01-tmrh20-library-receiver-gets-blank-data before you commented there as well. Thank you, have updated the question and code.

Thank you all so much. Not sure why I was expecting the radio.write function to return True without a receiving end. It's working.

How did you get RF_CH=0x76?  That's not the default radio channel on power up, so are you not showing the complete version of the code?

The Arduinos 3V3 does not privide enough current. To eliminate this as a source of your problem you can use a ceramic capacitor of 100µF across VCC and GND pins of the nRF24L01+ module or buy a 5V to 3V3 step down converter specially made for nRF24L01.

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


text:
ESP8266 /ESP12F use flash button as input without using loop()
I couldn't find a proper answer anywhere on internet.
I want to use the FLASH button as input in the setup() function and do not use the loop() with deepsleep mode (this part comes later).
I tried demos wherein the button events are sometimes failed to be captured. How can I make it 100% sure to get detected as soon as I press reset or along with reset? Because there is a mismatch in the time when reset is clicked and the flash button press gets detected.

you want to read in setup if the button is pressed? pinMode(D3, INPUT_PULLUP); if (digitalRead(D3) == LOW) ...

you can't read buttons while resetting, can you elaborate on the goal a bit more?


text:
Arduino stops logging data after ~32761 seconds
I made a small set up to log temperature on SD card, everything is running smoothly until it reach 9:06:01 of logging that is  32761 seconds. I know that corresponds roughly to the maximum value of an integer. But I made all my variables unsigned long.
Here is the code in the loop and the if condition to log or not. The timer is computed with currentTime (unsigned long) and startTime (unsigned long). So even if logCount*freq are both integers, they should reach maximum value after 32761 seconds, then the if condition should always be true.
void loop() {
 String date;
 unsigned long timer;
 int freq = 60;

 sensors.requestTemperatures();
 tempC1 = printTemperature(insideThermometer, 18);
 tempC2 = printTemperature(outsideThermometer, 19);

 // start serial port
 Serial.begin(9600);

 mainMenuDraw();
 operateMainMenu();

 CurrentTime = millis();
 timer=(CurrentTime - StartTime)/1000;
 date = TimeShowFormatted(CurrentTime - StartTime);

 if (timer > logCount * freq and StopStatus == 0) {
  logCount += 1;
  LastLoggedDate=date;
  DataLogg(date);

 }
}

What's StartTime? Add rest of your code so I can simulate it please.

To increment a variable, use logCount++;

@FilipFranik StartTime is a unsigned long that is initialized at zero when arduino is started or re-initialized at zero when the logging is restarted (via menu on LCD shield)

Instead of comparing absolute times you should use the following:
unsigned long now = millis();

if(now - time_last_log >= freq){
    logCount += 1;
    LastLoggedDate=date;
    DataLogg(date);
    time_last_log = now;
    // or if you really want fixed intervals
    // time_last_log += freq;
}

This is guaranteed to be overflow proof.

This code can also fail badly. It's possible for time_last_log to be close to max value of 'unsigned long' and then it never get's updated because now is always lower. I suggest adding || now < time_last_log to the if to escape that infinite loop.

@FilipFranik: No, it will not fail when time_last_log gets close to ULONG_MAX. Owing to the rules of modular arithmetic, this code is rollover safe. Try for yourself if you are not convinced.

@EdgarBonet You broke my brain. You are right.

@EdgarBonet Thank you for your helpful insight. It is always great to learn something! I'll test today the solution and validate the answer if everything is ok.

@EdgarBonet it works well, 21h of logging and still running.thank you very much


text:
problem with decrement in a loop
I am trying to write a sketch wherein the led brightness increases in increments of 15 until it reaches 255. At that point I want to make decrements of 15 until it reaches 0. The increment part of the program works well but the decrement part goes haywire. It gets stuck between 255 & 240. I am not sure how can I fix it. Could you please tell how can I make it work?
Here is my sketch:
int led = 9; //led pin
int fade = 0; // pwm value

void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

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

   analogWrite(led,fade);
   fade += 15;
   Serial.println(fade);
   delay(250);

  if (fade >= 240){
    fade = fade - 15;
    analogWrite(led, fade);
    Serial.println(fade);
    delay(250);
  }

}

the decrement part is not haywire ... it is doing exactly what you told it to do

see the Fading example in Arduino IDE

Perhaps with a for loop it's easier to implement as in Fading example but I was trying to do it using a conditional statement.

sorry, I thought the example is better

Does this answer your question? PWM delay without blocking the code

The problem is that you add 15, and than if it's >= 240, you decrease 15, so it will not change  (I wouldn't consider it haywire though).
You can better use a direction sign. Below is only the relevant code (not the GPIO functionality). What it does in the loop is, in case up is true, it adds fifteen, otherwise it subtracts 15. When 255 is reached, it starts counting down (up is false), when reaching 0, it starts counting up (up is true). This only works if 255 / the amount to add/subtracts reaches exactly 255, otherwise you have to check for <= 0 and >= 255.
bool up = true;
int fade = 0;

void loop()
{
    fade += up ? 15 : -15;
    if (fade == 0)
    {
      up = true;
    }
    else if (fade == 255)
    {
      up = false;
    }
}

Not considered good coding practices:
The last if statement can be substituted for the following line, which means: if going up and 255 is reached, go down, else if going down and 0 is reached, go up, otherwise don't change direction. But it is much less readable, so I prefer the longer if statement.
up = (up && (fade == 255)) ? false : ((!up && (fade == 0)) ? true : up);

Another version: if fade is 0 or 255 (only two possibilities), go up if 0 is reached, else (can only be 255) go down, else don't change.
up = (fade % 255 == 0) ? (fade == 0) : up;

Thanks. Yes I realized why the decrement loop was stuck. It wasn't going haywire. I am new to programming and loops within loops are not really my forte :) Need to practice more but thanks for explaining.

You're welcome. Just follow the first part (the 'good pcoding practice'), use good variable names, and break your problems in small steps. Good luck with your project.

The if condition is causing the issue. When the global variable fade reaches 240, upon entering the loop(), you are incrementing it by 15, making fade = 255. So, the if condition becomes true and 15 is subtracted from 255 making fade to be equal to 240 again. This keeps repeating and hence the value fade variable is stuck between the values 240 and 255.

Thanks. I see the error in my logic now :)

Great! Good luck!


text:
Getting wdt reset + reboots every 5 seconds on simple button/relay code that has worked previously, now it does not and I changed nothing
I have some arduino code I adapted from a simple 2 button 2 relay code I found online. I just multiplied everything so I could have 5 buttons/5relays. I am using a NodeMCU (ESP-12E) for this.
I have not changed anything, and now trying to upload it to other boards, and the same existing board I used before. Same results every time.
I have verified arduino is updated, the board manager link is up to date, and verified the code. Drivers re-installed. I have tried using different boards such as nodemcu 0.9, generic esp8266 module etc.
Code is verified, no error messages upon upload.
But every single time I get this error in the serial monitor over and over:

 ets Jan  8 2013,rst cause:4, boot mode:(3,6)

wdt reset
load 0x4010f000, len 1392, room 16
tail 0
chksum 0xd0
csum 0xd0
v3d128e5c
~ld

And here is the code I am using:
(But please keep in mind this WORKS and has worked before)
//Buttons

int button1 = 4;
int button2 = 13;
int button3 = 12;
int button4 = 15;
int button5 = 10;

//Relays
int rl1 = 5;
int rl2 = 0;
int rl3 = 14;
int rl4 = 16;
int r15 = 9;

//States for Relay and Button (1)

int state1 = HIGH;      // the current state of the output pin
int reading1;           // the current reading from the input pin
int previous1 = LOW;    // the previous reading from the input pin

//States for Relay and Button (2)

int state2 = HIGH;      // the current state of the output pin
int reading2;           // the current reading from the input pin
int previous2 = LOW;    // the previous reading from the input pin

//States for Relay and Button (3)

int state3 = HIGH;      // the current state of the output pin
int reading3;           // the current reading from the input pin
int previous3 = LOW;    // the previous reading from the input pin

//States for Relay and Button (4)

int state4 = HIGH;      // the current state of the output pin
int reading4;           // the current reading from the input pin
int previous4 = LOW;    // the previous reading from the input pin

//States for Relay and Button (5)

int state5 = HIGH;      // the current state of the output pin
int reading5;           // the current reading from the input pin
int previous5 = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time1 = 0;          // the last time the output pin was toggled
long time2 = 0;
long time3 = 0;
long time4 = 0;
long time5 = 0;

long debounce1 = 60;   // the debounce time, increase if the output flickers
long debounce2 = 60;
long debounce3 = 60;
long debounce4 = 60;
long debounce5 = 60;

void setup()
{
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);
  pinMode(button4, INPUT);
  pinMode(button5, INPUT);

  pinMode(rl1, OUTPUT);
  pinMode(rl2, OUTPUT);
  pinMode(rl3, OUTPUT);
  pinMode(rl4, OUTPUT);
  pinMode(r15, OUTPUT);

}

void loop() {

  reading1 = digitalRead(button1);
  reading2 = digitalRead(button2);
  reading3 = digitalRead(button3);
  reading4 = digitalRead(button4);
  reading5 = digitalRead(button5);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  //Condition Relay 1
  if (reading1 == HIGH && previous1 == LOW && millis() - time1 > debounce1) {
    if (state1 == HIGH)
      state1 = LOW;
    else
      state1 = HIGH;

    time1 = millis();
  }

  //Condition Relay 2
    if (reading2 == HIGH && previous2 == LOW && millis() - time2 > debounce2) {
    if (state2 == HIGH)
      state2 = LOW;
    else
      state2 = HIGH;

    time2 = millis();
  }

  //Condition Relay 3
    if (reading3 == HIGH && previous3 == LOW && millis() - time3 > debounce3) {
    if (state3 == HIGH)
      state3 = LOW;
    else
      state3 = HIGH;

    time3 = millis();
  }

  //Condition Relay 4
    if (reading4 == HIGH && previous4 == LOW && millis() - time4 > debounce4) {
    if (state4 == HIGH)
      state4 = LOW;
    else
      state4 = HIGH;

    time4 = millis();
  }

  //Condition Relay 5
    if (reading5 == HIGH && previous5 == LOW && millis() - time5 > debounce5) {
    if (state5 == HIGH)
      state5 = LOW;
    else
      state5 = HIGH;

    time5 = millis();
  }

  digitalWrite(rl1, state1);
  digitalWrite(rl2, state2);
  digitalWrite(rl3, state3);
  digitalWrite(rl4, state4);
  digitalWrite(r15, state5);

  previous1 = reading1;
  previous2 = reading2;
  previous3 = reading3;
  previous4 = reading4;
  previous5 = reading5;
}

If I google this error I get a myriad of results that so far have not helped me. Any help or insight on how I can better understand this error, where to start, and what I need to do to get this "simple" sketch working would be awesome.  I'm at my wits end and all I want is a simple lighting panel to work.

that looks like a status message, not an error message

But with this, it reboots over and over and shows the message each time.

that does not mean that it is an error message .... it may be boot status messages ... looks like the chip is in a wrong state ... could be something wrong with your breadboard, if you are using one ... or the watchdog timer is set incorrectly

I think it is a brown out

Did it ever work with 5 relays?

@orithena yes it did. i changed gpio9 to gpio2 and now it stopped rebooting every 10 seconds.

io 9 is used by the QIO to flash memory

For anyone that has a similar issue, I figured it out. GPIO 9 could not be used for a relay/output for whatever reason. Wish I knew why.  Switched it to GPIO2 (D4) and the reboots stopped.

Pins 6-11 on most NodeMCUs are used for connecting the on-board SPI Flash memory and are not recommended for use as general I/O pins.

@starcat I understand that but I just find it strange pin 9 worked in the past, nothing changed, then now it magically doesn't.

@Coltography Found the culprit. GPIO9 and GPIO10 are not usable on boards that use Quad-IO Flash SPI access (which needs 4 data lines instead of 2 on Dual-IO Flash). It seems that some NodeMCU boards do use DIO, some other use QIO -- and on those QIO boards, messing with the Flash SPI pins seem to trigger the watchdog, which then reboots the chip. Here's the schematics with commentary on GPIO9: https://www.esp8266.com/wiki/lib/exe/fetch.php?media=schematic_esp-12e.png -- and here's the issue in the Arduino ESP8266 core: https://github.com/esp8266/Arduino/issues/1446

First thing to realize for you is that the externally set status of three of the GPIO pins determine the boot mode for the ESP8266 used on your NodeMCU. So you must take care to check that your external wiring will not interfere with the boot mode:

GPIO15/D8 must be LOW on boot (i.e. no external pull-up resistors may be connected between D8 and 3.3V)
GPIO2/D4 must be HIGH on boot (i.e. no external pull-down resistors may be connected between D4 and GND)
GPIO0/D3 must be free of pull-up/down resistors so that the USB-to-serial chip can switch between RUN and FLASH mode.

Also, holding GPIO16/D0 LOW for an extended amount of time while running may have unintended side effects like triggering the watchdog, especially if the board manufacturer decided to add the deep sleep wakeup resistor between D0 and RST (you most certainly have a NodeMCU clone, so this might actually be possible).
So it might very well be that you need to reverse the button logic on GPIO15/D8 (i.e. connect the button between D8 and 3.3V). It also might be that the pin numbering on your NodeMCU is confusing; better use the D0-D10 constants.
Depending on the type of your relays, your relays may act as a pull-up/down resistor, too, further adding to the confusion.
I'd try this sketch without anything connected (no buttons, no relays) and when it works, I'd add buttons and relays one by one until you find the culprit. Sometimes it might be sufficient to swap a relay and a button, sometimes you need to reverse the logic on a button.
I would say that using any ESP8266 with that many input/output lines requires very careful consideration on where to connect what. The GPIO pins on an Arduino Nano are not involved in boot mode nor watchdog, so at least there you'd not get any interference.

Hello, thank you for the detailed response.  I do not have anything attached to the nodemcu so that unfortunately rules out any of the gpio issues.
What I don't get is how this exact code is on another nodemcu with no issues, but I've uploaded it to 3+ other boards and gotten this constant crash/boot cycle now.

According to Esp8266 documentation this is a software reset.
After a fast peek, I didn't find delay() or yield() in your code.
The esp8266 needs to attend some time to WiFi related background tasks, and it is does when your arduino code delays or yields the processor.

i was going to suggest adding a sleep(1). great minds think alike...

AFAIK a yield() is implicit in every repetition of loop()

Why would this work on another nodemcu without that, though? And where would I put the delay() part of the code?


text:
why this unexpected behaviour shows when i use the following code to send the data from the ultrasonic distance sensor to firebase
I am using nodeMCU esp8266 wifi module to send the data received by the ultrasonic distance sensor to the firebase.
here is my code:
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>

//Firebase settings
#define FIREBASE_HOST "dis3333333333333333aseio.com"
#define FIREBASE_AUTH "Lb21333333333333333333v6HzPatg1HA"

//Wi-Fi settings
#define WIFI_SSID "hello"
#define WIFI_PASSWORD "123456789"

//Define trigger and echo digital pins
const int trigPin = 5;
const int echoPin = 4;

// The amount of time the ultrassonic wave will be travelling for
long duration = 0;
// Define the distance variable
double distance = 0;
double cm=0;
double statusTemp=0;
int temp=0;
unsigned long time_now=0 ;
unsigned long time_prev=0 ;
String stringOne="consump/day";
String stringTwo;

void setup()
{

    Serial.begin(9600);
    // Connect to Wi-Fi
    Serial.print("Wi-Fi...");
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print("Connecting...");
    while (WiFi.status() != WL_CONNECTED)
    {
        Serial.print(".");
        delay(500);
    }
    Serial.println();
    Serial.print("Connected to: ");
    Serial.println(WiFi.localIP());

    Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

    // Ultrasonic sensor, set echo as Input and trigger as Output

}

void loop()
{

    getDistance();
    time_now = millis();

    Serial.print("Distance: ");
    Serial.println(distance);

    delay(500);
}

void getDistance()
{
    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    pinMode(echoPin, INPUT);
    Serial.print("Time: ");
    Serial.println(time_now);
    if(statusTemp==0){
      time_prev=time_now;
      statusTemp=1;
      Serial.println("Hello");
    }
    if(statusTemp==1)
    {
      if((time_now - time_prev)> 10000){
        statusTemp=0;
        stringTwo=stringOne+temp;
        Serial.print(stringTwo);
        Firebase.setFloat(stringTwo, distance);
        temp++;
        Serial.print(temp);
      }
        duration = pulseIn(echoPin, HIGH);

        distance = duration * 0.034 / 2;
        Firebase.setFloat("distance", distance);
        if (Firebase.failed()) {
        Serial.print("setting /number failed:");
        Serial.println(Firebase.error());
        return;
    }
 }
}
long microsecondsToCentimeters(long microseconds) {
   return microseconds / 29 / 2;
}

It works totally fine but after some time the below thing appears

Is the following thing happening due to my code or something else is causing this.

Looks like some memory issue (from the descriptions of similar errors found through google). You are using String, which is not good. Read Majenko's blog entry about the Evils of Arduino Strings. Try to use char arrays instead (also called C-Strings). If that works, I will write a full answer.

have you tried the exception decoder? it should tell you the line of code that crashes.


text:
434 RF Transmitter and Receiver for distance measurement problem
As a student I'm working on a project where we use 434 MHz RF Transmitter and receiver pairs for distance measurement. I know that this technology is not a good choice for this, but we have to deal with this problem due to external constraints.
Here is the receiver: RF Link Receiver - 4800bps (434MHz).
I did a little bit of research how these receivers works, but I found it a bit overwhelming to understand them bit by bit.
We want to use the signal strength for distance measurement. So we tried sending pulses of signals from one transmitter to a receiver. If the amplitude of the signal received is higher than a certain value (let's say 3V), it sends back a signal (let's call it trigger signal) in the gap between the two pulses.
The problem is that that these signals seems to affect each other even though they are not in the same time (so it's not superposition that we are talking about). When there is a signal sent back, the next pulse will be lower, which results in false distance measurement.
The whole difficulty is (to me it seems) that we are not using these signals to send data, we are using it for distance measurement. My idea is that we are using too long pulses and the AC coupling in the receiver doesn't tolerate it, but again, I don't have enough electrical knowledge to safely say that.
I know this is not descriptive, but I don't know how to make it more descriptive, so I'm happy to answer more questions on demand.

Did you read about the RX module? Does it have AGC (Automatic Gain Control)? If is does it will increase gain until noise level. When a signal is detected it has to "tune back".

Where can I read more about that? Or what is that for?

This does sound like transmitting the reply could be desensetizing the receiver's AGC.  Perhaps you can run some tests by sending pairs of pulses in one direction a varied time period apart, and a looking at how the amplitude of the second received pulse varies based on the time delay.  Perhaps you can simply reduce the experiment frequency to give the AGC more time to recover, or transmit the reply by some other means (2.4 GHz?  IR?).  Even better implementations of your RSSI distance idea (BTLE chips for example) are less than impressive.

What do you mean by reducing the experiment frequency? Isn't increasing what would be reasonable here? So it doesn't set its noise level to a new value?

That depends on which AGC gain you want.  I was thinking by waiting longer after each reply pulse (or opportunity) before a new transmit pulse, you could let the AGC reset.  Though I suppose an alternative would be to wait less time, and try to keep the AGC active.  To do that you would need to always transmit a reply.  Perhaps you could encode the result in a variable delay between the outgoing pulse and the reply, but always make the time from the reply to the next outgoing pulse the same. If you miss a reply entirely, you'll probably have to ignore the next one given the unkown AGC state.

This is the simple RSSI implementation for RF433 Virtual Wire that I came up with for Cosa; https://github.com/mikaelpatel/Cosa/blob/master/libraries/VWI/VWI_Receiver.cpp#L156. After receiving a message the receiver measures the time to "recover", i.e. the AGC to tune back to noise level. The weaker the TX was the faster the tune back.

It is very likely you have an AGC problem. Try to slow down the measurement. The sender shall send data not often than once per second.
This idea is not fully perfect for doing a distance measurement. It measures incoming power strength - affected by walls, reflection, AGC of the receiver, and a lot more. If you have a scope, measure the waveform on the pin 3 of the module (linear out). It is not a constant voltage, I am afraid, so you need some sort of averaging too.
A tricky way to get along even if you have an AGC is to measure how long the AGC needs to settle. The AGC works as follows: it detects the signal, and within some time (say, 2ms) it will change the amplification so that the signal will look having the full amplitude.

compare on a two channel scope the signal pulse driving the transmitter
and the signal on the pin 3 of the receiver module

If you are lucky, you'll see that actually pin3 or pin2 output is delayed a bit compared to the transmitter driving pulse. The delay depends on the power of the incoming signal to the receiver, which depends on the distance.
I was able to make an acceptable distance sensor from a standard AGC enabled IR receiver using the principles above.

We got around the problem today by sending 2ms pulses and 100ms gaps. This seems to solve the problem on the scope level. The thing is that our Arduino delays seem to be not precise enough to read the 2ms pulse in the right time, but that's another problem.

I found that delays are surprisingly precise. However, you have to have some mechanism to get the rising edge of your pulse first. For that, you either need a simple loop which checks for the pin state with digitalRead, and once a rising edge is found, you can start timing. But, aren't you planned to read the analog value on pin 3 of the module?

I don't know why I haven't accepted this answer before. It was a very old project and I do remember that making a sensor using an RF receiver is not a good idea. The automatic gain controller (AGC) was a significant problem. You would want to use probably something else but that wasn't available for me back then in an university setting.

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


text:
POV using ATmega328 powered with cr2032 cell
I am planning to make a POV (persistence of vision) display using ATmega328 with 5 red LEDs for display.
Below are my aims:

I want to power it with cr2032 coin cell, so power consumption has to be taken care, I am ready to keep single or 2 coin cell in parallel to meet current requirement.

Using 8MHz clock instead of 16MHz can help

Does it require separate boot-loader to be installed?
During boot-loading do I require to put external 16MHz clock?
How to ask controller to use the internal 8MHz clock?

Supply voltage of 3V instead of 5V can also help, and cr2032 gives out 3V

What care should I take while using it at 3V?
Any mechanism to set the threshold for controller to stop working?

To reduce the weight of whole circuit so I can rotate the board using small toy motor (I don't have a gear box).
I am planning to control the speed of motor using LM317 voltage regulator as a constant current source.
I will mount the LEDs on straw, keep the controller and the coin cells at the center. (Guessing that will reduce the torque required by the motor as torque=Force*radius and weight being at center reduced the radius)
I am okay, if this circuit works for just few hours OR days.

This video from "GreatScott" covers this type of project very well. https://m.youtube.com/watch?v=57carjNxI9A

In the Atmega datasheet, you can read that 16mhz may not work at 3V. You'll probably have to program it using an USBasp or something comperable, to also be able to change the fuse bits.

It may also help to have some kind of feedback that indicates whenever a full turn has been made. This way the display can be synchronized to the speed of the motor, and keep orientated right. Then you can most likely alsof skip the LM317

Why not use an Arduino LilyPad?

Welcome to StackExchange.  Be sure to take the Tour at https://arduino.stackexchange.com/tour to see how it works here.

Not exactly an answer, but too big to place into the "comments" area.
Clock
For the 8MHz vs 16MHz, you should be able to run your project at 1MHz. Just use a bare AVR MCU with the Internal 8MHz oscillator divided by 8 - search for AVR Fuses. You can program it using an ISP (or and Arduino as ISP)
Battery
About the CR2032 or coin-cells in general are not designed to constantly supply current. You can use it for very low currents, up to 2-4mA or in pulses. Otherwise you damage the cell, reducing it's total usable capacity. Maybe have a look on sub AAA batteries instead of coin-cells.
Motor
For the motor, have a look on the micro coreless dc motors. They are really tiny and should offer an excellent efficiency. Motor example
Motor Driver
Not sure about the LM317. You don't want any kind of regulation as it would waste energy. To drive the motor a small Mosfet should do the trick. You can control the Mosfet using PWM, which will define the motor speed. Don't forget to implement some kind of rotary encoder to count the motor RPM so you can precise speed control - a tiny magnet and a hall-sensor should be enough.

Indeed.  If the motor is powered by something else, this could work at a low clock rate.  But if the motor is supposed to be powered by this circuit, ie, it rotates itself, then a more capable power source is needed.

1. You said you wanted to use your Atmega328 at minimal power usage so you asked how can I use my Atmega at 8mhz. So for doing that first you need to bootloader your Atmega with a 8mhz Bootloader so that it could work with its internal 8mhz source.
2. You said you wanted to use coin cells. But coin cells provide a very low amount of power and they are used for small projects. So instead you could use Lithium Ion batteries or AAA batteries.
3. You said you will probably look forward to use LM317 as motor controller and a small toy DC motor. Well if you would use LM317 i.e. Voltage regulator you would ended up with a lot of power consumed by it. So I would probably say you to use a MOSFET as Talk said. Now for the motor it's ok upto when you are okay with it. Now I can't say you specifically which motor you looking for as there are many motors with many shapes and features. And that could be done by just searching on Google.

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


text:
Why am I getting only around 40% the range of my ADS1115 using an Arduino Uno?
I've connected my ADS1115 to an Arduino Uno as in the diagram (Vdd - 5V, Gnd - Gnd, SDA/SCL - SDA/SCL), all powered from the USB on a PC, with A0-3 unconnected, and am getting readings of around 3000 (i.e. 3000/65535 on 5V supply = 0.23V) from all four analog pins. Then if I connect them to 3.3V output on the arduino they give me only 17625 (i.e. 1.34V) i.e. about 40% of the full range I expected. If I try with a seperate 5V supply, it's still the same problem. Why is this?
P.S. sorry the code format below isn't very good, but basically it reads the four pins by
int16_t V1 = ads.readADC_SingleEnded(PIN).

#define THERMISTORPIN1 0
#define THERMISTORPIN2 1
#define SHELLPTPIN 2
#define SPAREPIN 3
#include < Wire.h >
#include < Adafruit_ADS1015.h >

Adafruit_ADS1115 ads(0x48);  //16 bit ADC add-on for arduino for better temperature resolution
float Voltage = 0.0;

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

void loop(void)
{
    int16_t V1;
    int16_t V2;
    int16_t V3;
    int16_t V4;
    long cumV1;
    long cumV2;
    long cumV3;
    long cumV4;
    float avgV1;
    float avgV2;
    float avgV3;
    float avgV4;

    //take readings of voltages between resistor and thermsitor
    int i=0;

    while(i<6) {
        V1 = ads.readADC_SingleEnded(THERMISTORPIN1); //5 readings to allow the arduino capacitors to equalize with the pin voltage, to increase accuracy
        V2 = ads.readADC_SingleEnded(THERMISTORPIN2);
        V3 = ads.readADC_SingleEnded(SHELLPTPIN);
        V4 = ads.readADC_SingleEnded(SPAREPIN);
        i++;
        delay(10);
    }

    while(6<=i && i<16) {
        cumV1+= ads.readADC_SingleEnded(THERMISTORPIN1);  //multiple measurements from which to take an average, to increase precision
        cumV2+= ads.readADC_SingleEnded(THERMISTORPIN2);
        cumV3+= ads.readADC_SingleEnded(SHELLPTPIN);
        cumV4+= ads.readADC_SingleEnded(SPAREPIN);
        i++;
        delay(10);
    }

    avgV1=cumV1/10;
    avgV2=cumV2/10;
    avgV3=cumV3/10;
    avgV4=cumV4/10;

    //print out information to serial monitor on laptop
    Serial.print(V1);
    Serial.print(" ");
    Serial.print(V2);
    Serial.print(" ");
    Serial.print(V3);
    Serial.print(" ");
    Serial.println(V4);
    Serial.print(" ");
    Serial.print(avgV1);
    Serial.print(" ");
    Serial.print(avgV2);
    Serial.print(" ");
    Serial.print(avgV3);
    Serial.print(" ");
    Serial.println(avgV4);
    //Serial.println();
    delay(1000);
}

first off, single ended readings are only 15 bit. secondly, providing 3.3v will limit the measurement to 3.3v; 66% of 5v.

Your readings are correct because you have the default gain set. You have incorrectly assumed that you can convert the ADC reading from your 16-bit ADC to Volts by dividing by 2^16 - 1. Your ADC has gain settings to have more accurate readings for certain voltage intervals. If we look at the example sketch, we see
 void setup(void)
{
  Serial.begin(9600);
  Serial.println("Hello!");

  Serial.println("Getting single-ended readings from AIN0..3");
  Serial.println("ADC Range: +/- 6.144V (1 bit = 3mV/ADS1015, 0.1875mV/ADS1115)");

  // The ADC input range (or gain) can be changed via the following
  // functions, but be careful never to exceed VDD +0.3V max, or to
  // exceed the upper and lower limits if you adjust the input range!
  // Setting these values incorrectly may destroy your ADC!
  //                                                                ADS1015  ADS1115
  //                                                                -------  -------
  // ads.setGain(GAIN_TWOTHIRDS);  // 2/3x gain +/- 6.144V  1 bit = 3mV      0.1875mV (default)
  // ads.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV      0.125mV
  // ads.setGain(GAIN_TWO);        // 2x gain   +/- 2.048V  1 bit = 1mV      0.0625mV
  // ads.setGain(GAIN_FOUR);       // 4x gain   +/- 1.024V  1 bit = 0.5mV    0.03125mV
  // ads.setGain(GAIN_EIGHT);      // 8x gain   +/- 0.512V  1 bit = 0.25mV   0.015625mV
  // ads.setGain(GAIN_SIXTEEN);    // 16x gain  +/- 0.256V  1 bit = 0.125mV  0.0078125mV

  ads.begin();
}

Your ADC has a default gain of 2/3, or 0.1875mV per count. You say when you connect 3.3V to the pin, you get a reading of 17625. Thus we have
17625 * 0.1875 / 1000.0 [V]
= 3.3046875 [V]

Which is a correct reading. A reading on a floating pin (nothing attached) is irrelevant. Use the correct factors from above to convert your read ADC value to voltage.
Side note: In line
avgV1=cumV1/10;

You have the float avgV1 on the left and cumV1 (a long) divided by 10 on the right; this will do a integer division. Make sure to divide by 10.0f if you want a floating point average.
Side note 2:
These factors do make sense. If you apply positive 6.144V on the 2/3rd gain setting, you will read the maximum positive value of a int16_t, i.e. 2^15-1 = 32767 (solve above formula for the count). If you apply -6.144V, you get -32768; thus the full 16-bit number space is used. On differnt gain settings it analogous.


text:
Can't connect to the server
I am working on a specific project that requires a database.
I have done the 'connection' and the "write" of data using a PHP file.
I have even reconfigured everything so it would be possible to access the database through a different device that is connected to the same wifi network as my computer.
All tested and working properly.
The Arduino for some reason is not connecting to the server, where Serial.println(client.connect(serv, 8095)); is returning 0, I have tried every possible solution but nothing seems to work.
I am using xampp, and I changed the port to 8095.
any possible information would be much appreciated.
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {
  0xFDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

byte sensorInterrupt = A2;
byte sensorPin       = A2;
float calibrationFactor = 4.5;
volatile byte pulseCount;
float flowRate;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;
unsigned long oldTime;
char valvestatus= 'ON';
byte ip[] = {192, 168, 1, 4 }; //Read the code explanation https://102.159.198.42/
byte serv[] = {192, 168, 1, 3} ; //Read the code explanation  192.168.1.3
EthernetClient client;

void setup() {
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
delay(1000);
   pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  pulseCount        = 0;
  flowRate          = 0.0;
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;
  oldTime           = 0;
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING);

}

void loop() {

  if((millis() - oldTime) > 1000) {
    detachInterrupt(sensorInterrupt);
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;
    oldTime = millis();
    flowMilliLitres = (flowRate / 60) * 1000;
    totalMilliLitres += flowMilliLitres;
     unsigned int frac;
    Serial.print(int(flowRate));  ////////
    Serial.print(totalMilliLitres); /////////////
   pulseCount = 0;
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING);

    }

    Serial.println(client.connect(serv, 8095));
    if (client.connect(serv, 8095)) { //Connecting at the IP address and port we saved before
client.print("GET /ost/write_data.php?"); //Connecting and Sending values to database
client.print(flowRate);
client.print(totalMilliLitres);
client.print(valvestatus);
 client.stop(); //Closing the connection
    }
 while(!client.available()){}

}

void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

firewall on the computer

tested with the firewall off already, yet not working.


text:
Mapping segments and memory allocation on a segment LCD driver
I've just configured a segment LCD and driver, everything works fine, but because I decided to not use vias on the PCB, the connections between the two are mixed.
To be more precise, in order to display the number 12, both memory addresses should be accessed.
So right now it's impossible to display a single digit without mapping all the segments.
In static mode, this is how RAM memory is allocated to SEG0-SEG7 and SEG8-SEG15 respectively:

What I've tried was to create two multidimensional arrays and map possible combinations of the two digits, like this:
// 01 to 09
const byte map1[10][2] = {
  {B01110111, B111111 },
  {B01110001, B100111},
  {B01111011, B011111},
  {B01111011, B110111},
  {B01111101, B100111},
  {B01111110, B110111},
  {B01111110, B111111},
  {B01110011, B100111},
  {B01111111, B111111},
  {B01111111, B110111}
};

// 10 to 19
const byte map2[10][2] {
  {B00010111, B111100},
  {B00010001, B100100},
  {B00011011, B011100},
  {B00011011, B110100},
  {B00011101, B100100},
  {B00011110, B110100},
  {B00011110, B111100},
  {B00010011, B100100},
  {B00011111, B111100},
  {B00011111, B110100}
};

If there is no way to mix or map them in a dynamic way so any possible combination between 00 and 99 can be achieved, the only solution is to add vias on the PCB and rewire everything as explained in the datasheet.
Any ideas?
Thanks

please explain how this post is about an Arduino

Have a lookup table, to map each segments to a bit in LCDs memory (14 (or 2x7) segments, mapping (probably easiest) a uint16_t for the bit). Then another lookup table for numbers (0-9) to segments. There's multiple ways to do this. I've done this myself, where having an easier layout meant some additional abstraction in my code to fix the weird pinout choice. What I've done sometimes was write some separate code that generated the 0-99 array; copy-paste that into my sketch. This makes the code run really fast, as it's just a lookup. To save RAM I've used PROGMEM, to keep the table in flash.

The trick here is to employ both a local memory buffer, and digit masking.
Step one: create a pair of masks that define which bits of the memory are associated with which digit.
Imagine you have your digits wired in this order in memory. For simplicity I am working with 16-bit values, but there is no reason why you can't split them into two 8 bit values each if you find that easier (P is the decimal point. Lower case is the left digit, upper case the right digit):
      MSB                         LSB
      a C d g E B p A c D f b e G F P

You would then create a pair of corresponding 16-bit values that represent which bits are associated with each digit.
      MSB                         LSB
      a C d g E B p A c D f b e G F P
Left  1 0 1 1 0 0 1 0 1 0 1 1 1 0 0 0
Right 0 1 0 0 1 1 0 1 0 1 0 0 0 1 1 1

The right is just the inverse of the left, so for right you can actually use ~left and save yourself 2 bytes.
So that would end up as:
uint16_t leftDigit = 0xB2B8;
uint16_t rightDigit = 0x4D47;

Now you create yourself a table of which segments create which numbers. Now the magic here is that you don't want individual digits. Not yet. What you want is a table of 16-bit values that represent the numbers 00, 11, 22, 33, 44, 55, 66, 77, 88, 99 (and optionally two spaces, but that's just 0x0000, so you may not need to store that explicitly).
You may end up with something like:
uint16_t digits[] = {
    0b1110110111111010, // 00
    0b0100010010010000, // 11
    0b1011110101011100, // 22
    // ... etc ...
};

Now the real magic happens.
You need a memory buffer that mirrors the contents of your driver memory.  You don't directly modify the driver memory - you modify your memory buffer, and then send both bytes of it to the display driver at once, updating all the segments together.
uint16_t buffer = 0;

Now to set a digit you first need to erase whatever is in the bits that correspond to the digit you want.  Let's say we want to display the number 12.  We'll start with the left digit.
// Step one, erase the left digit
buffer &= ~leftDigit;
// Step two, place into it the bits for 1 with the left digit mask imposed:
buffer |= (digits[1] & leftDigit);

// Step three, erase the right digit
buffer &= ~rightDigit;
// Step four, place into it the bits for 1 with the left digit mask imposed:
buffer |= (digits[2] & leftDigit);

That is actually quite a long winded way. But it does allow you to just change one digit without affecting the other.  If you want to just replace the entire content of the display (both digits at once) then you don't need as much work:
buffer = (digits[1] & leftDigit) | (digits[2] & rightDigit);

I'll just dismantle that for you so you can see what it does.
            MSB                         LSB
            a C d g E B p A c D f b e G F P
 digits[1]: 0 1 0 0 0 1 0 0 1 0 0 1 0 0 0 0
 leftDigit: 1 0 1 1 0 0 1 0 1 0 1 1 1 0 0 0
       AND: 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 // b and c enabled

 digits[2]: 1 0 1 1 1 1 0 1 0 1 0 1 1 1 0 0
rightDigit: 0 1 0 0 1 1 0 1 0 1 0 0 0 1 1 1
       AND: 0 0 0 0 1 1 0 1 0 1 0 0 0 1 0 0 // A B D E and G enabled

OR of ANDS: 0 0 0 0 1 1 0 1 1 1 0 1 0 1 0 0 // b c A B D E G enabled

And map those segments on to the standard layout of a 7 segment display:

And you form the number 12.
Then you take the buffer value and write it out to your display memory.  You can split the 16 bit value into 8 bit values with bit masking (& 0xFF) and bit shifting (>> 8).
uint8_t b1 = buffer & 0xFF; // Lower byte of memory
uint8_t b2 = (buffer >> 8) & 0xFF; // Upper byte of memory

An excellent answer, thank you so much for your time and effort. I'll give it a try today and get back to you with updates.


text:
Issue with Speck cipher on Arduino UNO
I found a library for the Speck cipher here: https://github.com/Chien-Ning/ArduinoCrypto
And I'm trying to use but haven't had much luck. My code is the following:
#include <SPECK_AVR.h>
#include <SPECK_spec.h>

#include "SPECK_AVR.h"

void setup() {
  // put your setup code here, to run once:

  SpeckTxtLen = 32;
  SpeckKeyLen = 64;
  speckTxtKey[]= 0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00;

  speckKey();
  speckEnc();

  Serial.println("");
  for (int i = 0; i < SpeckTxtLen/8; i++){
  Serial.print(speckTxtKey[i], HEX);
  Serial.print(", ");
  }
}

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

}

And I'm getting this error:
error: lvalue required as left operand of assignment

and
error: expected primary-expression before ']' token

Do you think I'm missing something in the usage of this library?
Thanks in advance

speckTxtKey[]= 0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00;

That's not how you assign an array.
And you never defined a type for the array.
It sould be:
byte speckTxtKey[] = {0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00};

EDIT:
I checked the source of the library to figure out how to use it, but it doesn't seem the library is meant for actual use.
SpeckTxtLen and SpeckKeyLen are macros inside SPECK_AVR.h, which are supposed to be changed there, not in your code.
The library also defines speckTxtKey inside SPECKenc_AVR.cpp with predefined test data based on the chosen length.
This library looks like a test implementation of the speck cipher, which was just dumped onto GitHub.

Thanks, I got rid of my error with this, but now I'm getting others, but I think it's related to the library. Should I post another question with respect to them?

False alarm, I'm still getting the "error: lvalue required as left operand of assignment". The other error is gone, but still with the one I mentioned.

@LuzA I now checked the source code of the library and it doesn't look like it's meant to be used for arbitrary data without modifications.

so I need to change the key and everything directly into the .h and .cpp files?


text:
Error using Crypto Library for Arduino: Speck
I'm trying to encrypt a string in my Arduino Uno using the following library:
https://github.com/rweather/arduinolibs/tree/master/libraries/Crypto
And I'm getting this error:

In function 'void setup()':
TESTING_SPECK_LIB:27: error: request for member 'setKey' in
  '(byte)(& cipher)', which is of non-class type 'byte {aka unsigned
  char}'
cipher->setKey(*key,keySize);
exit status 1 request for member 'setKey' in '(byte)(& cipher)',
  which is of non-class type 'byte {aka unsigned char}'

This is the code I'm using:
#include <Crypto.h>
#include <Speck.h>
#include <SpeckSmall.h>
#include <SpeckTiny.h>
#include <string.h>

Speck speck;
SpeckSmall speckSmall;
SpeckTiny speckTiny;

byte buffer[16];
byte cipher[16];
size_t keySize = 32;

void setup() {

  const uint8_t key[32]={0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                    0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00};
  byte plaintext[16]={0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                    0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20};
  byte ciphertext[16]={0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                    0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18};

  Serial.begin(9600);

  cipher->setKey(*key,keySize);
  cipher->encryptBlock(buffer, plaintext);

}

void loop() {

}

I know that I'm doing something wrong, but I don't understand what the error means, someone knows what it means and how to fix it?

byte cipher[16]; declares cipher as an array of 16 bytes.  As such, cipher has no methods, much less ones called setKey() or encryptBlock().
Note, setKey() and encryptBlock() look like method names one would find in Crypto or Speck library code; however, I don't find them in the Crypto and Speck headers I looked at on github sites.  Also, buffer, cipher, and keySize look like variables and parameters one would use in creating an object for use with encryption methods.
In short, it appears your code fails to set up an appropriate class of objects that have setKey() and encryptBlock() methods.
Note, while I am not familiar with their details, I question whether all of the header files Speck.h, SpeckSmall.h, and SpeckTiny.h should be included in your code.  It seems more likely that you would choose one of them as appropriate to your needs.

Edit 1:  Looking at TestSpeck.ino as mentioned in per1234 6's comment, one sees a function perfCipher(), with its first argument declared as BlockCipher *cipher.  That is, cipher is declared as an object of a class that has setKey() and encryptBlock() methods.
The TestSpeck.ino sketch includes all three of the header files Speck.h, SpeckSmall.h, and SpeckTiny.h because it runs performance tests that compare results using different Speck implementations.  In practice you usually won't need more than one of those headers.

See https://github.com/rweather/arduinolibs/blob/master/libraries/Crypto/examples/TestSpeck/TestSpeck.ino indeed it does include all three of those files. I'm guessing each adds an additional layer of functionality. That example declares an array named ciphertext, not cypher. I suspect OP confused the two, thus the error.

@per1234, thanks, have edited a note about that


text:
Is it possible to overclock the baudrate from the mega to 230400 bps?
i have a Arduino Mega 2560 and want send data with 230400bps to my laptop without any framingerror.
I want send the data over USB with serial.print ist that possible or must i use the ethernet?
When that is possible it will be really nice when someone can write what i have to do.
With friendly wishes sniffi

This might interest you; http://forum.arduino.cc/index.php?topic=150299.555. See section on UART optimization and the benchmark https://github.com/mikaelpatel/Cosa/blob/master/examples/Benchmarks/CosaBenchmarkUARTburst/CosaBenchmarkUARTburst.ino. What effective baud-rate are you looking for?

I need 230400 bps, my protocol has 38400 and i add 5 bytes (4 timestamp 1 byte filled with flags) so 6*38400= 230400 i think.

The error rate at 230400 bps with system clock 16 MHz is very high. 250000 bps is much better. Please see the AVR baud-rate calculation.

Is it possible to overclock the baudrate from the mega to 230400 bps?

Yes, setting that baud-rate is not a problem but this specific baud-rate may will give a high error rate. According to the AVR baud-rate calculation (UBRRn Settings for 16 Mhz system clock) the error is 8.5% (U2Xn=0) and -3.5% (U2Xn=1).
Simply choosing 250000 bps will remove this error.
Cheers!

Ok i can use 250kbps that will be work but what means -3.5% is 0% not the best?

How can i change the baudrate? I have switch the buffer from 8 bit to 16 bit because i need the second byte for my statusbit´s (e.g. my 9 bit protocol), is that still possible?

The error is generated sampling frequency relative optimal. Negative (as -3.5%) means the generated frequency is too low. To change the baudrate see Serial.begin() https://www.arduino.cc/en/Serial/Begin

You need to open a new question for the 8 to 16 bit. That is a new "can of worms". And you need to acknowledge if you think the original question has been answered :)


text:
Is it possible to receive a 9 bit protocol on the Arduino Uno with Arduino?
I want send and receive a 9 bit async-serial protocol with 4800 baud on my Arduino Uno, i have read on the specification from the ATmega328P that the uart can do that.
My aim is that when my Uart receive the 9th bit as a 1 he must throw a interrupt. On this interrupt i can recognize that this byte was an adress byte.
When he receive a zero he sould do nothing spezial, only transmit it as hex-byte over usb to the pc.
My Problem now, i can´t initialize the Uart right because the command Serial.begin(4800, config) is not enough, i must throw the interrupt and translate the data to hex-bytes.
My Question can i modify the Serial.begin() source code respectively where can i find the source code for the Serial.begin function?
When there is no possibility to change the code has someone a other option for me to send and receive the 9 bit protocol with an Arduino Uno?

How are you connecting the the '328p's UART?  I don't think you will get 9 bits through the '16u2 USB-serial chip on the Uno unless you modify its firmware, and you'd have to see how to get the USB side of things to support it.   Your functional description isn't very clear either, but it sounds like you would need to modify the serial receive ISR away from the usual Arduino one.  On the other hand, if what you want is for the Uno to be a bridge between some serial device and a PC, you will actually need to use and modify a software serial implementation or use a Leonardo instead of Uno.

If you want to set the UART to 9-bit mode, you will have to set the
UCSZ02 bit of the _ucsrb register to 1 in
HardwareSerial::begin().
For example:
void HardwareSerial::begin(unsigned long baud, byte config)
{
  // Mostly unchanged... but by the end:
  sbi(*_ucsrb, RXCIE0);
  cbi(*_ucsrb, UDRIE0);
  sbi(*_ucsrb, UCSZ02);  // set 9-bit data mode
}

Notice that you do not need to modify the Arduino core library for this:
you could set that bit in your setup(), right after calling
Serial.begin().
Then, in the HardwareSerial::_rx_complete_irq() interrupt
handler,
you will have to read the 9th bit as the RXB80 bit in UCSR0B, before
reading the low byte from _udr (emphasis in the datasheet). For
example, you could replace the line unsigned char c = *_udr; by:
bool is_address = UCSR0B & _BV(RXB80);  // read 9th bit first
unsigned char c = *_udr;                // then the other bits
if (is_address) {
  do_something_with_address(c);
  return;
}

where do_something_with_address() is the stuff you wanted to do in
another interrupt (no need for that, you are already in interrupt
context).
It is worth noting that, with an Arduino Uno, you will not be able to do
all this while sending data to the PC. This is because the communication
with the PC uses the only UART of the ATmega328P.

When i have insert a 1 in UCSZ02 what must i do with code? Must i patch my Arduino, or how can i add the bit at my Arduino?                                   I didn´t know how i read the RXB80 bit as 9th bit have you a example for me pls.

@sniffi: I added some examples of untested code to the answer.

Can i use the Arduino mega 2560 for that? He has 4 uart´s or can i expand my Uno with a uart?

I do not know about chips that could be used to add an UART to an Uno. They may exist, and if so they should be usable if they can be interfaced via I2C or SPI at 5 V. A Mega2560 is probably an easier solution. It's UART number 0 is used for communication with the host computer, so you can use any of the other 3 for your 9-bit protocol. Just make sure you tap into the correct registers, e.g. you set UCSZ12 and read RXB81 on UCSR1B if you use UART1.

It sounds like you want some device with a 9-bit protocol to send data to an Arduino, and then the Arduino to forward that data (perhaps in a slightly different format) to a PC.
People who want to connect their Arduino to two serial devices at the same time (and the PC counts as one) generally either:
Change the hardware to accept multiple serial devices
While the Arduino Uno has only one hardware serial port, the following (and probably many others) have 2 or more hardware serial ports:

Arduino Mega 2560 (USB and 3 other hardware serial ports)
Arduino Leonardo (USB and 1 other hardware serial port)
Teensy LC (USB and 3 other hardware serial ports) ("serial 9-bit on the t3")

("Sending and Receiving 9-bit Frames with Arduino" uses the hardware approach).
Change the software to accept multiple serial devices
In principle, it's possible to tweak SoftwareSerial to handle 9-bit data.
Several people have talked about it

"9bit SoftwareSerial library modification"
"Altering New Soft Serial NSS for 9 bit- cans of open source worms"

The Max3140 is a very capable USART with built-in full/half-duplex RS-485 drivers that interfaces to a uController via SPI. They are a bit pricey and you would have to make a board, solder, etc..
Another solution would be to dedicate a simple and inexpensive minimal Arduino-compliant board (like a Pro-Mini) to interface with the "main" Arduino via I2C or SPI, and program the Pro-Mini for 9-bit addressing mode and add the RS-485 driver. Pro-Mini or Nano clones are dirt cheap, but it is not even that expensive to use an authentic Arduino product and support their great contributions ;-).


text:
RS485 Multimaster Communication with collision avoidance
I'd like to know if there is an easy way to implement communication between multiple arduinos that avoids collisions using the RS485 module.
My setup would have multiple masters that send messages to only one slave that performs a task upon been given the message.
I've tried researching some libraries for this, but they normally don't fulfil the multimaster requisite, nevertheless I found this library which apparently does implement what I need, but I haven't been able to understand how it works.
My current options are either finding an easier library that is capable of doing what I need, learning how to make the linked library work (which I have already tried) or building my own serial communication protocol that implements collision avoidance and a multiple master configuration.
What path should I follow? Can you give me any recommendation for any of the paths I'm suggesting? Is there a better way of implementing this type of communication?

Collision avoidance is a tricky subject. You can never completely avoid collisions - all you can do is work out how to a) detect them, and b) recover from them.
There's many different ways of doing it, and how you implement it is very much dependent on what your hardware can do, and how you are actually using the protocol.
The best way of detecting a collision is to arrange it so that your master is always reading the bus even when it is sending. You require separate receiver and transmitter modules, so that as you place a byte on the bus you attempt to also receive that byte. If it doesn't get received, or the wrong byte gets received, then you have a collision.
That is a 100% guaranteed way of detecting a collision as it happens. If you know that what you sent didn't make it onto the wire properly then it collided.
A simpler scheme is to be watching the bus before you send. If there has been no sign of any traffic for more than a certain threshold time then you can assume that the bus is currently quiet. You can then try and send your data. You don't know if it got through OK though, since something else could have decided that the bus was quiet long enough for it to send too.
So you would have to have some kind of ACK signal coming back from the other end that says the packet got received OK. Keep retrying until you get that ACK back. Of course, the ACK could be colliding as well, so it may have been received, but you just haven't been told. So your remote device would have to be able to gracefully handle receiving the same packet multiple times and discarding (yet still ACKing) the repeated packets.
What you should do when you do detect a collision (or fail to receive an ACK) is also kind of tricky.  You have to wait and try sending again. But if there are two devices both waiting to send again, how can you be sure that they won't both be waiting for the same time, and thus collide again?
You have to ensure that both devices delay for a random period - and make sure that the random period truly is random. Using the default random() function, unless you can seed it from a truly random source of entropy, will generate the same sequence of numbers for all the devices - so each device would get the same "random" number. And collisions ensue.
So you see, you can't just throw a random library at it and say "This library will stop collisions" - the best you can say is "This library can help reduce collisions, detect them when they do occur, and gracefully recover from them."
For the library you link to it appears to attempt to implement the latter system:

Collision avoidance is implemented through the assignment of a message priority. A node will not start transmission before the bus has been idle for a time determined by the priority. Note that the highest priority is given to messages with the lowest priority number.
Collision detection is implemented by read-verified-write, i.e. all data written is checked on the fly for proper echo-back. If the software detects a frame error or a data mismatch when the echo character is received, it will disable the RS485 transmission and flag the collision status. The included transaction management will resend the message after the bus is idle again.

It waits for the bus to be free of traffic for a specific amount of time (the time is variable depending on the message priority), and expects the message to be sent back again as a form of ACK.
It makes no mention of random back-off times though to avoid collisions between different masters sending messages with the same priority.

There is a ready out the box solution documented in https://github.com/MichaelJonker/HardwareSerialRS485/wiki (This wiki describes the library you referred to).
The problem is quite complex: collision avoidance, collision detection and message retrial, message priority and message filtering. But the library solves it all. The software even provides a solution to interface a host (PC or Android) to the RS485, providing the same features.
In ‘understanding the library’ there are two aspects: how it works, and how to make it work.
The library itself is non-trivial (because the problem is also non-trivial), so to understand how it works is also non-trivial (Majenko, in his answer, gave a nice functional description of some of the features that are implemented by the library. The actual implementation has additional complications due to the direct interaction with the USART at interrupt level.). I guess you do not want to know (in first instance) how it works in such details.
However, the author (me) went to quite some detail to document how to make it work. But I reckon that documentation may be difficult to follow if the documentation does not match the expectations of the reader.
So I would be very interested to improve the documentation and to match the expectations of new users. However, here I need your help (or anyone interested) in pointing me out what and where I can improve.
The preferred way to contact me on these matters is by creating an issue on my Github project page:
https://github.com/MichaelJonker/HardwareSerialRS485/issues
BTW one of the issues addresses the same topic.
I guess that you need to create Github account in order to submit issues. Alternatively, you can contact me through this site (However, I might be less reactive through this channel).
Best regards
MichaelJonker

I did a post about rolling masters here on Arduino Stack Exchange.
The general idea is that you can set up multiple Arduinos to take turns becoming a master, based on waiting for its own "turn" in a time-based sequence, with provision for recovering from one of the units not responding.

I thinks the easiest way for software is not use any software do this at all, using a hardware controller chip/module instead which dedicated to support multi-master and arbitration for RS485 (the same way as CAN bus).
There is a protocol, named CDBUS, witch has stand-alone controller to do the work for you, which is very simple, I can even transfer video stream through it, details:
https://github.com/dukelec/cdbus_doc (Introduction)
https://github.com/dukelec/cdbus_ip (Protocol details & FPGA IP core)

You can also achieve this protocol by software only, if you don't care the speed or CPU usage.
Update: connect the CDCTL-Bx controller to an Arduino:

authors: บุรินทร์ จันทร์แก้ว


text:
Do I need one N3904 for each LED?
I want to control 4 (or more) LEDs using the PWM output pins of my Arduino.
Here is how I have it on a breadboard, and it's working for me.
Question:
Is this schematic inefficient? Are there any issues with this design?

How powerful are your LEDs?

It'll be more efficient if you'd just connect anode to the PWM output and cathode to the ground through resistor. Now there will be more current through the base to the ground than through LED

I will be using pink, blue, green, and yellow LED's.
I need to control each LED independently, and change voltage dynamically (fade on / off  or blink etc.. )
Hopefully that helps some.

@ThomasWeller sorry, do you mean using the PWM output pins to supply power to each LED?  If I turn on multiple LED's at the same time, would they receive enough power?  I guess I'm not sure if there is a voltage difference when using analogWrite(n, 255) across multiple pins at the same time.

@KIIV oh wow, I think you're referring to something like the schematic in the answer for this question: https://arduino.stackexchange.com/questions/34989/controlling-common-anode-rgb-led-with-pwm-can-individual-colors-be-done-w-o-tr?rq=1
That is really neat and may be a much simpler circuit design. Thanks

@user3228313 Just keep that resistor for each LED. Without it, you might be operating on the maximum IO port currents and it may fail eventually

in general, MOSFETs are a better way to go than BJTs for switching on/off (incl PWM) and they are more efficient energy-wise, not dropping a junction of voltage to be multiplied by the load...

In the schematic you don’t have any resistors between the PWM pin an the base of the transistor. You really need to add those. Also the resistors for the leds are typically placed on the other side of the transistor (connected directly to the leds).


text:
Want to display an image from SD card to ILI9486 LCD display
I am completely new to Arduino. I have been given a side project to display a image from SD card to display. LCD used is ILI9486 which has a SD card slot at the back of the display module. I have inserted an 1 GB micro SD card. I am using below example code to try to open the SD card and display the image on display module. I am getting error on serial monitor "Initializing sd card - failed". Can anyone let me know how to display image from SD card to screen.
#include <SD.h>
#include <SPI.h>
#include <TFT.h>  // Arduino LCD library

// pin definition for the Uno
#define sd_cs  4
#define lcd_cs 10
#define dc     9
#define rst    8

TFT TFTscreen = TFT(lcd_cs, dc, rst);

// this variable represents the image to be drawn on screen
PImage logo;

void setup() {
    // initialize the GLCD and show a message
    // asking the user to open the serial line
    TFTscreen.begin();
    TFTscreen.background(255, 255, 255);

    TFTscreen.stroke(0, 0, 255);
    TFTscreen.println();
    TFTscreen.println(F("Arduino TFT Bitmap Example"));
    TFTscreen.stroke(0, 0, 0);
    TFTscreen.println(F("Open serial monitor"));
    TFTscreen.println(F("to run the sketch"));

    // initialize the serial port: it will be used to
    // print some diagnostic info
    Serial.begin(9600);

    while (!Serial) {
        // wait for serial port to connect. Needed for native USB port only
    }

    // clear the GLCD screen before starting
    TFTscreen.background(255, 255, 255);

    // try to access the SD card. If that fails (e.g.
    // no card present), the setup process will stop.
    Serial.print(F("Initializing SD card..."));
    if (!SD.begin(sd_cs)) {
        Serial.println(F("failed!"));
        return;
    }
    Serial.println(F("OK!"));

    // initialize and clear the GLCD screen
    TFTscreen.begin();
    TFTscreen.background(255, 255, 255);

    // now that the SD card can be access, try to load the
    // image file.
    logo = TFTscreen.loadImage("arduino.bmp");
    if (!logo.isValid()) {
        Serial.println(F("error while loading arduino.bmp"));
    }
}

void loop() {
    // don't do anything if the image wasn't loaded correctly.
    if (logo.isValid() == false) {
        return;
    }

    Serial.println(F("drawing image"));

    // get a random location where to draw the image.
    // To avoid the image to be draw outside the screen,
    // take into account the image size.
    int x = random(TFTscreen.width() - logo.width());
    int y = random(TFTscreen.height() - logo.height());

    // draw the image to the screen
    TFTscreen.image(logo, x, y);

    // wait a little bit before drawing again
    delay(1500);
}

Most SD card modules don't allow other chips on the same SPI bus

Hi, Thanks for the info. I was able to resolve the issue of initializing sd card failing. i made the sd_cs value as 10 and it worked. But now I am running into another problem.
I am facing issue during loading of image from sd card. Getting error: "loadImage: file not found: arduino.bmp
error while loading arduino.bmp"
I am using 1 gb sd card and the size of bmp image is 7.5kb. its a 50x50 pixel 24 bit bmp image. What can be the problem?

Make sure your SD card is Fat16 format.  At least that was a requirement of the test code I had on the same sort of display.


text:
Coin recognition using Coin Accepter in Arduino Uno
I'm working on a vending machine project and I'm using CH-926 and an Arduino Uno for that. I've already set the coin accepter for different number of coins and respective output pulses. I'm unable to get the desired output for this. With every coin I insert the output varies even when I put the same coin.
int pulse = 0;

void coin_value() {
  pulse = pulse + 1;
}

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
  Serial.println("Ready to be collected");
}

void loop() {
  if (digitalRead(2) == HIGH) {
    attachInterrupt(0, coin_value, FALLING);

    if (pulse == 3) {
      Serial.println("50");
    }
    if (pulse == 2) {
      Serial.println("20");
    }
    if (pulse == 1) {
      Serial.println("10");
    }
  }

  pulse = 0;
}

For each coin there are different specific pulses which helps to recognize the coin.int pulse=0;.
So when I insert coin 1 then the output should be 10, for coin 2 the output should be 20 and for coin 3 the output should be 50.

Don't cross post. You already asked this on SO.

However he was asked on Stack Overflow to ask the question here, which he did.

what does this actually mean? I'm unable to get the desired output for this ..... what do you expect? .... what do you actually get?

@NickGammon The question should be only on one site. If found a better site for it, he should delete the old one.

@gre_gor  I've flagged the SO post for deletion. However Sumit Kumar could help by self-deleting, if the system lets him.

Your code is faulty in a number of respects.

pulse should be declared volatile, i.e.
volatile int pulse = 0;

That is because it can change in an interrupt service routine.

You should only do attachInterrupt once, in setup.

Your code to display the count will be timing dependent. What if you happen to display the count after one pulse has arrived, but before they all have? Then you set the count back to zero.

Better would be something like this, untested however:
volatile int pulse = 0;

void coin_value() {
  pulse = pulse + 1;
}

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
  Serial.println("Ready to be collected");
  attachInterrupt(0, coin_value, FALLING);
}

void loop() {

  if (pulse > 0)
    {
    delay (1000);   // let the other pulses arrive
    if (pulse == 3) {
      Serial.println("50");
    }
    if (pulse == 2) {
      Serial.println("20");
    }
    if (pulse == 1) {
      Serial.println("10");
    }
    pulse = 0;  // clear for next time
  }

}

(Edited to add)
Even then your test for 1/2/3 might fail if the coin acceptor sends the pulses twice. Then you might get 2/4/6 pulses. You probably need to display something if there is another count, eg.
  if (pulse == 3) {
    Serial.println("50");
  }
  else if (pulse == 2) {
    Serial.println("20");
  }
  else if (pulse == 1) {
    Serial.println("10");
  }
  else {
     Serial.print ("Unexpected number of pulses: ");
     Serial.println (pulse);
  }

First of all you said

So when I insert coin 1 then the output should be 10, for coin 2 the
  output should be 20 and for coin 3 the output should be 50.

Yes coin 3 would be 50 but it does not means that coin 3 has 3 impulses(he will have 5 impulse), I recommend to you always use this formula:

Coin_Value = Pulse_Count * Denomination.

I don't recommend to you use 3 Impulses from coin acceptor Because you don't have 15 cent and 30 cent coins. In most cases Coin acceptors have:

1/4 1/2 1 2 4 5 8 10 impulses

Generally I prefer to save all data in variables
So lets get to variables for code
const int coinIntPin = 2;          //interruptPin 0 is digital pin 2
volatile boolean newCoin = false;
volatile int pulseCount;          //counts pulse for
volatile int timeOut = 0;         //counts timeout after last coin inserted
float coinType;
float denomination = 0.50;         // in my case 1 Pulse = 0.50 $
int max_impulse = 4;              // this is the maximum impulses I use
volatile long timeFPulse = 0;     // to determine when First impulse was interrupted
volatile long interval;           // to determine interval from first and last impulse

And always use attachInterrupt(digitalPinToInterrupt(pin), ISR, mode); It is recommended by Arduino  as below:
void setup(){
    Serial.begin(9600);
    attachInterrupt(digitalPinToInterrupt(coinIntPin), coinInserted, FALLING);

}

And I will give you rest of code:
void coinInserted(){
    newCoin = true;
    timeFPulse = millis();
    pulseCount++;
}

void loop()
{

     while (newCoin == true)
    {
            interval = millis() - timeFPulse;  //interval from first and last impulse
            if(pulseCount == max_impulse || (interval > 500 && pulseCount > 0)) //Max_impulse will avoid any extra impulses for any reason.
            {
// This is the reason why I recommended to you use 1 2 4 5 10 20 Impulses instead of 3 7 9 etc...
              coinType = pulseCount * denomination;
              newCoin = false;
              sendData();
              delay(5);

             }

    }
}

void sendData(){
  Serial.print("Do what ever you want. Inserted Money = ");
  Serial.println(coinType);
  coinType = 0;  // remove if you want to save Coins and print sum of inserted coins
  pulseCount = 0;  // remove if you want to save impulses determined by coin acceptor
}

And Finally look at ( interval > 500 ) If you have different max impulses you must change 500 to (impulse length * Max impulses + 100); so if you have max 10 impulses you must enter 1100 and not 500 (in my case);