texts: non asssign variable using by for in loop() can remeber last value. what happen here?

texts:
I modify this code from my friend and it look strange.
void setup() {
    Serial.begin(115200);
    Serial.println("reset");
}
void loop() {
    for (int d; d <= 32767; d++) {
      Serial.println(d);
      delay (1000);
    }
}

for some reason when you press reset, the variable will keep counting from last value as shown.

this not gonna happen when you put these block in setup()
I know that not good idea to use varible in for loop without assigned the value, but I belived it must have a interesting reason for this.
For my hypothesis, the variable value just allocate with same address in memory. when this code run in setup() some how the complier detect this situation and assign 0 as initial value. but when in the loop() some how the compiler don't assign new value to the memory address and it get old value from last time the program was run before resetted. I still need further explanation.


texts:
I have a LG TV(LG 32SL800 ZB), which has a RS232-Port for Control and Service.

And I am wondering if I could control this port with my Arduino (NODE-MCU) and a module like this one RS232 Board?

How could I then control the TV? This is the Manual for the TV at page 124 there are the commands how to control it, but how can I send them?

My last question is, how long can the cables from the arduino to the module be? They have to be about 2-3m long! Is that possible without any other hardware?


texts: What happens, memory-wise, when I call a function from another function?

texts:
I'm inspecting where the memory is used in an application which runs on Arduino. To my surprise, there are several locations where 100 to 200 bytes are consumed by simply calling a function. Example:
void Dispatcher::processCommand() {
    ...
    displayMemory();
    this->process(this->instruction);
}

void Dispatcher::process(const Instruction &instruction) {
    displayMemory();
    if (instruction.length > 0) {
        ...
        return;
    }

    ErrorResponse::componentNotFound(instruction).output(this->serial);
    TerminationResponse(instruction.commandId, 0xFF).output(this->serial);
}

The first call to displayMemory() will report that there is 351 bytes left. The second one will tell that only 159 bytes remain (that is, 192 bytes less).
If I alter the body of the process function, the difference between the two memory reports vary. For instance, if I remove the two last lines, the difference drops from 192 bytes to 12 bytes.
I don't understand why this happens. I was thinking that between the moment I'm ready to call a function and a moment when the function starts, the memory should be used exclusively by the additional element in the call stack (the aforementioned 12 bytes maybe?) and the copying of the parameters passed by value (none here). Why is this not the case? What really happens under the hood?


texts:
I was playing around with an Adafruit Flora and a strip of NeoPixel LEDs.  After uploading the sketch to the Flora (via Arduino IDE), the LED strip lights for about 1 second and then dims to a dull orange color for all the lights.  When this orange color appears, it seems to indicate that the Flora has crashed.  If I unplug the Flora from power and plug it back in, the LEDs light again for about 1 second and then it crashes again.

The time between boot and crash is short enough that I can't upload a new sketch.

So how would I go about rescuing the Flora?
Is there a couple pins I can jumper to put it into bootloader mode?  Or some other way of resetting the Flora so as to remove the offending code?


texts: analogWrite(PIN, 1023)  digitalWrite(PIN, HIGH)

texts:
This question is very similar to this one.
I'm using an ESP8266 for which the maximum analogWrite value is 1023 rather than 255 for some other Arduino boards, but I believe the principal is just the same.
I'm driving 3 LEDs directly from 3 outputs via current limiting resistors.
When I turn them on using analogWrite(PIN, 1023) they are not quite a bright as when the same LED is driven by the same pin using digitalWrite(PIN, HIGH). Which leads me to think that either 1023 does not give a 100% duty cycle or the maximum voltage in the analog case is less than that in the digital one.
Is this to be expected? Are the pins significant (4,5 and 14)?
Another similar Q&A would lead me to believe they should be the same.


texts: Is there a way to set a time for instance 8.00 PM to make the arduino-uno start or stop at that time?


texts: Read from the SD card - ACMD41 times out

texts:
I'm trying to read from the SD card using an Arduino Pro Mini (3.3 V), Pololu micro-SD reader (the 3.3V one) over a SPI protocol.

I've tried both the SD library from Arduino SDK, and the Adafruit one.

Connections:

Arduino pin 10 -> CS,
pin 11 -> DI
pin 12 -> DO
pin 13 -> SCLK.

I've also connected VCC and GND of course.

This call (from the DumpFile example) fails:

// I've tried SD.begin(), SD.begin(10) as well.
if (!SD.begin(10, 11, 12, 13)) {
  // I can see this print statement in serial monitor.
  Serial.println("Card failed, or not present");
  return;
}

I've also tried manually setting pin 10 to OUTPUT, as well as to set it to HIGH.

Now, with the Adafruit SD library, I investigated this issue a bit more. It seems, that SD.begin() invokes the card.init(SPI_HALF_SPEED, csPin, mosi, miso, sck) (of the Sd2Card class).

I added print statements and discovered this exact piece fails:

while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) {
    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
     // This is being printed.
     // status_ is 1
     Serial.println("init err here!");
     Serial.println(status_);
     error(SD_CARD_ERROR_ACMD41);
      goto fail;
    }
}

I've prepared a card (2GB one) - it's FAT16 formatted, and contains one partition. On this partition there's a single file ony, named "a.txt".

EDIT: After trying another SD card, I got some progress. Now, the following call fails:

volume.init(card) // in SD.cpp

After digging in, I discovered that this invokes the cacheRawBlock(volumeStartBlock, CACHE_FOR_READ), which invokes sdCard_->readBlock(blockNumber, cacheBuffer_.data) and then Sd2Card::readData(block, offset, count, dst).

In readData(), the following fails:

if (!inBlock_ || block != block_ || offset < offset_) {
    block_ = block;
    // use address if not SDHC card
    if (type()!= SD_CARD_TYPE_SDHC) block <<= 9;
    if (cardCommand(CMD17, block)) {
      // ****************************
      // FAIL IS HERE - cardCommand(CMD17, block) fails.
      // ****************************
      error(SD_CARD_ERROR_CMD17);
      Serial.println("SD_CARD_ERROR_CMD17");
      goto fail;
    }
    if (!waitStartBlock()) {
      goto fail;
    }
    offset_ = 0;
    inBlock_ = 1;
}

What the issue can possibly be?


texts: Need to turn on project twice in order for screen to work!

texts:
This problem is really stumping me. I made a simple printed circuit board with an ATtiny85, a 128x64 I2C OLED display, and a Sharp IR analog distance sensor. You can view the circuit here: circuits.io.

If I turn the system on using the simple 3-pin slide switch that I put on the board, the screen does not turn on. I can see that the system is powered though, because I can see a little bit of red light escaping from the IR sensor where some of the IR light borders on the visible end of the spectrum. If I turn the board off then immediately turn it back on, the display powers up just fine. If I upload a new program to the board and use the programmer's 3.3v power I don't need to do it twice - the screen works first time.

I'm using a 3.7v LiPo battery, so I know power is not an issue (everything is 3-5v tolerant, and the LiPo battery can deliver plenty of current). Why do I need to turn it on twice in order for the screen to work? Thanks!


texts: Arduino Ethernet Client crashes after obtaining values from string

texts:
My Ethernet server keeps crashing after pulling the RGB values from the string. It remains connected if I'm just toggling a pin, but whenever the string has the rgb values in it, the RGB values are pulled, the LED changes but then the server crashes and won't take any more requests. Do I need to restart the server after it plucks the RGB values for another read? If so, how would I go about doing this?

Thanks, James :)

Example HTTP request that causes the crash: /?LED=B233+G011+R133&t=T HTTP/1.1

    #include <SPI.h>
    #include <Ethernet.h>
    #include <string.h>

    byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    byte ip[] = {192, 168, 0, 102 };
    byte gateway[] = {192, 168, 0, 1 };
    byte subnet[] = {255, 255, 255, 0 };
    EthernetServer server(84);
    ;

    char* redstring={0};
    String blue1;
    String green1;
    String red1;
    String testString = "0123456789";

    int blue;
    int green;
    int red;
    int been=0;
    int b=0;
    int g=0;
    int r=0;
    //////////////////////

    void setup(){

    pinMode(11, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(6, OUTPUT);

    //start Ethernet
    Ethernet.begin(mac, ip, gateway, subnet);
    server.begin();

    //enable serial data print
    Serial.begin(9600);
    Serial.println("SERVER RUNNING HTTP / GET");
    }

    void loop(){
     ////////////////////////////////////////
     EthernetClient client = server.available();
if (client) {
while (client.connected()) {
  if (client.available()) {
    char c = client.read();

    //read char by char HTTP request
    if (sizeof(redstring) < 100) {

      //store characters to string
      redstring += c;
      //Serial.print(c);
    }

    //if HTTP request has ended
    if (c == '\n') {

      ///////////////////////////////////////////

      Serial.println(redstring);

      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println();
      client.println("");
      client.println("<link rel=\"shortcut icon\" href=\"data:image/x-icon;,\" type=\"image/x-icon\">");
      client.println("");
      client.println("<TITLE>Arduino GET</TITLE>");
      client.println("");
      client.println("");

      client.println("
HTML GET
");
      //change ip back if not local
      client.println("<FORM ACTION=\"http://192.168.0.102:84\" method=get >");

      client.println("JQUERY: <INPUT TYPE=TEXT NAME=\"LED\" VALUE=\"\" SIZE=\"25\" MAXLENGTH=\"50\">
");

      client.println("<INPUT TYPE=SUBMIT NAME=\"t\" VALUE=\"T\">");

      client.println("</FORM>");

      client.println("
");

      client.println("");
      client.println("");

      delay(1);
      //stopping client
      client.stop();
      /////////////////////
      //readString = Character.toUpperCase(readString);
      for (int i = 1; i < sizeof(redstring); i++) {
        if (strchr(redstring, 'B') && && redstring[i+1] > -1) {
          blue=redstring[i+1, i+4];
          analogWrite(11, blue);
          delay(1000);
                      }

        if (strchr(redstring, 'G') && redstring[i+1] > -1) {
          green=redstring[i+1, i+4];
          analogWrite(9, green);
          delay(1000);
                      }

        if (strchr(redstring, 'R')&& redstring[i+1] > -1) {
          red=redstring[i+1, i+4];
          analogWrite(7, red);
          delay(1000);
                      }

      }

      //clearing string for next read
           redstring="";
          (redstring, "0", sizeof(redstring));
        }
      }
    }
  }
}


texts:
I've just installed the last version of Arduino 1.6.7 plug my Arduino SmartEverything (http://www.smarteverything.it/) to OS X 10.11.2, try to compile this project: https://github.com/nicolsc/sigfox-weather-station/blob/master/sigfox_smart_weather.ino But i got this error

/Applications/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware "/Applications/Arduino.app/Contents/Java/hardware" -hardware "/Users/nunito/Library/Arduino15/packages" -tools "/Applications/Arduino.app/Contents/Java/tools-builder" -tools "/Applications/Arduino.app/Contents/Java/hardware/tools/avr" -tools "/Users/nunito/Library/Arduino15/packages" -built-in-libraries "/Applications/Arduino.app/Contents/Java/libraries" -libraries "/Users/nunito/Documents/Arduino/libraries" -fqbn=AMEL:samd:AMEL_SmartEverything_native -vid-pid=0X2341_0XE002 -ide-version=10607 -build-path "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/arduino_50d3a89dbbfb2b67c903ba23d4913431/sketch_jan21c.ino"
/Applications/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware "/Applications/Arduino.app/Contents/Java/hardware" -hardware "/Users/nunito/Library/Arduino15/packages" -tools "/Applications/Arduino.app/Contents/Java/tools-builder" -tools "/Applications/Arduino.app/Contents/Java/hardware/tools/avr" -tools "/Users/nunito/Library/Arduino15/packages" -built-in-libraries "/Applications/Arduino.app/Contents/Java/libraries" -libraries "/Users/nunito/Documents/Arduino/libraries" -fqbn=AMEL:samd:AMEL_SmartEverything_native -vid-pid=0X2341_0XE002 -ide-version=10607 -build-path "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/arduino_50d3a89dbbfb2b67c903ba23d4913431/sketch_jan21c.ino"
Build options changed, rebuilding all
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/dev/null"
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/dev/null"
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/preproc/ctags_target_for_gcc_minus_e.cpp"
exec: "-w": executable file not found in $PATH
Error compiling.


texts:
Im getting this error:

iotHook.ino: In function 'void setup()':
iotHook:13: error: request for member 'begin' in 'esp', which is of non-class type 'Esp8266()'
request for member 'begin' in 'esp', which is of non-class type 'Esp8266()'

When I try to lunch my begin function of my class:

class Esp8266 {

  public:
    Esp8266();
    void begin(HardwareSerial *wifiCom, HardwareSerial *debugCom);
    ...
  private:

    HardwareSerial *wifiCom;
    HardwareSerial *debugCom;
    ...

}

Esp8266::Esp8266() {
}

void Esp8266::begin(HardwareSerial *wifiCom, HardwareSerial *debugCom) {
  this->wifiCom = wifiCom;
  this->debugCom = debugCom;

  this->debugCom->begin(115200);
  while (!this->debugCom) {
  ;
  }
}

EDIT 1:
Updated image with new code

Why is not picking up the begin function?


texts:
I have a project where I use a software serial connection to read serial data from a barcode scanner.

All is good. However from time to time I have some problems with the data that I'm receiving.

  You said : 123456789��?�: @���?���?���?���?���?

  You said : 123456789

  You said : 123456789123456

  You said : 987654321789456123

My code is something similar to the one below

int count = 0;
void parseSerial() {
  char ser[20];
  while (Serial.available() > 0) {
    char c = Serial.read();
    if ( c != '\r' && count <= sizeof(ser)) {
      ser[count] = c;
      count++;
    } else {
      Serial.print("You said : ");
      Serial.println(ser);
      for(int i=0; i < sizeof(ser); i++) {
        ser[i] = '\0';
      }
      count = 0;
    }
  }
}

Any idea on how I can get rid of "��?�: @���?���?���?���?���?"?

Thanks.


texts: Arduino components for smartening my current doorbell

texts:
I would like to modernize my current (dumb) doorbell with arduino but as this is my first project, I need some advice on what I need to accomplish this :)

So, currently I own only Raspberry Pi 3 and I plan on using openHAB on it. My current doorbell is actually an intercom so it has two different bells (one for the call and second for the bell), it has a door opener button and thats about it. My intention is to be able to mute both bells (every bell its own switch), be able to receive some kind of notification (sms/email/whatever) in case  the bell event happens, and finally, to be able to simulate a door open button via mobile.

As my RasberryPi is dislocated from the location of the intercom where this project should be placed, I would need to have some kind of wireless communication (do I need a wifi that should be connected to my router or I could be using some other kind of wireless connection [radio, bluetooth]?).

What would you reccomend for this project (components should be as small as possible and its resources should only be sufficient for this purpose).


texts: How do I connect a PS4 controller connected to an Arduino that's connected to a laptop to another Arduino?

texts:
My high school is entering an ROV competition and for next year's competition we want to try and set it up so that we can control it using a PS4 controller. I have done research and found this shield for Arduino and this library that allows you to connect it to an Arduino. I plan to then connect the Arduino to a computer via USB and then send each button press to a Processing program via serial. Would it then be possible to send this from Processing to another Arduino out of the laptop? I'm just wondering how feasible this project is.

We initially had just a single Arduino at the top with the Ethernet shield and took inputs from standard joystick potentiometers. We want to add in using the PS4 controller this year for easier control. We found the USB Host Shield that gives us that capability, but uses the same pins as the Ethernet shield. So we added another Arduino, connecting the laptop as the bridge also allows to have a GUI. The Ethernet is wired, by the way. We need the laptop, it's not just for a bridge.


texts: How to store 1 bit Boolean data into EEPROM and retrieve this 1 bit data?

texts:
I am building a project where I have to store the digital state which is Boolean (either HIGH or LOW) of each I/O port such that after power off the state of I/O ports store in EEPROM and I can retrieve this I/O port's state after power on.

This is my code..

    #include <IRremote.h>
    #include <EEPROM.h>
    int EEPROMaddress = 0;
    int EEPROMaddress1 = 1;
    byte EEPROMbyte = EEPROM.read(EEPROMaddress);
    byte EEPROMbyte1 = EEPROM.read(EEPROMaddress1);
    int RECV_PIN = 11;
    int led = 10;//1FE50AF
    int led1 = 9;//1FED827
    boolean previousState = bitRead(EEPROM.read(EEPROMaddress), led);
    boolean previousState1 = bitRead(EEPROM.read(EEPROMaddress1), led1);
    boolean state;
    boolean state1;
    IRrecv irrecv(RECV_PIN);
    decode_results results;
    void setup()
    {
      Serial.begin(9600);
      pinMode(10,OUTPUT);
      pinMode(9,OUTPUT);
      irrecv.enableIRIn();
    }
    void loop() {
      if (irrecv.decode(&results))
      {
        Serial.println(results.value, HEX);
        switch(results.value)
        {
           case 0x1FE50AF:
           if (previousState == LOW)
           {state = HIGH;
            digitalWrite(led,state);
           previousState=state;
           bitWrite(EEPROMbyte,led,state);
           EEPROM.update(EEPROMaddress,EEPROMbyte);
           delay(50);}
           else
           {state=LOW;
           digitalWrite(led,state);
           previousState=state;
           bitWrite(EEPROMbyte,led, state);
           EEPROM.update(EEPROMaddress,EEPROMbyte);
           delay(50);
           }
           break;
            case 0x1FED827:
           if (previousState1 == LOW)
           {state1=HIGH;
           digitalWrite(led1,state1);
           previousState1=state1;
           bitWrite(EEPROMbyte1,led1, state1);
           delay(50);}
           else
           {state1=LOW;
           digitalWrite(led1,state1);
           previousState1=state1;
           bitWrite(EEPROMbyte1,led1,state1);
           delay(50);}
           break;
}
        irrecv.resume();
      }
}


texts: MQTT bridging with Arduino and ESP8266 - What software should I use?

texts:
Sorry for the vagueness in my question, I am just looking for ideas to point me in the correct direction please...

I wish to connect many (read: 20+) different sensors to a local wifi network and have them all datalogged and controlled by a single server on the network. Pretty standard stuff for the home automation people etc. Some sensors are connected to esp8266 boards directly, others communicate via serial and will employ an 8266 to provide wifi.

I am having trouble deciding which direction to go or which software / firmware to combine since its changing rapidly and a fair number of tutorials are around but all have different approaches and end goals.

This must be entirely contained offline - I have a raspberry pi, a wireless router, and the various sensors (mostly arduino based).

Now from research it would seem I need to setup a serial to MQTT 'bridge' - and have the esps 'talk' to the pi by MQTT. And that the pi should be running 'mosquitto' if I wish the MQTT to be bi-directional (i.e. I can receive serial data AND send serial commands. I have never dealt with MQTT so I am trying to learn as I go.

I have been working for a time with 'ESP-Link' software and had success using it as a simple serial to tcp-ip bridge and using virtual serial ports to communicate with the attached device. However using virtual serial ports on the server is clunky, unreliable and not what I wish to do - does anyone know if it can be setup so I can send 'raw' serial messages over TCP to the server for use? And from the server to control the connected devices? Or if there is an easier way? I cannot modify all of the serial devices I wish to connect, so just want to get the data out/in and have it manipulated by the server where necessary.

In essence I wish to end up with several sensors all connected to the router, and logged / controlled through a web interface hosted on the PI, all 'offline' and contained. Eventually I would like the server to be able to recognize what devices it can 'see' automatically, however at this moment I simply wish to gain insight into how I can most easily achieve this? Or even if I am completely mistaken in my approach?

Thanks


texts: How to upload code to an Arduino Uno using HC08 Bluetooth module

texts:
How do you upload code to an Uno from a Mac using the HC08 Bluetooth module? I know I need to use this wiring.

Anyone know?


texts: Chip sync error while updating ATfirmware in esp8266

texts:
I find trouble updating my firmware with esp8266 with following error message.

[espDownloader.py][line:351][ERROR]: Chip sync error: Failed to connect to ESP8266: Timed out waiting for packet header
[2019-06-04 07:53:16,009][ESP8266Loader_spi[1]][espDownloader.py][line:439][ERROR]: ESP8266 Chip sync error esp_sync_blocking.

I am unable to resolve even after a number of attempts.
Please help me resolve my issue. Thank you in advance.


texts: Using two digits to display a number using TM1637 and a 4-digit display

texts:
I decided to build a digital clock using a 4-Digit Display (TM1637) from Grove.

For that, I have been using the DigitalTube library by Grove for the TM1637 controller.

My idea is to use the two first digits of the display (left to right) to display the hour and the two last digits to display the minutes. However, managing displays is difficult and all the libraries I have found for the previously mentioned controlled can only display one number per digit.

Here you have an example:
Using tm1637.display(1,2);, lets you display a "2" in the second digit (L to R), using tm1637.display(0,3); lets you display a 3 on the firt digit and etc.

As I said, I want to display the hour on the first two digits and the minutes in the two last digits.
I've have readed all the examples coming with the DigitalTube library but nothing was useful.

Note: I'm using the DS3231 for managing the time with a RTC.

I don't know if you undestand my question. If not, let me know please.
Arduino UNO R3.


texts:
i just started using Arduino IDE for my XMC1100XMC2Go. Information about the microcontroller can be found here: https://github.com/Infineon/XMC-for-Arduino/wiki/XMC-2Go
I now started with my first codes and want to print things on the serial monitor with this code:
*/
/* For on board LEDs */
#include <LED.h>

/* Create an LED object */
LED Led;

//#define SERIAL_DEBUG 1

int p_LED = 5;
int p_Button = 4;
int i_stateButton = 0;

void setup()
{
  Led.Add(LED1);            // Configure the LEDs
  Led.Add(LED2);
  pinMode(p_LED, OUTPUT);
  pinMode(p_Button, INPUT);

  // Set default state of LEDs
  Led.On(LED2);
  Led.Off(LED1);

  digitalWrite(p_LED, LOW);
  Serial.print("Hello World!");

  Serial.begin(9600);
}

void loop()
{
  Serial.write("Hello World!");
  Serial.println(i_stateButton);
  delay(200);
  Led.Toggle (LED2);
  Led.Toggle(LED1);

  i_stateButton = digitalRead(p_Button);
  //digitalToggle(p_LED);
  digitalWrite(p_LED, i_stateButton);
}

I checked under tools that SerialOutput is set to PC (https://github.com/Infineon/XMC-for-Arduino/blob/master/variants/XMC1100/config/XMC1100_XMC2GO/pins_arduino.h#L54)
There are two Ports, COM1 and COM3. I can send new sketches to the microcontroller using COM3. I checked my Serial Monitor and it is set to COM3, too.
Baudrate is for both the same (code and monitor)
Now that i send the above sketch to the microcontroller it stops working. one LED is on and the other is off. But they do no longer change the state. Nothing appears on the monitor.
When i remove the both lines Serial.write("Hello World!");  Serial.println(i_stateButton); and send the sketch, the LEDs start flashing again.
I'm pretty sure it's a kind of configuration problem, but i cannot find out what it is. Does anyone have an idea?


texts: Arduino SIM5320e HTTP GET request to 000webhost.com

texts:
Im having trouble getting a successful HTTP GET request to a domain under 000webhost.com

I am trying to do a GET request which sends data to a php file on my domain and save it to MySQL database. I also did this first on my browser and it works fine so I don't think there are problem in my php file.

MY DOMAIN: wastedb.000webhostapp.com

But if I try to send a request to dweet.io, it works as expected.

I am using a modified version of Adafruit_FONA library and will post the code snippet and response from serial monitor below.

Here are the parameters that I used for the WORKING GET request:

Host Address: www.dweet.io

Host: dweet.io

Response from Serial monitor for dweet.io (working):

---> AT+CHTTPSSTART
<--- OK
---> AT+CHTTPSOPSE="www.dweet.io",80,1
<--- OK
---> AT+CHTTPSSEND=64
<--- >
---> GET /dweet/for/gearhead?hello=world HTTP/1.1
Host: dweet.io

<--- OK
---> AT+CHTTPSSEND
<--- OK
<--- +CHTTPSSEND: 0
---> AT+CHTTPSRECV?
<--- +CHTTPSRECV: LEN,361
---> AT+CHTTPSRECV=361
<--- OK
+CHTTPSRECV: DATA,361
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Date: Wed, 30 Jan 2019 00:16:43 GMT
Connection: keep-alive
Content-Length: 196

{"this":"succeeded","by":"dweeting","the":"dweet","with":{"thing
---> AT+CHTTPSCLSE
<--- OK
---> AT+CHTTPSSTOP
<--- OK

As we can see, the Arduino received a JSON response from the website.

Here are the parameters that I used for the NOT WORKING GET request:

Host Address: wastedb.000webhostapp.com

Host: wastedb.000webhostapp.com

Response from Serial monitor for wastedb.000webhostapp.com (NOT WORKING):

---> AT+CHTTPSSTART
<--- OK
---> AT+CHTTPSOPSE="wastedb.000webhostapp.com",80,1
<--- OK
---> AT+CHTTPSSEND=113
<--- >
---> GET /wastedb/get_location.php?lat=14.640155&lon=120.974920&stat=LOW HTTP/1.1
Host: wastedb.000webhostapp.com

<--- OK
---> AT+CHTTPSSEND
<--- ERROR

Am I missing something here? Seems like the shield cannot find the Host Server I provided for my website.

EDIT: It is working now. The only solution that worked for me is to find another hosting site.


texts: How to declare char array[] using integers?

texts:
Can anyone please tell me how to declare a char variable using a few integers?
I need to declare a byte information for shiftOut() function as char.
int a = 0;
int b = 1;
int c = 0;
int d = 1;
int e = 1;
int f = 0;
int e = 0;
int f = 1;

char information[] = {"B" + a + b + c + d + e + f};

void setup() {
  Serial.println(information);
}

void loop() {
  shiftOut(pin, pin, MSBFIRST, information);
}

In command Serial.println(information); I want to get back B01011001
Now the output I am getting ⸮⸮
Of course the simpliest way to create that will be:
char information[] = "B01011001";
But I need to change the individual bits in int bit = variable.
Please note that substition int bit = with char bit = is unable for my code, using int of value of individual bits is necessarily. Because I am using my project with blynk, and there is function a = param.asInt(); ,  param.asChar(); does not exist.
How to do that?
Thank you for responses!


texts: How to set PC (Program Counter) register to another function (for scheduler)

texts:
I am trying to implement a scheduler for Arduino Mega 2560. I think I lack understanding of how to set the PC register to another instruction.
Here is my simple approach so far:

void dummy(){
    digitalWrite(LED_BUILTIN, HIGH);
 }

in a naked ISR method:

SP = (uint16_t)(&dummy)
__asm volatile(
"reti     \n\t"
)

However it is not working. How should the PC register be set to a certain function or to where it was in a previous process for a scheduler approach?


texts:
Code:

int motorPin = 9;  // the pin the motor is connected to

void setup()
{
 pinMode(motorPin, OUTPUT);
}

void loop()
{
 motorOnThenOff(); //motorAcceleration
}

void motorOnThenOff(){
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for
  int offTime = 1000; //the number of milliseconds for the motor to turn off for

  digitalWrite(motorPin, HIGH); // turns the motor On
  delay(onTime);                // waits for onTime milliseconds
  digitalWrite(motorPin, LOW);  // turns the motor Off
  delay(offTime);               // waits for offTime milliseconds
}

void motorOnThenOffWithSpeed(){

  int onSpeed = 200;  // a number between 0 (stopped) and 255 (full speed)
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for

  int offSpeed = 50;  // a number between 0 (stopped) and 255 (full speed)
  int offTime = 1000; //the number of milliseconds for the motor to turn off for

  analogWrite(motorPin, onSpeed);   // turns the motor On
  delay(onTime);                    // waits for onTime milliseconds
  analogWrite(motorPin, offSpeed);  // turns the motor Off
  delay(offTime);                   // waits for offTime milliseconds
}

void motorAcceleration(){
  int delayTime = 50; //milliseconds between each speed step

  //Accelerates the motor
  for(int i = 0; i < 256; i++){ //goes through each speed from 0 to 255
    analogWrite(motorPin, i);   //sets the new speed
    delay(delayTime);           // waits for delayTime milliseconds
  }

  //Decelerates the motor
  for(int i = 255; i >= 0; i--){ //goes through each speed from 255 to 0
    analogWrite(motorPin, i);   //sets the new speed
    delay(delayTime);           // waits for delayTime milliseconds
  }
}

This code spins the motor. In the circuit, I have a button which I want to toggle the spinning of the motor.

This is the circuit:

https://circuits.io/circuits/4267039-spin-motor-spin/edit

How would I make it so that the button toggles the spinning of the motor? like a fan and its switch?


texts: Using Arduino UNO to retrieve ATMega328P-PU chip signature

texts:
Good day.

I have successfully built and tested an Arduino-on-breadboard about 2 days ago.

The device is rather straight forward, I have added a voltage divider and an LED to indicate power.

The schematics are as follows:

And this is a picture of the actual board:

I am using an ATMega328P-PU as a Microcontroller chip.

I uploaded quite a few sketches on the board and all seemed to work well. I was trying to upload a sketch yesterday but I got:
 "avrdude: Yikes! invalid device signature".

I rebooted the computer, rebuilt the entire board again, and tried once again to load a sketch using Arduino as ISP. The message changed again to:

avrdude: Expected signature for ATmega328P is 1E 95 0F
         Double check chip, or use -F to override this check.
Wrong microcontroller found.  Did you select the right board from the Tools > Board menu?

I did a search online and I have found many forums suggesting that I change the avrdude.conf file parameters to different signatures "Although these are mainly targeted at people using ATMega328-PU, not ATMega328P-PU" but this also did not help.

I tried burning the bootloader again but I still get the same error message.

I tried to find a way to "retrieve" the chip signature, but I didn't.

I know that there is a chance that I have bricked the chip somehow, but how do I know for sure? and is there anyway that one can use and Arduino as a tool to retrieve the chip signature or verify if the chip itself is dead?

Thank You


texts: Is it possible that a 12V transformer is creating EM interference that's coupling onto a long antenna cable?

texts:
I have an Arduino Mega, Adafruit RFM96W 433MHz LoRa Transceiver Breakout and 2 Channel OptoCoupler Relay Module.
https://www.adafruit.com/product/3073
https://www.amazon.co.uk/SUNFOUNDER-2-Channel-Optocoupler-Expansion-Raspberry/dp/B00E0NTPP4
The Arduino Mega runs a sketch that waits for the press of a button and then:
If Button A:
Switches on a 12V pump connected to the Relay for 30 seconds
Then sends a radio message (using RH-RF94 library) to another device
If Button B:
Sends a radio message (using RH-RF94 library) to another device
https://github.com/kenbiba/RH-RF95
The Ardunio is being powered by the USB connector.
The Relay Board has it's own 5V supply and is connected to the arduino by a digital line (for the pump) and the Vcc to Arduino 5V
I don't use the Arduino Vcc to power the relay board, it has it's own 5V supply into JDVcc (see below) schematic of the relay board:

There is a 12V power supply in the COM terminal, then the +ve lead of the pump is in NO.
The problem:
When the 12V power supply is connected to the COM terminal the Arduino will freeze when trying to send a radio message (send) - even if the pump has not been activated and there is no 12V current flowing.
I have only seen this happen when I have an antenna on an extension wire connected to the LoRa transceiver. If there is no antenna, or a very short antenna with no extension wire I do not see this problem.
An antenna on a extension wire works no problem if I unplug the 12V supply from the relay board - even if the transformer is left plugged in within the project enclosure.
I am very confused by this.
Initially, I suspected there was some sort of power surge going on when the pump started (big motor) but I see this problem even if the pump never runs, all it takes is the 12V power supply be applied to the relay.
Is it possible that the 12V transformer is creating EM interference that's coupling onto a long antenna cable?
Thanks for any help.


texts: Using 433 MHz transmitter and receiver pair on a single Arduino Mega 2560

texts:
Folks,
Is there a method available to set the 433 MHz transmitter to keep sending a message and the receiver to receive the message on the same Arduino Mega 2560?
I saw an answer elsewhere with the following as the "solution":
RH_ASK driver(2400, 8, 50, 50, false);
If someone knows a solution, please provide the complete sketch (for both transmitter & receiver)?


texts:
So, I am an Engineer working on a very time tight project.

I want to create a system capable of collecting data from a Photodiode and compiling it in a way that will separate data into four columns which correspond to colours (red, green, blue, yellow) the columns will have rows of data corresponding to a number.

I have elected to use Arduino for this project but need some help on what to get and whether this is possible or not... I have an intermediate knowledge of C, C++ and previous Arduino experience, but have never undertaken something like this.

The project is envisaged to look like this.

Hardware:

Photodiode with RS232-C connection
An Arduino (Which sort is best? now I have Uno and Mega but can purchase others should these not be sufficient for the project)
Touchscreen Interface
Storage capacity (SD card or email/Bluetooth capability or something alike to collect the data to edit on PC).

The Process should is like this: Input = User interacting with GUI on Touchscreen - First page will have Four Colours Available (Once one of these inputs selected let’s say Red, jump to next page) -> Page two will have a Touch Number Pad Input (User selects number, let's say 2 in this case and hits enter), For less complexity this could be on one page correct? ->
The Data will then be read off a Photodiode communicating via RS232-C to Arduino and stored in a .csv or something similar under its previously selected values (Red, 2, Photodiode Value)

Output: A compiled list of all the data collected under their relative user inputs.

I currently have these items but am happy to purchase others.

S130C Thorlabs Photodiode Sensor
Null Modem Cable (Pins are swapped on S130C)
RS232 Shield (DFRobot RS232 Shield V0.1)
Arduino Uno, Arduino Mega
TouchScreen (Duinotech 2.8” TFT LCD)

After re-reading what I wrote I suppose there are a few:

Could I complete this project using Uno and Mega?
Is there a method for compiling data and storing/sending using Arduino?
What are the capabilities of Arduino? Could a project of this complexity be done using Arduino components or is there another microprocessor or microcomputer which would be a better choice for this project?


texts: Why Ethernet webclient fails to initiate?

texts:
I use the Ethernet shield with an Uno and create a web client. If I put a delay like one second for initialization it works fine. However if I wait for it in a while loop (like waiting for the serial, and as mentioned in Arduino docs) it never gets out of the loop that means the client instance is null.

I found this method on Arduino website in an example code:

while(!client) { ; } // waiting to get ready

Here's the code; if I uncomment it will stay there. Also the same with providing the MAC argument only.

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE };
char server[] = "www.google.com";    // name address for Google (using DNS)

IPAddress ip(192, 168, 1, 213);

EthernetClient client;

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

  Ethernet.begin(mac, ip);
  delay(1000);
  //while(!client){ ; }
  Serial.println(Ethernet.localIP());
}


texts:
I am using ESP01 as a microcontroller that retrieves information from Firebase and sends them over serial to an Arduino Uno for other uses. I am not using NODEMcu since it has few analog pins and ESP01 is the only option available for me at this time.
Can the GPIO 0 and GPIO 2 pins available in the ESP01 be used as a serial communication pins when defined with SoftwareSerial library?
I want to keep the serial from the existing TX and RX for debugging and testing.


texts:
I want to make a gesture controlled car using this IMU.. What is the simplest way to detect tilts? I've seen many programs on the Internet that calculate the angles but is this really necessary?
Why can't we just get components of acceleration in the x, y plane and then detect tilts..Pls tell me how to do this!


texts:
I tried to run a sketch that tests my AVR's interrupts,
I have an UNoriginal Arduino Uno, and I've checked pins 2 and 3 like the following:

- at void setup()
attachInterrupt(2, inter, CHANGE);
- at void inter()
Serial.println("Interrupt pin 2");

I did the same on pin 3, I checked them by attaching the pins to a button with a Pull-Up,
When I click the button it goes from HIGH to LOW.
But yet, the arduino doesn't run the 'inter'.
Is it possible that because my Arduino is not original it won't work?
And this type of interrupts are software not hardware right?


texts: using esp8266 feather to burn bootloader on redboard

texts:
Is it possible to burn the bootloader of an arduino redboard using an esp8266 feather? whenever i connect my redboard to my pc the ports list on the ide would just be greyed out. I've looked around online and tried everything I found except burning the bootloader since I didnt have a spare arduino, atmega or a programmer. I have an EPS8266 feather though.

If anyone know whether or not this is possible to do and could walk me through on how to do it if it was.


texts: I am trying to make a mesh network of three nrf24l01 nodes in which all three are transceivers, such that all three are in a line. The modification I want to make is that if two end nodes are not able to communicate with each other as they fall short of range the signal must be sent via the middle node. How should I approach?


texts:
I'm using an Arduino clone (Seeeduino Lotus) together with a Shinyei PPD42NS sensor to measure air quality. The sensor reports its measurement as Low-Pulse occupancy. What would be the best way how to collect the value with Arduino? Currently I'm simply looping for some predefined duration using pulseIn:

unsigned long starttime;
register unsigned long sample_time; // ms
register unsigned long lowpulseoccupancy = 0; // us

// Wait for the signal to return to HIGH
pulseIn(DUSTPIN, LOW);
// Now start measuring
starttime = millis();
while ((sample_time = (millis() - starttime)) < DUST_SAMPLE_TIME_MS) {
    lowpulseoccupancy += pulseIn(DUSTPIN, LOW);
}

ratio_pct = lowpulseoccupancy / (sample_time * 10.0);

Is there a better way? In particular, this tight loop prevents Arduino from doing anything else for 30s (or a similar period).

I was thinking about using interrupts, either triggering on CHANGE, or (if that's possible) having two functions, one triggering on RISING and another on FALLING. Are there any caveats when doing so?


texts: Adafruit_GFX setRotation not working when called from within a class

texts:
Using an ILI9341. I'm trying to set the rotation from within a class, but it's not working.  The code is very straight forward.

If I rotate in the class, the setRotation code does not work but the text is still printed. The pointer is set properly and the text is still printed, it just doesn't get rotated.

Outside of the class, the rotation works fine.

Any help would be greatly appreciated!

#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"

#define TFT_DC 5
#define TFT_CS 3

Adafruit_ILI9341 *tft;
uint8_t newRotationAngle = 0;

void drawStuff() {
    tft->setTextColor(map(rand(), 0, RAND_MAX, 0, 0xffff));
    tft->fillRect(0, 0, tft->width(), tft->height(), ILI9341_BLACK);
    tft->setCursor(0, 0);

    tft->print(F("01234567890"));
    delay(250);
}

class test {
public:
    void init(Adafruit_GFX *_p) { ptrTft = _p; };

    void inClassRotation(int newRotation) {
        ptrTft->setRotation(newRotation);
        drawStuffInClass();
    };

    void drawStuffInClass() {
        ptrTft->setTextColor(map(rand(), 0, RAND_MAX, 0, 0xffff));
        ptrTft->fillRect(0, 0, ptrTft->width(), ptrTft->height(), ILI9341_BLACK);
        ptrTft->setCursor(0, 0);

        ptrTft->print(F("01234567890"));
        delay(250);
    }

    Adafruit_GFX *ptrTft;
};

test instance;

void setup() {
    tft = new Adafruit_ILI9341(TFT_CS, TFT_DC);

    tft->begin();
    tft->setTextSize(2);

    instance.init(tft);
}

void outsideClassRotation(Adafruit_GFX *passed) {
    passed->setRotation(newRotationAngle);
    drawStuff();
}

void loop(void) {
    newRotationAngle++;

    // This works. No problems.
//    outsideClassRotation(tft);

    // This does NOT rotate but still prints the text fine.
    instance.inClassRotation(newRotationAngle);

}


texts: Arduino Leonardo on Win 8.1 COM port disappeared

texts:
I've been using an Arduino Leonardo on my Windows machine for a few days now without too much trouble but today the COM port disappeared. I've been able to successfully send sketches to the arduino and execute them so everything was working until recently. When I look in Device manager on the control panel there is no com port listed for the arduino. If I reset the device then a com port shows up briefly with "Arduino Leonardo BootLoader" but after a few seconds that disappears. I've tried USB2.0 and USB 3.0 ports on my PC and a different cable but to no avail. I don't have anything listed under "Other Devices" and I'm out of ideas for what could be the trouble.
I'm trying to get it recognised now as just the leonardo with nothing connected to any pin. Any ideas of what to try?


texts: What is the correct way to create large project files?

texts:
I am currently working on a 10x10 RGB LED screen (using Neopixels from Adafruit) and my project files are starting to get rather large.
I have several different devices used in this project:

The LED matrix
A DS3232 RTC
An MSGEQ7 DSP chip
7 push button switches

Currently i'm using separate classes for each of the devices (RTC, DSP & buttons) as well as the Adafruit GFX and Neopixel library.

What would be the best way to organize this project? Should I put the patterns for the screen in the main.ino file or should they have their own class.

Any help would be greatly appreciated, I can upload the source code if its needed.

Cheers

As a side note, I'm using "Sublime Text 3" along with Stino.


texts:
I can upload simple sketch on my ESP-01 like:

void setup() {
  Serial.begin(115200);
  Serial.println("Hello there");
}
void loop() {
  Serial.println("Hello from loop");
  delay(1000);
}

I also ran successfully the sample ESPWebServer -> HelloServer

But if just modify my sketch to include #include <ESP8266WiFi.h>

#include <ESP8266WiFi.h>

void setup() {
  Serial.begin(115200);
  Serial.println("Hello there");
}
void loop() {
  Serial.println("Hello from loop");
  delay(1000);
}

I got this result in the serial monitor:

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

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

My ESP-01 is connected to my computer through FT232RL FTDI with the following cabling:

FTDI GND - GND
ESP TX - FTDI RX
ESP RX - FTDI TX
ESP VCC - VCC 3.3V
ESP GND - GND
ESP CH_PD - VCC
ESP GPIO2 - VCC
ESP GPI00 - GND to upload sketch, VCC to run sketch

Here is a picture of my cabling (the USB of both the TTL and power supply MB102 are connected to my laptop):

Also, regularly my sketch fails to load correctly:

-Sometimes it does not load at all and I get this after compilation before uploading starts:

warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

- Sometimes it fails at the end of the upload:

Uploading 256064 bytes from C:\Users\20000263\AppData\Local\Temp\arduino_build_32221/ESP01-Basic.ino.bin to flash at 0x00000000
................................................................................ [ 31% ]
................................................................................ [ 63% ]
................................................................................ [ 95% ]
..........warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_DATA) failed
warning: espcomm_send_command: wrong direction/command: 0x01 0x03, expected 0x01 0x04
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

Any idea about what is wrong ?


texts:
I am trying to get Arduino nano and SIM800L module working together. I provided the module with the recommended external voltage of 4.0V (documentation states 3.6V - 4.2V) transformed via LM2596. The original source is 5V 3A.
LED on SIM800L blink once a second as stated in documentation when in an unconnected state.
The schema is the following:
                  Antena
                   \_/
                    |
Arduino    SIM800L  |  External 4.0V
             NET ---/
             VCC ----- +4.0V
D2 --------- RST
D3 --------- RX
D4 --------- TX
             GND ----- GND

I have already tried 3 different libraries for AT communication and also sending raw AT commands using writing to serial manually. I also tried another SIM800L module because I thought the module is faulty.
Here is the dump from serial communication:
[551135] ### TinyGSM Version: 0.10.9
[551139] ### TinyGSM Compiled Module:  TinyGsmClientSIM800
AT
��AT
�AT
H�j���[552012] ### Unhandled: Hj
AT
AT-���[552317] ### Unhandled: AT-
AT
��AT
��AT
�Z5
[553228] ### Unhandled: Z5
AT
␚)O���[553532] ### Unhandled: ␚)O
AT
AT���[553836] ### Unhandled: AT
AT
��AT
��AT
�)OK��[554748] ### Unhandled: )OK
AT
���[555053] ### Unhandled: 5
AT
���AT
��AT
��AT
�j�H�[556266] ### Unhandled: jH
AT
CC����[556570] ### Unhandled: CC
AT
AT���[556875] ### Unhandled: AT
AT
��AT
AT
���[557787] ### Unhandled: T
AT
�H����[558091] ### Unhandled: H
AT
AT���[558395] ### Unhandled: AT
AT
��AT
��AT
AT
jRO���[559610] ### Unhandled: jRO
AT
AT���[559915] ### Unhandled: AT
AT
��AT
��AT
AT
�
OK��[561128] ### Unhandled: OK
Failed to initialize SIM800L

As you can see the module is trying to negotiate the baudrate. By default, I use speed 9600 as stated in the documentation. When I use a different baudrate the module does not respond at all.
It seems the module replies and sometimes even correctly. Response to AT command should be OK.
Do you know how do I successfully negotiate the speed and establish reliable serial communication with the module? Do I miss any electrical components in my circuit like a capacitor or resistor? I tried to use capacitor 35V / 3300µF but without any difference. I think my power source is strong enough.
The source code is the following:
#define PIN_GSM_RST             2
#define PIN_GSM_TX              3
#define PIN_GSM_RX              4
#define GSM_BAUDRATE            9600

#define TINY_GSM_MODEM_SIM800
#define TINY_GSM_DEBUG          Serial
#define TINY_GSM_USE_GPRS       true
#define TINY_GSM_USE_WIFI       false

#include <Arduino.h>
#include <SoftwareSerial.h>
#include <TinyGsmClient.h>
#include <StreamDebugger.h>

SoftwareSerial serial_SIM800L(PIN_GSM_RX, PIN_GSM_TX);
StreamDebugger debugger(serial_SIM800L, Serial);
TinyGsm modem(debugger);
TinyGsmClient client(modem);

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

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

    serial_SIM800L.begin(GSM_BAUDRATE);
    delay(5000);

    while (!modem.init()) {
        Serial.println("Failed to initialize SIM800L");
    }
}

void loop() {
    //
}


texts:
First of all, we connected our usb plug to arduino board (starter kit). After that, we completed Project 1 successfully (circuit with led and switch.) We tried unplug the usb cable, but it was very difficult, we had to pull very hard, but we couldn't unplug it. Finally, I managed to take it away with the help of my partner. I was pulling the usb and my partner was keeping the arduino board stable. The result wasn't very nice, we probably broke the usb cable. You can see what I mean in these images, the metallic coating part of the cable is still stuck on the board.
https://ibb.co/6wtf02J
https://ibb.co/4pZg2w0
https://ibb.co/WPchtgN
https://ibb.co/gPHZYnt
Nevertheless, we put the remaining cable back where it was, and the board seems to be working normally.
My question is if it safe to use it. Is there any chance of electrical damage or something like that?
Thank you!
P.S. In addition, we are planning to buy a new arduino starter kit. How can we avoid this problem with the new board?


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

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

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

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

void setConnection(){

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

void dweet(){

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

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

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

void setup(){

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

}

void loop(){
dweet();
}

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

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

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

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


texts: Hardware serial not working, SoftwareSerial is

texts:
On my Uno-equivalent Arduino, a SoftwareSerial connection (on RX, TX = 8, 9) is working*, while a hardware serial connection to the same device, set up in the same way (but on pins RX, TX = 0, 1) is not working. Why is the hardware serial setup not working?

*By working I mean receiving a byte from the external device

Edit: as a simple example:

void setup() {
  Serial.begin(38000);
  pinMode(7, OUTPUT);
}

void draw() {
  if (Serial.available() > 0) {
    Serial.read();
    tone(7, 440, 1000);
  }
}

The above, using Serial, doesn't work, whereas

#include <SoftwareSerial.h>

SoftwareSerial serial(8, 9);

void setup() {
  serial.begin(38000);
  pinMode(7, OUTPUT);
}

void draw() {
  if (serial.available() > 0) {
    serial.read();
    tone(7, 440, 1000);
  }
}

does work.

I don't know if this helps, but connecting RX/TX through an LED to ground gave me the following, using Serial on (0, 1) and SoftwareSerial on (8, 9):

Serial
RX: bright
TX: bright
SoftwareSerial
RX: dim (but still lit)
TX: bright

Is the fact that RX is dim using SoftwareSerial significant?


texts: I plan to use my Arduino with a small battery all the time so I don't want it to use so much power. I was checking power consumption of DS3231 with a multimeter, at first it was fluttering around 1 mA and 0.4 mA with 3.3 volts. I removed the battery on DS3231 to reduce affect of charging but now it's still high, about 0.4 mA. The official paper says it should use a lot lower than that. Is it an error about my multimeter or is there something I missed like a configuration or something?


texts: Arduino hangs after 3-4 minutes on battery power, but not on USB

texts:
I have a simple sketch running on a BE Leonardo-compatible board.

It reads input from a potentiometer, and outputs to two RGB LEDs which change colour over time - in a different pattern if certain inputs are received.

Other than that, the only code is serial I/O for debug purposes.  (It's disabled using a #define in the running version, to prevent serial buffer overflow when not connected.)

When the board is powered by USB, everything works.

When the board is powered by 9V battery, after about 4 minutes it hangs - the LEDs go off, and the L13 light on the board starts glowing at varying strength.  (There is nothing connected to pin 13.)  Even the reset button doesn't work.

If the board is then connected to the computer's USB port, after a few seconds the hang clears and the program resumes.

Can anyone offer a possible explanation for (and solution to) this fault?


texts: My Arduino Nano clone doesn't show in the serial this simple code. Why?

texts:
Here is the code:

void setup() {
  Serial.print("hi");
}
void loop() {
}

The product is in here.

I also installed the drivers.


texts: I'm building an automatic warehouse system using 3 nema17 stepper motor. My problem is to move the motors with precision, since I do not have any kind of encoder on the motor and so I cannot know the position of the axes. I tought that the system could be similar to a 3d printer, since neither 3d printers have encoder on the motor. Where can I find a sketch for Arduino of a 3d printer, to understand how they work? How do they move with such precision without any kind of sensor?


texts: Changing the brightness on a Hitachi HD44780 LCD screen

texts: I am finishing up a project- an LED game alarm clock. Seeing as this is a clock, I need to have a way to conserve power, which right now my Uno R3+ is eating up like a politician. My question is, how do I turn the screen off, or turn the back-light off using software only on a Hitachi HD44780 16x2 LCD screen? Or how do I set a sleep mode on one component? The way I plan on turning it off is with an ultrasonic range finder, if I get close it turns on the screen. If anything I say doesn't make sense, ask me to clarify, I'm in a bit of a rush.


texts:
I'm using an Arduino Due with a logic level converter to interface with two different 5v sensors via I2C. Being of poor quality, these sensors have no data sheet.

When either one of these sensors is plugged in, I am able to read from it without issue. The moment I plug the other one in as well, the I2C stops working, and I just get 0. I know that it's not an address collision issue, because they have different addresses.

I tried adding an additional set of pull-up resistors (such that they are in parallel with the built-in ones) in order to counteract potentially increased bus capacitance, but no dice.

What could be causing this issue? I apologise for asking such a noob question.


texts: Stopping a countdown timer when it hits 0

texts:
I am trying to modify the following sketch to count down (which seems to be partially working).  What do I need to modify, to get the timer to stop at zero? Right now it counts down from 10 seconds, goes past zero and into the negatives.  I really struggle with coding, I've tried studying other peoples sketches, researching on-line, purchased (and studied) a couple Simon Monks books, but I'm still unable to work through this.  Can someone please point me in the right direction?

#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
#define WAITING 0 // waiting to start
#define TIMERONE 1 // timer one running
#define FINISHED 3 // timer complete
#define countdown 10
const int resetPin = 6;
const int buttonPin = 7;
const int ledPin =  13;      // the number of the LED pin

long startTime = 0;
long timeOne = 0;
int timer = WAITING; // timer state. Initially waiting for first button press
int reset = 0;  // reset button state
int button = 0; // main button state

void setup()   {

  pinMode(buttonPin, INPUT); //init button pin to input
  pinMode(resetPin, INPUT);  //init reset pin to input
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3c
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(55, 00);
  printDigits(0);
}

void loop() {
  //-------- main loop -------
  switch (timer) {
    case WAITING: // initial state - waiting for first button press.
      display.clearDisplay();
      display.setCursor(55, 00);
      printDigits(0);
      display.display(); // display screen showing 00:00
      button = digitalRead(buttonPin);
      if (button) { // button is pressed.
        timer = TIMERONE;
        startTime = millis();//read the time the button is pressed.
        while (digitalRead(buttonPin)) {
          //--- wait for button to be released.
        }
      }
      break;
    case TIMERONE:
      timeOne = millis();
      button = digitalRead(buttonPin);
      reset = digitalRead(resetPin);
      display.clearDisplay();
      display.setCursor(55, 00);
      printDigits (timeOne - startTime);
      display.display();
      //-----------------------------------
      if (reset) { //reset button was pressed. Clear screeen and start again
        timer = WAITING;
        while (digitalRead(resetPin)) {
          //--- wait for reset button to be released.
        }
      }
      if (button) { // button was pressed
        timer = FINISHED;
        while (digitalRead(buttonPin)) {
          //--- wait for button to be released.
        }
      }
      break;
    case FINISHED:
      reset = digitalRead(resetPin);
      if (reset) { //reset button was pressed. Clear screeen and start again
        display.clearDisplay();
        display.setCursor(55, 0);
        printDigits(0);
        display.display();
        timer = WAITING;
        while (digitalRead(resetPin)) {
        }
      }
      break;
  }
}

void printDigits(long timeInMillis) {
  int seconds;
  int hundredths;

  seconds = countdown - timeInMillis / 1000;
  hundredths = (timeInMillis % 1000) / 10;

  if (seconds < 10) { // print leading zero if necessary
    display.print("0");
  }
  display.print(seconds);
  display.print(":");
  if (hundredths < 10) { //print leading zero if necessary
    display.print("0");

  }
  display.print(hundredths);

}


texts:
I am trying to make motion capture and someone gave me these boards.

I think it's a test board for MPU 9500. I tried to google but I only found datasheets. What boards are these?

"ITG-3500 evb" is written on the back of the green board.
I think this is datasheet of green board maybe

"EV_ARM_XXAXA_D" is written on the back of the blue board.


texts: problem in integrating the slave code in attiny 84

texts:
I tried the whole process by using two arduino unos.It worked perfectly.
Though when i tried to replace the slave uno with attiny 84 uC it showed following errors in compiling.

Arduino: 1.6.7 (Windows 7), Board: "ATtiny24/44/84, ATtiny84 @ 1 MHz  (internal oscillator; BOD disabled)"

WARNING: Category '' in library ArduinoJson is not valid. Setting to 'Uncategorized'
C:\Users\LEGEND\AppData\Local\Temp\arduino_8a75bcb6a2713182a57eb1014198ceb3\sketch_may12c.ino: In function 'void setup()':

sketch_may12c:12: error: 'SPCR' was not declared in this scope

   SPCR |= bit (SPE);

   ^

In file included from C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/WProgram.h:12:0,

                 from C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/Arduino.h:4,

                 from sketch\sketch_may12c.ino.cpp:1:

sketch_may12c:12: error: 'SPE' was not declared in this scope

   SPCR |= bit (SPE);

                ^

C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/wiring.h:158:25: note: in definition of macro 'bit'

 #define bit(b) (1UL << (b))

                         ^

sketch_may12c:15: error: 'MISO' was not declared in this scope

   pinMode (MISO, OUTPUT);

            ^

sketch_may12c:22: error: expected unqualified-id before '.' token

   tinySPI.attachInterrupt();

          ^

C:\Users\LEGEND\AppData\Local\Temp\arduino_8a75bcb6a2713182a57eb1014198ceb3\sketch_may12c.ino: In function 'void SPI_STC_vect()':

sketch_may12c:30: error: 'SPDR' was not declared in this scope

 byte c = SPDR;  // grab byte from SPI Data Register

          ^

exit status 1
'SPCR' was not declared in this scope

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.


texts: Using millis() and micros() inside an interrupt routine

texts:
The documentation for attachInterrupt() says:

  ... millis() relies on interrupts to count, so it will never increment inside an ISR. Since delay() requires interrupts to work, it will not work if called inside an ISR. micros() works initially, but will start behaving erratically after 1-2 ms. ...

How does micros() differ from millis() (except of course for their precision)? Does the above warning mean that using micros() inside an interrupt routine is always a bad idea?

Context - I want to measure low pulse occupancy, so I need to trigger my routine when my input signal changes and record the current time.


texts: Setting EN_AA (auto ACK) to 0x01 or 0x02 makes nRF24L01+ stop sending/receiving

texts:
Test case:

2 arduino nodes with nRF24L01+ transceivers. Using maniacbug's RF24 library. Using pipes 0 and 1. (Auto-ACK is ON for all pipes by default)

When I set Auto-ACK ON for all pipes rf24.setAutoAck(true): it works.
When I set Auto-ACK OFF for all pipes rf24.setAutoAck(false): it works.

But when Auto-ACK is ON for pipe1 and OFF for pipe0 (I want pipe0 for broadcasting) rf24.setAutoAck(0,false):it stop working (no packet is received or sent).
Same thing with Auto-ACK ON for pipe0 and OFF for pipe1

Couldn't find anything about it on the datasheet neither other forums nor here. Is there something I'm missing?

Test sketches:

Node 1

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

RF24 rf24(9,8);

uint64_t pipe0 = 12312312LL;
uint64_t pipe1 = 11111111LL;

int data[2];

void setup()
{
    Serial.begin(115200);
    data[0] = 123;
    data[1] = 456;

    rf24.begin();
    rf24.setChannel(109);
    rf24.setPayloadSize(2);
    rf24.setDataRate(RF24_2MBPS);
    rf24.openReadingPipe(0,pipe0);
    rf24.openReadingPipe(1,pipe1);
    rf24.openWritingPipe(22222222LL);
    rf24.setAutoAck(0,false);
}

void loop()
{
    delay(1000);
    Serial.print("ACK: ");
    Serial.println(rf24.write(data,sizeof(data)));
}

Node 2:

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

RF24 rf24(9,8);

uint64_t pipe0 = 12312312LL;
uint64_t pipe1 = 22222222LL;

int data[2];

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

    rf24.begin();
    rf24.setChannel(109);
    rf24.setPayloadSize(2);
    rf24.setDataRate(RF24_2MBPS);
    rf24.openReadingPipe(0,pipe0);
    rf24.openReadingPipe(1,pipe1);
    rf24.setAutoAck(0,false);
    rf24.startListening();
}

void loop()
{
    if(rf24.available())
    {
        Serial.println("Got somethin");
        int incoming;
        rf24.read((byte *) &incoming,2);
        Serial.println(incoming);
    }
}


texts: Servo motor (HSR-1425R) not running continuously

texts:
I'm trying to programme a servo motor to reach certain positions. I have a 360 degrees servo motor, so I can not use the Servo library and I can only control the speed. Therefore I want to regulate the time for the pulse. The setup is simple, 5 V, GND and pin 9 from the Arduino to the motor.

int servo1 = 9;

void setup{
    Serial.begin(9600);
    pinMode(servo1, OUTPUT);
}
void loop{
    digitalWrite(servo1, HIGH);
    delay(5000);
    Serial.println(digitalRead(servo1));
    digitalWrite(servo1, LOW);
    delay(5000);
    Serial.println(digitalRead(servo1));
}

Expected:
I expect the code to run the servo motor at full speed for 5 seconds.

Actual:
The motor runs at the first impulse and pauses for 10 seconds.

How can I improve the code to do what I expect?


texts: Mega 2560 & smoking/burning 5v requlator, probable cause?

texts:
Problem: board seriously fried.
Desired outcome: measures to take in future.

Background:
This project has been running for about a week on the 2560, and previously for a few weeks on an UNO clone. Board switch a result of program size/expansion.  It sits on a shelf with others of the same ilk.  Nothing is touched unless I need to plug in USB cable for update.
The Arduino is a clone, connected to DS3231, LCD1602 via I2C Serial Interface board, LCD2004 also via 12C SIB, SD card adapter, HC-12 wireless, 5 leds [normally off, used to flag specific conditions, each in series with 470 ohm resistor.
The unit receives data from another Arduino and logs to the SD, updating the two LCD displays.

Steps leading to failure:
Plugged in USB cable [no other physical changes, nothing else touched, power jack remained connected]. went to Arduino s/w to make minor changes, would not upload to Arduino.  While scratching my head, smelled something burning, then saw smoke coming from the shelf.

Post failure:
Board seriously scorched around 5v regulator, can provide photo, but seems unnecessary.
Visual wiring inspection revealed no obvious problems.
Input to power jack measured at 10.06v.
Replaced with new Arduino 2560 clone, matching connection for connection, connected USB but not power port [just in case of ?, seen ancedotal posts of possible conflict; a clone after all].  Uploaded my modified program, and all works fine. Disconnected USB, reconnected power jack and all still fine, 16 hours in.
Also searched internet for possible problems related to such a failure, but found nothing to suggest probable cause.

Seeking:
Words of wisdom from others far more knowledgeable and experienced than I.
Could the dual connection of USB and power jack, be the root cause?  Never experienced this with UNO clones.

I do not want to put more boards at risk in the future.


texts: How to stop OLED flicker when using SSD1306Ascii.h?

texts:
Why does the OLED display flicker when using the SSD1306Ascii.h library? The Adafruit library does not have this issue, but I've been told uses a lot of memory and so I'm trying to use Ascii to conserve memory resources. The problem manifests itself when the void loop() begins. When using similar code with the Adafruit library, the display stays steady as a rock.

Here is my example code. many thanks in advance.

// Edit AVRI2C_FASTMODE in SSD1306Ascii.h to change the default I2C frequency.

#include "SSD1306Ascii.h"
#include "SSD1306AsciiAvrI2c.h"

#define I2C_ADDRESS 0x3C

// Define proper RST_PIN if required.
#define RST_PIN -1

SSD1306AsciiAvrI2c oled;
//------------------------------------------------------------------------------
void setup() {

#if RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS, RST_PIN);
#else // RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS);
#endif // RST_PIN >= 0
  // Call oled.setI2cClock(frequency) to change from the default frequency.

  oled.setFont(System5x7);
  oled.clear();
  oled.print("Hello World!");
  delay(2000);
  oled.clear();

}
//------------------------------------------------------------------------------
void loop() {

  oled.setFont(System5x7);
  oled.print("Hello fuuuzzzzyyyy world!");
  delay(1);
  oled.clear();

}


texts: Servo motor activation with pressure sensor

texts:
I need to run my servo motor within a specific pressure range, given by a pressure sensor. I don't understand how to code this. I have coded for servo motor movement but I need to activate that movement in a specific range. Please, help me.

This is my servo code:

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // twelve servo objects can be created on most boards
int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);
  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for(pos = 0; pos <= 30; pos += 1) {
    // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);
    // tell servo to go to position in variable 'pos'
    delay(5); // waits 15ms for the servo to reach the position
  }
  for(pos = 30; pos>=0; pos-=1) {
    // goes from 180 degrees to 0 degrees
    myservo.write(pos);
    // tell servo to go to position in variable 'pos'
    delay(5);
    // waits 15ms for the servo to reach the position
  }
  delay(1500);
}

I need to activate this servo within a 10-70 pressure range.


texts:
I'm experimenting adding DHCP option 160 to dhcpserver.c in the Arduino core for ESP8266 and therefor need to rebuild the relevant parts.

I made an initial guess that I might be able to make the change by installing using git according to the instructions in the readme and just restarting the IDE. I wasn't surprised to learn that this didn't help. The modifications to dhcpserver.c did not make it to the device following restart of the IDE and a new upload.

From another forum I saw a suggestion that the following commands could be used to rebuild from source:

$ cd esp8266/tools/sdk/lwip/src
$ make install

Again the changes didn't make it to the device after restarting and uploading the sketch again.

Does anyone have any clearer instructions for how to build a new Arduino core for esp8266?


texts: HID multiCLASS RFID reader all Mifare to Wiegand 32bit

texts:
I'm using an Arduino Uno to read from a "HID multiCLASS (RP40CKPNN) reader", which is a stand-alone reader that reads cards and returns a number of bits via Weigand Data0/Data1 protocol.  The "multiCLASS" readers can read both 125HZ PROX tags, and 13.57MHz mifare tags.

I have it reading and decoding 125HZ (multiple-PROX format) tags of various bit-lengths just fine, but when the reader is presented with a 13MHz card (specifically Mifare cards) the reader decodes the CSR/UID of ALL Mifare cards to 32bits.  The Mifare cards come in two types, Classic (that use a 4byte UID), and Ultra (that use a 7byte UID), so I would expect 32bits for the Classic cards, and 56bits for the Ultra, but I only ever get back 32bits.

The reader's data-sheets specifically calls out that for mifare tags it should return a 32bit or 56bit CSR value based on the serial number of the card, but I've looked through lots of HID literature on this reader, and I can't find any specifics on how to change/modify its configuration.

Does anyone have any experience with these readers, and is there some trick to changing the configuration so that it returns more bits for Mifare cards?


texts: Trying to pass a single char to a serial device

texts:
Good day,
I have a serial device that when connected via hyper terminal gives me a status report when I press the letter 'd' no enter key or anything required just the letter d. Also Ctrl-t will give me some routing information.

I would like to press a button connected to the arduino and send the b to the serial device and view the status information back from it.

At this point I have the Serial device connected to the arduino and am able to see messages from it, however when I press the switch connected to pin 2 the serial device does not send me the status output as expected and as seen via direct serial connection to my computer with hyperterminal.

Does anyone have an experience or input regarding this?

#include <SoftwareSerial.h>
// software serial #1: TX = digital pin 10, RX = digital pin 11
 SoftwareSerial portOne(10, 11);
 const int buttonPin = 2;     // the number of the pushbutton pin
 const int button1Pin = 4;
 const int ledPin =  13;      // the number of the LED pin
//define char to send to serial

char stat = 'd';
char route = '\x14';
// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status
int button1State = 0;

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
                pinMode(ledPin, OUTPUT);
                pinMode(buttonPin, INPUT);
                pinMode(button1Pin, INPUT);
                Serial.begin(4800);
                while (!Serial) {; // wait for serial port to connect. Needed for native USB port only
                }
                // Start each software serial port
                portOne.begin(4800);
                while (!portOne) {; // wait for serial port to connect. Needed for native USB port only
                }
              }

// the loop function runs over and over again forever
void loop() {
            static int Once = 0;
            static int Once1 = 0;
            buttonState = digitalRead(buttonPin);
            button1State = digitalRead(button1Pin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
            if (buttonState == HIGH ) {
                                      if (Once == 0) {
                                                        Once = 1;
                                                        // turn LED on so I can tell the button is working
                                                        digitalWrite(ledPin, HIGH);
                                                        // send d to Radio
                                                        portOne.write(stat);
                                                        // send d to serial monitor so I can see the charector
                                                        Serial.print(stat);
                                      }
                                      }

if (buttonState == LOW) {
                          // turn LED off:
                          Once = 0;
                          digitalWrite(ledPin, LOW);

                          }

  // check if the other pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (button1State == HIGH) {
    if (Once1 == 0) {
          Once1 = 1;
    // turn LED on:
   // digitalWrite(ledPin, HIGH);
    // send ctrl-t to radio
    portOne.write(route);
    }
  }
  if (button1State == LOW) {
    // turn LED off:
    //digitalWrite(ledPin, LOW);
    Once1 = 0;
  }
    portOne.listen();
      // read data from the Software Serial portOne
   // and send to the hardware serial port:
   while (portOne.available() > 0) {
     char inByte = portOne.read();
     Serial.print(inByte);
   }
}


texts: What module should I use for high precision localization?

texts:
I have a toy car and I want to measure the coordinates/location of that car in my house.
It need to bee high precision equipment so GPS won't work here.
My precision requriments is 5+- cm and the distance is like 10-20 meters as maximum raduis.
What module should I use then?


texts: AVR program upload overrides unrelated program area

texts:
I develope a new bus system (uartbus) which includes a host application that can handle new program uploads throught the bus.

How it's work in short: The host application flashed to the AVR. This located between 0-2000 addresses and the flashing function at the end in the NRWW section. Application is written between 2000 and before NRWW section when it's received from the bus.

It's worked for a while with small AVR codes, but now as i try to integrate with the arduino system i've faced a weird problem: sometimes a page between
100 and 180 (one 128 byte page) been erased and some code filled almost at the beginning.

I thought the flashing function has been called with some wild parameter that results this fault, so i added some guard condition to check before write the flash:

__attribute__((section(".bootloader"))) void bootloader_main()
{
    asm ("jmp 0x0");
}

//modified version of:
//https://www.nongnu.org/avr-libc/user-manual/group__avr__boot.html#gaeb0dba1dd9d338516a94c0bd8a8db78a
__attribute__((section(".bootloader")))  void ubh_impl_write_program_page(const uint32_t page,const  uint8_t *buf,const uint8_t size)
{
    if(page < 0x2000 || (page > 0x7900+SPM_PAGESIZE) || size > SPM_PAGESIZE)
    {
        return;
    }

    uint16_t i;
    uint8_t sreg;
    // Disable interrupts.
    sreg = SREG;
    cli();
    eeprom_busy_wait ();
    boot_page_erase (page);
    boot_spm_busy_wait ();      // Wait until the memory is erased.
    for (i=0; i<size; i+=2)
    {
        // Set up little-endian word.
        uint16_t w = *buf++;
        w += (*buf++) << 8;

        boot_page_fill (page + i, w);
    }
    boot_page_write (page);     // Store buffer in flash page.
    boot_spm_busy_wait();       // Wait until the memory is written.
    // Reenable RWW-section again. We need this if we want to jump back
    // to the application after bootloading.
    boot_rww_enable ();
    // Re-enable interrupts (if they were ever enabled).
    SREG = sreg;
}

But the problem remained. Because the host code has been partially overwritten, the AVR can't receive new code from the bus. After dumped the AVR's flash and disassembled to invesigate what's happened.

avrdude -p atmega328p -b 19200 -P /dev/ttyUSB0 -c avrisp -U flash:r:flash.hex:i
avr-objdump -j .sec1 -d -m avr5 flash.hex > flash.asm

  ... good code ...
      fc:       fb 01           movw    r30, r22
      fe:       31 83           std     Z+1, r19        ; 0x01
     100:       ff ff           .word   0xffff  ; ????
     102:       ff ff           .word   0xffff  ; ????
     104:       ff ff           .word   0xffff  ; ????
     106:       ff ff           .word   0xffff  ; ????
     108:       ff ff           .word   0xffff  ; ????
     10a:       ff ff           .word   0xffff  ; ????
     10c:       ff ff           .word   0xffff  ; ????
     //looks like this code is from the application space between 2b8e and 2b96
     10e:       ff 1f           adc     r31, r31
     110:       05 90           lpm     r0, Z+
     112:       f4 91           lpm     r31, Z
     114:       e0 2d           mov     r30, r0
     116:       09 94           ijmp
     118:       ff ff           .word   0xffff  ; ????
     11a:       ff ff           .word   0xffff  ; ????
     11c:       ff ff           .word   0xffff  ; ????
     11e:       ff ff           .word   0xffff  ; ????
 ....

     17c:       ff ff           .word   0xffff  ; ????
     17e:       ff ff           .word   0xffff  ; ????
     180:       9f 93           push    r25
     182:       8f 93           push    r24
     184:       0e 94 9e 0a     call    0x153c  ;  0x153c
   ...good code ...

How is this possible to happen even after adding some guard condition before writing the flash?

(Another guard is also installed: when AVR accidentally starts in bootloader mode it's jumps immedialty to 0x00).
I also checked, there's no SPM instruction in the code i uploaded and as far as i know they can be run outside of the NRWW section.


texts:
Hı everyone I am trying give my led a breathing effect using millis()
But neither led isnt breathinng and it stucks I cannot use other fucntions.
Please help...
#include <IRremote.h>
#define irPin 2
int led1 = 9;
int turn = 11;
bool breathing = false;
IRrecv irrecv(irPin);
decode_results results;

int a;

void breathe()
{
  static unsigned long previousMillis = 0;
  static boolean breathingIn = true;
  static unsigned int brightness = 0;
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > 30)
  {
    previousMillis = currentMillis;

    if(breathingIn){
      brightness++;
      analogWrite(turn, brightness);
      if (brightness == 255){
        breathingIn = false;
      }
    }
    else{
      brightness--;
      analogWrite(turn, brightness);
      if (brightness == 0){
        breathingIn = true;
      }
    }
  }
  a = brightness;
}
void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn();
  pinMode(led1, OUTPUT);
  pinMode(turn, OUTPUT);
  a = 0;
}
void loop() {
  if(breathing){
    //Serial.println(millis());
    breathe();
    Serial.println(a);
  }
  if(irrecv.decode(&results)){
    switch(results.value){
      case 0xFF6897: //IR remote key to pwmLED LED1 ON
        digitalWrite(led1, HIGH);
        break;

      case 0xFFB04F: //IR remote key to pwmLED LED1 OFF
        digitalWrite(led1, LOW);
        break;

      case 0xFFA25D: //I want to use this key to start breathing
      //  Serial.println(results.value, HEX);
        breathing = true;
        break;

      case 0xFFA857: //I want to use this key to stop breathing
        Serial.println(results.value, HEX);
        breathing = false;
        break;

    }
    irrecv.resume();
  }
}


texts: Arduino UNO doesn't produce expected square waveform

texts:
I want to produce quick square waveform for testing purposes. If I will use this code:

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

void loop()
{
 bitSet(PORTD, 2);
 bitClear(PORTD, 2);
}

I will get expected pulses but I also will get these 6.25 us dips in waveform roughly every 1 ms.

I use latest Arduino 1.6.9 environment.

Whole loop cycle take 1 us which mean 16 instructions (62.5 ns per instruction). So I will get 125 ns high and rest of the time low signal.

Any idea what I'm doing wrong?

Same results if I use asm sbi and sci instead of macros bitSet/bitClear.

Thank you!

/*

So after yours advices and little bit further searching I came up with solution to produce clean square waveform. It make 2.66 Mhz and it's probably fastest what you can get:

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

void loop()
{
 while(true)
 {
 bitSet(PORTD, 2);
 bitClear(PORTD, 2);
 }
}


texts: Print Byte Array in Serial monitor screen of Arduino IDE

texts:
I need to print mentioned below byte array on the serial monitor screen of Arduino IDE

char b[]= {'0x7E', '0x00', '0x1C','0x90', '0x00', '0x13', '0XA2', '0x00', '0x41', '0x58', '0x1C', '0xCB', '0xFF', '0xFE', '0xC1', '0x7C', '0x00','0x0F', '0x00', '0x01', '0x00', '0x00', '0x37', '0x46', '0x46', '0x46', '0x00', '0x00', '0x00', '0xE7' };
void setup() {
Serial.begin(9600);
}

void loop() {
Serial.println(b[]);
delay(500);
}

But whenever I am trying a print, the error problem was there which was not resolved which is

C:\Users\Misha\Desktop\test\Test_2\Test_2.ino: In function 'void loop()':

Test_2:8:18: error: expected primary-expression before ']' token

 Serial.println(b[]);

                  ^

exit status 1
expected primary-expression before ']' token

Any suggestions on this will be great help.


texts: UltraSonic Sensor wirh ESP-01 Standalone

texts:
I'm trying to build a cheap device to measure water level in a tank using HC-SR04 sensor and ESP-01 which send the data to MQTT topic. I used the same code with ESP-E12 which works just fine. As I'm trying to drive the cost down with ESP-01, I faced a problem with I/O pins. I searched the web and found some contradicting info about which pins could be used in this case.
So here is the schematic of my setup:

Coming to the ESP-01, I used a USB adapter to program it and the code uploaded successfully. Here I'm just showing the Ultrasonic sensor part which I believe I have issues with.

#define echoPin 2 // Echo Pin
#define trigPin 0 // Trigger Pin

long duration, distance; // Duration used to calculate distance

void setup(){
  Serial.begin (115200);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop(){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration/58.2;
  Serial.println(distance);
  delay(200);
}

I read somewhere in the internet that GPIO2 can't be used and must be replaced with Rx = GPIO3. However, I tried that and it didn't work too.
So the question here, am I really using the right pins or is it really possible to do that with esp-01?


texts:
Working on my first real sketch, so will try to keep this short.  Feel free to ask more info if needed.

To power a flyback transformer I need to apply PWM -to- a PWM signal.  The easiest way to describe this is that while a standard PWM signal is 'on' for some set time, then 'off' for the remainder of the period, I need to send a signal where the 'on' is actually a 14kHz square wave of 50% duty...then pulse this signal ~1 to 100% duty at ~500Hz.

No problem with the 14kHz PWM - I found the PWM.h library and set that up.

But what is the best way to chop that up with a second PWM at, say 500Hz?

With some amount of kludge, can I 'bit bang' it with DO - WHILE?  Will WHILE read a variable outside the loop?  Are there easier ways?

i=1;
do {                                //Pulse microsecond 'frames' of high freq signal?
                                    //ie 14kHz carrier PWM'd at 500Hz = 2000 microseconds per 'frame' cycle
                                    //at 50% duty would be 1000 micros high and 1000 micros low

    pwmWrite( outpin, 128 );        //Turn on 14kHz carrier at 50% duty
    delayMicroseconds(1000);        //Delay to generate the 'HIGH' portion of the frame
    pwmWrite( outpin, 0 );          //Turn 14kHz carrier off
    delayMicroseconds(1000);        //Delay to generate the 'LOW' portion of the frame
   } while (i == 1);                //...and keep doing loop while the state is '1' or 'ON'

delay(1000);                        //?Will this allow the above loop  to repeat while waiting here for 1 second?
i=0;                                //i != 1, so break out of the while loop above?
                                    //then continue doing other stuff below...

Any help greatly appreciated.


texts:
i'm trying to send String from an Arduino(Uno) using the Serial. to an another Arduino(Uno). using nRF24l01+. and I'm using the library RF24.h
the String is sended correctly but I have some problems with the acknowledgement.

This is my Rx code.

#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
const uint64_t pipe[1]= {0xF0F0F0F0E1LL};
RF24 radio(9,10);
char buf[32]= "";
char false_buf[32]= "MKJK212U1H7";
void setup()
{
  Serial.begin(115200);
  radio.begin();
  radio.setChannel(0x35);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  radio.openReadingPipe(1,pipe[0]);
  radio.startListening();
  radio.setRetries(1,15);
  radio.writeAckPayload( 1, false_buf, sizeof(false_buf) );
}
void loop()
{
int OkMsg;
  while(!radio.available()){};
  if ( radio.available() > 0) {
    radio.read(&buf,sizeof(buf) );
    Serial.println(buf);
    radio.writeAckPayload( 1, buf, sizeof(false_buf) );
      while(!radio.available()){};
  if ( radio.available() > 0) {
    radio.read(&OkMsg,sizeof(OkMsg) );
    Serial.println(OkMsg);
    if(OkMsg == 1){Serial.println("OkMsg's true!");}
    else {Serial.println("OkMsg's false!");}
    }}
  }

and this is my Tx code

#include <SPI.h>
#include <RF24.h>
#include <nRF24L01.h>
RF24 radio(9, 10); // CE, CSN

const uint64_t pipe[1]= {0xF0F0F0F0E1LL};

char CharToSend[32]= "" ;
char Ack[32]= "" ;
String inputString = "";
String Allconfiguration = "";
boolean stringComplete = false;
char  inChar;
boolean isConnected = false;
int OkMsg = 0;

void setup()
{
  SPI.begin();
  Serial.begin(115200);
  RadioSetupTransmiter();
}

void loop()
{
  if(stringComplete)
  {
         if(Allconfiguration.startsWith("\n")){Allconfiguration.remove(0,1);}
     Allconfiguration.remove(Allconfiguration.length());
    inputString = "";
    Serial.print("Allconfiguration : ");
     Serial.println(Allconfiguration);
    int counter = 0;
    for(int i=0; i<Allconfiguration.length(); i++)
    {
      if((Allconfiguration[i] == '\n')&&(i!=Allconfiguration.length()))
      {
        int pre_counter = counter;
        counter = i+1;
        inputString = Allconfiguration.substring(pre_counter, counter);
        if(inputString[0]!='$'){inputString.toCharArray(CharToSend,32);}

        if(radio.write(&CharToSend, sizeof(CharToSend)))
        {CheckData();
       Serial.print("inputString : ");
         Serial.print(CharToSend);}
      }
       if(i == Allconfiguration.length()){
        const char EndChar[2] = "$";

       }
        inputString = "";
    }
    Allconfiguration = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
  char inChar = (char)Serial.read();
    Allconfiguration +=inChar;
     if (inChar == '$'){stringComplete = true;
    }
    }
}

void RadioSetupTransmiter(){  radio.begin();

  radio.setChannel(0x35);
  delay(100);
  radio.setAutoAck( true ) ;
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  // radio.printDetails();

  radio.stopListening();
  radio.openWritingPipe(pipe[0]);

  radio.setRetries(1, 15);
 }

void CheckData(){
  int OkMsg = 0;
    while (!radio.isAckPayloadAvailable()){};
      if(radio.isAckPayloadAvailable())
      {
       radio.read(&Ack,sizeof(Ack));
       //Serial.println(Ack);
       if(strcmp(CharToSend,Ack) == 0){
        OkMsg = 1  ;
        Serial.println("AckRecived");
        radio.write(&OkMsg,sizeof(OkMsg));}
    }
}


texts: Can I use an Arduino Uno to support an RFID reader, Zigbee module and a touch screen at the same time?

texts: I'm almost a beginner to microcontrollers and have done a few simple projects, but this time I have to use an Arduino Uno (powered by a battery) to support an RFID reader (RC522), a Zigbee module and a touch screen altogether. Apparently there are too few pins to support all the modules. What is the easiest way to implement such a system?


texts: Communication between 2 nRF24l01s and 2 Arduino unos

texts:
I am having a logical error that I can not figure out with the communication. I am communicating fine with the two boards such that I can send and receive data. Code to my Transmitter and Receiver. Serial outputs here. Using library from this site: (Sorry reputation too low to add another link)

www.instructables.com/ORIG/FV6/0AAE/IBXM5ZIY/FV60AAEIBXM5ZIY.zip

(WARNING: will download with out permission if you visit link above. Use below link if dont want to download)

www.instructables.com/id/Wireless-Remote-Using-24-Ghz-NRF24L01-Simple-Tutor/?ALLSTEPS

(Scroll down to step 4, library's are labeled as "library files.zip". Names inside the zip folder are "nRF24L01" and "RF24")

From the Serial outputs I do not understand why on my transmitter it says it sent the time in milliseconds, 5873, but on my receiver output it says it received 241. Also I do not understand how the millis() function on the receiver returned a lesser value than what the transmitter should have sent.

I have novice understanding of c++ and the nRF24L01 radio at best. Any information is appreciated.

Thank you in advance!


texts:
I can't get to work a circuit that doesn't look that hard to copy.
This circuit was done for an Arduino extension of my DSC HS2032 system. I was trying the example "Status" on the Arduino's library DSC Keybus Interface v1.2.0.
On the example, we can see this circuit:
 *      DSC Aux(+) --- Arduino Vin pin
 *
 *      DSC Aux(-) --- Arduino Ground
 *
 *                                         +--- dscClockPin (Arduino Uno: 2,3)
 *      DSC Yellow --- 15k ohm resistor ---|
 *                                         +--- 10k ohm resistor --- Ground
 *
 *                                         +--- dscReadPin (Arduino Uno: 2-12)
 *      DSC Green ---- 15k ohm resistor ---|
 *                                         +--- 10k ohm resistor --- Ground

Here on the photos, I'm showing what I have done.

This is the HS2032 panel where (on the YEL and GRN) I connect the Arduino. I changed the Arduino's power source to be from my laptop so I could easily test it on the Serial Monitor. YEL->White/Green wire and GRN->Green wire
Now goes the Arduino's wiring.

Remember from the panel, the yellow is the white/green and the green is the green (they are coming from the right). First, each of both wires goes directly to 15kOhm resistor. Secondly, it splits between a 10kOhm resistor which then ends up into Arduino's ground, or it goes directly to the Arduino's pin 3 or 5, depending on the cable.
Results
The Serial Monitor shows "DSC Keybus Interface is online" and over.
If I connect green and white directly to 3 and 5, it will say sometimes "Keybus disconnected" and "Keybus connected" without any additional messages ever.
So my question is, am I missing something here? Why is the Serial Monitor not responding or what can I do to check where is the problem?
EDIT
This are the serial monitor readings, nothing from the Panel. I had to connect without resistances to get this output, otherwise, the only output would be "DSC Keybus Interface is online."
08:26:32.359 ->
08:26:32.359 -> DSC Keybus Interface is online.
08:26:35.345 -> Keybus disconnected
08:26:42.722 -> Keybus connected
08:26:47.838 -> Keybus disconnected
08:26:51.131 -> Keybus connected
08:26:54.937 -> Keybus disconnected
08:27:12.661 -> Keybus connected
08:27:17.122 -> Keybus disconnected
08:27:34.218 -> Keybus connected
08:27:41.697 -> Keybus disconnected
08:28:19.509 -> Keybus connected
08:28:22.487 -> Keybus disconnected
08:28:25.068 -> Keybus connected
08:28:28.053 -> Keybus disconnected
08:29:23.692 -> Keybus disconnected
08:29:31.175 -> Keybus disconnected
08:29:33.990 -> Keybus connected
08:29:37.005 -> Keybus disconnected