body:
So I want to create an application where I can send data with a SIM-Module, and when it's not needed it should fall into a "standby-mode" because it's battery powered. But I always get this exact output, and I have no clue why:

>     wakeup condition fulfilled
>     Tes

When it wants to print out "Testing ..." it always stops after three letters.

Here's my code:

    /*
     *  PINOUT:
     *
     *  UNO >> SIM800L
     *  RX (8) >> TX
     *  TX (9) >> RX
     *
    */

    #include <BareBoneSim800.h>

    BareBoneSim800 sim800("hologram"); //APN of the carrier

    void sendData(char *url)
    {
      sim800.enterSleepMode(false);
      Serial.println("Testing GSM module For GPRS Connectivity");
      delay(8000); // this delay is necessary, it helps the device to be ready and connect to a network

      Serial.println("Should be ready by now");
      bool deviceAttached = sim800.isAttached();
      if (deviceAttached)
        Serial.println("Device is Attached");
      else
        Serial.println("Not Attached");

      // Connecting the the GPRS APN Network
      Serial.println(" Connecting to APN");
      bool netConnect = sim800.gprsConnect();
      if (netConnect)
        Serial.println("Connected to Network");
      else
        Serial.println("An Error Occured");

      if (netConnect)
      {
        Serial.println("Making HTTP Get Request");
        String result = sim800.sendHTTPData(url);
        Serial.println("Received Info: ");
        Serial.println(result);

        Serial.println("Current time utc+0: ");
        Serial.println(sim800.getTime());
      }

      sim800.closeHTTP(); // disconnect from server
      sim800.gprsDisconnect();
      sim800.enterSleepMode(true);
    }

    void wakingUp()
    {
      //hardware interrupt measurement goes here
    }

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

      while (!Serial)
        ;

      //Save Power by writing all Digital IO LOW - note that pins just need to be tied one way or another, do not damage devices!
      for (int i = 0; i < 20; i++)
      {
        if (i != 8 && i != 9 && i != 2)
        {
          // pin 2 is for waking the arduino up from deep sleep

          //pin 8 and 9 are used to connect with the sim module,
          //these pins must be exluded from power saving
          pinMode(i, OUTPUT);
        }
      }

      attachInterrupt(0, wakingUp, FALLING); //interrupt for waking up

      /*
          various flags for turning stuff down when not needed
    based on this very good tutorial https://www.youtube.com/watch?v=urLSDi7SD8M

      */
      //SETUP WATCHDOG TIMER
      WDTCSR = (24);      //change enable and WDE - also resets
      WDTCSR = (33);      //prescalers only - get rid of the WDE and WDCE bit
      WDTCSR |= (1 << 6); //enable interrupt mode

      //Disable ADC - don't forget to flip back after waking up if using ADC in your application ADCSRA |= (1 << 7);
      //ADCSRA &= ~(1 << 7);

      //ENABLE SLEEP - this enables the sleep mode
      SMCR |= (1 << 2); //power down mode
      SMCR |= 1;        //enable sleep

      //BOD DISABLE - this must be called right before the __asm__ sleep instruction
      //MCUCR |= (3 << 5);                      //set both BODS and BODSE at the same time
      //MCUCR = (MCUCR & ~(1 << 5)) | (1 << 6); //then set the BODS bit and clear the BODSE bit at the same time
      __asm__ __volatile__("sleep"); //in line assembler to go to sleep
    }

    void loop()
    {
      //do nothing, use ISR instead
    }

    char targetURL[] = "http://www.example.com/restAPI/";

    ISR(WDT_vect)
    {
      //DON'T FORGET THIS!  Needed for the watch dog timer.  This is called after a watch dog timer timeout - this is the interrupt function called after waking up
      //todo, turn on adc conversion again

      int halfHourCounter = 0; //30 minutes => 225 8sec intervals

      bool wakeUpCondition = (halfHourCounter % 225 == 0);

      if (wakeUpCondition)
      {
        Serial.println("wakeup condition fulfilled");
        //reset counter
        halfHourCounter = 0;

        //ADCSRA |= (1 << 7); // turn analog digital conversion back on

        //... measure data and send it away :)
        sendData(targetURL);

        //ADCSRA &= ~(1 << 7); // disable ADC again
      }
      else
      {
        Serial.println("wakeup condition not fulfilled");
      }

      halfHourCounter += 1;

    } // watchdog interrupt

I'm using an Arduino Uno in combination with a SIM800L evaluation board. If I call the sendData()-function without any standby-flags enabled everything works fine. Vice versa if I call just a print function for debugging with all the standby flags enabled

title: Low power error with serial connection

Answers: 1

body:
It seems, that the Sim800 module is drawing too much current, when you start it again. The voltage drops and the Arduino/Sim800 stops working.

[This datasheet][1] of the Sim800 states, that it can draw up to 2A when doing a sending burst. An USB port on a computer can provide up to 500mA and you can draw between 200mA to 1A from the Arduino's 5V pin (depending on the version, that you use: Older Unos can provide 200mA, Uno r3 should be able to provide 1A). If you draw too much current through the Arduino from USB, you will fry the diode for voltage source seletion. Also you can fry the electronics of the USB port, if you draw too much current from it (though normally the port should go into shutdown, if you do that, and work again, if you restart the computer).

You have to provide the Sim800 module with enough power and not through the Arduino. You should choose a fitting battery for this. If you don't want to involve a battery at this point, since you are still testing, you can use an USB phone charger to provide enough current.

  [1]: https://img.filipeflop.com/files/download/Datasheet_SIM800L.pdf


body:
I am building a simple telnet style interface for experimental settings on my project. I am getting all the serial output sent to serial (and USB to PC). The code works fine, but if I try to read from Serial or check 'Serial.available()' I will get:

> Fatal exception 9(LoadStoreAlignmentCause)

Definition:
```bool pridaj_cely(uint8_t source_from=0, uint8_t line_LCD=0);```

The code:

    bool Vstup::pridaj_cely(uint8_t source_from, uint8_t line_LCD) {
      uint8_t i = 0;
      Serial.println(F("one piece input read"));
      switch (origin) {
        case 0: { //Serial
            int16_t znak = -1;
            while (Serial.available() < 0) {
              Serial.print(F("."));
              delay(100);
            }
            Serial.print(F("Somothing is comming"));
            while (Serial.available() > 0) {
              celok[i] = Serial.read();
              if (i < 12)  i++;
            }
          }
          break;
      }
      return 1;
    }

Code of Priojenie:

    bool pripojenie(bool force_it = 0) {
      Serial.println(("Beginning connection routine"));
      kolo = millis();
      while (!WiFi.isConnected()) {
        int8_t sieti = WiFi.scanComplete();
        Serial.printf("Search result %X", sieti);
        switch (sieti) {
          case -2:
            Serial.println(("\tSearch begins"));
            WiFi.scanNetworks(1);
            delay(50);
            break;
          case -1:
            Serial.print(("."));
            delay(300);
            break;
          default: //This is the relevant case
            Vstup odpoved;
            Serial.ciara;
            Serial.ciara;
            Serial.printf(("Found %X networks"), sieti);
            Serial.ciara;
            Serial.println();
            for (uint8_t i = 0; i < sieti; i++) {
              Serial.printf("%d: %s, Kanál:%d (�Bm) %s\n", i, WiFi.SSID(i).c_str(), WiFi.channel(i), WiFi.RSSI(i), WiFi.encryptionType(i) == ENC_TYPE_NONE ? "Otvorena" : "");
            }
            Serial.ciara;
            Serial.println(("\nChose network number:"));
            odpoved.pridaj_cely(0);
            // -------------------Never gets past this one-------
            if ((odpoved.Nacislo10() >= 0) && (odpoved.Nacislo10() < sieti)) {
              Serial.printf(("Zadaj heslo pre %s\n"), WiFi.SSID(odpoved.Nacislo10()).c_str());
              String heslo = Serial.readString();
              Serial.print(F("Dostal som "));
              for (uint8_t i = 0; i > heslo.length(); i++) Serial.print(heslo[i]);
              Serial.println();
              Serial.printf(("Vybral som možnosť číslo %d a sieť: "), odpoved.Nacislo10(), WiFi.SSID(odpoved.Nacislo10()).c_str());
              //WiFi.begin(WiFi.SSID(odpoved.Nacislo10()).c_str(), heslo);
            } else Serial.printf(("Nesprávny výber %d"), odpoved.Nacislo10());
        }
      }
    }

I have commented all the functions that use pins. The source compiles without any problem.

I am adding the result of exception decoder as it did not help me solve it.

```

Decoding stack results
0x40202a8d: __yield() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 105
0x40202355: Stream::timedRead() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Stream.cpp line 37
0x40202392: Stream::readString() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Stream.cpp line 240
0x402013b6: pripojenie(bool) at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 315
0x40203411: malloc(size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/heap.cpp line 95
0x40204548: umm_malloc(size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/umm_malloc/umm_malloc.cpp line 1685
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x4020141c: pripojenie_samo(unsigned char) at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 327
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x40204bb1: std::_Function_handler ::_M_invoke(std::_Any_data const&, int) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 2073
0x4020197c: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 2300
0x4020e5b8: sys_check_timeouts at core/timeouts.c line 368
0x40202957: loop_task(ETSEvent*) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 133
0x4020ac9a: __ssputs_r at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/nano-vfprintf.c line 233
0x40206938: _printf_i at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/nano-vfprintf_i.c line 194
0x4020ac9a: __ssputs_r at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/nano-vfprintf.c line 233
0x402034b4: malloc_loc(size_t, char const*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/heap.cpp line 126
0x40204548: umm_malloc(size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/umm_malloc/umm_malloc.cpp line 1685
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x40204738: umm_realloc(void*, size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/umm_malloc/umm_malloc.cpp line 1745
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x4020299c: esp_yield() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 91
0x40202f53: delay(unsigned long) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_wiring.cpp line 54
0x40201a89: ESP8266WiFiScanClass::scanNetworks(bool, bool, unsigned char, unsigned char*) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 98
0x40203942: uart_write(uart_t*, char const*, size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/uart.cpp line 498
0x4020299c: esp_yield() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 91
0x40202f53: delay(unsigned long) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_wiring.cpp line 54
0x402015fd: loop() at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 460
0x40201410: pripojenie_samo(unsigned char) at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 325
0x40204bb8: std::_Function_base::_Base_manager ::_M_manager(std::_Any_data&, std::_Any_data const&, std::_Manager_operation) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 1934
0x40204ba4: std::_Function_handler ::_M_invoke(std::_Any_data const&, int) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 2069
0x40201e50: HardwareSerial::setDebugOutput(bool) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.cpp line 79
0x40202a4c: loop_wrapper() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 125

```
line 325 is a wrapper function because async scan can only call void function of specific type and calls pripojenie_samo(uint8_t pointless)

Serial Output: (after translation to English)
```
Beginning connection routine
Search result 3
-----------------------------------------------------
-----------------------------------------------------
Found  3 networks

-----------------------------------------------------

0: VM5070527, Kanál:11 (-55dBm)
1: Virgin Media, Kanál:11 (-74dBm)
2: VM5076233, Kanál:11 (-85dBm)
-----------------------------------------------------

Chose network number:
Instance cleared
one piece input read

Panic /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp:103 __yield

>>>stack>>>
```
```

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

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld

SDK:2.2.1(cfd48f3)/Core:2.5.2=20502000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020

```

title: NodeMCU V3 Serial input results in Fatal exception 9 (LoadStoreAlignmentCause)

Answers: 1

body:
I have figured it out
There seem to be understandable limitations if what kind of function can be run as a result of asynchronous scanning (which doesn't seem to interrupt running of a loop function)
So if I have used ```delay(x)``` or a while loop until there is input on serial, MCU resets after allotted time runs out.
I have re-written code to start function from loop when scan is complete, and it all runs fine now.
I guess Arduino isn't right language for parallel programing


body:
I am testing esp8266's deep sleep mode. And i have some questions about that.

1- I want to wakeup esp via timer. I did it. I implemented GPIO16-RST connection and this version done.

2- I want to ake up esp with external button too. It means, I will use timer and button to wake up esp8266 same time.

Is it possible and how can i connect  button to RST pin that while GPIO16 has already connected to RST?

title: ESP8266 Deep Sleep Wake Up

Answers: 1

body:
The reset pin of the ESP8266 has internal pull-up. Connecting the pin to ground activates the reset of the ESP.

To create a reset button, wire a momentary push button between reset pin and ground. Pushing the button will connect reset to ground, causing a reset of the esp8266.

The io 16 pin is connected internally to RTC, which in deep sleep counts down the time and then sets the pin LOW. If io 16 is wired to reset pin, this resets the ESP8266 to end the deep sleep.

The only way to end the deep sleep of the esp8266 is a reset. There is no conflict between RTC io 16 and a reset button, both wired to reset pin. Both can activate the reset to end the deep sleep.


body:
I have an Arduino wired to ws2812b with 10 100uF capacitors and 2 1000ohm resistors(picture). When I'm plugging 5v power supply everything is working when I plug 9v battery everything is fine but when I'm plugging 12v power supply in one moment leds stops.(NeoPixel standardtest example. How I can power the ws2812b by 12v[![enter image description here][1]][1]

[![][2]][2]

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/0WsPt.jpg
  [2]: https://i.stack.imgur.com/Itas1.jpg
  [3]: https://i.stack.imgur.com/vwRgI.jpg

title: Problem with power supply ws2812b Arduino 5v vs 12v

Answers: 2

body:
The regulator on an Arduino is likely analog.  On [this Arduino Uno][1] the regulator is an analog [NCP1117ST50T3G][2] as seen in [this schematic][3].  On page 2 of the NCP1117ST50T3G spcification it is stated:

> Internal thermal shutdown protection limits the die temperature to
> approximately 175°C. Proper heatsinking is required to prevent
> activation.

Being an analog power regulator, the difference between the input voltage and the regulated output voltage eventually turns into heat.  This may explain why a 9 volt source may work (drop is only 9V - 5V = 4V) while a 12 volt source may not work (drop is 12V - 5V = 7V).

Consider using a 5 volt power source avoiding the Arduino analog power regulator.  Or, if the only source is 12 volts (for example an automobile), consider using an external switching or buck power supply to convert the 12 volt down to 5 volts and again avoiding the Arduino analog power regulator.  Lastly, it should be possible to still power the Arduino with 12 volts and use its internal power regulator to only power the Arduino. Then independently power the LED strip using an external power regulator.  This last option will likely have the benefit of eliminating the capacitor bank seen in the question and associated components.

  [1]: https://store.arduino.cc/usa/arduino-uno-rev3
  [2]: https://www.onsemi.com/pub/Collateral/NCP1117-D.PDF
  [3]: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

body:
See if arduino works with strips disconnected
Assuming that you are connecting your 12V to the breadboard
Do not try to use Arduinos voltage regulator to supply something this massive as LED strip (if you did, then arduinos voltage regulator would be burned by now)

If arduino works with strips disconnected
If it does:
check the voltage of the strip if its not written check if each LED has its own resistor. If it doesn't you may see Two or three LED per resistor in series That usually means 12V
This would mean that LEDS would have been dim when on 5V
Then you need to drop the voltage(difficult, I am not sure if even LM350A is strong enough)you can try putting 100 ohm resistor before and across the LED strip this will not be sustainable, but might light the LEDS bit for a bit.

if it works with strips disconnected:
If it doesn't:
Does arduino start?
If it does. see first half of this message
If it doesn't: Does arduino start when connected via USB? (Disconnect from breadboard for this test) if it doesn't board is damaged
if it does you have burned your voltage regulator.
I am not sure what are those capacitors there for. LED's arent very picky about the supply and standard CE marked (legaly) 12DC supply would be suitable for both arduino and the strip supply out of the box


body:
    #include <LiquidCrystal.h>
    LiquidCrystal 1cd(12, 11, 5, 4, 3, 2);
    const int switchPin = 6;
    int switchState = 0;
    int prevSwitchState = 0;
    int reply;
    void setup() {
     1cd.begin(16, 2);
     pinMode(switchPin, INPUT);
     1cd.print("Interroga");
     1cd.setCursor(0, 1);
     1cd.print("la sfera!");
     // put your setup code here, to run once:

    }

    void loop() {
      switchState = digitalRead(switchPin);
      if (switchState != prevSwitchState){
        if (switchState == LOW){
          reply = random(8);
          1cd.clear();
          1cd.setCursor(0, 0);
          1cd.print("La sfera dice");
          1cd.setCursor(0, 1);
          switch(reply){
            case 0:
            1cd.print("si");
            break;
            case 1:
            1cd.print("probabilmente");
            break;
            case 2:
            1cd.print("certo");
            break;
            case 3:
            1cd.print("bene");
            break;
            case 4:
            1cd.print("forse");
            break;
            case 5:
            1cd.print("chiedi ancora");
            break;
            case 6:
            1cd.print("improbabile");
            break;
            case 7:
            1cd.print("no");
            break;// put your main code here, to run repeatedly:
          }
        }
      }
     prevSwitchState = switchState;
    }

title: Why am I receiving this error: “expected unqualified-id before numeric constant”?

Answers: 1

body:
You're using an invalid variable name (1cd starts with the number 1).

 - Variables can consist of both uppercase (A-Z) and lowercase(a-z)
   letters.
 - Variables can contain numbers 0 to 9, but **cannot start with a number**.
 - Variables may not have the same names as Arduino language keywords,
   e.g. you cannot have a variable named float.
 - If you try and save a sketch with a space in the file name, the IDE will change the space to an underscore.


body:
**Why won't my motors work?**

My setup is as followed:

 - arduino mega 2560 -> L296N motor controller -> Gikfun 3-6v dc motors.

To power the motors the setup is as followed:

- arduino mega 2560 5v -> L296N motor controller.
- 9v battery -> LM2596 buck converter(7-8v) -> L296N motor controller.

I have 2 issues.

- Issue 1: that no matter the code, the motors seem to only want to run at maximum speed. The code can be the simple example code or my code **see bottom**.

- Issue 2: When given a code that changes the speed, it only works for one motor and the other motor will not run regardless if the first motor is hooked up or not, it will not work with the example code provided nor will it work in my code **see bottom**.

Note that this is not a simple wiring fix. Either the code is wrong, my hardware setup is wrong, or my hardware may not be functioning properly. **Thank you for taking the time to review.**

```
// ex code:
int a = 2;
int b = 3;
int c = 22;
int d = 23;
int e = 24;
int f = 25;

void setup(){
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(e, OUTPUT);
  pinMode(f, OUTPUT);

void loop() {
  digitalWrite(c, HIGH);
  digitalWrite(d, LOW);
  digitalWrite(e, HIGH);
  digitalWrite(f, LOW);
  analogWrite(a, 0);
  analogWrite(b, 0);
```

```
// ex code:
for (int i = 0; i > 150; i++){
  analogWrite(a, i);
  analogWrite(b, i);
  delay(1000);
}

for (int i = 150; i <= 0; --i){
  analogWrite(a, i);
  analogWrite(b, i);
  delay(1000);
}
```

```
/* my code. Note that the timed function is not finished.
* I also x'd out 4 motors for easy debugging purposes.
*/
// Motor 1
int a = 2;
int a1 = 22;
int a2 = 23;
// Motor 2
int b = 3;
int b1 = 24;
int b2 = 25;
// Motor 3
int c = 4;
int c1 = 26;
int c2 = 27;
// Motor 4
int d = 5;
int d1 = 28;
int d2 = 29;
// Motor 5
int e = 6;
int e1 = 30;
int e2 = 31;
// Motor 6
int f = 7;
int f1 = 32;
int f2 = 33;
// Motor halt
unsigned int i;
int x;
int x1;
int x2;
void setup(){
  Serial.begin(9600);
  pinMode(a, OUTPUT);
  pinMode(a1, OUTPUT);
  pinMode(a2, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(b1, OUTPUT);
  pinMode(b2, OUTPUT);
  pinMode(x, OUTPUT);
  pinMode(x1, OUTPUT);
  pinMode(x2, OUTPUT);
  pinMode(x, OUTPUT);
  pinMode(x1, OUTPUT);
  pinMode(x2, OUTPUT);
  pinMode(x, OUTPUT);
  pinMode(x1, OUTPUT);
  pinMode(x2, OUTPUT);
  pinMode(x, OUTPUT);
  pinMode(x1, OUTPUT);
  pinMode(x2, OUTPUT);
}
void motor1(){
  digitalWrite(a1, HIGH);
  digitalWrite(a2, LOW);
  analogWrite(a, 0);
  if (a = 1){
    Serial.println(" MotorA not working");
  }
  delay(1000);
  digitalWrite(a1, LOW);
  digitalWrite(a2, LOW);
  delay(250);
  digitalWrite(a1, LOW);
  digitalWrite(a2, HIGH);
  analogWrite(a, 0);
  if (a = 1){
    Serial.println(" MotorAr not working");
  }
  delay(1000);
  digitalWrite(a1, LOW);
  digitalWrite(a2, LOW);
  delay(250);
}
void motor2(){
  digitalWrite(b1, HIGH);
  digitalWrite(b2, LOW);
  analogWrite(b, 0);
  if (b = 1){
    Serial.println(" MotorB not working");
  }
  delay(1000);
  digitalWrite(b1, LOW);
  digitalWrite(b2, LOW);
  delay(250);
  digitalWrite(b1, LOW);
  digitalWrite(b2, HIGH);
  analogWrite(b, 0);
  if (b = 1){
    Serial.println(" MotorBr not working");
  }
  delay(1000);
  digitalWrite(b1, LOW);
  digitalWrite(b2, LOW);
  delay(250);

}
void motor3(){
  digitalWrite(x1, HIGH);
  digitalWrite(x2, LOW);
  analogWrite(x, 0);
  if (c = 1){
    Serial.println(" MotorC not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);
  digitalWrite(x1, LOW);
  digitalWrite(x2, HIGH);
  analogWrite(x, 0);
  if (c = 1){
    Serial.println(" MotorCr not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);

}
void motor4(){
  digitalWrite(x1, HIGH);
  digitalWrite(x2, LOW);
  analogWrite(x, 0);
  if (d = 1){
    Serial.println(" MotorD not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);
  digitalWrite(x1, LOW);
  digitalWrite(x2, HIGH);
  analogWrite(x, 0);
  if (d = 1){
    Serial.println(" MotorDr not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);

}
void motor5(){
  digitalWrite(x1, HIGH);
  digitalWrite(x2, LOW);
  analogWrite(x, 0);
  if (e = 1){
    Serial.println(" MotorE not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);
  digitalWrite(x1, LOW);
  digitalWrite(x2, HIGH);
  analogWrite(x, 0);
  if (e = 1){
    Serial.println(" MotorEr not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);

}
void motor6(){
  digitalWrite(x1, HIGH);
  digitalWrite(x2, LOW);
  analogWrite(x, 0);
  if (f = 1){
    Serial.println(" MotorF not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);
  digitalWrite(x1, LOW);
  digitalWrite(x2, HIGH);
  analogWrite(x, 0);
  if (f = 1){
    Serial.println(" MotorFr not working");
  }
  delay(1000);
  digitalWrite(x1, LOW);
  digitalWrite(x2, LOW);
  delay(250);

}
void timed(){
  analogWrite(a, i);
  digitalWrite(a1, HIGH);
  digitalWrite(a2, LOW);
  analogWrite(b, i);
  digitalWrite(b1, HIGH);
  digitalWrite(b2, LOW);
  delay(2000);
  digitalWrite(a1, LOW);
  digitalWrite(a2, LOW);
  digitalWrite(b1, LOW);
  digitalWrite(b2, LOW);
  analogWrite(b, i);
  digitalWrite(b1, LOW);
  digitalWrite(b2, HIGH);
  analogWrite(a, i);
  digitalWrite(a1, LOW);
  digitalWrite(a2, HIGH);
  delay(2000);
  digitalWrite(a1, LOW);
  digitalWrite(a2, LOW);
  digitalWrite(b1, LOW);
  digitalWrite(b2, LOW);
}
void loop(){
  motor1();
  motor2();
  motor3();
  motor4();
  motor5();
  motor6();
  if (i = 0){
    i++;
  }
  if (i >=100){
    --i;
  }
  timed();

}
```

title: Troubles with motors for arduino

Answers: 1

body:
I cannot say much about the example code, that you mentioned. The posted example code is not complete, also the second part with the for loop is plain wrong. A for loop looks like this

    for(<Variable initialization>; <Condition for running the loop>; <Action done for every loop iteration>)

So the condition in the middle is the condition for the loop running. If the condition evaluates to `false`, the loop will not run anymore. You have the line

    for (int i = 0; i > 150; i++)

where `i` has the value zero at the start of the first iteration. zero is not bigger than 150, so the condition will evaluate to false. Thus the for loop will never run. The situation is similar with the second for loop of the example code. Where did you get that code? I think you should not trust this source very much, if it gives you this code.

---

Your own code also has some errors:

- You are doing the if statement for equality wrong. If you want to check for equality, you need to use double equal signs. A single equal sign means an assertion (so you are actually changing the variable instead of check it's value), which will always evaluate to true. An example of a correct if statement is this:

        if(i == 0)

- You are doing things like

        analogWrite(a, 0);

    all over your code. but nearly always you are doing a

        if(a == 1)

    directly after it. This does not make sense. The first parameter of `analogWrite()` is the pin number, where you want to output the PWM voltage. A pin number is constant, why should it ever change, unless you are plugging the motor into other pins. So the above if statement will not check, if the motor runs or not. It will compare the pin number to 1, which is always false, since none of the pin numbers, that you used, is 1.

- Again with the line

        analogWrite(a, 0);

    You are never providing a different second parameter as zero in your code (except for the `timed()` function, but I will get to this later). So the corresponding pin (here pin a aka 2) is turned off aka outputs LOW. With H-bridge controllers like the L296N, you use 2 digital pins to set the direction and then provide a PWM voltage (mostly at the enable pin) to change the speed. But as described, you never output a PWM voltage, so the motors cannot run, if you connected them corrected.

- Connected the the previous sentence. Your code will not run any motors. But since you wrote, that they actually do run, this means, that the hardware is also a problem. Please revisit tutorials on how to use the L296N with an Arduino or provide information about your wiring by editing your question.

- In your `loop()` function you have this passage:

        if (i == 0){
             i++;
        }
        if (i >=100){
            --i;
        }

    (I already corrected the double equal signs as described above). If `i`is exactly zero, `i` will be incremented. If `i` is greater or equal to 100, it will decrement. It only changes in this code portion and it will be initialized implicitly with a value of zero at the startup of the program. So the first if statement will trigger exactly once. Then `i` is not equal to zero, so it will not increment or even ever change again. Also `i` is not greater or equal to 100 (it is 1), so it will never decrement. Your code sets `i` to 1 once, and then never changes it again. That cannot be, what you tried to do. If you want a sweep from 0 to 100 and then from 100 to 0, you need an extra variable for the direction. Something like this:

        boolean direction=false; // define this at global scope
        ...
        // the following code would replace your `i` related code in your loop function
        if(direction){
            i++;
        } else {
            i--;
        }
        if(i==0) direction = true;
        if(i>=100) direction = false;

- Connected to the previous issue: Since `i` stays `1` forever, you also only write a PWM duty cycle of 1 out of 255 to the motors a and b inside the `timed()` function. A value this small is most likely not enough to even move the rotor of the motors (since motors also experience friction). Again, these motors should not run with your current code. If you change the `i` related code like I suggested above, the code should run the motors with changing speed. But also note, that this would still be a very slow change. A full run of the `timed()` function takes 4s (since the two 2s delays). With 100 steps, a full sweep from 0 to 100 will take 400s (aka 6.7 minutes) and the same time back to 0. (And this isn't accounting for the huge delays from the previous motor functions. With this you won't be able to see the change, until you wait really long time for it)

- You wrote, that you are using a 9V block battery as power source. If it is a 9V block battery, then you should know, that these batteries are not made for providing much current. They are made for low power applications. For driving motors for a longer time over battery or driving more motors at the same time, you should consider using a different battery (for example multiple AA batteries in series). As your motors currently run from it, you seem to get away with it, which is just fine. I just wanted to provide the information, in the case you reach this limit at some point.

---

All in all I can only agree with VE7JRO, that you should start with code for 1 single motor. Then, if it works like it should, you can move on and add the next motor. This will ensure, that you are getting things right early in the process and that you don't generate a big mountain of problems to cope with at once.


body:
I am dealing with code thatt i received that relies heavily on timer interrupts.
i am using arduino Mega (Funduino)

More specifically, when a signal arrives in a pin, an interrupt is run that starts a timer. A different interrupt is run from inside the 1st interrupt, when the timer overflows.

The interrupts measure time between the incoming signal pulses, to figure out the resistance of a sensor, that is being produced from a supporting analog circuit.

The problem is when the sensor doesn't work. For example, the resistance is open circuited. Then the analog circuit does not produce and signal, and no interrupt is triggered.

My code is stuck on the loop() function. It cannot progress because it requires a flag to be set up ,from when the interrupt finishes execution (the interrupt sets that flag at the end).

What i would like to do, is to detect when the resistance is open circuited and move on.
This means i have to figure out how to detect when the interrupt is not run.

Perhaps i would set a timer to that flag that the interrupt sets? And if some time passes without the flag being set, this means that the interrupt did not run.

But using another timer (my interrupt already uses two timers) maybe would complicate things further. Any ideas?

Maybe i could also check if the pin that receives the signal does not receive anything for some time... Maybe this would be a better option. If it is, what's the best way to do so, considering the fact i already use two different timers?

This is the code:

    /***** CONSTANTS *****/
    const int BAUD_RATE = 9600;

    const int INTERRUPT_PIN = 3;

    const int S0_PIN = 4;
    const int S1_PIN = 5;
    const int S2_PIN = 6;
    const int OE_BAR_PIN = 22;

    const int NUM_OF_SENSORS = 8;

    /***** ANALOG CIRCUIT CONSTANTS *****/
    const double CAPACITOR_VALUE = 400; //pF
    const double GAIN_VALUE = 3.5222672065;
    const double R_BIAS_VALUE = 98.7; //kΩ

    /***** GLOBAL VARIABLES *****/
    int number_of_samples = 10;

    int pulse_counter = 0;
    byte measurement_counter = 0;

    unsigned long overflows = 0;
    unsigned long ticks = 0;
    double period = 0;

    boolean interrupts_enabled = false;
    boolean measurement_finished = false;

    int sensor_coord;

    boolean full_mode = false;

    void setup() {
      attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), count_time_of_k_pulses, RISING);

      pinMode(OE_BAR_PIN, OUTPUT);
      pinMode(S0_PIN, OUTPUT);
      pinMode(S1_PIN, OUTPUT);
      pinMode(S2_PIN, OUTPUT);

      TIMER1_init();

      Serial.begin(BAUD_RATE);
      while (! Serial);
    }

    void loop() {
      if (Serial.available()) {
        /***** DEFINE MEASUREMENT MODE *****/
        String input = Serial.readString();
        if (input[0] == 'r' && interrupts_enabled == false) {
          if (input[1] == 'f') {
            full_mode = true;
            sensor_coord = 0;
          } else
            sensor_coord = input[2] - '0';

          select_sensor();

          /***** SET VARIABLES FOR DUMMY MEASUREMENT *****/
          number_of_samples = 10;

          pulse_counter = 0;
          measurement_counter = 0;

          TIMER1_clear();

          interrupts_enabled = true;
        }
      }

    //THIS IS WHERe I BELIEVE THE CHECK SHOULD OCCUR, OF WHETHER THE INTERRUPT DID NOT RUN. OR WHETHER THE PIN 3 IS RECEIVING A ZERO SIGNAL FOR SOME TIME

      if (measurement_finished) {
        measurement_counter++;

        ticks = (overflows * 65536) + TCNT1;
        period = (ticks * 0.0625) / (number_of_samples - 1);

        if (measurement_counter == 1) {
          /***** SET VARIABLES FOR MEASUREMENT *****/
          number_of_samples = 500;

          pulse_counter = 0;

          TIMER1_clear();

          interrupts_enabled = true;
        }
        else {
          TIMER1_print_results();

          if (full_mode) {
            sensor_coord++;

            select_sensor();

            /***** SET VARIABLES FOR DUMMY MEASUREMENT *****/
            number_of_samples = 10;

            pulse_counter = 0;
            measurement_counter = 0;

            TIMER1_clear();

            interrupts_enabled = true;

            if (sensor_coord == NUM_OF_SENSORS) {
              full_mode = false;
              interrupts_enabled = false;
            }
          }
        }
        measurement_finished = false;
      }
    }

    /***** INTERRUPT ROUTINES *****/

    void count_time_of_k_pulses() {
      if (interrupts_enabled) {
        pulse_counter++;

        if (pulse_counter == 1)
          TIMER1_start();

        if (pulse_counter == number_of_samples) {
          TIMER1_stop();

          measurement_finished = true;
          interrupts_enabled = false;
        }
      }
    }

    ISR (TIMER1_OVF_vect) {
      overflows++;
    }

    /***** FUNCTION FOR SENSOR SELECTION *****/

    void select_sensor() {
      digitalWrite(OE_BAR_PIN, LOW);
      digitalWrite(S2_PIN, ((sensor_coord & 4) == 4) ? HIGH : LOW );
      digitalWrite(S1_PIN, ((sensor_coord & 2) == 2) ? HIGH : LOW );
      digitalWrite(S0_PIN, ((sensor_coord & 1) == 1) ? HIGH : LOW );
    }

    /***** TIMER1 FUNCTIONS *****/

    void TIMER1_init() {
      TCCR1A  = 0;
      TCCR1B  = 0;
      TIMSK1  = 0;
      TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
    }

    void TIMER1_start() {
      TIMSK1 |= (1 << TOIE1);
    }

    void TIMER1_stop() {
      TIMSK1 = 0;
    }

    void TIMER1_clear() {
      TCNT1     = 0;
      overflows = 0;
    }

    void TIMER1_print_results() {
      Serial.println("----------------------------------------");
      Serial.print("SENSOR COORDINATE         = ");
      Serial.println(sensor_coord);

      Serial.print("NUMBER OF PULSES MEASURED = ");
      Serial.println(pulse_counter);

      Serial.print("TIMER1 VALUE              = ");
      Serial.println(TCNT1);

      Serial.print("TIMER1 OVERFLOWS          = ");
      Serial.println(overflows);

      Serial.print("TICKS                     = ");
      Serial.println(ticks);

      Serial.print("MEASURED PERIOD           = ");
      Serial.print(period);
      Serial.println(" US");

      Serial.print("MEASURED RESISTANCE       = ");

      double resistanse = ((period * GAIN_VALUE * 1000) / (4 * CAPACITOR_VALUE)) - R_BIAS_VALUE; //kΩ
      Serial.print(resistanse);

      Serial.println(" kΩ");

      Serial.println("----------------------------------------");
    }

EDIT: This is the updated code, with help from chrisl.
Only the lines or blocks of code with '!!!!!!!!!!!' are new, so there is not much new code.

    /***** CONSTANTS *****/
    const int BAUD_RATE = 9600;

    const int INTERRUPT_PIN = 3;

    const int S0_PIN = 4;
    const int S1_PIN = 5;
    const int S2_PIN = 6;
    const int OE_BAR_PIN = 22;

    const int NUM_OF_SENSORS = 8;

    /***** ANALOG CIRCUIT CONSTANTS *****/
    const double CAPACITOR_VALUE = 400; //pF
    const double GAIN_VALUE = 3.5222672065;
    const double R_BIAS_VALUE = 98.7; //kΩ

    /***** GLOBAL VARIABLES *****/
    int number_of_samples = 10;

    byte measurement_counter = 0;

    unsigned long overflows = 0;
    unsigned long ticks = 0;
    double period = 0;

    //variables for determining if a resistance cannot be measured !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    unsigned long timestamp = 0;
    unsigned long measurement_timeout = 5000;  //5 secods is the timeout time
    boolean sensor_corruption[7]; //each element of the array is the sensor info. If false, resistance is working. If it's true, resistance is open.
    boolean ISR_unavailable = false; //this flag is raised, when the ISR dose not run, because no signal comes from the circuit, because resistance is open circuit
    boolean setup_finished = false;

    //variables that get changed inside the ISR - thus are declared volatile!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    volatile int pulse_counter = 0;
    volatile boolean interrupts_enabled = false;
    volatile boolean measurement_finished = false;

    int sensor_coord;

    boolean full_mode = false;

    void setup() {
      attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), count_time_of_k_pulses, RISING);

      pinMode(OE_BAR_PIN, OUTPUT);
      pinMode(S0_PIN, OUTPUT);
      pinMode(S1_PIN, OUTPUT);
      pinMode(S2_PIN, OUTPUT);

      TIMER1_init();

      Serial.begin(BAUD_RATE);
      while (! Serial);

      //Initializing all array elements to false!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      for (int i=0; i<=7; i++)
      {
        sensor_corruption[i] = false; // false means it's working ok. true means it's corrupted
      }

      setup_finished = true; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    }

    void loop()
    {
      if (Serial.available())
      {
        /***** DEFINE MEASUREMENT MODE *****/
        String input = Serial.readString();
        if (input[0] == 'r' && interrupts_enabled == false)
        {
          if (input[1] == 'f')
          {
            full_mode = true;
            sensor_coord = 0;
          } else
            sensor_coord = input[2] - '0';

          select_sensor();

          /***** SET VARIABLES FOR DUMMY MEASUREMENT *****/
          number_of_samples = 10;

          pulse_counter = 0;
          measurement_counter = 0;

          TIMER1_clear();

          interrupts_enabled = true;
        }
      }

    // TIMEOUT CODE HERE. TO DETERMINE IF A RESISTANCE IS OPEN CIRCUITED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      if(setup_finished && millis() - timestamp > measurement_timeout)
      {
        sensor_corruption[sensor_coord] = true; //label the resistance (indicated by sensor_coord) as true in the boolean array. this means it's open circuited (no signal from circuit)
        measurement_finished = true;
        interrupts_enabled = false;
        ISR_unavailable = true;
      }

      if (measurement_finished)
      {
        //This does not get executed when the resistance is open circuited
        if (!ISR_unavailable) //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! this if statement is the only thing i added here
        {
          measurement_counter++;

          ticks = (overflows * 65536) + TCNT1;
          period = (ticks * 0.0625) / (number_of_samples - 1);

          if (measurement_counter == 1)
          {
             /***** SET VARIABLES FOR MEASUREMENT *****/
            number_of_samples = 500;

            pulse_counter = 0;

            TIMER1_clear();

            interrupts_enabled = true;
           }
        }
        else
        {
          TIMER1_print_results();

          if (full_mode)
          {
            sensor_coord++;

            select_sensor();

            /***** SET VARIABLES FOR DUMMY MEASUREMENT *****/
            number_of_samples = 10;

            pulse_counter = 0;
            measurement_counter = 0;

            TIMER1_clear();

            interrupts_enabled = true;

            if (sensor_coord == NUM_OF_SENSORS)
            {
              full_mode = false;
              interrupts_enabled = false;
            }
          }
        }
        measurement_finished = false;
        ISR_unavailable = false; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        timestamp = millis();  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      }
    }

    /***** INTERRUPT ROUTINES *****/

    void count_time_of_k_pulses() {
      if (interrupts_enabled) {
        pulse_counter++;

        if (pulse_counter == 1)
          TIMER1_start();

        if (pulse_counter == number_of_samples) {
          TIMER1_stop();

          measurement_finished = true;
          interrupts_enabled = false;
        }
      }
    }

    ISR (TIMER1_OVF_vect) {
      overflows++;
    }

    /***** FUNCTION FOR SENSOR SELECTION *****/

    void select_sensor() {
      digitalWrite(OE_BAR_PIN, LOW);
      digitalWrite(S2_PIN, ((sensor_coord & 4) == 4) ? HIGH : LOW );
      digitalWrite(S1_PIN, ((sensor_coord & 2) == 2) ? HIGH : LOW );
      digitalWrite(S0_PIN, ((sensor_coord & 1) == 1) ? HIGH : LOW );
    }

    /***** TIMER1 FUNCTIONS *****/

    void TIMER1_init() {
      TCCR1A  = 0;
      TCCR1B  = 0;
      TIMSK1  = 0;
      TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
    }

    void TIMER1_start() {
      TIMSK1 |= (1 << TOIE1);
    }

    void TIMER1_stop() {
      TIMSK1 = 0;
    }

    void TIMER1_clear() {
      TCNT1     = 0;
      overflows = 0;
    }

    void TIMER1_print_results() {
      Serial.println("----------------------------------------");
      Serial.print("SENSOR COORDINATE         = ");
      Serial.println(sensor_coord);

      //Added the if-else statement, to cover the possibility of open circuited resistance !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      if (sensor_corruption[sensor_coord])
      {
      Serial.println("This resistance is open circuited!!!");
      }
      else
      {
      Serial.print("NUMBER OF PULSES MEASURED = ");
      Serial.println(pulse_counter);

      Serial.print("TIMER1 VALUE              = ");
      Serial.println(TCNT1);

      Serial.print("TIMER1 OVERFLOWS          = ");
      Serial.println(overflows);

      Serial.print("TICKS                     = ");
      Serial.println(ticks);

      Serial.print("MEASURED PERIOD           = ");
      Serial.print(period);
      Serial.println(" US");

      Serial.print("MEASURED RESISTANCE       = ");

      double resistanse = ((period * GAIN_VALUE * 1000) / (4 * CAPACITOR_VALUE)) - R_BIAS_VALUE; //kΩ
      Serial.print(resistanse);

      Serial.println(" kΩ");
      }

      Serial.println("----------------------------------------");
    }

And this is the output i get:

    ----------------------------------------
    SENSOR COORDINATE         = 0
    This resistance is open circuited!!!
    ----------------------------------------
    ----------------------------------------
    SENSOR COORDINATE         = 1
    This resistance is open circuited!!!
    ----------------------------------------
    ----------------------------------------
    SENSOR COORDINATE         = 2
    This resistance is open circuited!!!
    ----------------------------------------
    ----------------------------------------
    SENSOR COORDINATE         = 3
    This resistance is open circuited!!!
    ----------------------------------------
    ----------------------------------------
    SENSOR COORDINATE         = 4
    This resistance is open circuited!!!
    ----------------------------------------
    ----------------------------------------
    SENSOR COORDINATE         = 5
    This resistance is open circuited!!!
    ----------------------------------------
    ----------------------------------------
    SENSOR COORDINATE         = 6
    This resistance is open circuited!!!
    ----------------------------------------
    ----------------------------------------
    SENSOR COORDINATE         = 7
    This resistance is open circuited!!!
    ----------------------------------------
    ----------------------------------------
    SENSOR COORDINATE         = 8
    This resistance is open circuited!!!
    ----------------------------------------
    ----------------------------------------
    SENSOR COORDINATE         = 8
    This resistance is open circuited!!!
    ----------------------------------------
    ----------------------------------------
    SENSOR COORDINATE         = 8
    This resistance is open circuited!!!
    ----------------------------------------
    ----------------------------------------
    SENSOR COORDINATE         = 8
    This resistance is open circuited!!!
    ----------------------------------------
    ----------------------------------------
    SENSOR COORDINATE         = 8
    This resistance is open circuited!!!
    ----------------------------------------

As you can see, all the resistances are falsely labeled as open circuited.
Not only that but for some reason, it measures resistance 8 which does not exist, multiple times. Actually then it loops forever on resistance 8 (Normal operation stops at resistance 7 )

title: Detecting when a timer interrupt does not run

Answers: 2

body:
In your code you are using the `measurement_finished` variable as a flag, that a new measurement was finished inside the ISRs, so that it can be handled inside the `loop()` function. This is very useful. As I understood, an open circuit means, that no measurement can happen, since no pulses are created. So you need to check, how much time passed since the last measurement.

Also the Arduino core sets up Timer0 for general timekeeping purposes. For example the `delay()` function uses it, and also functions like `micros()` and `millis()`, which will return the number of micro/milli-seconds elapsed since startup. So, if you are using these functions, you are actually using a hardware timer, but you don't have to set it up yourself. It is already done by the Arduino core.

So I suggest a principle similar to the `BlinkWithoutDelay` example from the Arduino IDE. First you define a global timestamp variable and a timeout value (here 1s aka 1000ms):

    unsigned long timestamp=0;
    unsigned long measurement_timeout=1000;

Then inside your `loop()` function (in fact you can do this exactly, where you placed the corresponding comment for the check), you check for the difference between the current time and the timestamp:

    if(millis() - timestamp > measurement_timeout){

This will trigger, when the timestamp was last updated 1s ago. Inside this measurement, you do, what ever you need to do, if a measurement timeout happens (like printing an appropriate message to Serial). And now, we want to start a new timeout by updating the `timestamp` variable to the current time, as given by `millis()`. We could do this inside the corresponding ISR, but that would give us a problem. The ISR could fire right in between of the calculation of our if statement. This cannot happen for single byte variables (as for an 8 bit controller the current 8 bit action will be completed in one step), but `unsigned long` has 4 bytes. We would need to disable interrupts, when accessing it, to keep it from getting corrupted.

So we can simply set the timestamp inside the

    if (measurement_finished) {

statement in the loop function. There we simply do

    timestamp = millis();

to update the timestamp. As long, as the if statement is evaluated often enough (at least 1 time during the timeout range), it will work.

So, what happens in the changed code? When you start the code, it might think, that a zero measurement was done (if your `setup()` function needs longer than the timeout), but as soon, as the first measurement arrives, the `if (measurement_finished)` statement will execute and update the timestamp. Now the `millis()` if statement is disabled for the timeout duration, each new finished measurement will reset this timeout. It is like a dead man's switch. The timeout will trigger, when there is no one (or no code) to reset the timeout again.

---

BTW: As you are using interrupt routines, you should declare all variables, that get changed in an ISR as volatile like this:

    volatile int pulse_counter = 0;

If you are not doing this, the compiler might optimize the variable to use a cached value, instead of the real value. Also think about, what I wrote above about variables changed by ISRs in the middle of a calculation. You have to be careful to not run in difficult to debug situations, if you don't protect your variables in the main code against change from an ISR.

body:
I tried to understand your program and found quite a few issues, which I
am listing below. This is more a general review than a specific answer.
I hope it nevertheless helps you fix the code.

The major issue is the logic of `loop()` being quite convoluted and hard
to follow. My guess is that the issue you face is a direct consequence
of this single problem. I won't propose a fix because I can't really
understand what this logic is supposed to accomplish. I think this
problem is rooted in that logic having too much “state”, i.e. too many
global variables that influence its behavior.

You may be able to make the logic of the function a lot clearer if you
consolidate various state-defining variables into a single `enum`
variable named `state`, and write the logic as in a regular [finite
state machine][FSM]. This should make it a lot easier to understand,
which in turn should make the bugs evaporate like magic.

Now, some specific details in the code.

I can't understand the purpose of `measurement_counter`. It is used only
in the test `if (measurement_counter == 1)`. A boolean named
`first_measurement` may be more appropriate here. Better yet if you can
merge it into the unique `state` variable.

The variable `setup_finished` has no purpose at all. It is used only in
`loop()` to test whether `setup()` is done. However, `loop()` only
starts running after `setup()` is complete, so the test is pointless.

The handling of `OE_BAR_PIN` looks wrong: the pin goes `LOW` in
`setup()` and never goes `HIGH` again. It would seem saner to initialize
it `HIGH`, keep it `HIGH` when toggling the sensor-select pins, and only
turn it `LOW` once a sensor has been properly selected. Thus:

```c++
void setup() {
  ...
  digitalWrite(OE_BAR_PIN, HIGH);
  pinMode(OE_BAR_PIN, OUTPUT);
  ...
}

void select_sensor() {
  digitalWrite(OE_BAR_PIN, HIGH);
  digitalWrite(S2_PIN, ((sensor_coord & 4) == 4) ? HIGH : LOW );
  digitalWrite(S1_PIN, ((sensor_coord & 2) == 2) ? HIGH : LOW );
  digitalWrite(S0_PIN, ((sensor_coord & 1) == 1) ? HIGH : LOW );
  digitalWrite(OE_BAR_PIN, LOW);
}
```

Note that `setup()` turns the pin `HIGH` _before_ setting it as
`OUTPUT`: this prevents an unwanted short `LOW` pulse.

The handling of Timer 1 is also flaky: it runs continuously.
`TIMER1_start()` and `TIMER1_stop()` start and stop the overflow
counting, not the timer itself. This means the measured tick count can
be off by as much as ±65,535 ticks. It would be more sensible to really
start and stop the timer as needed:

```c++
void TIMER1_init() {
  TCCR1A  = 0;
  TCCR1B  = 0;
  TIMSK1 |= (1 << TOIE1);
}

void TIMER1_start() {
  TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
}

void TIMER1_stop() {
  TCCR1B  = 0;
}
```

You probably want to call `TIMER1_stop()` when you detect a timeout.

[FSM]: https://majenko.co.uk/blog/finite-state-machine


body:
I have been working on a problem for a couple of days that I can't figure out.

I am using a Teensy3.6 with Arduino IDE to build a CAN Bus monitor for a car. For those familiar, I am trying to save the data in the format of can-utils so it can be easily replayed on Linux machines. The board uses the FlexCAN library to facilitate communication.

Everything works well using the Arduino Serial Monitor. However, I want to save the output to a host computer. Unfortunately, I've not been able to get any other serial programs to work. I have tried PuTTY & Python via PySerial. The output seems to get interrupted & doesn't print on a new line correctly.

Sample Output from Arduino Serial Monitor:

    (1302.864746) can0 1C5#2C032C032E01
    (1302.864868) can0 1F4#000000000000
    (1302.865356) can0 287#0000
    (1302.865601) can0 F1#340000400000
    (1302.865845) can0 96#BFF00A120000
    (1302.866455) can0 97#35800A1518300A0A
    (1302.866821) can0 98#00000A0080000A13
    (1302.867065) can0 1E5#4400335000000103
    (1302.867554) can0 C7#00000000
    (1302.867798) can0 1E9#FF8300EFFC0000
    (1302.868042) can0 232#0000000000000000
    (1302.868652) can0 1E1#00000000001CC0
    (1302.868896) can0 2F9#83000000000007
    (1302.869019) can0 222#001607AD0C00
    (1302.869629) can0 BC#A11E005C00000000
    (1302.869751) can0 D3#2C02
    (1302.869995) can0 186#44005D0000017C
    (1302.870483) can0 224#CBC8C8
    (1302.870605) can0 228#005B5F5B
    (1302.870850) can0 1F3#80BC00
    (1302.871460) can0 B9#000A800002000000

Output from PuTTY/PySerial:

    (1443.927002) can0 C1#10026B0210037D86
    (1443.927246) can0 C5#10026B0310026B02
    (1443.927490) can0 D1#40007FFF00FF00
    (1443.927856) can0 1EB#0241(1444.011230) can0 AA#2C032C030253FC00
    (1444.011597) can0 C9#8000002000101800
    (1444.012085) can0 1E7#019000000000316D
    (1444.012329) can0 1ED#019000000000316D
    (1444.012451) can0 34A#000000001B
    (1444.012939) can0 1EF#00000000
My naive opinion is it seems the CAN data comes faster than the serial is writing. However, it's odd that it works fine in the Arduino IDE. It happens about 1x/second--which is well enough to cause a headache.

Outside of SD cards or writing locally--does anyone know why this might happen? Or how I could save this data to a host computer? Worst case I can copy/paste the output from the Arduino Serial Monitor, but that isn't very elegant.

Thank you!

Edit: Here is some relevant code from my Arduino IDE. I modified the object oriented can example from flexcan to print in my desired format.

    #include <FlexCAN.h>
    static CAN_message_t msg;
    elapsedMicros sinceStart;

    class CANHandler : public CANListener{
      void printFrame(CAN_message_t &frame);
      void gotFrame(CAN_message_t &frame, int mailbox); //overrides the parent version so we can actually do something
    };

    void CANHandler::printFrame(CAN_message_t &frame){
       Serial.print("("); Serial.print(sinceStart / 1000.0 / 1000.0, 6);
       Serial.print(") "); //cast to 6 decimals to make compatible with can-utils
       Serial.print("can0 "); // to identify a CAN channel for can-utils
       Serial.print(frame.id, HEX);
       Serial.print("#");
       for ( uint8_t i = 0; i < frame.len; i++ ) {
         if(frame.buf[i] < 15){
            Serial.print("0"); Serial.print(frame.buf[i], HEX);
         } else {
            Serial.print(frame.buf[i], HEX);
         }
     }
     Serial.println();
    }

    void CANHandler::gotFrame(CAN_message_t &frame, int mailbox){
    printFrame(frame);
    }

    CANHandler canHandler;

    void setup() {
        Serial.begin(115200);
        Can0.begin(500000);
        Can0.attachObj(&canHandler);
        CanHandler.attachGeneralHandler();
    }

    void loop() {
    //run until exit
    }

title: What would cause a delay when using serial between the Arduino IDE & external clients?

Answers: 1

body:
If your data input rate is higher than, or even close to, your serial output rate (baudRate/10 char/s), your system will be unable to keep up.

With an interrupt driven system, make sure your interrupt function executes and returns as quickly as possible, i.e., does as little as needed to not lose data. Let the background process (the main sketch code) deal with the incoming data as it appears. Make sure the both processes are short enough to deal with the worst-case input-data bursts without losing any. For the background process, use as high a baud rate as it is capable of - and as it's downstream neighbor (Storage device? Another MCU or PC?) is capable of - keeping up with.


body:
I wonder why the following minimal example sketch doesn't compile (`unknown type name 'uint16_t'`):

`sketch_does_not_compile.ino`:

    #include "myheader.h"

    void setup() {
      char a[]="hello world";
      uint16_t l=str_len(a);
      Serial.println(l);
    }

    void loop() {}

`myheader.c`:

    uint16_t str_len(char* input_string) {
      uint16_t i=0;
      while (input_string[i++]!='\0');
      return i;
    }

`myheader.h`:

    #include "myheader.h"

    uint16_t str_len(char* input_string);

Compilation fails with:

    myheader.c: At top level:
    myheader.c:3:1: error: unknown type name 'uint16_t'
     uint16_t str_len(char* input_string);
     ^
    exit status 1
    unknown type name 'uint16_t'

Using `uint16_t` in the .ino-file directly like in the sketch below compiles fine.

`sketch_compiles.ino`:

    uint16_t str_len(char* input_string) {
      uint16_t i=0;
      while (input_string[i++]!='\0');
      return i;
    }

    void setup() {
      char a[]="hello world";
      uint16_t l=str_len(a);
      Serial.println(l);
    }

    void loop() {}

What am I missing?

title: Can't use uint16_t in library

Answers: 1

body:
Using `#include <Arduino.h>` in your myheader.h will also include `<stdint.h>` and probably solve this.

The Arduino IDE automatically includes Arduino.h in the sketch itself, but apparently not for external stuff.


body:
I bought online this LCD Touchscreen Kuman SC3A-NEW-UK. It uses ILI9486 drivers, but it didn't include any instructions manual, and kumantech.com seems to be devoid of complete technical documentation about SC3A-NEW-UK model.

I am trying to figure out:

* Which are the minimum connections I have to make between Arduino UNO and the LCD screen.
* Which "Arduino's C++" (AKA G++ ?) library I need to use in order to display stuff programatically

[![Arduino UNO & Kuman LCD Touchscreen --> PinSets][1]][1]

## To summarize
Just in case it wasn't noticable: I am trying to make a "Hello World" for my SC3A-NEW-UK's LCD Touchscreen from an Arduino UNO board. In other words: just print "Hello World" to see if it works.

## What I tried so far
Searching on the Internet wasn't enough. Searching "ILI9486" on Google led me to this Github project:

https://github.com/schreibfaul1/ESP32-TFT-Library-ILI9486

To see if I can use it, I tried downloading a whole ZIP from this Github project, and inside the Arduino IDE, I tried adding the downloaded library using the option "Include .ZIP library". If I copy-paste the code example provided within README.md (the following) and compile:

    #include "Arduino.h"
    #include "SPI.h"
    #include "tft.h"

    // defaults can be changed in tft.begin
    // CS=22, DC=21, MOSI=23, MISO=19, SCK=18

    TFT tft;
    //-------------------------------------------------------------------------------------
    void setup() {
        SPI.begin();
        tft.begin();
        tft.setRotation(1); //landscape
        tft.fillScreen(TFT_BLACK);
        tft.setFont(Garamond34x42);
        tft.setTextColor(TFT_CYAN);
        tft.setCursor(20,30);
        tft.print("Hello World!");
    }
    //-------------------------------------------------------------------------------------
    void loop(void) {
        for(uint8_t rotation=0; rotation<4; rotation++) {
            tft.setRotation(rotation);
            tft.fillScreen(TFT_BLACK);
            tft.setCursor(20,30);
            tft.print("Hello World!");
            delay(3000);
        }
    }
    //-------------------------------------------------------------------------------------

...it results in this compile error:

    In file included from C:\Users\MyUser\ArduinoProjects\test_external_library\test_external_library.ino:3:0:

    C:\Users\MyUser\Documents\Arduino\libraries\Arduino-TFT-Library-ILI9486-master\src/tft.h:5:16: fatal error: FS.h: No such file or directory

    compilation terminated.

    exit status 1
    Error compiling for board Arduino/Genuino Uno.

Line 5 at `tft.h` says:

    #include "FS.h"

...and I have no idea what this FS library is supposed to be, so I don't think I can use that Github project at all... I am tempted to assume that Github's project is dead.

**So, perhaps I am fine just using the IDES's built-in `TFT` library, perhaps like this? I don't know...:**

    #include <SPI.h>
    #include <TFT.h>
    #define CS   10
    #define DC   9
    #define RESET  8

    #define TFT_CYAN    0x07FF
    #define TFT_BLACK   0x0000

    // Initialization inspired in code example found at
    // https://www.arduino.cc/en/Guide/TFT
    TFT tft = TFT(CS, DC, RESET);
    int dummy_second_cnt = 0;

    void setup() {
        // I don't know what's SPI for, anyway...
        // just found it in the code example present at GitHub's library's README.md
        // ...(which I am not trying to use at this point, so it's useless in this code example... commented-out for reference, just in case)
        //SPI.begin();

        tft.begin();
        tft.background(0,0,0);
        tft.setRotation(1);
        tft.fillScreen(TFT_BLACK);
        tft.setTextColor(TFT_CYAN);
        tft.setCursor(20,30);
        tft.print("Hello LCD Screen");

        delay(3000);
    }

    void loop() {
        tft.fillScreen(TFT_BLACK);
        tft.setCursor(20,30);
        tft.print("Seconds: ");
        tft.print(dummy_second_cnt);
        dummy_second_cnt++;
        delay(1000);
    }

**This compiled in Arduino IDE, no problem, but I still don't know if it will work well with my screen.** I am also confused about initialization of the TFT object and how would I have to wire the LCD screen to the Arduino depending on this initialization:

    TFT tft = TFT(CS, DC, RESET);

...i mean, my LCD screen has CS and RESET pins, but what is DC supposed to be here? (in this context, I don't think it stands for "Direct Current"... but there's no DC pin reference in my LCD screen written "AS IS"... ?? This brings me more confusion...

...specially having in mind that I don't know how am I supposed to wire the LCD screen to the Arduino yet. It seems the LCD pins have been designed to fit in directly to the Arduino board without thinking too much about it (like the shape is the same), but that would make the screen getting all the Arduino UNO's pins for itself, so I don't think so...

These are the `LCD_*` pins present at my LCD screen:

* LCD_RST (Reset I guess)
* LCD_CS
* LCD_RS
* LCD_WR (Write I guess)
* LCD_RD (Read I guess)

(and the following I guess are 8-bit digital pins):

* LCD_D0
* LCD_D1
* LCD_D2
* LCD_D3
* LCD_D4
* LCD_D5
* LCD_D6
* LCD_D7

It also has 5V, 3V3 and GND pins (Which I guess are for power)

...so, powering the screen shouldn't be a big deal, but, how am I supposed to connect everything else? I am completely misguided about how am I supposed to interact with the screen from Arduino code... what is RS pin for? Should I use 4-bit or 8-bit mode? (I think 4-bit would imply connecting 4 digital pins for the screen, and 8-bit the whole 8 pins from screen to the Arduino UNO board)? Should I use LCD_RD and LCD_WR? Well you have a picture of my confusion.

Searching for documentation in the internet only leads me to partial examples. Not even using the model Ref ( SC3A-NEW-UK ) or the driver's ref ( ILI9486 ) as keywords for searching in Google leads me to clear documentation about howto wire stuff, or which specific libraries should I use...

Even though I know how to control Input/Output in Arduino code to interact with analog/digital input and output pins at will with C++ in Arduino code (but even so, I think I'm still an Arduino n00b), this LCD screen's physical interface is very confusing to me...

**Can you help me to overcome this confusion, please?** I'd rather have my mind clear before making any physical wiring and fry something...

**PD:** I have read somewhere that this SC3A-NEW-UK Touchscreen is made to shield Arduino MEGA boards (by fitting the PINs directly into it), but mine is an Arduino UNO Board! (perhaps I shouldn't have bought This LCD model, then?)... but I have sets of wires, pinboards and stuff... I don't want to give up the idea of harnessing this LCD screen using an Arduino UNO. I don't care about shielding feature, I just want to wire it and make it work. I will figure out how to shield electronics later on.

----

**EDIT:**
Based on VE7JRO's answer, I managed to map the connections by seeing where the connections would go if I just fit the connections shielding the Arduino UNO, the way VE7JRO suggested:

    +--------------+------------------+
    | Arduino UNO  |    LCD Screen    |
    +--------------+------------------+
    |     GND      |        GND       |
    +--------------+------------------+
    |      5V      |         5V       |
    +--------------+------------------+
    |     3.3V     |       3.3V       |
    +--------------+------------------+
    |      A0      |      LCD_RD      |
    +--------------+------------------+
    |      A1      |      LCD_WR      |
    +--------------+------------------+
    |      A2      |      LCD_RS      |
    +--------------+------------------+
    |      A3      |      LCD_CS      |
    +--------------+------------------+
    |      A4      |      LCD_RST     |
    +--------------+------------------+
    |      A5      |       NONE       |
    +--------------+------------------+
    |       8      |      LCD_D0      |
    +--------------+------------------+
    |       9      |      LCD_D1      |
    +--------------+------------------+
    |    2 TO 7    | LCD_D2 TO LCD_D7 |
    +--------------+------------------+
    |      10      |       SD_SS      |
    +--------------+------------------+
    |      11      |       SD_DI      |
    +--------------+------------------+
    |      12      |       SD_DO      |
    +--------------+------------------+
    |      13      |      SD_SCK      |
    +--------------+------------------+

I put `NONE` for A5 input, because that pin of LCD screen doesn't have any name on it. There are another ones without name as well, that I didn't include in this table. I believe (perhaps I'm wrong believing it, I don't know) that those pins without name have no use.

The bad thing about this layout is that it consumes almost all the Arduino pins, so I would not be able to attach additional circuits. However, perhaps I should not be worrying about earning connections yet, before testing the screen.

I still don't know much of the details about what pins do what for the screen, but I have read somewhere that `LCD_D0` to `LCD_D7` are meant to receive digital data in some kind of 8-bit parallel mode. But I also heard that there is a 4-bit mode. If I could use that mode with this screen, I would be able to have 4 free digital pins for anything else...

**Ok, I got the connections mapped. Next step would be trying those three libraries that VE7JRO suggested.**

----

**EDIT2:**
I tested VE7JRO's code. LCD Screen did draw the interface as expected. But buttons didn't respond. I found out the code sample needs further calibration.

So, I started printing through the Serial the coordinates of the object `TSPoint p`, to find out if there was something wrong <s>with the `z` coordinate. And indeed, there was: setting `MINPRESSURE` and `MAXPRESSURE` according to what I saw in Serial Monitor while I pressed and I didn't pressed, fixed this. However, there's another more issue...

...when I tell Serial to print if the boolean operation `down && on_btn.contains(pixel_x, pixel_y)` results in either `true` or `false`, it prints it is false... while I am touching ON button. `down` is true for sure (after I calibrated `MINPRESSURE` and `MAXPRESSURE` constants); **so that must mean `on_btn.contains(pixel_x, pixel_y)` is returning false for some reason.** If I figure out why, I will be able to accomplish that the ON Button does what it's supposed to when I press it. And that will mean I will have completed calibration process. I would bet perhaps `pixel_x` and `pixel_y` need calibration as I already did with pressure detection based on `z`; or perhaps `contains` method is not reliable and I have to figure out some other methodology... I will tell you after I try</s>

**All stroken through is based on assumption that Z is depth, and Y is height; Actually, it seems to be the other way around...**

After somemore trial-and-error research, it seems that Z is height, and Y is depth (at least within the `TSPoint` object's properties `x`, `y` and `z`, which values seem way more reliable than the `pixel_x` and `pixel_y` values, which purpose seems to be if the pixel is contained in the button's squares and nothing else)... I still don't get why is there the need to use this within the function `Touch_getXY(void)`:

    if (pressed) {
        pixel_x = map(p.x, TS_LEFT, TS_RT, 0, tft.width()); //.kbv makes sense to me
        pixel_y = map(p.y, TS_TOP, TS_BOT, 0, tft.height());
    }

...because their values when I touch the screen with the touchpen are very weird. I tried to guess which ranges they go, and they don't make sense when I move around the screen. Perhaps it's because this strange "Z instead of Y" mapping from the `TSPoint` object. Perhaps `pixel_x` and `pixel_y` don't need to make an intuitive sense, perhaps it's just some intrincated in-bound logic that only makes sense within electronics' low-level scope, or within `Adafruit_GFX_Button.press` method, I don't know... but **`x`, `y` and `z` readings from `TSPoint` object seem very accurate**, despite Y being Z and Z being Y...

...perhaps reading any documentation I can find about `Adafruit_GFX_Button` class, its properties and methods (specially `contains`) will lead me to comprehend clearly what's wrong...

**...also, it might be time to focus on searching those test sketches that VE7JRO talked me about:**

> There are 22 test sketches that come with the MCUFRIEND_kbv library. One of them scans your display and outputs configuration information (sorry, it's been a while since I tested my screen). Another sketch will draw little boxes in each corner and sides. This is used to get the x y coordinates of the edges of your particular screen (it might be called TouchScreen_Calibr_native.ino).

----
**EDIT3**

X is Y? Y is Z? Z is X? *I don't know what to think anymore!* The last I tried, changing the formula for `pixel_x` and `pixel_y` to:

    pixel_x = map(p.x, 1023, 0, 0, tft.width());
    pixel_y = map(p.y, 1023, 0, 0, tft.height());

...and the constants for the pins:

    const int XP = 6, XM = A2, YP = A1, YM = 7;

This seems to make `z` the pressure axis within `TSPoint` object, but ends up in strange behaviours:

 - `x` seems numb (no matter if I press the touchscreen with touchpen or not, neither it's position: it always prints 65 to 70!
 - `z` seems indeed sensitive to touch pressure, but **it's like its sensitivity is different depending on the touchpen's position on screen** (altough I'm not a robot, I think I was using more or less the same amount of force with my hand). It prints 0 when i do not touch the screen.
 - `y` **seems sensible to both horizontal and vertical position at the same time!** This blows my head.

I don't know what to think anymore...

  - Did I short-circuit something for not paying attention to the script's constants in my previous tests?
  - Was the screen broken from the begginning?
  - Is it a calibration error with values in the script?
  - Might the libraries I am using be broken, or have some kind of bug with my TFT?

**This is becoming overwhelmingly more difficult than I thought...**

...according to [some article I found][2](in Spanish, sorry), the `Touchscreen`'s initialization's params:

    TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

  - `XP` is supposed to be the pin for `LCD_D6`: `6` in the Arduino.
  - `YP` is supposed to be the pin for `LCD_WR`: `A1` in the Arduino.
  - `XM` is supposed to be the pin for `LCD_RS`: `A2` in the Arduino.
  - `YM` is supposed to be the pin for `LCD_D7`: `7` in the Arduino.
  - The fifth parameter is supposed to be the resistance measured between `LCD_D6` and `LCD_RS` with the screen unplugged. Unfortunately, my multimeter can't measure it for some reason (I put it in 2000 Ohms mode for reading resistance: I always get '1', the same than when I don't connect anything... like if multimeter's contacts aren't working well, I don't know)... so I left the default 300 value.

I did initializate it well, as far as I know... **except the fifth parameter**. Would a wrong resistence value make such a big difference in calibration, up to the point this strange behaviours I have seen do happen?

**Damn, I am so close... what am I doing wrong?**

  [1]: https://i.stack.imgur.com/HEibE.png
  [2]: https://eldesvandejose.com/2016/04/23/la-libreria-touchscreen/

title: First time using Kuman 3.5" TFT screen model SC3A-NEW-UK with Arduino

Answers: 2

body:
> Which are the minimum connections I have to make between Arduino UNO
> and the LCD screen.

The TFT screen plugs right on top of your Arduino Uno. I have a "cheaper" model with the same size screen and identical pins as your screen (exact same text printed beside the pins).

Before you plug it in, I have a few pieces of advise.

 - It's possible to install the screen one or 2 pins "out of proper
   alignment", so plug it in before you apply power. Verify the correct
   pins are in the correct "holes", using the location of the `5V`,
   `3V3` and `GND` pins as a guide.
 - This screen used lots of power, especially when you are using a test
   sketch that turns all the pixels on / off and cycles through various
   graphics / text output to the screen. My Uno's voltage regulator was
   getting pretty warm after 10 minutes, and I was suppling it with 8
   VDC to the barrel jack power input. Using a 12 VDC supply would
   exacerbate the heat issue, so please be careful.

> Which "Arduino's C++" (AKA G++ ?) library I need to use in order to
> display stuff programatically?

I used the `MCUFRIEND_kbv` library, `Adafruit_GFX` library and the Adafruit `TouchScreen` library, all available in the Arduino IDE Library manager.

There are 22 test sketches that come with the `MCUFRIEND_kbv` library. One of them scans your display and outputs configuration information (sorry, it's been a while since I tested my screen). Another sketch will draw little boxes in each corner and sides. This is used to get the x y coordinates of the edges of your particular screen (it might be called `TouchScreen_Calibr_native.ino`).

Getting the screen to display anything is step 1. Step 2 is to calibrate the edges of the screen. Step 3 is to get the touch screen part of it to work.

Here is a sketch I used to test the screen by changing the color of a "box". Touching each of the 2 buttons on the screen changes the "box" color. I've left in all the config data I saved (see the end of this sketch). Your screen is different than mine, so running the test sketches from the library first is where I would start.

    // SEE BOTTOM OF SKETCH FOR MORE DATA / test results.
    #include <Adafruit_GFX.h>
    #include <MCUFRIEND_kbv.h>
    MCUFRIEND_kbv tft;
    #include <TouchScreen.h>
    #define MINPRESSURE 200
    #define MAXPRESSURE 1000

    // ALL Touch panels and wiring is DIFFERENT
    // copy-paste results from TouchScreen_Calibr_native.ino
    // OEM: const int XP = 6, XM = A2, YP = A1, YM = 7; //ID=0x9341
    // OEM: const int TS_LEFT = 907, TS_RT = 136, TS_TOP = 942, TS_BOT = 139;
    // MINE - WORKS.
    const int XP = 7, XM = A1, YP = A2, YM = 6; //320x480 ID=0x9488
    const int TS_LEFT = 929, TS_RT = 204, TS_TOP = 963, TS_BOT = 213;

    TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

    Adafruit_GFX_Button on_btn, off_btn;

    int pixel_x, pixel_y;     //Touch_getXY() updates global vars
    bool Touch_getXY(void)
    {
        TSPoint p = ts.getPoint();
        pinMode(YP, OUTPUT);      //restore shared pins
        pinMode(XM, OUTPUT);
        digitalWrite(YP, HIGH);   //because TFT control pins
        digitalWrite(XM, HIGH);
        bool pressed = (p.z > MINPRESSURE && p.z < MAXPRESSURE);
        if (pressed) {
            pixel_x = map(p.x, TS_LEFT, TS_RT, 0, tft.width()); //.kbv makes sense to me
            pixel_y = map(p.y, TS_TOP, TS_BOT, 0, tft.height());
        }
        return pressed;
    }

    #define BLACK   0x0000
    #define BLUE    0x001F
    #define RED     0xF800
    #define GREEN   0x07E0
    #define CYAN    0x07FF
    #define MAGENTA 0xF81F
    #define YELLOW  0xFFE0
    #define WHITE   0xFFFF

    void setup(void)
    {
        Serial.begin(9600);
        uint16_t ID = tft.readID();
        Serial.print("TFT ID = 0x");
        Serial.println(ID, HEX);
        Serial.println("Calibrate for your Touch Panel");
        if (ID == 0xD3D3) ID = 0x9486; // write-only shield
        tft.begin(ID);
        tft.setRotation(0);            //PORTRAIT
        tft.fillScreen(BLACK);
        on_btn.initButton(&tft,  60, 200, 100, 40, WHITE, CYAN, BLACK, "ON", 2);
        off_btn.initButton(&tft, 180, 200, 100, 40, WHITE, CYAN, BLACK, "OFF", 2);
        on_btn.drawButton(false);
        off_btn.drawButton(false);
        tft.fillRect(40, 80, 160, 80, RED);
    }

    /* two buttons are quite simple
     */
    void loop(void)
    {
        bool down = Touch_getXY();
        on_btn.press(down && on_btn.contains(pixel_x, pixel_y));
        off_btn.press(down && off_btn.contains(pixel_x, pixel_y));
        if (on_btn.justReleased())
            on_btn.drawButton();
        if (off_btn.justReleased())
            off_btn.drawButton();
        if (on_btn.justPressed()) {
            on_btn.drawButton(true);
            tft.fillRect(40, 80, 160, 80, GREEN);
        }
        if (off_btn.justPressed()) {
            off_btn.drawButton(true);
            tft.fillRect(40, 80, 160, 80, RED);
        }
    }

    /*
    Read Registers on MCUFRIEND UNO shield
    controllers either read as single 16-bit
    e.g. the ID is at readReg(0)
    or as a sequence of 8-bit values
    in special locations (first is dummy)

    reg(0x0000) 00 00  ID: ILI9320, ILI9325, ILI9335, ...
    reg(0x0004) 00 54 80 66 Manufacturer ID
    reg(0x0009) 00 00 61 00 00  Status Register
    reg(0x000A) 00 08 Get Power Mode
    reg(0x000C) 00 06 Get Pixel Format
    reg(0x0061) 00 00 RDID1 HX8347-G
    reg(0x0062) 00 00 RDID2 HX8347-G
    reg(0x0063) 00 00 RDID3 HX8347-G
    reg(0x0064) 00 00 RDID1 HX8347-A
    reg(0x0065) 00 00 RDID2 HX8347-A
    reg(0x0066) 00 00 RDID3 HX8347-A
    reg(0x0067) 00 00 RDID Himax HX8347-A
    reg(0x0070) 00 00 Panel Himax HX8347-A
    reg(0x00A1) 00 93 30 93 30  RD_DDB SSD1963
    reg(0x00B0) 00 00 RGB Interface Signal Control
    reg(0x00B4) 00 02 Inversion Control
    reg(0x00B6) 00 02 02 3B 3B  Display Control
    reg(0x00B7) 00 06 Entry Mode Set
    reg(0x00BF) 00 00 00 00 00 00 ILI9481, HX8357-B
    reg(0x00C0) 00 0E 0E 0E 0E 0E 0E 0E 0E  Panel Control
    reg(0x00C8) 00 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0  GAMMA
    reg(0x00CC) 00 03 Panel Control
    reg(0x00D0) 00 00 00  Power Control
    reg(0x00D2) 00 00 00 00 05  NVM Read
    reg(0x00D3) 00 00 94 88 ILI9341, ILI9488
    reg(0x00D4) 00 97 00 00 Novatek ID
    reg(0x00DA) 00 54 RDID1
    reg(0x00DB) 00 80 RDID2
    reg(0x00DC) 00 66 RDID3
    reg(0x00E0) 00 00 07 0C 05 13 09 36 AA 46 09 10 0D 1A 1E 0F GAMMA-P
    reg(0x00E1) 00 00 20 23 04 10 06 37 56 49 04 0C 0A 33 37 0F GAMMA-N
    reg(0x00EF) 00 00 00 00 00 00 ILI9327
    reg(0x00F2) 00 58 04 12 02 22 22 FF 0A 90 14 88 Adjust Control 2
    reg(0x00F6) 00 00 00 00 Interface Control

    -----

    TouchScreen.h GFX Calibration
    Making all control and bus pins INPUT_PULLUP
    Typical 30k Analog pullup with corresponding pin
    would read low when digital is written LOW
    e.g. reads ~25 for 300R X direction
    e.g. reads ~30 for 500R Y direction

    Testing : (A1, D7) = 23
    Testing : (A2, D6) = 34
    Diagnosing as:-
    XM,XP:  (A1, D7) = 23
    YP,YM:  (A2, D6) = 34
    ID = 0x9488

    cx=904 cy=951 cz=418 LEFT, TOP, Pressure
    cx=907 cy=584 cz=535 LEFT, MIDH, Pressure
    cx=910 cy=229 cz=504 LEFT, BOT, Pressure
    cx=554 cy=948 cz=608 MIDW, TOP, Pressure
    cx=563 cy=230 cz=674 MIDW, BOT, Pressure
    cx=228 cy=947 cz=946 RT, TOP, Pressure
    cx=228 cy=583 cz=1038 RT, MIDH, Pressure
    cx=225 cy=230 cz=929 RT, BOT, Pressure
    MCUFRIEND_kbv ID=0x9488  320 x 480

    const int XP=7,XM=A1,YP=A2,YM=6; //320x480 ID=0x9488
    const int TS_LEFT=929,TS_RT=204,TS_TOP=963,TS_BOT=213;
    PORTRAIT CALIBRATION     320 x 480
    x = map(p.x, LEFT=929, RT=204, 0, 320)
    y = map(p.y, TOP=963, BOT=213, 0, 480)
    Touch Pin Wiring XP=7 XM=A1 YP=A2 YM=6
    LANDSCAPE CALIBRATION    480 x 320
    x = map(p.y, LEFT=963, RT=213, 0, 480)
    y = map(p.x, TOP=204, BOT=929, 0, 320)
    */

body:
You sound very much the same as me when I got this screen, it took me a while,
 There is one of 'Dronebot's sessions on Youtube where he is connecting this screen which may get you started. I got drivers and information on lcdwiki.com with examples in the library folder.
I believe you get either a Uno to Mega version of this screen as the pinout is different for each, if you have the box for the screen, under the bar code it has the item description tell you which version you have.Uno or Mega.
On the lcdwiki site you'll find drivers for  both under the pics of each screen and for  of loads of  other screens LCD OLED and TFT's.
there is in the library folder when you download /install a fair few examples to have a play with and get the hang of this
DRONEBOT, and LCDWIKI sites have a fair bit of info and both worth a visit.
As of yet I can't get any of Adafruits examples going because of driver differences


body:
I am making a DIY gaming steering wheel and am stuck.
For measuring the rotation of the wheel, I'm using a sensor encoder timing disk, which is usually found in printers. - https://robu.in/product/photoelectric-speed-sensor-encoder-coded-disc-code-wheel.

A lot of tutorials on youtube use this.
But I just cannot seem to understand how to use this sensor.

Please help me in figuring this out: using this sensor, how to -

1. Measure how much the wheel rotated?

2. Know which direction did the wheel rotates in (clockwise, anti-clockwise).

PS: I tried using a rotatory encoder, but it is unable to sense rotation when rotated by a 1000 RPM motor. Would love to understand why.

Thanks!

title: How to detect the direction of rotation with a sensor encoder timing disk (photoelectric speed sensor)?

Answers: 1

body:
It seems to be a A/B coding : if A gets high before B, it's one way (count for exemple), and if B gets high before A, it's other way (decount).
So, connect power and ground. Then connect the two wires to input pins :
```Arduino
    int P_A=2; int P_B=3; //Inputs
    long int position = 0; //Position of wheel
    long int lastPosition = 0; //last position of wheel : for speed computing
```
Notice that one pin must be an hardware interrupt pin (Uno 2 an 3 are interrupt pins. Then attach interrupt in the stup :
```
    attachInterrupt(2, wheel, RISING);  //wheel is arbitray
```
Then create the interruption code :
```
    void wheel(){
        int sB = digitalRead(P_B);
        if (sA == sB)   { //Clockwise
        position++;
        }
        else   { //Counterclockwise
        position--;
        }
```
Then, in your loop, you can print position when it changes to read current position :
```
    if(lastPosition != position){
        Serial.println(position);
    }
```
i hope it will help...
Notice that if you use both interruptions, you get a better resolution, but speed limit is lower.


body:
I'm new programming arduino. I have connected an Adafruit thermal printer to an ESP8266 board.

I've the example code for use the board like a webserver that allow upload files. What i want is to upload a BMP file, convert it to an array of "uint8_t PROGMEM", and send the array to the printer in order the image would be printed.

Do you know any code i could use to convert the BMP file to "unint8_t PROGMEM"???. When i get the uploaded file it is an array of "unsigned char".

Thanks in advance.

title: 8266 get uint8_t PROGMEM array from uploaded file

Answers: 0


body:
**Architecture**

- MKRZero
- BME280 Atmospheric Sensor
- SSD1306 128x64 OLED Screen
- SparkFun GPS:
  - device: https://www.sparkfun.com/products/14414
  - arduino library: https://github.com/sparkfun/SparkFun_I2C_GPS_Arduino_Library
- K30 CO2 Sensor:
  - device: https://www.co2meter.com/products/k-30-co2-sensor-module
  - arduino library: https://github.com/FirstCypress/K30_CO2_I2C_Arduino

**System Setup**

[![Wiring Diagram][1]][1]

The system essentially just pulls measurements from these sensors every few seconds (adjustable), and writes them to Serial, to the OLED, and to an SD Card. Everything works fine and essentially forever when the K30 is not attached.

**"Random" system freezes happen only once I attach the K30...**

Once the K30 is attached to I2C, the system will run fine, recording and displaying data from all sensors (including the K30) for an indeterminate amount of time before "freezing." The every-so-often freeze happens during a call to my write_to_screen() function. The system will freeze during [the first wire->endTransmission() that is called in the screen library (see library here)][2]. Usually that while loop executes a few times, the screen updates, and the program continues, but not when it freezes.

**write_to_screen() Function**

> Screens are cycled using the blue button that increments the
> `screen_page` var.

 // display info on oled screen
 //
 // - many different displays available, cycled using button one
 //
 void write_to_screen() {
   Serial.println(F("  - writing to screen"));
   display.clearDisplay();
   display.setCursor(0,0);

   // default data display
   if(screen_page == 0) {
     display.setTextSize(2);
     // print co2
     display.print(F("CO2:"));
     display.println(co2);
     // resize text
     display.setTextSize(1);
     // print temp
     display.print(F("Temp: "));
     display.print(temperature_c);
     display.print(F("C "));
     display.print(temperature_f);
     display.println("F");
     // print humidity
     display.print(F("Humi: "));
     display.print(humidity);
     display.println(F("%"));
     // print pressure
     display.print(F("Pres: "));
     display.print(pressure);
     display.println(F(" hPa"));
     // print altitude
     display.print(F("Alti: "));
     display.print(gps.altitude.meters());
     display.println("m (GPS)"); // gps altitude is presumably more accurate/precise
     // print lat/lon
     display.print(F("LtLn: "));
     display.print(gps.location.lat());
     display.print(F(", "));
     display.println(gps.location.lng());
     // print time
     display.print("Time: ");
     display.print(gps_to_time());

   // k30
   } else if(screen_page == 1) {
     display.setTextSize(2);
     display.println(F("K30"));
     display.print(F("CO2:"));
     display.println(co2);
     display.setTextSize(1);
     display.println(F("\n\nAdd a time graph?"));

   // bme280
   } else if(screen_page == 2) {
     display.setTextSize(2);
     display.println(F("BME280"));
     display.setTextSize(1);
     // print temp
     display.print(F("Temp: "));
     display.print(temperature_c);
     display.print(F("C "));
     display.print(temperature_f);
     display.println(F("F" ));
     // print humidity
     display.print(F("Humi: "));
     display.print(humidity);
     display.println(F("%"));
     // print pressure
     display.print(F("Pres: "));
     display.print(pressure);
     display.println(F(" hPa"));
     // print pressure based Altitude
     display.print(F("Alti: "));
     display.print(altitude);
     display.println(F("m"));
     // print gps based altitude
     display.print(F("Alti: "));
     display.print(gps.altitude.meters());
     display.println(F("m (GPS)"));

   // gps
   } else if(screen_page == 3) {
     display.setTextSize(2);
     display.println(F("GPS"));
     display.setTextSize(1);
     if( is_gps_valid() ) {
       display.println(gps_to_datetime());
       // print sats
       display.print(F("Sats: "));
       display.print(gps.satellites.value());
       display.println(F(" (# of)"));
       // print lat/lon
       display.print(F("LtLn: "));
       display.print(gps.location.lat());
       display.print(F(", "));
       display.println(gps.location.lng());
       // print gps based altitude
       display.print(F("Alti: "));
       display.print(gps.altitude.meters());
       display.println(F("m"));
       // print pressure based altitude
       display.print(F("Alti: "));
       display.println(altitude);
       // print hdop
       display.print(F("HDOP: "));
       display.println(gps.hdop.value()/100.0);
     } else {
       display.println();
       display.println(F("Sats: 0 (NO SAT LOCK)"));
       display.println(F("LtLn:"));
       display.println(F("Alti:"));
       display.print(F("Alti: "));
       display.print(altitude);
       display.println(F("m (BME)"));
       display.println(F("HDOP:"));
     }

   // init statuses
   } else if(screen_page == 4) {
     display.setTextSize(1);
     display.print(F("Carbon Cutter "));
     display.print(ccversion);
     display.print(F("\nby Dan & Brian"));
     display.println(gps_to_datetime());

     // display init statuses
     // I2C and screen -- if we're reading data here, they are working
     //display.println("I2C Init:" + get_init_status(i2c_init) );
     //display.println("Screen Init:" + get_init_status(screen_init) );
     display.println(F("K30:    DEV"));
     display.print(F("BME280: "));
     display.println(get_init_status(bme280_init));
     display.print(F("GPS:    "));
     display.println(get_init_status(gps_init));
     display.print(F("SD:     "));
     display.println(get_init_status(sd_init));
     display.print(F("File:   "));
     display.println(get_init_status(file_init));
   }

   display.display();
   Serial.println(F("  - done writing to screen"));
 }

**Unplugging SDA Wire Unfreezes I2C**

I can unplug the K30's SDA wire and the system will resume, again, for some amount of time before it freezes again, when I can once again, unplug the K30 SDA wire and things will resume. Sometimes it will run for ten minutes. Other times for a few seconds/cycles. When it's running, data is pulling fine, and I2C seems to be working fine (I'm testing with a PicoScope). When I unplug the K30 SDA wire, the text on the screen updates and is garbled (sometimes wrong text in the wrong spot, and sometimes just messed up pixels) until I2C resumes working.

**System / I2C Working Fine**

[![System / I2C Working Fine][3]][3]

**System / I2C Frozen**

[![System / I2C Frozen][4]][4]

I've fixed 50 things in my code that I thought were the root cause here, but none of them have stopped this very specific freeze event. I thought it was a memory issue for a while. I chased that, and don't think that's the problem, but I'm not truthfully sure.

  [1]: https://i.stack.imgur.com/ijbRH.jpg
  [2]: https://github.com/adafruit/Adafruit_SSD1306/blob/master/Adafruit_SSD1306.cpp#L917
  [3]: https://i.stack.imgur.com/XVocV.png
  [4]: https://i.stack.imgur.com/wjDqE.png

title: I2C Hangs (sometimes) when Wire->endTransmission() is called

Answers: 0


body:
I have paired 2 BT modules HC-05 and HC-06. When I write something through Serial Monitor and send it from HC-05 to HC-06, everything works well. But when I send continuous data through loop, HC-06 receives only specific amount and then just stops! Is it because of BT module, or there is something else?
My code for HC-05:

    #include <SoftwareSerial.h>
    SoftwareSerial BTserial(2, 3);
    void setup()
    {
        Serial.begin(9600);
        BTserial.begin(38400);
    }

    void loop()
    {
            BTserial.write('1');
    }

Code for HC-06:

    #include <SoftwareSerial.h>
    SoftwareSerial BTSerial(2, 3);
    void setup()
    {
        Serial.begin(9600);
        BTSerial.begin(9600);
    }
    void loop()
    {
    if (BTSerial.available())
        Serial.write(BTSerial.read());
    }

Baud rates are good.
Thanks!

title: Problem with HC-06 receiving data

Answers: 1

body:
I think you have 2 problems:

- First about the shown sketch: I don't think, that the Baud rates are good. In your HC-05 code (the sender) you are using `BTserial.write('1');` without any delay or other code, thus this will run very fast, so the `SoftwareSerial` interface is almost completely busy. You sending almost at the maximum speed, that you can get with 38400 baud. On the receiving site you are using 9600 baud, which is significantly slower than 38400 baud. How should the HC-06 transmit all data, that it get's, to the Arduino, when you only use 9600 baud, but the data is coming with 38400 baud? That cannot work. You should configure the HC-05 and HC-06 to use the same baudrate, so that this cannot happen. Or - if you really don't want to - you can restrict the overall speed, that you are sending with, by just sending less data per time unit (sending the data slower, but on the same baudrate as before). This will prevent the HC-06 to get flooded by data. (Also there might be a limit on how fast you can send data over the HC-05, but I haven't tested this). All in all it mostly isn't a good idea, to do communication totally without any speed brake. That can get you into troubles, that you mostly don't want to think of.

- Secondly: In your comment you wrote, that you tried to change the baudrate, but that gave you garbled data. Since you didn't describe more, we cannot say much about this. But garbled data is a normal symptom for wrong baudrate. So it seems, that you haven't changed the baudrate successfully. I would suggest, that you again look into this and that you try to change the baudrate successfully. It is possible and there are many tutorials and codes on the web, that show how it is done. (When you again have problems with this, you can ask a question about this specific problem, including all the relevant information)