text:
Can I compile a sketch for my attiny85 without an arduino board?
I have a lot of Raspberry Pi's laying around, so I want to use those to program my attiny85 chips. The problem is that most of the code examples, libraries, and documentation out there assume you're using Arduino. Can I run Arduino commandline software on my Raspberry Pi, and use that to program the attiny85?
I'm trying to compile an RF24 program for the attiny using avr-g++, but I'm running into too many dependency errors, and I wonder if things will just be easier if I use Arduino software.`

I would suggest that things might be easier if you don't use the Arduino software. The AVR toolchain should work well in just about any *nix environment, as well as the command line programming tools.

The answer is s simple and plain yes. I know this is not a very useful answer, but you did not provide enough details about your problem to enable people to write useful answers.

Can I run Arduino commandline software on my Raspberry Pi? - what command line software are you referring to? The Arduino IDE has a GUI interface.

By "program the attiny85", do you mean "upload an already build program to the attiny85" or do you mean "build an executable program for attiny85 from source code", or both?

Why wouldn't you be able to?
The compiler runs on the computer, not on the Arduino board. You don't need a board to be connected to compile either. If you enable verbose output during compile in the Arduino IDE settings it will tell you where it puts the resulting .hex file, after which you can use avr-dude to upload it to the target MCU.
If you want to use Arduino libraries you'll need to use an core for ATTiny devices (e.g. ATTinyCore). But either way you don't need an Arduino board to compile.

I'd also echo what @Marcus says, for the small devices you are better off completely ditching the Arduino stuff (it's such badly written, bloated, and inefficient), and simply starting with a nice clean C file.
There is nothing stopping you using the Arduino IDE or the avr-libc tools which it uses. If you add your own main() function in a C file and don't put anything in the .ino file you will be able to compile without any of the bloat.

You can disregard the answers that say you can't compile for the ATtiny85 using the Arduino IDE. I have done so many times, for example my torch locator project which uses the ATtiny85 and the Arduino IDE to compile for it.
Here's my "board":

View from other side:

Code:
// ATtiny85 torch detector
// Author: Nick Gammon
// Date: 25 February 2015

// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

/*

  Pin 2 (PB3) <-- LDR (GL5539) --> Pin 7 (PB2) <----> 56 k <----> Gnd

  Pin 5 (PB0) <---- LED ---> 100 R <-----> Gnd

*/

#include <avr/sleep.h>    // Sleep Modes
#include <avr/power.h>    // Power management
#include <avr/wdt.h>      // Watchdog timer

const byte LED = 0;          // pin 5
const byte LDR_ENABLE = 3;   // pin 2
const byte LDR_READ = 1;     // Ain1 (PB2) pin 7
const int LIGHT_THRESHOLD = 200;  // Flash LED when darker than this

 // when ADC completed, take an interrupt
EMPTY_INTERRUPT (ADC_vect);

// Take an ADC reading in sleep mode (ADC)
float getReading (byte port)
  {
  power_adc_enable() ;
  ADCSRA = bit (ADEN) | bit (ADIF);  // enable ADC, turn off any pending interrupt

  // set a2d prescale factor to 128
  // 8 MHz / 128 = 62.5 KHz, inside the desired 50-200 KHz range.

  ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);

  if (port >= A0)
    port -= A0;

#if defined(__AVR_ATtiny85__)
  ADMUX = (port & 0x07);  // AVcc
#else
  ADMUX = bit (REFS0) | (port & 0x07);  // AVcc
#endif

  noInterrupts ();
  set_sleep_mode (SLEEP_MODE_ADC);    // sleep during sample
  sleep_enable();

  // start the conversion
  ADCSRA |= bit (ADSC) | bit (ADIE);
  interrupts ();
  sleep_cpu ();
  sleep_disable ();

  // reading should be done, but better make sure
  // maybe the timer interrupt fired

  // ADSC is cleared when the conversion finishes
  while (bit_is_set (ADCSRA, ADSC))
    { }

  byte low  = ADCL;
  byte high = ADCH;

  ADCSRA = 0;  // disable ADC
  power_adc_disable();

  return (high << 8) | low;

  }  // end of getReading

// watchdog interrupt
ISR (WDT_vect)
{
   wdt_disable();  // disable watchdog
}  // end of WDT_vect

#if defined(__AVR_ATtiny85__)
  #define watchdogRegister WDTCR
#else
  #define watchdogRegister WDTCSR
#endif

void setup ()
  {
  wdt_reset();
  pinMode (LED, OUTPUT);
  pinMode (LDR_ENABLE, OUTPUT);
  ADCSRA = 0;            // turn off ADC
  power_all_disable ();  // power off ADC, Timer 0 and 1, serial interface
  }  // end of setup

void loop ()
  {
  // power up the LDR, take a reading
  digitalWrite (LDR_ENABLE, HIGH);
  int value = getReading (LDR_READ);
  // power off the LDR
  digitalWrite (LDR_ENABLE, LOW);

  // if it's dark, flash the LED for 2 mS
  if (value < LIGHT_THRESHOLD)
    {
    power_timer0_enable ();
    delay (1);  // let timer reach a known point
    digitalWrite (LED, HIGH);
    delay (2);
    digitalWrite (LED, LOW);
    power_timer0_disable ();
    }

  goToSleep ();
  }  // end of loop

void goToSleep ()
  {
  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  noInterrupts ();       // timed sequence coming up

  // pat the dog
  wdt_reset();

  // clear various "reset" flags
  MCUSR = 0;
  // allow changes, disable reset, clear existing interrupt
  watchdogRegister = bit (WDCE) | bit (WDE) | bit (WDIF);
  // set interrupt mode and an interval (WDE must be changed from 1 to 0 here)
  watchdogRegister = bit (WDIE) | bit (WDP2) | bit (WDP1) | bit (WDP0);    // set WDIE, and 2 seconds delay

  sleep_enable ();       // ready to sleep
  interrupts ();         // interrupts are required now
  sleep_cpu ();          // sleep
  sleep_disable ();      // precaution
  }  // end of goToSleep

Compiled under the IDE it uses 16% of program memory:
Sketch uses 1,370 bytes (16%) of program storage space. Maximum is 8,192 bytes.
Global variables use 9 bytes of dynamic memory.

Claims that the Arduino IDE is badly written and inefficient are not generally true. To a certain extent the Arduino libraries favour ease-of-use over compactness, however you don't have to use them.
The IDE is just a front-end to the avr-g++ compiler. It is easy to use, and produces a .hex file which you can then upload to your chip using a suitable ICSP interface.
The avr-g++ compiler itself does aggressive code optimization. You won't get any advantage from ditching the IDE and using the avr-g++ compiler yourself - it's the same compiler. And if you think you can do better in assembler, good luck! The compiler-writers know all the tricks for storing variables in registers, and minimizing code in various ways. You will be hard pressed to write better code than the compiler generates anyway.

Claims that the IDE generates bloated code are Complete Nonsense. Take this sketch:
int main ()
  {
  DDRB = bit (2);  // pin 7 on chip

  while (true)
    {
    PINB = bit (2); // blink it
    }
  }

Compiled for the ATtiny85 under the IDE 1.6.9 I get this program memory usage:
Sketch uses 60 bytes (0%) of program storage space. Maximum is 8,192 bytes.
Global variables use 0 bytes of dynamic memory.

There are 15 interrupt vectors at the start of program memory, for which space has to be reserved. So 30 of those bytes are accounted for by that unavoidable overhead.
Here is the full disassembly of the above:
Disassembly of section .text:

00000000 <__vectors>:
   0:   0e c0           rjmp    .+28        ; 0x1e <__ctors_end>
   2:   15 c0           rjmp    .+42        ; 0x2e <__bad_interrupt>
   4:   14 c0           rjmp    .+40        ; 0x2e <__bad_interrupt>
   6:   13 c0           rjmp    .+38        ; 0x2e <__bad_interrupt>
   8:   12 c0           rjmp    .+36        ; 0x2e <__bad_interrupt>
   a:   11 c0           rjmp    .+34        ; 0x2e <__bad_interrupt>
   c:   10 c0           rjmp    .+32        ; 0x2e <__bad_interrupt>
   e:   0f c0           rjmp    .+30        ; 0x2e <__bad_interrupt>
  10:   0e c0           rjmp    .+28        ; 0x2e <__bad_interrupt>
  12:   0d c0           rjmp    .+26        ; 0x2e <__bad_interrupt>
  14:   0c c0           rjmp    .+24        ; 0x2e <__bad_interrupt>
  16:   0b c0           rjmp    .+22        ; 0x2e <__bad_interrupt>
  18:   0a c0           rjmp    .+20        ; 0x2e <__bad_interrupt>
  1a:   09 c0           rjmp    .+18        ; 0x2e <__bad_interrupt>
  1c:   08 c0           rjmp    .+16        ; 0x2e <__bad_interrupt>

0000001e <__ctors_end>:
  1e:   11 24           eor r1, r1
  20:   1f be           out 0x3f, r1    ; 63
  22:   cf e5           ldi r28, 0x5F   ; 95
  24:   d2 e0           ldi r29, 0x02   ; 2
  26:   de bf           out 0x3e, r29   ; 62
  28:   cd bf           out 0x3d, r28   ; 61
  2a:   02 d0           rcall   .+4         ; 0x30 <main>
  2c:   05 c0           rjmp    .+10        ; 0x38 <_exit>

0000002e <__bad_interrupt>:
  2e:   e8 cf           rjmp    .-48        ; 0x0 <__vectors>

00000030 <main>:
  30:   84 e0           ldi r24, 0x04   ; 4
  32:   87 bb           out 0x17, r24   ; 23
  34:   86 bb           out 0x16, r24   ; 22
  36:   fe cf           rjmp    .-4         ; 0x34 <main+0x4>

00000038 <_exit>:
  38:   f8 94           cli

0000003a <__stop_program>:
  3a:   ff cf           rjmp    .-2         ; 0x3a <__stop_program>

I can't see much bloat there.

I wonder if things will just be easier if I use Arduino software

Yes, much easier.

Although your answer is OK, I think it does not answer the main OP question: is it possible to program ATtiny85 chips on a Raspberry Pi?

Does the Pi not use Unix? The Arduino IDE runs under Unix. I run it myself under Ubuntu.

@jfpoilpret  The question was actually Can I run Arduino commandline software on my Raspberry Pi? - what Arduino commandline software?

Well I would say this one: https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc

That's because you are bypassing all of the bloat by adding your own main() function. Try doing the same with loop() instead you'll end up with 326 bytes - that's a 400% overhead on top of the simple one. But also you are using direct port access rather than digitalWrite() which is again bypassing the bloat. Try doing digitalWrite() in loop() and you'll end up with 812 bytes - a 1200% overhead! Tell me, would you consider that bloat?

@TomCarpenter - as I said, functions like digitalWrite allow for a variable pin number to be passed, as opposed to a constant. For that to be looked up at runtime takes code. It is designed to be beginner-friendly. If you don't want to use those functions, then don't.

Unix can be different binary-wise, hence one executable running on a PC Linux might not be able to run on an ARM Linux. It does not seem so obvious to use the AVR buildchain (itself used by Arduino) on a Respberry Pi.

Well I would say this one - that wasn't referenced in the question. I am not assuming that is what the OP is on about.

@TomCarpenter Tell me, would you consider that bloat? - not really. You are asking if 246 bytes of code, which allow you to pass a variable rather than a constant is bloat? No, code which does something has to take space.

If I write some code that takes 16 bytes, and you can rewrite it to take 8 bytes, you can say that my code is 100% bloated. But it's only 8 bytes longer! You need to distinguish between percentages and actual values.

Like, if country X has one murder per year, and next year it has two murders, you can say that the number of murders doubled! Shock, horror, employ more police! But, it's only one more murder.

Guys, your comments seem totally unrelated to the original question. The OP did not even mention "bloated".

@NickGammon but we aren't taking about 1 or 2 bytes, we are talking about 10% of the ATTiny85 flash! And on a relatively slow MCU those extra instructions are bloated in speed as well. At 8MHz direct port manipulation will take 250ns, whereas digitalWrite will take about 30us, which again is a massive overhead. I understand the reason behind the abstraction, but I think the point was it's very costly on very small MCUs.

Yes, but if you abandon the IDE, you also abandon digitalWrite. My point was that you can abandon digitalWrite and still use the IDE.

"Arduino" makes a statement on the mcu in use.
Technologically, it's extremely unlikely you could run most sketches on devices with less than 1kB of RAM (largest SRAM in Attiny85 is 512 B; most models are smaller).
So, no. The idea "microcontrollers are by now capable enough to run a C++ subset on them directly" behind arduino simply doesn't seem to apply to the Attiny85.
However, there's the "cuteduino", which actually should work with a small set of basic Arduino libraries. It's based on the Attiny85.
I'd argue that you simply don't want to use Arduino on Attinies; these devices are so resource-constrained, that you probably want to keep in control.
Now, the RF24 lib comes with non-arduino attiny85 support, so go for that? http://tmrh20.github.io/RF24/ATTiny.html


text:
Implement Visible Light communication using Arduino
I want to implement a simple VLC based communication system using two Arduinos and send messages/data/files between two PCs. For that I have a simple transmitter circuit with an LED on Tx side and a photo-transistor on the receiver side. The codes im using for transmission and reception are attached below, also the circuit image is attached below, but im unable to bring about any communication between the two PCs, the transmitter side works fine as the LED flickers indicating data is being transferred, but its not being received by the photo transistor. I don't know what im doing wrong. Any help would be appreciated, I am doing this as a part of my academics.
Transmitter Code :
void setup()
{
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

  // Clear Timer on Compare Match (CTC) Mode
  bitWrite(TCCR1A, WGM10, 0);
  bitWrite(TCCR1A, WGM11, 0);
  bitWrite(TCCR1B, WGM12, 1);
  bitWrite(TCCR1B, WGM13, 0);

  // Toggle OC1A and OC1B on Compare Match.
  bitWrite(TCCR1A, COM1A0, 1);
  bitWrite(TCCR1A, COM1A1, 0);
  bitWrite(TCCR1A, COM1B0, 1);
  bitWrite(TCCR1A, COM1B1, 0);

  // No prescaling
  bitWrite(TCCR1B, CS10, 1);
  bitWrite(TCCR1B, CS11, 0);
  bitWrite(TCCR1B, CS12, 0);

  OCR1A = 210;
  OCR1B = 210;

  Serial.begin(2400);
}

void loop()
{
  Serial.println("testing testing testing");
  delay(500);
}

Receiver Code:
void setup()
{
  Serial.begin(2400);
  pinMode(13, OUTPUT);
}

void loop()
{
  // if incoming serial
  if (Serial.available()) {
    readSerial();
    digitalWrite(13, HIGH);
  }
  else {
    digitalWrite(13, LOW);
  }
  delay(500);
}
void readSerial() {
  char val = Serial.read();
  Serial.print(val);
}

the transmitter works fine, but the receiver is not receiving anything, I don't know what i'm doing wrong.

And how exactly are you wiring these components up?

I thin a led may be too weak for this. Did you try to use a flashlight to check if you got any response with a more powerful source? Have you checked for interferences? Are you transmitting it in a dark room or in a illuminated room? I would suggest you to try to make a simpler circuit with just a photo-transistor and an arduino board and then print the output of the fototransistor to the serial so you can know how it behaves.

I did a simple connection, Rx to phototransistor and through a resistor to pin 13. thats it

@D_batmaniac I don't follow you. Please draw full schematics of both ends.

Have you tried using RadioHead (the successor to VirtualWire)? That should work out of the box for such a simple case.

I'm voting to close this question as it has been abandoned without ever presenting an attempt that actually accomplishes anything - the alleged transmit code here transmits no information, at most it simply blinks an LED at a steady rate, and no viable receive code has been provided.  Repeated requests for the wiring have not been honored.

The amplitude of the signal at the photodetector is small. Better use ADC for reading.

The problem is even more fundamental  - there's not only no viable encoding scheme being used, there's actually no data being transmitted at all.

I think you have problem with your hardware side. I would like to suggest a few things; maybe it will work.
Transmitter
Instead of a normal LED use an IR LED because it has advantages over normal led for transmission of data like it is more secure, support max transmission speed,
less power consumption, and much more. For transmitter of signal use the following circuit. Ihave used TSOP1738 for receiver, so we need to generate the modulated IR of 38 kHz. You can use any TSOP, but you need to generate IR of respective frequency as TSOP. So using 555 timer in Astable mode to oscillate the IR at 38KHz frequency. As we know oscillation frequency of 555 timer is decided by resistor R1, R2 and capacitor C1. We have used a 1k R1, 20K R2 and 1nF capacitor to generate a frequency of approx. 38 KHz. It can be calculated using this formula: 1.44/((R1+2*R2)*C1)

and instead of a push button you can use a transistor or mosfet as switch, which will be controlled with a controller.
Receiver
I don't know which phototransistor you are using but I'll suggest to use a TSOP17XX. TSOP17XX receives the modulated Infrared waves and changes its output. TSOP is available in many frequency ranges like TSOP1730, TSOP1738, TSOP1740 etc. The last two digits represent the frequency (in Khz) of modulated IR rays, on which TSOP responds. Like for example TSOP1738 reacts when it receives the IR radiation modulated at 38Khz. Means it detects the IR which is switching On and Off at the rate of 38Khz. TSOP’s output is active low, means its output is remains HIGH when there is no IR, and becomes low when it detects IR radiation. TSOP operates on particular frequency so that other IRs in the environment can’t interfere, except the modulated IR of particular frequency.
To receive the data here is some simple circuitry:

Instead of LED connect that pin to your receiver controller; you will get the signal properly. Hope this works for you.
Please try to perform our experiment in a noiseless (IR free) environment to get the correct output.
Reference: https://circuitdigest.com/electronic-circuits/ir-transmitter-and-receiver-circuit

Your receiver(ldr) might not be accurate enough, rather try using an led as a receiver as well. You will just need to boost the signal then with something like a 1Mohm resistor in parallel with the receiving led.
You can use something like this as well, haven't tried it but it looks like it will work: http://www.instructables.com/id/Arduino-Communication/
maybe just a 1Mohm resistor instead of the 1Kohm one

@LookAlterno not measure light but detect light like a photo transistor. For example: https://www.sparkfun.com/news/2161, https://makezine.com/projects/make-36-boards/how-to-use-leds-to-detect-light, https://www.edn.com/design/led/4363842/Use-LEDs-as-photodiodes

no it uses an LED as a photo-diode, if an LED receives photons it acts like a photo-diode, the links describe how you can use an LED as a photo-diode

source: Stack Exchange

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

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

sort: votes


text:
Not sure which Arduino to pick
Is the Arduino Uno the best one to purchase for a complete beginner?
I eventually want to get into building Nodebots since I already have experience writing Nodejs web-based applications.
Or should I go directly to purchasing an Arduino Starter Kit? SparkFun Inventors Kit? Adafruit ARDX Experimentation Kit for Arduino? Seeed Studio ARDX starter kit? or Freetronics Experimenter’s Kit for Arduino?
I don't know the difference between these and based off what I have shared about my situation so far, which one should I start with to A. Learn the Basics, B. Evolve into developing Nodebots.

Start simple, buy a cheap arduino uno clone from aliexpress: https://www.aliexpress.com/item/Free-shipping-high-quality-UNO-R3-MEGA328P-CH340G-for-Arduino-Compatible-NO-USB-CABLE/32231525607.html Learn how to use the arduino ide with the arduino board, and while you do that, you can investigate where to go next. It can be circuitpython, or esp32 with wifi, or a arduino mkr board or the nodebots. A arduino fan does not have just one arduino board, but a box full of things to tinker with. You need an extra driver for those cheap clones: http://www.wch.cn/downloads/CH341SER_EXE.html

NodeBots does external control of Arduino with Java Script. The controlling computer is a PC or a SOC like Raspberry PI. (Eventually Raspberry can run NodeBots without Arduino.)
For NodeBots, Arduino board runs a firmware called Firmata which executes the commands sent by the Johnny-Five Java Script firmata master library.
I would recommend you to learn C++ and Arduino functions and libraries and code the Arduino directly without Firmata and a controlling computer.

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


text:
DHT11 + ESP plus Arduino
Someone could help me?
I want to use dht11 with arduino and esp. Both will read data from dht11
the problem is that simultaneously cannot be done. So the solution will be to set one as a master and the other one as a slave.
the control will be done like so...
another wire from arduino pin->set as output ->esp pin->set as input.
if wire == 1 then dht11 will be read by arduino
if wire == 0 then esp will read dht.
with some delay ofcourse. but the problem is that i dk how to stop the communication between one board and the sensor when the other board will read it. so does it not exist any conflict

Please add your sketch (so far).

I've added it already

Disclaimer:
I've never used an ESP chip based board I know almost nothing about them. I am going to assume that it works, in software terms, like an Arduino, and base my answer on Arduino code. If the esp chip works differently, you'll need to adapt my suggestion.

Try something like this:
Connect a GPIO line between the microcontrollers. Also connect that line - through a 10K resistor - to +5V.
Have both microcontrollers set up it's GPIO as an input.
(We'll call the GPIO pin on both microcontrollers the "DHT_available" line. It will be HIGH when the DHT sensor is not being used by the other controller.)
When one of the microcontrollers wants to read the DHT11, have it check the GPIO line. If it's HIGH switch the GPIO line to an output and pull it low, then take a reading. When the reading is complete, switch the GPIO line back to an input.
If the GPIO line is LOW, wait and check again.

Alternately you could attach each of the microcontroller's GPIO lines to interrupt handlers on a rising edge. Then have the interrupt handler set the GPIO line to an output, pull it to LOW, and set a flag that means "begin reading".
Have your loop function check the "begin reading" flag, and if true, trigger a read from the DHT, and once it's complete, set the GPIO back to an input.
With the first option, each microcontroller would need to poll the "DHT_available" line continuously until it goes HIGH before beginning reading.
With the second option, as soon as one of your microcontrollers is done taking a reading, it would stop pulling the communications line LOW, the other one's rising edge interrupt would fire, and the other one would immediately begin reading.

I don;t know how to write code for all of that stuff. i am a beginner in microcontrollers

So use 2 separate DHT11 sensors, one for each microcontroller. They're cheap.

Also.. i would see a problem there. Lets say so..
Sensor data.
Gnd.
Vcc
uC 2560
uC Esp
If sensor data is linked to both uC
And  use a line dht_available btween 2560 and esp to handle the uC reading.. then..
If dht_available == HIGH then 2560 read after switch dht line to Low
If dht_available == LOW then esp read after reading dhtline》 HIGH
But the sensor wil continue to send data to both.. regqrding the dhtline is high or low.
I dk how to say to sensor.. if dhtline is LOW stop sending data to 2560 because is esp time to read.


text:
128x64 and pushButtons
Could someone give me some advice related to building a menu for a 128x64 LCD using 5 pushButtons?
i have 5 screens.
btn1 is for display MainMenu and Selection.
btn2 and btn3 is for up and down scrolling
btn 4 and btn4 is for switching on/off and increase decrease values.
the problem which i encounter is related to btn2 and btn3.
i don;t know how to use them for scrolling in in another screen except screen1 (MainMenu).

#include "U8glib.h"
U8GLIB_ST7920_128X64_1X u8g(13,12,11); //Enable, RW, RS, RESET

int selectionButton = A1, selectionButtonState, selectionButtonLastState = 0, cntSelectionButtonPressed = 0, cntSelectionButtonPressed2ForMenu2 = 0;
int menuButton = A0, menuButtonState, menuButtonLastState = 0;
int scrollDownButton = A3, scrollDownButtonState, scrollDownButtonLastState = 0;
  boolean mainMenu = false;

void setup()
{
    Serial.begin(9600);
    if ( u8g.getMode() == U8G_MODE_R3G3B2 )
    u8g.setColorIndex(255);     // white
    else if ( u8g.getMode() == U8G_MODE_GRAY2BIT )
    u8g.setColorIndex(3);         // max intensity
    else if ( u8g.getMode() == U8G_MODE_BW )
    pinMode(selectionButton,INPUT);
    pinMode(menuButton,INPUT);
    pinMode(scrollDownButton,INPUT);

}

void loop()
{

 scrollDownButtonState = digitalRead(A3);
 selectionButton = digitalRead(A1);
 menuButton = digitalRead(A0);

//pin A1 = RiGHT
 if(selectionButton != selectionButtonLastState)
 {
  if(digitalRead(A1) == HIGH)
  {
    cntSelectionButtonPressed += 1;
    if(cntSelectionButtonPressed == 4)
    {
      cntSelectionButtonPressed = 0;
    }
  }
  selectionButtonLastState = selectionButton;
 }

////////////////////////
 if(menuButton != menuButtonLastState)
  {
    if(cntSelectionButtonPressed == 1 && digitalRead(A0) == HIGH)
    {
         cntSelectionButtonPressed2ForMenu2 += 1;
    }
      if(cntSelectionButtonPressed2ForMenu2 == 4)
      {
        cntSelectionButtonPressed2ForMenu2 = 0;
      }
       u8g.firstPage();
       do{
           Menu2();
         }while(u8g.nextPage());

       menuButtonLastState = menuButton;
  }
 else
 {
 u8g.firstPage();
  do{
    MainMenu();
  }while(u8g.nextPage());
 }

}

void MainMenu(){
switch(cntSelectionButtonPressed)
{

  case 1:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("> Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("  Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("  Exterior casa");
           break;
  case 2:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("> Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("  Exterior casa");
           break;
           break;
  case 3:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("  Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("> Exterior casa");
           break;
}
}

void Menu2()
{

  switch(cntSelectionButtonPressed2ForMenu2)
{
  case 1:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("> Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("  Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("  Stil3");
           break;
  case 2:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("> Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("  Stil3");
           break;
           break;
  case 3:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("  Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("> Stil3");
           break;
}
}

First, I'm a bit surprised you use analog pins for button checks, instead of digital pins.
About the code, without analyzing it completely, the easiest way is to make a state diagram in pseudo code first.
E.g.suppose you want to have the following screens(a screen 'title/content' is shown in[], a button transition with ---(key)-->
InitScreen--- (right)--> MenuOption1Highlight---(right)-->MenuOption1Items
                              |       ^     \---(left)----+
                           (down)    (up)
                              v       |
                           MenuOption2Highlight---(right)-->MenuOption2Items
                                              \---(left)----+

To program this (roughly), create an enumeration for each menu page :
enum EMenuPage
{
        None,
    InitScreen,
    MenuOption1Highlight,
    MenuOption1Items,
    MenuOption2Highlight,
    MenuOption2Items
};

Than create a current state for it as global variable:
EMenuPage _eMenuPage;

And initialize it in Setup:
_eMenuPage = None;

Create an enum for the keys :
enum EKey
{
    None,
    Up,
    Down,
    Right,
    Left
};

It is easier to create a function that reads keys, and returns one key, maybe one key has priority over another,
or you can combine keys (in that case add in EKey e.g. UpAndDown). If no key has been pressed, None is selected.
In the loop, use a state transition diagram to program out the options :
EKey pressedKey = GetPressedKey(); // This is for yourself to implement, it updates _pressedKey;

switch (_eMenuPage)
{
case None:
    InitScreen();
    break;

case InitScreen:
    ProcessInitScreenKeys();
    break;

case MenuOptions1HighLighted:
    ProcessMenuOptions1HighLightedKeys();
    break;

...
default:
    // Illegal key
    break;
}

For each page you make a function (e.g. InitScreen) which updates the state and shows the content on the display:
void InitScreen()
{
    _eMenuPage = InitScreen;

    // Show content on display.
}

Also, you create a Process...Keys function to handle the keys. Like:
void InitScreen()
{
    EKey pressedKey = GetPressedKey();
    switch (pressedKey)
    {
    case Right:
        MenuOptions1HighLighted();
        break;

    default:
        // Ignore other keys
        break;
    }
}

For another function it would look like:
void ProcessMenuOptions1HighLightedKeys()
{
    EKey pressedKey = GetPressedKey();
    switch (pressedKey)
    {
    case Down:
        MenuOptions1HighLighted();
        break;

    case Right:
        MenuOption1Items();
        break;

    default:
        // Ignore other keys
        break;
    }
}

(Btw I did not check neither compiled the code).
Probably there is a nicer more object oriented way to do this, but it costs more memory and is more advanced. This is to create an abstract Page class, which has two virtual methods (one to show and one to handle keys), and create a derived class for each page implementing the two functions from the base class.


text:
LCD connection problem
First of all, i have some problems with an lcd .
For a better understanding, the lcd datasheet could be found here:
https://www.mikrocontroller.net/attachment/53098/DGF-12232-S1FBLY-325-17231-1006.pdf
i want to connect it to arduino mega but it has 20 pins and i can't figure it out how it should be connected.
Could someone help me ?

Looks pretty much like any other graphic LCD, so I'd start with that.

This display has a very old (20 year+) SED1520 display controller that is not really suited for low pin count microcontrollers like the Arduino. It needs a full parallel 8-bit data bus  and some (5) control signals, so you will need ~13 pins to connect it to your Arduino. It's not supported by common Arduino libraries so you would need to write your own low-level software to get it to display something. Frankly I would not bother and just buy a better supported (OLED or small TFT) I2C or SPI display instead.

For those reading this answer prior to acquiring an LCD for an Arduino project, consider using a more common alpha / numeric LCD rather than a graphic LCD or GLCD.  Likely there will be more examples to follow as well as more software with more community support.
The linked to Graphical LCD (or GLCD) uses a SED1520 controller.  Searching the Arduino community resulted in finding this openGLCD project.  There may be others.  Looking here (near the end of 2019) we see the comment "added custom sed1520 init routine to fully initialize sed1520 chips" next to the sed1520_Device.h file.  Likely this project supports GLCD modules which use the SED1520 chip.
With regards to wiring GLCD module, on page 19 of the specifications linked to in the question, the table in section 5.1 lists the description of the 20 GLCD pins.


text:
Digispark Micro (ATTINY85) not working on Macbook Pro 2016
I just bought 2 Digispark Micro to start learning some Arduino things.
But when I try to upload the code to my Digispark, it just send me an "Device search timed out" error.
My Digispark is plugged with an USB-C to USB connector and the Red dot on the Digispark is working. The connector is working well with any other device.
Arduino app (1.8.9) settings:

Tools

Board → Digispark (Default - 16.5 mhz)
Programmer → Micronucleus

I tried using the micronucleus CLI, but, even if I try plug/unplug several times (~10s between each unplug/plug) I got this :
> Please plug in the device ...
> Press CTRL+C to terminate the program.

Digisparks are known to have problems with USB3 ports (which your USB-C adaptor probably provides). Try using a cheap USB2 hub between the DigiSpark and the adaptor.
It's always a good idea to use a cheap USB hub between whatever experimental device you want to connect and your machine, so that if you wire something up incorrectly you don't end up frying an expensive laptop. This is particularly true for a device such as the digispark which does not have a real USB interface but really bit-bangs the protocol out of ordinary I/O pins.
There is no guarantee that the hub will protect you from all wiring mistakes, but it's an added level of protection.

Hi @JayEye ! Thanks for those information. I'm already using this device (https://www.apple.com/fr/shop/product/MJ1M2ZM/A/adaptateur-usb-c-vers-usb?afid=p238%7Cs4VqawkmI-dc_mtid_187079nc38483_pcrid_102671600198_&cid=aos-fr-kwgo-pla-btb--slid-----product-MJ1M2ZM/A-FR). Isn't it enoough?

Good thing I speak French :)
No, this will not be enough; this just converts the physical connector (USB-C to USB-A). You need something like https://www.amazon.com/Black-4-Port-High-Speed-USB/dp/B002FFT8Z6 between the adaptor you have and the digispark


text:
code error- Real Time Clock program-DS3231 RTC module
I'am a NEW-B with an ELEGOO mega 2560 starter kit.The program code came from their disc.The verifying error message for the declaration: RTCDateTime dt; is
RTCDateTime' does mot name a type
exit status 1
'RTCDateTime'does not name a type
I can not determine what this means or how to correct.
HELP,Dick

I downloaded the tutorial code for ELEGOO Mega Most Complete Starter Kit from here: http://www.elegoo.com/tutorial/ (their web site is a mess of broken links). The RTC example (Lesson 19) does indeed use RTCDateTime type. However, the accompanying DS3231 library does properly define that type in DS3231.h. So, in that package the problem you are reporting does not exist. Maybe the version on the disc has some kind of typo? And your sure you are using their libraries?

My bet would be that you simply included a third-party DS3231.h, which has nothing to do with the proper DS3231.h. Hence the error.


text:
Arduino IDE + Metro + I2C device (Grideye) + Code for Uno = weird results?
I have been working successfully with the arduino uno and a thermal camera device called grid eye. There is a board available at the popular suppliers of arduino addons.
For the uno, the code looks something like this and works.
// Load Grideye Library
#include <SparkFun_GridEYE_Arduino_Library.h>
uint8_t pixelTable[64];
void setup() {
    grideye.setI2CAddress(104); //This means, that one pin of the device is pulled up
    grideye.begin();
    Serial.begin(115200);
}
void loop() {
// loop through all 64 pixels on the device and map each float value to a number
// between 0 and 15 using the HOT and COLD values we set at the top of the sketch
  for (unsigned char i = 0; i < 64; i++) {
    if (i % 8 == 0) {
      Serial.print("\n");
    }
    pixelTable[i] = grideye.getPixelTemperature(i);
    Serial.print(pixelTable[i]);
    Serial.print(" ");
  }

For the Metro I use Arduino IDE with the Libraries installed and the board selected. But all I get is an Array full of '0'.
Connected, both times, to the designated SDA and SCL pins, as well as the 3.3V and GND Pin.
Any Ideas?

does I2CScaner sketch find the device?

what is the correct GridEye I2C address? ...... btw, do not use decimal numbers for the address, it can cause errors because all of the documentation is in hex or in binary

Thank you for your comments and sorry for initially posting in the wrong community.  I downloaded I2Cscanner, which does not find any devices. This, I don't understand, the UNO works fine with the same setup..   The Correct ist either 0b1101000 or 0b1101001, depending on whether one Pin is connected to GND or pulled up. MIe is connected to GND, so 0b1101000 or 104, or 0x68 it shold be  I changed to hex btw, also no effect.


text:
Can't parse large json file
For a project I've to parse a big json file. Unfortunately it does not work as expected.
Here is the json file:
{
  "data1": "[encoded data, 4800 characters]",
  "data2": "[encoded data, 4800 characters]",
  "data3": "736",
  "data4": "266",
  "data5": "3211",
  "data6": "0"
}

I was able to successfully implement the whole thing on an ESP8266 with this code:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

// WiFi Parameters
const char* ssid = "SSID";
const char* password = "PASSWORD";

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting...");
  }
}

void loop() {
  // Check WiFi Status
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;  //Object of class HTTPClient
    http.begin("http://jsonplaceholder.typicode.com/users/1");
    int httpCode = http.GET();
    //Check the returning code
    if (httpCode > 0) {
      // Parsing
      const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8) + 370;
      DynamicJsonBuffer jsonBuffer(bufferSize);
      JsonObject& root = jsonBuffer.parseObject(http.getString());

      const char* data1 = root["data1"];
      const char* data2 = root["data2"];
      const char* data3 = root["data3"];
      const char* data4 = root["data4"];
      const char* data5 = root["data5"];
      const char* data6 = root["data6"];

      Serial.print("data1:");
      Serial.println(data1);
      Serial.print("data2:");
      Serial.println(data2);
      Serial.print("data3:");
      Serial.println(data3);
      Serial.print("data4:");
      Serial.println(data4);
      Serial.print("data5:");
      Serial.println(data5);
      Serial.print("data6:");
      Serial.println(data6);
    }
    http.end();   //Close connection
  }
  delay(60000);
}

The ESP Code works perfect for me, but for my application I need an microcontroller with ethernet. So I bought an enc28j60 and a W5500 Board to migrate the ESP Code to the Arduino UNO.
The Code result is this:
#include <ArduinoJson.h>
#include <Ethernet.h>
#include <SPI.h>

void setup() {
  // Initialize Serial port
  Serial.begin(9600);
  while (!Serial) continue;

  // Initialize Ethernet library
  byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  if (!Ethernet.begin(mac)) {
    Serial.println(F("Failed to configure Ethernet"));
    return;
  }
  delay(1000);

  Serial.println(F("Connecting..."));

  // Connect to HTTP server
  EthernetClient client;
  client.setTimeout(10000);
  if (!client.connect("192.168.178.5", 80)) {
    Serial.println(F("Connection failed"));
    return;
  }

  Serial.println(F("Connected!"));

  // Send HTTP request
  client.println(F("GET /test.json HTTP/1.0"));
  client.println(F("Host: arduinojson.org"));
  client.println(F("Connection: close"));
  if (client.println() == 0) {
    Serial.println(F("Failed to send request"));
    return;
  }

  // Check HTTP status
  char status[32] = {0};
  client.readBytesUntil('\r', status, sizeof(status));
  if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
    Serial.print(F("Unexpected response: "));
    Serial.println(status);
    return;
  }

  // Skip HTTP headers
  char endOfHeaders[] = "\r\n\r\n";
  if (!client.find(endOfHeaders)) {
    Serial.println(F("Invalid response"));
    return;
  }

  // Allocate JsonBuffer
  // Use arduinojson.org/assistant to compute the capacity.
  const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
  DynamicJsonBuffer jsonBuffer(capacity);

  // Parse JSON object
  JsonObject& root = jsonBuffer.parseObject(client);
  if (!root.success()) {
    Serial.println(F("Parsing failed!"));
    return;
  }

  // Extract values
  Serial.println(F("Response:"));
  Serial.println(root["data1"].as<char*>());
  Serial.println(root["data2"].as<char*>());
  Serial.println(root["data3"].as<char*>());
  Serial.println(root["data4"].as<char*>());
  Serial.println(root["data5"].as<char*>());
  Serial.println(root["data6"].as<char*>());

  // Disconnect
  client.stop();
}

void loop() {

}

Every time a run the sketch I get the following error:
"Parsing failed!"
So I got to the following page:
https://arduinojson.org/v5/faq/why-parsing-fails/
I've tested the sketch with different buffer sizes, without success?
Is it possible that the memory simply is too small?
Or did I miss something?

you can use W5500 or enc28j60 with esp8266. use MemoryFree library to print free memory size at runtime

Do you have an example or a sketch for me? I did not make it work.

use esp8266 package 2.4.2 and delete the bundled Ethernet library

try an esp32, they have phy built in, and a lot more ram to boot...


text:
Arduino Uno 3.3V pin to GND short how to fix
Hi I am new to the Arduino world. I was playing around with my Arduino UNO making LEDs go on and off in a sequence. Then I connected a motor to the N.0 pins but found it doesn't work so I plugged it doesn't work so I plugged it in 3.3V pin and it worked. I tried to reverse the connections but the one cable slipped and it connected to the metal shielding of the motor now it is not working when plugging it in USB it. Power LED just flashes red and turns off emediatly. Reset button doesn't seem to do annything. Is there a possible fix for this.

There is, but it would probably cost you more than the cost of a new counterfeit Uno from AliExpress.

First you need to identify what component is what, and then work out which has been destroyed by your short circuit (probably the 3.3V regulator, whichever component that is). Then identify the component make and model, and buy a new one. Then replace it and hope. Since that is not an official Arduino UNO you are probably going to have problems identifying the components and their model numbers in order to get a replacement. Just ditch it and get a new one.

@Majenko I believe it is a "clone" and not a "counterfeit". A "counterfeit" would have the Arduino logo and would be sold as an "original" with fake box etc.

Tomaytos, tomahtos. It's a piece of cheap Chinese crap either way.

It was working fine so I really don't care about quality I just need a processing board for my project besides I am a begginer and not really worth it to invest in high quality expensive equipment I will break so thanks for suggesting AliExpress but is it trust worthy.


text:
MPU6050 - Why is my gyro integration incorrect?
My situation:

I am able to communicate over i2c with my MPU6050 IMU
I can get accelerometer and gyro data
I can compute the sensor's orientation using my accelerometer

Issue:

when trying to compute the sensor's orientation using my gyroscope my values seem to be totally incorrect. I am computing the orientation using a complementary filter.

This is the code I use https://paste.ubuntu.com/p/vZmbnc23gj/
This is the computed orientation, when the sensor is lying on a table: https:https://paste.ubuntu.com/p/W7DzVKR9c7/
Those measurements are totally incorrect, because when moving the senor randomly around its axis it never goes above 1.8. (even when I do an 180 degree turn)
Could somebody give me some hints or explanation on why my results are incorrect and drifting so much?

Could you post a schematic of your connections? I understand you can communicate with it, but am interested in what you have.

@Wendall connection, are just typical "i2c connection" without pull ups

You need to perform offset calibration, otherwise you'll get large drift errors. The MPU6050 has a dedicated Digital Motion Processor (DMP) where data from the gyro and accelerometer are fused for you. I recommend grabbing the results of that fusion from the DMP. As far as I know the only libraries that do this are ones based on Jeff Rowberg's work. For a detailed guide please see:
https://youtu.be/k5i-vE5rZR0


text:
Common ground serial communication trouble SIM800L
I have a trouble when i'm using SIM800L module with common ground with combinaison with : FTDI232+ARDUINO PRO and Li-po battery. I use common ground to allow Arduino see the serial of SIM800L.
I use battery (lipo) to power the SIM800L to allow 2A peak current.
Serial work but sometime the module reset(i think) and i see strange character. The SIM800L no work correctly.
I meet the same trouble when i use the FTDI's VCC, every time I use the common ground i have this problem.
Look the gif you can see the problem :

I'm using this wiring
It's strange because when i connect the SIM800L directly with FTDI232 i have no problem all work fine.
I use this code to debug the Serial communication :
#include <SoftwareSerial.h>
SoftwareSerial serialSIM800(RX,TX)
[..]
//On Setup
 Serial.begin(115200);
  while(!Serial);

  //Being serial communication witj Arduino and SIM800
  serialSIM800.begin(115200);
  delay(1000);
  serialSIM800.print("AT\r");
  //[..]
void loop(){

 if (serialSIM800.available())
     Serial.write(serialSIM800.read());

 if (Serial.available()) {
    while(Serial.available()){
      Serial.print(">");
      char test=Serial.read();
      Serial.print(test);
      Serial.println();
      serialSIM800.write(test);
 }

There are a few things that escape me that's why I need your lights, thanks by advance.
Regards

Two suspicions can be investigated.
First thing is Software Serial which is always a candidate for  suspicion. I understand that you debug from the pc via FTDI.
You maybe better debug using Arduino Mega since it has multiple hardware serials until you satisfied with your project and port the code to the Arduino Pro afterward.
And second thing is If Arduino Pro version is 3v (you didn't mention) and causing logic levels issues.

If I were you, I would start testing from lower rates like 9600 and make higher until the data  is started to garble as you see.

Btw, your wiring shows SIM900L not SIM800 which have slightly different wiring recommendations. Which one is yours?

@Sener i do a mistake is really sim800l

I use 1200 baud rate and i use https://github.com/nickstedman/SoftwareSerialWithHalfDuplex for Software Serial this no work i have the same problem

I finally fixed my issue.
I disable the auto baud rate of SIM800L trough FTDI232, with these at commands:
AT + IPR = 9600
AT & W

AT + IPR: Fix the baud rate at 9600
AT & W: Save in SIM800L
Then when i use with SoftwareSerial i have no issue anymore. When i reset the module with short connect RST with GND i have a good reply from SIM800L :
RDY

+CFUN: 1

+CPIN: READY

Call Ready

SMS Ready

Thanks for your help.
Note : And be sure you are a good power supply and good wire.

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


text:
Voltage divider arduino 5v and Ethernet board 3.3
I have an Arduino Nano 5v module and I just received an Ethernet Interface Board - ENC28J60 that runs at 3.3v. (https://www.sparkfun.com/products/765)
Might sound a dumb question but I will power the Ethernet board from a Voltage regulator that can deliver 3.3v but then I have to connect via SPI to my Arduino controller. I guess I can't connect my Arduino pins directly to the Ethernet board right? because HIGH in the pin will be 5v instead of 3.3v.

Do I need to add a Voltage divider for those pins connections? And in case I need to what resistance values are the right ones to use?

Thanks

Yep, you need Bi-directional logic voltage converter https://learn.sparkfun.com/tutorials/bi-directional-logic-level-converter-hookup-guide

@martynas those are more geared towards I2C, since I2C has a bidirectional data line.

Wooow nice!!! yes I have seen those Bi directional logic voltage converters now I know whats that for. Appreciat it

And I guess that logic voltage converters are only used for the Pins right... for powering the module then is right to use a voltage regulator such as the LM3940 IC.

Yup you are correct.

From experience with 3.3v ESP8266es with 5v Arduinos, only the signals to the 3.3v device need to be converted (5v high -> 3.3v high). A 3.3v level to the Arduino is high enough for 5v logic to still read it as HIGH. That means you can get away with just a voltage divider on each of the Arduino -> ENC28J60 pins.


text:
analogRead seems to freeze some seconds the program
I have the following code that reads a RFID reader, it was working perfect without any dealy and then I try to an analog read from a potentiometer using analogRead.
The analog read works fine but then when I hover the card over the RFID it takes about 7 seconds or so to go into the line where I turn on a LED.
Im sure Im doing something wrong with analogReader because this is the first time I use it.

I really appreciate any help

    #include <MicroView.h>

    MicroViewWidget *widget;        // create widget pointer

    #define MAX_BITS 100                 // max number of bits
    #define WEIGAND_WAIT_TIME  3000      // time to wait for another weigand pulse.

    unsigned char databits[MAX_BITS];    // stores all of the data bits
    unsigned char bitCount;              // number of bits currently captured
    unsigned char flagDone;              // goes low when data is currently being captured
    unsigned int weigand_counter;        // countdown until we assume there are no more bits

    unsigned long facilityCode=0;        // decoded facility code
    unsigned long cardCode=0;            // decoded card code

    int sensorPin = A1;    // select the input pin for the potentiometer
    int sensorValue = 0;  // variable to store the value coming from the sensor

    // interrupt that happens when INTO goes low (0 bit)
    void ISR_INT0()
    {

      bitCount++;
      flagDone = 0;
      weigand_counter = WEIGAND_WAIT_TIME;

    }

    // interrupt that happens when INT1 goes low (1 bit)
    void ISR_INT1()
    {

      databits[bitCount] = 1;
      bitCount++;
      flagDone = 0;
      weigand_counter = WEIGAND_WAIT_TIME;
    }

    void setup()
    {

      pinMode(2, INPUT_PULLUP);     // DATA0 (INT0)
      pinMode(3, INPUT_PULLUP);     // DATA1 (INT1)
      pinMode(5, OUTPUT);           // LED

      Serial.begin(9600);

      // binds the ISR functions to the falling edge of INTO and INT1
      attachInterrupt(0, ISR_INT0, FALLING);
      attachInterrupt(1, ISR_INT1, FALLING);

      digitalWrite(sensorPin, HIGH);      // Internal Pull-up
      pinMode(sensorPin, INPUT);          // make pin as INPUT

      uView.begin();                      // start MicroView
      uView.clear(PAGE);                  // clear page
       uView.setCursor(5,0);
      uView.print("TEST");
       uView.setCursor(0,20);
       uView.print("RFID READ");
      widget = new MicroViewSlider(0, 35, 0, 1024);    // make widget as Slider
      //widget2 = new MicroViewSlider(0, 20, 0, 1024, WIDGETSTYLE1);    // make widget as Silder STYLE1
      uView.display();                    // display the content in the screen buffer

      weigand_counter = WEIGAND_WAIT_TIME;
    }

    void loop()
    {

      // This waits to make sure that there have been no more data pulses before processing data
      if (!flagDone) {
        if (--weigand_counter == 0)
          flagDone = 1;
      }

//****** THIS IS THE NEW CODE THAT FREEZE FOR ABOUT 7 SECONDS THE PROGRAM ***//
      sensorValue = analogRead(sensorPin);    // read sensorPin
      widget->setValue(sensorValue);          // set value of sensorPin to widget
      //widget2->setValue(sensorValue);         // set value of sensorPin to widget
      uView.display();

//****** THIS IS THE NEW CODE THAT FREEZE FOR ABOUT 7 SECONDS THE PROGRAM ***//

      // if we have bits and we the weigand counter went out
      if (bitCount > 0 && flagDone) {
        unsigned char i;

        Serial.print("Read ");
        Serial.print(bitCount);
        Serial.print(" bits. ");

        if (bitCount == 32){

          // **** AFTER 7 SECONDS I GET INTO THIS CODE ****///

          uView.clear(PAGE);      // clear the page buffer
          uView.setCursor(0,0);

          digitalWrite(5, HIGH);

        }

         // cleanup and get ready for the next card
         bitCount = 0;
         facilityCode = 0;
         cardCode = 0;
         for (i=0; i<MAX_BITS; i++)
         {
           databits[i] = 0;
         }
      }
    }

analogRead() is fine, it takes only about 110 µs, but there are
several other issues with your code that you should fix:

Any variable that is shared between interrupt code and normal code
should be declared volatile in order to prevent the compiler to do
some unsafe optimizations.
Any such variable that is more than one byte in size should be
accessed from the main program with interrupts disabled.
You should take care of not writing into databits[] past the end of
the array.
Counting loop iterations is a very bad way of measuring elapsed time,
as the counting speed will change whenever you change your loop code.
Use micros() instead.

There is also an issue with how you use flagDone. You set it to 1,
then you call analogRead(), MicroViewSlider::setValue() and
uView.display(), then you read it back. What if your ISR has set it
back to 0 in the meantime? I suspect this is the main cause of the
problem you see.
I suggest you use flagDone to inhibit the ISRs: the main loop sets it
to true to tell the ISRs “Let's say we are done with this card. Please
do not touch anything while I process the already received information.”
And later it sets it to false meaning “You can proceed reading bits
now.”
Given the above considerations, I would try something along these lines:
volatile bool flagDone;     // if we are done, pause the reading
volatile uint8_t bitCount;  // number of bits received so far
volatile uint32_t rxTime;   // last time we got a bit

// Interrupt that happens when INTO goes low (0 bit).
void ISR_INT0()
{
    if (!flagDone && bitCount < MAX_BITS) {
        rxTime = micros();
        databits[bitCount++] = 0;
    }
}

// Same thing, but writes 1 instead of 0 into databits[].
void ISR_INT0() { ... }

void loop()
{
    // Safely read rxTime.
    noInterrupts();
    uint32_t rxTimeCopy = rxTime;
    interrupts();

    if (bitCount > 0 && micros() - rxTimeCopy >= WEIGAND_WAIT_TIME) {
        // Assume we are done reading this card.
        flagDone = true;

        // Do whatever with databits[].
        // ...

        // Get ready for the next card.
        bitCount = 0;
        flagDone = false;  // do this last: it re-enables the ISR
    }
}

Appreciate it I will give a try. Do you recommend me to use ArduinoThread library instead?

@VAAA: Not sure I understand in which way you expect ArduinoThread to help here...

you are totally right Im very sorry Im new and I have to understand a lot of things before asking dumb questions. Let me understand your code first :)


text:
What if I detach AVR micro controller from the Arduino Board after uploading program?
What if I detach AVR microcontroller from the Arduino Board after uploading program? Does the microcontroller still have the program on it? Or the program will be deleted?
On the board where does Arduino store hex file?
I am very beginner in Embedded Programming. I am learning about microcontroller and Arduino. While learning about programming Arduino-Uno I got these question in my mind.

the microcontroller itself stores the program in flash, so you can remove the part and move it elsewhere and the program goes with it.

Just look at the documentation for the AVR part it describes where the application lives.

historically there have been boards (basic stamp, etc) that the program on the microcontroller was an interpreter for a bytecode that actually lived on another device on the board, eeprom or flash.  No reason to do this on an arduino, since you are learning examine the schematic and see what else you see on the board, where else could the program live?  (combined with reading datasheets for the parts you find)

Make sure to check this link (https://www.arduino.cc/en/main/standalone)

The AVR µC got a flash memory that can store the code loaded in. That mean you can load the code with the arduino board, detach the avr and put it on another circuit. If the µC is powered well, it will behave just like the arduino.
Don't forget to set the /reset pin to high, if you do, the µC will be stuck to the 1st line of code ;)

authors: Игорь Лавренко


text:
How to return a value from a non integer input between 0-5 from an output range of 0-320 in map() method
I am experimenting using the map() method in an ArduinoIDE sketch in an attempt to obtain a pixel position for a horizontal meter in the range 0-320 from an input value in the range 0-5.  However, when I do this I see in the method that the input must be 'long' type.  Here's my example code:
  float voltage = 2.5;
  float meterPosition = map(voltage, 0, 5, 0, 320);
  tft.fillRect(0, 0, meterPosition, 10, TFT_GREEN);
  tft.setCursor(10, 70);
  tft.setTextSize(3);
  tft.println(voltage);
  tft.println(meterPosition);

But when I run this, despite the input value being 50% of the input range, I expected the meterPosition value to be 160, but it is 128, due I think because the values for this method must be of type 'long' and so the 'float' value is rounded and becomes a 'long' type (I think that's what is happening!!).
I am confused as to the function of the map() method if you are unable to map any range to any other range without using decimals as the input.  I am obviously missing something here, so what do I need to change in my map() method code for it to work in my example please, if I am unable to use floats?
Thanks.
John

What about just saying float meterPosition = voltage * 64.0 ; ?

As you already noticed, the map() function is meant to work with the
long data type. Here is its implementation:
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

If you want to use floats, you could write a version of this function
that works with floats. Note, however, that since you are using zeros
for both in_min and out_min, the expression simplifies itself to the
point of becoming trivial:
float meterPosition = voltage * 320 / 5.0;

I would suggest two small changes to this expression though:

add parentheses around (320 / 5.0): this ratio will then be
evaluated at compile-time and you will save an expensive run-time
floating-point division

round to the nearest integer in order to minimize the error: your
pixel position will have to be an integer anyway.

With these suggestions, we have:
int meterPosition = round(voltage * (320 / 5.0));

Do not forget the .0 in 5.0, otherwise you would get an integer
division.
Note that using map() with ranges scaled by a factor 100 is not a
terribly good idea: you will waste quite a lot of CPU cycles doing
useless computations, and the result will be polluted by two rounding
errors instead of one.

Apologies for my stupidity folks!  I think I have realised how to do this, it is simply a matter of scaling the input values and input range by 100.


text:
How to get average of 16bit ADC readings?
I have an Adafruit ADS1115 analog-to-digital converter, configured in single ended mode. I want to average over 3 sensor readings to increase the reading stability.
  //initialize variables
  int16_t rawData, ambient;
  int i=0;

  // start loop
  while(i<3) {
      rawData = ads.readADC_SingleEnded(0); //read from ADC
      // divide sensor reading by three
      // (doing so after summation will lead to an overflow)
      rawData=rawData/3;
      Serial.println(rawData); // print data to serial for debugging (OK)
      ambient+=rawData;
      i+=1;
      delay(100);
      Serial.println("I LIVVVVEEE"); // print text to serial for debugging (OK)
  }

  // Print signal (NOT OK)
  Serial.print("Ambient is ");
  Serial.println(ambient);

The "rawData" is printed correctly on the serial monitor. However, the value for "ambient" can be crazy: the resulting output is over an order of magnitude higher. Somehow, the summation doesn't seem to be performed correctly.

this is not avarege of 3 readings. it is a sum a of 1/3 of readings

If you are trying to average out three sensor ADC reading first you need to store and add them all then divide it by 3.
 int16_t rawData =0;
 int32_t avg=0,ambient=0;
  int i=0;

 while(i<3) {
      rawData = ads.readADC_SingleEnded(0); //read from ADC
      // divide sensor reading by three
      // (doing so after summation will lead to an overflow)
     Serial.println(rawData); // print data to serial for debugging (OK)
     avg += rawData;
      i++;
      delay(100);
      Serial.println("I LIVVVVEEE"); // print text to serial for debugging (OK)
  }
  abmient = avg /3;
  avg = 0;
  // Print signal (NOT OK)
  Serial.print("Ambient is ");
  Serial.println(ambient);

This approach is great for small numbers. However, the ADC is 16 bit. By adding three 16bit values, this may (can) lead to buffer overflow for "ambient".

@plasma, sum of 3 16 bit numbers will not run out of 32 bit

@Juraj there is nothing like that. I just made changes in his program.

appreciated....

you will actually get more stable readings if you take the median of the 3 readings instead of the mean. consider reading 12,13,5 when the true reading is 13. with avg you get 10 (err=3), but with median you get 12 (err=1). I used this method for a DMM project and it made a HUGE difference compared to my naive oversample+avg method... You can also adjust how many internal AD1115 samples are collected, and at the expense of reading time, get a more stable set of values from the get go.

@dandavis Its not necessary that always median will be the right value. It might happen in your case but I had tested it on ST controller where I take average of 4 readings and I get the expected value, though I calculated voltage using ADC, the error I got is about -0.01V from actual voltage.

Calculating a mean the way the OP does is absolutely valid. It doesn't make a difference wether the sum or the summands are divided by the number of values. Your code might fix the issue, but that's because you initialize the variables explicitly.

You forgot to initialize ambient to zero, so it got whatever happened to be in that place of memory when it got instantiated. Some unpredictable, seemingly random data.

are you saying that int16_t ambient; Serial.println(ambient, DEC); could show something besides 0?

@dandavis: Yes, absolutely. The value of ambient here is indeterminate. In some circumstances, using such a value can even lead to undefined behavior.


text:
HX711 Wemos D1 Weird Characters In Serial Monitor
I am using the HX711 with a load cell attached on my Wemos D1. I have the connections correctly as if I use the same setup on my Arduino Uno board and the same code it runs fine and prints to the serial log. If I comment out the HX711 scale(DOUT, CLK); in my code the serial print is fine. I am not sure if this is an issue with the board or something I am doing with it. I would use the Arduino Uno but it does not have Wifi whereas my Wemos board does. Attached is a screenshot of the serial print from the monitor.

#include "HX711.h"

#define DOUT  3
#define CLK  2

HX711 scale(DOUT, CLK);

float calibration_factor = -117441.00; //-7050 worked for my 440lb max scale setup

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

  Serial.println("HX711 calibration sketch");
  Serial.println("Remove all weight from scale");
  Serial.println("After readings begin, place known weight on scale");
  Serial.println("Press + or a to increase calibration factor");
  Serial.println("Press - or z to decrease calibration factor");
  scale.set_scale();
  scale.tare(); //Reset the scale to 0

  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
}

void loop() {

  scale.set_scale(calibration_factor); //Adjust to this calibration factor

  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1);
  Serial.print(" lbs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
  Serial.print(" calibration_factor: ");
  Serial.print(calibration_factor);
  Serial.println();

  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp == '+' || temp == 'a')
      calibration_factor += 10;
    else if(temp == '-' || temp == 'z')
      calibration_factor -= 10;
  }
}

had you tried using other pins like 8,9 in place of 2,3

@Vaibhav Yup, tried that

io 3 is TX of Serial. use Dx constants to match the labels on board https://electronics.stackexchange.com/questions/402066/esp8266-free-gpios-for-relay-switching/404845#404845

@Juraj This does not make a lot of sense and does not solve my issue. My board does not look like that it looks like this https://storage.googleapis.com/stateless-www-faranux-com/2017/06/Reloaded-295x300.jpg and in this image my hx711 is hooked up to D3 and D3

ok, you have the D1 R1. on Wemos D1 R1 the pin labeled D3 is io 5 of the esp8266. in code use D3 not 3. https://github.com/esp8266/Arduino/blob/4e0e4e4340e6110cbb63ff77cb43d316cc318368/variants/d1/pins_arduino.h#L38

@Juraj I tried replacing 3 in the code with both D3 or even 0 as defined in that Github but both didn't work. I also tried replacing 2 with D2 or 4 as that code specifies but that also didn't work for me

@Juraj Okay cool now I am using D3 in the spot of 3 and D2 in the spot of 2 and it's working! Perfect.


text:
Pin 13 fires relay when powering on... How to disable?
Pin 13 fires relay when powering on... How to disable?
I'm using pro mini 5v 16MHz and a DC 12V 2 Channel Relay Module Optocoupler. The relay Jd-VCC is powered by a 12V and it's VCC is 5V (the same as Arduino VCC). The relay is active low and I soldered pins 12 and 13 of the pro mini to IN1 and IN2 of the relay.
When I power the board up it cycles Pin 13(and the on-board LED) ON and then OFF before resuming to the code I uploaded. I believe that this can be fixed by disabling this blinking function in the startup process.
I understand that I can use other pins. Why not learn how to remove this from startup, if I prefer to use this pin for circuit layout purposes?
Any help would be much appreciated. Most of my searches ended up with people using the pin as an input... My issue is when using D13 as an active low pin it has some funky behavior at startup but then works as programmed.
Thanks!!!

Tehee, imagined your TV going on and off every time you would reboot/program your Arduino xD. But Majenko has some good solutions I see.

There are three things you can do:

Remove the bootloader entirely and program the board with a hardware programmer (USB-ASP, Another Arduino, etc).
Edit the bootloader source, recompile, and reinstall it to the board using a hardware programmer (as in option 1).
Just don't use pin 13 for the relay.

Of the three options the third one is by far the simplest.

:( no fun... I just moved my pins down to D11 and D12. I was hoping it was a simple as commenting some code out in the bootloader.

One step is as simple as commenting some code out in the bootloader. The rest of the steps involve compiling that bootloader and installing it. All can be done, but is it really worth the effort when you can just choose different pins?

There is a define in the bootloader:  LED_START_FLASHES - you could set that to zero, and recompile. But then you need extra hardware to upload it. Plus, compiling the bootloader is not something the IDE is set up to do.

@NickGammon: Way back in the day I saw a youtube video of someone programming the bootloader by putting switches/resistors on the SPI pins, and toggling it in by hand.  I've gone looking for that video again, but can't find it :(

That would take a long time. Mind you, I had to key my first assembler into my Motorolo 6800 by typing it in in hex. After that, I could use that version to assemble the next one.

Fond memories of recovering an HP2000 mainframe in 1975, using the front panel switches to enter about 50 bytes, just enough to initialize the paper tape reader which reads in the disk boot loader, which initializes the disk controller just enough to load the operating system from the disk drive.

A little bit late, but due to the fact that pin 13 has a on-board led it is basically pulled up.
Workarounds:

Remove led physically.
Remove the 330ohm resistor connected to led
OR both.

How does that stop the bootloader manipulating pin 13 and hence the unwanted activity of the relay ? The simplest solution is avoiding pins which have a special function at boot time unless you understand the consequences.

the relay is active low and the pin is switched by the bootloader so this answer is not applicable


text:
HX711 Soft WDT Reset
I am using the following code to check if the value is 0 e.g there is no weights placed and if so, it will ignore this value and do nothing with it. The code runs correctly but keeps outputting the following:

Soft WDT reset

stack>>>

ctx: cont sp: 3ffffd70 end: 3fffffc0 offset: 01b0 3fffff20:  00000050
  00000000 31310010 36323439   3fffff30:  00000000 00000000 00000010
  00000001   3fffff40:  3ffee408 00000000 00000000 40202927   3fffff50:
  4022dff2 a0000000 bf2cc404 3ffe84dc   3fffff60:  3ffee408 bf2cc404
  3ffee408 40202962   3fffff70:  3ffeeb9c 40202c00 3ffee408 40202996
  3fffff80:  3ffee448 bf2cc404 3ffee408 40202664   3fffff90:  3fffdad0
  fffe2d7e 3ffee448 3ffee4b0   3fffffa0:  3fffdad0 00000000 3ffee480
  40203848   3fffffb0:  feefeffe feefeffe 3ffe8514 40100a41
  <<

If I remove if(reading < 0.01){ the code runs fine. What could be causing this?
#include "HX711.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#define DOUT  D3
#define CLK  D2
const char* ssid = "Curtis";
const char* password = "password";

HX711 scale(DOUT, CLK);
float calibration_factor = -118470; //-7050 worked for my 440lb max scale setup
void joinwifi(){
    WiFi.begin(ssid, password);
  Serial.println();
  Serial.print("Connecting");
   while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("success!");
  Serial.print("IP Address is: ");
  Serial.println(WiFi.localIP());
}
void setup() {
  Serial.begin(9600);
  joinwifi();
  Serial.println("HX711 calibration sketch");
  Serial.println("Remove all weight from scale");
  Serial.println("After readings begin, place known weight on scale");
  Serial.println("Press + or a to increase calibration factor");
  Serial.println("Press - or z to decrease calibration factor");
  scale.set_scale();
  scale.tare(); //Reset the scale to 0
  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
}
void loop() {
  while (WiFi.status() == WL_CONNECTED)
  {
    scale.set_scale(calibration_factor); //Adjust to this calibration factor
    float reading = scale.get_units(1);
    if(reading < 0.01){
      Serial.print("no need");
       Serial.println();
    }
    else{
      Serial.print("Reading: ");
      Serial.print(reading);
      Serial.print(" lbs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
      Serial.print(" calibration_factor: ");
      Serial.print(calibration_factor);
      Serial.println();
      if(Serial.available())
      {
        char temp = Serial.read();
        if(temp == '+' || temp == 'a')
          calibration_factor += 10;
        else if(temp == '-' || temp == 'z')
          calibration_factor -= 10;
      }
    }
  }
  while (WiFi.status() != WL_CONNECTED)
  {
    joinwifi();
  }

}

Because your code is all running in a while inside your loop (which is redundant - loop() loops, hence its name), and you have no delays or yield() calls, you are not giving the watchdog the required kick that it needs to stay alive.
Either remove your whiles and turn them into ifs instead, or add yeild() calls inside your while loops.

@CurtisBoylan if it solves the issue then please accept Majenko's answer as the solution.


text:
A1-A5 pins not declared in this scope error
When I set my board to 'Generic ESP8266 module'  then only A0 pin of arduino is working while all other analog  pins are coming out of scope ,
 when I set the board to 'arduino /genuino uno' ,
 then "Error compiling for board Arduino/Genuino Uno." this error is coming how to set the board such that all analog pins with ESP8266 will work?

To my knowledge the ESP8266 only has 1 analog input pin, so the others being out of scope is completely correct, because they just don't exist on this board

and for what board do you want to compile and upload?

If you look at the ESP8266 pinout diagram (for example here), you will only find 1 analog input: A0. This is because the ESP8266 simply just has 1 analog input. The Arduino IDE states A1-A5 being out of scope, because on that board these inputs just don't exist. That is completely correct.
Also: When you try to compile code, that is meant for an ESP, for the Arduino Uno board, it will naturally fail, because it is just different hardware. The ESP basis code just cannot run on the Uno.
You will have to compile the code for the board, that you actually want to use AND you can only use codes/libraries, that are meant for your board. You cannot mix them in general. Only some function might be transferable (if so, it will not be easy) and WiFi is definitely not something to transfer to the Uno, which doesn't have the hardware for it.

thanks for your help, is there any way i can use two analog pins on arduino and use wifi and connect to internet as well

You can try to multiplex the one analog pin, by connecting only 1 analog signal at a time to the input (for example switched through a MOSFET by a GPIO pin). You then have to activate that input signal through the code, perform a measurment with the ADC, switch to the second input signal and perform a measurement there too. Depending on what you want to connect to the analog pin, it may also be possible to just power one of the sensors at a time.

Or you can instead use an ESP32, which seems to have 2 individual ADCs which many usable pins each.

use two analog pins on arduino you were just told the ESP8266 only has one


text:
Trying to print "occur = 1" in an if statement but it wont work
Cant seem to get this code to work with my arduino, and yes its all hooked up properally, even used leds to show that the button is being pressed, what am i doing wrong or dont know?
const int digitalInPin3 = 8;     //switch
int Occur = 0;
int Switch = 0;

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

void loop() {
int Switch = digitalRead(digitalInPin3);

if (Switch == 1){
  int Occur = 1;
}

else {
 int occur = 2;
}

   Serial.print("\t Switch =");
   Serial.print(Switch);
   Serial.print("\t occur =");
   Serial.println(Occur);

  delay(1);
}

You have 3 independent Occur variables; 1 global, 2 local. You also spell them differently!

Welcome to Arduino SE.  Be sure to take the tour and earn a badge at https://arduino.stacvkexchange.com/Tour

Remove the int from inside the if and else statement. The code would always show 0 because access of occur, which is assigned value 1 or 2 is limited to the if..else statement. So the global occur remains 0 always.
So change it to:
if (Switch == 1){
 Occur = 1;
}
else {
 Occur = 2;
}

This will work.

The capitalization of the second variable name is incorrect.

oh, yes. Haven't seen it.

The comments are right, as is the other answer.
Also, I see that both Switch and Occur are highlighted as if they are keywords.
I know for sure Switch is a reserved word.
Take all of these suggestions together.  Remove the int from inside the if.
I recommend you change the variable names entirely to something else.  And make them consistent.
Define them one time at the top then just modify them within the code.


text:
Arduino Uno wont power up when GND is plugged in Logic Converter
Good day.
I am trying to use an ESP8266 12e Wifi Module that requires 3.3V
I used a Logic Converter to reduce the 5v to 3.3v
My problem is when I plug the GND from the arduino to the GND on the Logic Converter, the Power On Led dies slowly on the arduino and no power at all.
When I plug the 5v only the power is back.

I have tried both the USB power from the laptop and a 9V 250mA power adapter but still the same result.
Any advice would really save me.

Is that soldering really as terrible as it looks?

yes. I really have no knowledge in soldering but i did my best to bind them :(

It looks like one huge blob of so solder shortcircuiting everything out.

I think you'll need an external power supply to make both of them works. ESPs need more current than arduinos.

I think you need to practice your soldering a little more. It's hard to make out, but I would say all that solder is just one huge short circuit linking the power and ground pins and risking melting your Arduino.

thank you for the enlightenment everyone. I recall that my arduino ticked and smoked a little when i plugged it using an external power source and immediately I unplugged it. It seems like my messy soldering is the culprit. I have planned to use an ESP8266 ESP-01 + adapter so i wont need to do some horrible soldering again...


text:
How to secure the communication between android app and door lock controller?
I have been working on a small project using android app over Bluetooth to control a servo motor (close or open lock). To authenticate the communication, I implement HMAC (with SHA256) on both the android app and the arduino controller.
When user press the button to unlock the door, it will generate a random code,  which will be seen as a message. Then HMAC is called to create a hash string with this message and the shared key. The final string sent to arduino would be  "randomcode+commmand+hashed-string"
Something like this:

 5uq0xboq82oih111e30774e4bf8302a04e71eb84c70ce2c130717304f52c67ce709203caea0ce5
(command and the random code are hidden in the string)

As the arduino received the message, it will break the string into three parts. The command, the random code and the hashed string. It will run HMAC with the shared key and the random code. Then compare that with the received hashed string. If matched, the perform the action (command).
This is my first project on implementing HMAC. I know this may be sort of subjective question but any comment on this implementation may helpful. Thanks.

How do you prevent replay attacks? Also, if someone can intercept the message; he could change the command part, and send it to the Arduino, and it will accept it. I'd hash the randomcode+command, not just the randomcode.

I am not an expert on this but I don't think replay attacks would work. HMAC deals with user authentication and validates data integrity. The command is just 1 or 0.  Adding it to the HMAC or not wouldn't make much difference, I think. The arduino controller will not execute any command unless the HMAC message is matched.

HMAC only does the authentication part. Since you don't hash the command, it doesn't do anything for data integrity. HMAC also doesn't solve the replay attack problem. Unless the Arduino stores all previous randomCodes, and rejects if they are re-used again. What would happen if you send a "door open" message, I intercept the message, and resend it after you've gone for work? The hash will match!

I could append the command to the random code, if it will make any difference. Someone may be able to guess what it may be. Intercepting the message is indeed possible as there is no secure communication channel, however my findings show that you would have to know the shared key in order to have a matched HMAC hash. So as long as the shared key is not compromised, the application will be safe and sound. No?

You still haven't solved to the replay-attack problem. The attacked doesn't need to "decyper" the message. It just needs to store it, and play it back later. This is the third time I brought this up. Why do you think your solutions isn't vulnerable to it?

it is wide-open to replay as described. you just need to generate the random salt on the ardunio (easier said than done), send it to the app, let the app create the derivation, send the arduino the result to dis-assemble and compare. that way, old keys won't work and the app itself cannot mint valid keys.

Thank you both for raising the alarm! I started with generating a random code from Arduino but walked away when finding that's not an easy task. Having your input,  I should go back to the drawing board.

Generating the random code from arduino controller as soon as the connection is being established and set a time limit such as 30 seconds, after that the code will no longer valid, should address the replay attack, at least for an application such as door lock control.


text:
HMAC SHA256 in Arduino use case?
I am doing a school project and wanted to implement HMAC on a arduino UNO like board. I have been testing the Cryptosuite, but none of the examples work for me. Such as this one: https://github.com/Cathedrow/Cryptosuite/blob/master/Sha/examples/hmacsha256test/hmacsha256test.pde
This one https://github.com/simonratner/Arduino-SHA-256, a trimmed-down version, which sounds good but there's none working example.
Can any one point me to the right direction? Thanks a lot!!

When you are asking a question, here or on a forum, then please tell what you did and what the result was. When you say that it is not working, then we have not enough information and your question might not get answered.
I have tested the first link that you gave to Cryptosuite. It is outdated and needs to be fixed.
I renamed "hmacsha256test.pde" to "hmacsha256test.ino".
The compiler errors and warnings are in the lower part of the Arduino IDE. Scroll up to find the first problem and fix that. Repeat it until it works.
The PROGMEM requires that the 'const' keyword is used. For example in "sha256.cpp":
const uint32_t sha256K[] PROGMEM = {

The 'write' function should return a size_t value.
In sha256.h:
// virtual void write(uint8_t);
virtual size_t write(uint8_t);

In sha256.cpp:
size_t Sha256Class::write(uint8_t data) {
  ++byteCount;
  addUncounted(data);
  return 1;
}

Then it compiles and runs on a Arduino Uno, although there is a warning for low memory because 75% of the sram is used.
The second link is a changed version of the same Cryptosuite. It should be able to use the examples of the Cryptosuite, but it does not.
I can make that work as well.
Using the same example of the Cryptosuite "hmacsha256test.pde" (I renamed it to "hmacsha256test.ino"), create a object 'sha' after including the "sha256.h":
#include "sha256.h"
Sha256 sha;

In the example, replace all "Sha256" function calls with "sha" function calls:
sha.initHmac(hmacKey1,20);
sha.print("Hi There");

Then it works as well.

Thank you very much!! You are a great teacher! I have Arduino IDE 1.8.9 downloaded and installed. And added a SHA folder inside "C:\Program Files (x86)\Arduino\libraries" to install the libraries (sha256.cpp and sha256.h) adopted from the second link and use the example (hmacsha256test.pde) from the first link, and made changes as you suggested. It works well!! Although I am getting "Low memory available, stability problems may occur" due to the sketch is taking up 22% of the storage space. But that is fine for a test of the HMAC for arduino. Thanks again! Merci! Gracias! Vielen Dank! 谢谢!

I have used the https://github.com/Cathedrow/Cryptosuite/ on ESP8266. For that in addition to the changes desribed by Jot it is enough to remove
#include <avr/io.h>
#include <avr/pgmspace.h>

from the header files. Then it is working fine.


text:
How to read this hmackey for arduino?
I understand the HMAC with SHA256 example provides a set of keys:
(https://github.com/Cathedrow/Cryptosuite/blob/master/Sha/examples/hmacsha256test/hmacsha256test.pde)
#include "sha256.h"
uint8_t hmacKey1[]={
  0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,
0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b
};
uint8_t hmacKey2[]={
  0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,
0x0e,0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19
};
...

I did a bit research and have a sense that these keys are in hexadecimal form with 0x added as prefix. If I like to use my own key, like a string, abece123*, do I just convert the key string to hex?
I tried to use this site below to convert above hmacKey2 to see what the key may look like. But the result is not recognizable. Here's what I did: copy and past
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,
0x0f,0x10,0x11,0x12,0x13,0x14, 0x15,0x16,0x17,0x18,0x19

to the site below to convert to string.
https://codebeautify.org/hex-string-converter
I am very new to this field. Please help me understand how these key works and and the steps needed to replace one of the preset hmac keys with my own key string (e.g. abece123*). Thanks.

Those are examples for keys. You need one key and you can choose any text with any length.
Did you see this line in the example:
sha.initHmac((uint8_t*)"Jefe",4);

It uses the key "Jefe" with a length of 4.
You can use your own key, but you also need the length.
char myKey[] = "abece123*";
int length = strlen(myKey);
sha.initHmac((uint8_t*)myKey, length);

Yes, I also found this later. Thanks for your attention.

Now that we know your key, don't use "abece123*" anymore. You can for example use a full sentence, something that you can remember and is long (for example more than than 20 bytes).

Yep, that will be my next thing to consider. And there's some discussion here: https://security.stackexchange.com/questions/95972/what-are-requirements-for-hmac-secret-key/96176 . I will use a password generator to do that. Although I couldn't tell how secure it is as there's no tool to test if it can be hacked.

Sometimes I make up a fairy tale story that is completely different from other passwords. For example: "once upon a time there was a blue moon that ate cookies", with or without capitals and with or without spaces.


text:
For Arduino Uno it is possible to use the digital pins with PWM to read analog data, is this also possible with the Wemos D1 Mini?
I want to read out data from a load cell, for this I seem to need 2 analog input pins, the Wemos doesn't have this. In the Arduino I was also able to use the digital pint with PWM, there are also Wemos pins who have that. Is it possible to use them to read the data from the load cell?

You need to clarify what are you talking about. How did you manage to use digital pins in Arduino Uno to read analog data? And what does PWM have to do with it?

You can use a capacitor and resistor to build a simple circuit to turn a voltage into a time duration, then precisely measure the timing to get a voltage. This isn't as fast as a direct read, but it can be more precise in some cases, and the sampling might be fast enough for your needs. The cost is great compared with external or home-brew ADCs.  I once used this method to build an ohmmeter with an ESP-01, which had a much greater range than a naive voltage divider would have provided.
You feed your voltage through a resistor into a capacitor, and have a digital input pin watching the resistor-cap voltage. You'll need to be generous with the timing because you want the cap to fully drain, and you can't tell from the MCU when that's completed, but a few preliminary DMM measurements will give you that info.
To measure voltage, you switch the GPIO from OUTPUT/low to to INPUT-PULLUP and wait for it to go HIGH. By measuring the time it takes before the pin goes high, you can calculate the voltage expected to fill the cap to the trigger threshold in that amount of time. You will need to do some manual measurements to calibrate it up-front, as different pins have different pull-up values and slightly different schmitt trigger voltage thresholds. Once setup, it can be repeatable to about +/- 5%, maybe more with slower sampling.
ascii schematic:
(vSensor) --- [R1] --- (GPIO) --- [C1]  --- GND

There is one way you could measure analogue voltages using a PWM output: Use it as a DAC to build your own Successive Approximation ADC:

The PWM is filtered through a low-pass filter to create an analogue voltage
That is compared to an incoming voltage using a comparator
The output of the comparator is recorded for different reference voltages using a "divide and conquer" method.

You can read more about how Successive Approximation works here.
However, doing that would be overly complex and needlessly expensive. It is far better to just add an ADC chip using I2C or SPI. It's cheaper, easier, and the results will be far superior.
But as a learning exercise to discover how ADCs work, it could be kind of fun.

PWM is quasi-analog output, and they have no symmetric analog read function.
The ESP8266 that is the heart of the Wemos D1 Mini has only 1 analog input.
If you need to read 2 analog signals, you can use an analog switch/multiplexer to read one value, and then the other value in quick succession. Or you can purchase an external ADC with multiple inputs -- these often communicate with a host by SPI or I2C connection, which the Wemos supports.


text:
can i configure 2 (XBee series 2) modules using one explorer
Can I configure 2 XBEE modules one then another using 1 XBEE Explorer, or I MUST do this configuration operation for them at the same time and I need 2 Explorer modules?

You only need one.
In order to communicate in Point To Point, you must configure each xbee to belong to the same NetworkID (PAN ID). XBees can only communicate with each other if they have the same network ID. Configure one, switch the xbee then configure the other (see here)
There are more advanced configurations that you can use (check this tutorial for extended information).

thank you, it's the same if i'll do star or mesh right?.                  I have another question can I send information from 2 sources to one destination .. or xbee is only for broadcasting?

I've never tested it, but yes it is possible according to manual in multicast(see page 74 example 4). Just remember that star must have only one coordinator. take a look here also: http://jeffbelback.me/projects/2014/09/17/XbeeDeviceTypes/

thanks again.  I have another new question, I was test the communicating of the 2 XBEEs series 2, and I connected one to the computer and the other to the arduino... but while running a code to send hello world msg from arduino, it doesn't appear in the XBee XTC console.. what should I do?

You don't see anything? Have you set the same PAN ID right? Correct baudrates also?


text:
Arduino Uno to Processing, using Serial
So I have 7 different sensor I’d like to send to Processing, then use each of their values as variables inside different webcam filters.
I’m going off of this tutorial which has been helpful, but it doesn’t give linear steps – more like different techniques depending on what you’re trying to use it for.
In that tutorial, it shows two ways to initialize connection between Serial and Arduino – the Punctuation method and the Call-and-response method. I used the Punctuation method.
To sum up the Punctuation method, you put the sensor values into one string, separated with commas. Once the values are sent over, you split the string and put all of the values into an array. Once in an array, you can individually take out each of the values and turn them into variables that are usable in the draw loop.
My Processing sketch runs perfectly fine sometimes. Otherwise it will give either this error :
  Error, disabling serialEvent() for /dev/cu.usbmodem1421
  null

Or this one :

Does anyone see anything fishy with the syntax or structure I’m setting up?
(I took out all filter functions except the temp -> blur to make debugging easier.)
// get the serial lib :
import processing.serial.*;

// give port a variable :
Serial port;

// get the webcam lib :
import processing.video.*;

// give webcam a variable :
Capture webcam;

// sensors
int cap1, cap2, piezo, temp, axisX, axisY, axisZ;

void setup() {
  size(480, 360, P2D);
  smooth();

  webcam = new Capture(this, width, height, 24);
  webcam.start();

  String portName = "/dev/cu.usbmodem1421";
  port = new Serial(this, portName, 9600);
  //port.bufferUntil('\n');
}

void captureEvent(Capture webcam) {
  webcam.read();
}

void serialEvent(Serial port) {

  String reading = port.readStringUntil('\n');
  if (reading != null) {
    reading = trim(reading);

    int values[] = int(split(reading, ','));

    for (int valNum = 0; valNum < values.length; valNum++) {
      print(values[valNum] + "|");
    }
    println();

    if (values.length > 1) {
      cap1 = values[0];
      cap2 = values[1];
      piezo = values[2];
      temp = values[3];
      axisX = values[4];
      axisY = values[5];
      axisZ = values[6];
    }
  }
}

void draw() {

  // temp
  float t;
  if (temp >= 100) { //when analog pin unplugged
    t = 6;
  } else {
    t = 0;
  }

  image(webcam, 0, 0);
  filter(BLUR, t);
}

//if down key pressed, saveImage();
void saveImage()
{
  saveFrame("images/captured-####.jpg");
}

void keyPressed() {
  if (key == CODED) {
    if (keyCode == DOWN) {
      saveImage();
    }
  }
}

I’m thinking it’s an issue with memory, or maybe the way I’m sending/receiving the data is shoddy.
Apparently one of the disadvantages to using Punctuation rather than Call-and-response is that it can slow down the program if it contains a lot of graphic work… but why would it work in perfect time sometimes and then not work at all?
Any insight would be amazing!!

What did the print in SerialEvent print out just before the error?  Also, why if (values.length > 1)?  Seems like if (values.length > 6) would work better

The baudrate is really low, try a higher one (115200) maybe it is just a timing problem (pipe full/unready). Remember changing both - arduino and your program.


text:
Arduino with Bluetooth
HI I am a newbie and need some suggestions
Is there a possibility to do this?? I am trying to send MIDI data through a button using Arduino and bluetooth module HM10. Can someone help me write the loop part or am going the right way.
#include <MIDI.h>
#include <SoftwareSerial.h>
SoftwareSerial mySerial (2, 3);
char c = ' ';
int pushButton7 = 7;
int buttonState7 = 0;
int note7 = 0;
void setup() {
  MIDI.begin(4);
  // 115200 hairless MIDI
  Serial.begin(9600);
  mySerial.begin(9600);
  pinMode(pushButton7, INPUT);
}

  void loop() {

   int buttonState7 = digitalRead(pushButton7);

 // Button 7

  // when button pressed:
  if (buttonState7 == HIGH) {
    // if note not playing
    if (note7 == 0) {
      // play note (note number, velocity, channel)
      // more info: http://arduinomidilib.sourceforge.net/a00001.html
      // MIDI notes chart http://www.phys.unsw.edu.au/jw/notes.html
      // 55 = G3, 127 = trigger note with max volume
      MIDI.sendNoteOn(55,127,1);
      // note is playing
      note7 = 1;
    }
  // when button released
  } else {
    // if note playing
    if (note7 == 1) {
      // if playing - stop
      MIDI.sendNoteOff(55,0,1);
    }
    // if button released note is off
    note7 = 0;
  }

  delay(1);

  }


text:
Change the mac address on an HC-05
So I tried to save a little money and bought (5) HC-05 bluetooth modules off of our good buddy eBay.
When the modules arrived, as I was testing and setting up for my project (2 nano's connected via an HC-05 each to a Galaxy S4), I noticed all 5 modules shipped with the same MAC address.
I have been looking everywhere I can think of to modify the MAC address of the modules, but have had no luck.  Well, that isn't 100% accurate.  I found bdaddr on linux, but I do not have a linux machine.  Just Windows for me right now.
So, my issue is trying to find a way to set the HC-05 modules with different MAC addresses so I can have (2) connect at the same time to my S4.  I have been able to change the name of the units via the AT commands, just not the MAC address.
Thank you in advance for your help.

i do not have any experience with the HC-05 module, but it looks like AT+BIND=<Param> sets the MAC ..... page 8 of this https://exploreembedded.com/wiki/images/a/a5/HC_05_Core_Datasheet.pdf

Any luck with this topic I have a similar problem on my HC-06 I have seen a set of instructions to update the firmware of the HC-05 and HC-06 on line and wonder if the MAC address can be changed during this process.