texts: Having an issue accessing values from a pointer

texts:
Context

This may be more of a C++ question than an arduino specific question, but it's dealing with arduino c++ so I thought I'd start here.

I'm building a class to abstract some simple melody playing that I want for a project. I got everything working in a procedural way, so I started moving everything out to a header and cpp file (still new-ish territory for me).

The general concept is that I want to call a public method on my class to allow my code to play a specific melody. I defined an enum for each melody available and in my playMelody() method I'm using a couple of pointers and a switch statement to get the specific frequencies and durations I need to play the specific melody. These frequency and duration values are stored in private arrays in the class.

Here's the header:

// MelodyPlayer.h

enum MELODY
{
    SHAVE_AND_A_HAIRCUT = 0,
    IDLE,
    READY,
    PROCESSING,
    COMPLETE,
};

class MelodyPlayer
{
    uint8_t speakerPin;

    int melody_shaveAndAHairCut[9];
    int durations_shaveAndAHairCut[9];
    int *activeMelody;
    int *activeDurations;

    void _playMelody();

public:
    MelodyPlayer(uint8_t speakerPin);
    void playMelody(MELODY name);
};

MelodyPlayer::MelodyPlayer(uint8_t pin)
{
    speakerPin = pin;

    int melody_shaveAndAHairCut[] = {
        NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4, 0};

    int durations_shaveAndAHairCut[] = {
        4, 8, 8, 4, 4, 4, 4, 4, 4};
}

void MelodyPlayer::playMelody(MELODY name)
{
    switch (name)
    {
    case SHAVE_AND_A_HAIRCUT:
        Serial.println("Shave and a hair cut");
        activeMelody = melody_shaveAndAHairCut;
        activeDurations = durations_shaveAndAHairCut;
        break;
    }

    _playMelody();
}

And here's the implementation:

// MelodyPlayer.cpp

void MelodyPlayer::_playMelody()
{
    Serial.println("Playing Melody");
    // * pulled from the toneMelody arduino example
    for (int thisNote = 0; thisNote < 8; thisNote++)
    {

        int activeDuration = activeDurations[thisNote];
        int noteDuration = 1000 / activeDurations[thisNote];
        int noteFrequency = activeMelody[thisNote];

        Serial.println(thisNote);
        Serial.println(activeDuration);
        Serial.println(noteDuration);
        Serial.println(noteFrequency);

        tone(speakerPin, noteFrequency, noteDuration);

        int pauseBetweenNotes = noteDuration * 1.30;
        delay(pauseBetweenNotes);

        noTone(speakerPin);
    }
}

And I call it in my .ino file like this:

MelodyPlayer player = MelodyPlayer(SPEAKER);
player.playMelody(SHAVE_AND_A_HAIR_CUT);

The problem

I'll upload the sketch and everything fires. The problem I'm running into is that when I get to the private _playMelody() method the values I get for activeDuration, noteDuration and noteFrequency are all ultra wrong:

I imagine I'm doing something wrong with the setting and getting of the values via the pointer variable I set in the switch statement, but I'm not sure where I'm going wrong.

You can see/pull down the actual code from the abstracting-to-class branch of my repo if you want to dig in.

I've done a similar dynamic-selection-via-pointer in a proof of concept before, but it was procedurally written, not classed. I can't seem to figure out where the difference is :|

Any ideas?


texts: Executing multiple functions/commands on Arduino

texts:
I am using an RFduino and an iOS application to control some RGB LEDs.

This is how I'm sending a string command to the module:

- (IBAction)fadeButtonPressed:(id)sender {
    [rfduino send:[@"fade" dataUsingEncoding:NSUTF8StringEncoding]];
}

These command(s) are coming back just fine on the RFduino side:

void RFduinoBLE_onReceive(char *data, int len) {
  if (strncmp(data, "fade", 4) == 0) {
    // begin fading chosen LED colour
  }
}

Is there a better way of executing multiple functions on Arduino? It seems to me that there should be a better way of doing what I'm trying to do.

Originally for example I was getting an issue where the "fade" string was coming back as "fadek" so I used strncmp(data, "fade", 4) instead of strcmp(data, "fade") and this fixed the issue.

I guess I'd like a way of cleaning up my code and perhaps make it easier to introduce new bits of functionality depending on which strings are coming back.

The functions I would like to be able to do would be controlling of the RGB colours and then Fading or Blinking that particular chosen colour.

What if I wanted to introduce faster blinking? Rather than setting another command integer and adding another condition is there a cleaner approach?

The selection of the colours is set by selection of a color wheel within my iOS application. This is working fine. The problem is that the Blinking and Fading does not blink/fade the selected colour (command 0).

Here is my entire sketch so far:

#include <RFduinoBLE.h>

// Pin 2 on the RGB LED.
int rgb2_pin = 2; // red
int rgb3_pin = 3; // green
int rgb4_pin = 4; // blue
int brightness = 0;
int fadeAmount = 5;

// Command properties.
int command = 0;

void setup() {
  // debug output at 9600 baud
  Serial.begin(9600);

  // Setup the LEDs for output.
  pinMode(rgb2_pin, OUTPUT);
  pinMode(rgb3_pin, OUTPUT);
  pinMode(rgb4_pin, OUTPUT);

  // This is the data we want to appear in the advertisement
  // (the deviceName length plus the advertisement length must be <= 18 bytes.
  RFduinoBLE.advertisementData = "rgb";

  // Start the BLE stack.
  RFduinoBLE.begin();
}

void loop() {
  if (command == 1) { // Fade in/out chosen colour.
    analogWrite(rgb2_pin, brightness);
    analogWrite(rgb3_pin, brightness);
    analogWrite(rgb4_pin, brightness);

    // Change the brightness for next time through the loop:
    brightness = brightness + fadeAmount;

    // Reverse the direction of the fading at the ends of the fade:
    if (brightness == 0 || brightness == 255) {
      fadeAmount = -fadeAmount ;
    }

    // Wait for 30 milliseconds to see the dimming effect
    delay(30);
  } else if (command == 2) { // Blink
    digitalWrite(rgb2_pin, HIGH);
    digitalWrite(rgb3_pin, HIGH);
    digitalWrite(rgb4_pin, HIGH);
    delay(200);
    digitalWrite(rgb2_pin, LOW);
    digitalWrite(rgb3_pin, LOW);
    digitalWrite(rgb4_pin, LOW);
    delay(200);
  }
}

void RFduinoBLE_onConnect() {}

void RFduinoBLE_onDisconnect() {}

void RFduinoBLE_onReceive(char *data, int len) {
  Serial.println(data);

  // Each transmission should contain an RGB triple.
  if (strncmp(data, "fade", 4) == 0) {
    command = 1;
  } else if (strncmp(data, "blink", 5) == 0) {
    command = 2;
  } else { // Change colour.
    // Reset other functions.
    command = 0;

    if (len >= 3) {
      // Get the RGB values.
      uint8_t red = data[0];
      uint8_t green = data[1];
      uint8_t blue = data[2];

      // Set PWM for each LED.
      analogWrite(rgb2_pin, red);
      analogWrite(rgb3_pin, green);
      analogWrite(rgb4_pin, blue);
    }
  }

  Serial.println(command);
}


texts: Can the 'Adafruit Non-Latching Mini Relay FeatherWing' be used with an Arduino microcontroller such as an Arduino Mega 2560?

texts:
Can this relay found here:

https://www.adafruit.com/product/2895

Be used with an Arduino Mega? The description given seems to specify that you should hook it up to their dedicated 'Featherwing Board' but it's the only relay available on their site. Looking at the pins it has it seems it should hook up to an Arduino with no problems. Has anyone here had the chance to use this relay with an Arduino microcontroller? I asked them about this on their forum but I haven't received a reply yet.

PS: I want to use it to connect a 'Strobe Siren 12VDC' and the relay I was looking to get is out of stock at my local shop.

https://store.nerokas.co.ke/index.php?route=product/product&product_id=1398
https://store.nerokas.co.ke/index.php?route=product/product&product_id=1679


texts: Can't able to detect Square wave from 74HC14

texts:
In my recent project, I want square wave which length vary according our timing. And this square wave is take reference as a another square wave.

For that, I made Square wave with help of Arduino.

Here, it's code.

int kPinSqrOut = 13;

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

void loop()
{
  digitalWrite(kPinSqrOut, HIGH);
  delay(1000);
  digitalWrite(kPinSqrOut, LOW);
  delay(2000);

}

This is just simple HIGH and LOW one pin of arduino and we get Square wave.

Oscilloscope output :

Now based on this, I'm getting Square wave which length can be able to vary.

Here, it's code.

const uint8_t button_pin = 2;
const uint8_t kPin = 3;

void setup()
{
   pinMode(button_pin, INPUT_PULLUP);
   pinMode(kPin, OUTPUT);
   Serial.begin(9600);
}

void loop()
{
   static int last_button_state = LOW;
   static unsigned int push_count;
   static unsigned long last_press_time;
   int button_state = digitalRead(button_pin);
   unsigned long now = millis();

  // Record when the button is pressed.
  if(last_button_state == LOW && button_state == HIGH)
  {
    push_count++;
    last_press_time = now;

    digitalWrite(kPin, HIGH);
    delay(20);
    digitalWrite(kPin, LOW);
  }

  // Report when the button is released.
  if(last_button_state == HIGH && button_state == LOW)
  {
    unsigned long push_duration = now - last_press_time;
    if (push_duration < 10)   // discard bounce
    {
        push_count--;
    }
    else
    {
       Serial.print(F("pushes: "));
       Serial.print(push_count);
       Serial.print(F(", duration: "));
       Serial.print(push_duration);
       Serial.println(F(" ms"));
    }
  }

  last_button_state = button_state;
}

And Serial Monitor output :

pushes: 1,    duration: 1001
pushes: 2,    duration: 1000
pushes: 3,    duration: 1001
pushes: 4,    duration: 1002
pushes: 5,    duration: 1001

ve
So, basically what I'm try to do. One Arduino generate Square wave and another Arduino take this Square wave as Input and calculate it's length and also generate another Square wave based on first one.

Here, I just detect HIGH state of Square wave and according that generate another Square wave which length vary.

Oscilloscope output :

Ideally, all this things work fine. Now, when I apply this things in real implement then not working.

Here, it my square wave(upper one) from 74HC14. But not getting another square wave based on that.

So, give me some suggestion.


texts: WEMOS D1 MINI NodeMCU, how to correctly powering it?

texts:
I'm developing a simple project using a WEMOS D1 MINI NodeMCU to drive an rgb LED strip so I managed to use a 12V power source to drive the current to the 12V pin of the led strip, a STEP DOWN converter takes in the 12V and reduce it to an output of 5V, the problem is that if I connect the WEMOS via USB it ALWAYS load in the right way, but if I'm powering it via the 5V pin 95% of the time it fails to correctly startup requiring to press the reset button in order to solve the problen, but sometimes it doesn't solve the problem, anyone knows why? I'm powering it around 4.9-5.1V is it relevant should I reduce the Voltage or rising it?

EDIT:

I also posted the question here, just in case


texts: If I run a function in loop() or setup(), and the function doesn't work after some time, is there a way to escape the function and return to the code?

texts:
The hardware is an Arduino Uno, using the Arduino IDE.
As a simplest working example, say I have this code
(partially from Edgar Bonet's answer):

// Simulate an initialization that can hang. Connect pin 8 to ground if
// you want the function to ever return.
void initialize()
{
    pinMode(8, INPUT_PULLUP);
    while (digitalRead(8) == HIGH)
    ;  // wait
}

setup()
{
    initialize();             //Function I want to run

    Serial.begin(9600);       //Baud rate
    Serial.println("TEST 1"); //Test message
}

loop()
{
    Serial.println("TEST 2"); //Test message
    delay(1000);
}

if the initialize() function does not complete after some time, such as 2 secs.,
is there a way to ignore that function and continue with the rest of the code?


texts: ESP8266 connecting keypad and lcd display

texts:
I have ESP8266 type -

I have added a keypad

With a standard lcd display.

I have connected the keypad from d0 to d7, however after watching some tutorials i have to connect the lcd display(SDA,SCL) to D0 and D1, where i should connect the display to when they are taken by the keypad?


texts: I have bought a new Arduino UNO and it works on CH340G. I want to code it using iOS phone, don't have a PC is there any way to install CH340G driver for iOS.


texts: avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30 etc. Arduino Uno

texts:
I've seen other posts on here and other places but none of them seems to work for me, which is why I am currently writing here. When I try to compile an empty sketch or an example sketch from Arduino to my Arduino Uno (atmega328P) using my AVRISP mkll programmer I get the following:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x20
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x20
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x20
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x20
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x20

avrdude done.  Thank you.

I have nothing connected on the TX/RX pins, I've tried disabling the firewall, I've done the loop thingie to make sure that stuff echoes back to me in the arduino monitor, I can't select "old bootloader" as the option is no longer valid in newer arduino releases for some reason?, I've tried to disconnect and re-plug the usb cable, I can see that it has found my COM3 port in my device manager and identify it as an Arduino device, and I've selected both the correct port and board within the Android IDE. So please, if anyone has some alternative solution to this problem my ears are all yours (also deadline for my master thesis soon, and currently the Arduino is messing that up).
Worth noting that I can upload programs from Atmel Studio using C code (but this is not what I want atm), so there is nothing wrong with the arduino uno or programmer; its in Arduino.


texts:
Is it possible to extract a backup of the sketch uploaded to a NodeMCU (as I know that it is possible to backup the firmware).

If so, using which tools?


texts:
Hi I have problem with school project. I have 3 Arduino - 1 Transmiter with NRF; 2,3 - NRF receiver and wire slave receiver.
I can't send data via "Wire" library (in code char "datar") to receiver arduino. I won't get anything, but when I want to send like Wire.write("blablabla"); it pass. But when in char is NRF data code crashing when go to "Wire.write".

/*
*/
#include <Wire.h>
#include <SPI.h>
#include "RF24.h"

char datar = '';

//Konfiguracja
const uint64_t pipes[2] = {0xF1F2F3F0F7/*odbieranie*/, 0xF1F2F3F0F8/*wysylanie*/};
RF24 radio(9, 10); //Piny nrf (SPI) 9 i 10
//-- Konfiguracja

void setup() {
  Serial.begin(9600);
  Serial.println("LOL");
  Wire.begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.openReadingPipe(1, pipes[0]);
  radio.openWritingPipe(pipes[1]);
  radio.setChannel(78);
  radio.setAutoAck(true);
  radio.startListening();
}

void loop() {

  int len;
  if(radio.available())
  {
  len = radio.getDynamicPayloadSize();
  radio.read(&datar, len);
  delay(5);
  Serial.println(datar);
  Wire.beginTransmission(7);
  Wire.write(&datar);
  Wire.endTran345smission();
  radio.printDetails();
  }
  delay(5);

}


texts: Waking up a NodeMCU when force load is applied to device

texts:
I am currently designing a device that will take measurements from a load cell that  is in tension. I am using a v1.0 NodeMCU device that features an HX711 load cell amplifier and is running off of battery power. In order to conserve that power, I am wanting to be able to put as many parts of the device as possible into a sleep of some level when there is not a load on the cell. Then, I would like the device to be a be able to wake up when a load is applied and it goes into use. Going into a sleep will be simple enough, if the device is getting a reading around zero for a period time, it can enter sleep. Other notable hardware involved on the device will be a real-time-clock and an accelerometer.

From what I have already tried to look up, there doesn't seem to be any good way to use the load cell to get this action. The only idea I have been able to come up with for how to activate the device without having to wake it up extremely often other than a manual switch or checks very often came from this question. It suggests using a vibration sensor like this, which is how bathroom scales put themselves to sleep.

While I think it might be possible to use a vibration sensor to wake up the device, I am not sure if the loads involved and use case will disallow me from using one. Are there any other sensors or methods that could be used to achieve goals that I have for this device?


texts: Syntax for declaring more than one serial pins of Arduino mega?

texts:
How can I declare multiple serial ports for Arduino Mega as it has been in the example below?

#include <SoftwareSerial.h>
SoftwareSerial mySerial(18,19); // RX, TX  //how this syntax can be modified for multiple Rx module?

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

void loop(){
   Serial.write(45);    // send a byte with the value 45

   int bytesSent = Serial.write(â€œhelloâ€); //send the string â€œhelloâ€ and return the length of the string.
}


texts: Interrupt routine for button somehow respondng to room lamp turning off and on

texts:
I have a sketch that has been running fine on an Uno 24x7 for a few months now.  The part of interest is an interrupt routine associated with a momentary contact switch [on pin 2].  When pressed, the interrupt routine handles debouncing and simply toggles a boolean variable.  The main routine checks status, takes action, warbles a buzzer, and does a Serial.print of the event.

Today, I moved the unit to the other side of the room and plugged it into a different PC via USB. Whilst it was running, I happened to turn on a nearby fluorescent light [not connected to anything but a 120v outlet].

The Uno buzzer went off, and appropriate msgs were written to the serial connection.  I flipped the light back on, and got the same kind of results.  I repeated this numerous times and got the same.  I could flip the light or push the button attached to the Uno, and the results were indistinguishable.

I unplugged the USB cable and used the power jack instead.  I got the same results, sans the print msgs to the serial connection.

The board itself has only a DS3231, an 8x8 LED matrix, a button, two LEDs & resistors, and a buzzer.

What is happening?  How can I resolve the problem?  [If another person had posted this, I would be disinclined to believe it, but surely someone out there understands the situation.]

I can readily supply a minimal code set and a Fritzing if it would help, though I suspect it would not.


texts: MPPT using preassembled 'adjustable' buck/boost IC

texts:
This is more of a thought experiment, as I don't know if I'll have the time to work on it.

Items:

Arduino
Homebrew MPPT controller from Instructables
LM2596 Adjustable Buck Regulator

Idea:

Looking at the Instructable, that seems like a fairly interesting and robust circuit, originally developed by one Tim Nolan whose website no longer seems to exist.

I'm somewhat lazy/fearful of messing things up when building from scratch, so I like to get preassembled modules and tinker instead. So, my thought is simple (ish). Looking at the LM2596 module, the output voltage is determined by the setting of the multiturn pot. I'd like to replace that pot with, say, a PWM controlled voltage from an Arduino, which I can then adjust using Tim Nolan's code to achieve MPPT.

So to be very specific, the question is: can I safely remove that pot and use a PWM'd voltage in its place, in order to control the output for MPPT?


texts: how to get an unofficial WiFi Shield to work?

texts:
I just bought these two WiFi Shields -> http://www.ebay.de/itm/262525969091?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

As they arrived I put one of them onto my Arduino Uno R3 and tried if my LED test sketch still works. It did.

After that I tried this WiFi tutorial (https://www.arduino.cc/en/Tutorial/ConnectWithWPA) to play around with the WiFi API a little bit. Sadly it prints to the serial monitor "WiFi shield not present" which tells me I missed something when setting up the shield.

I just thought the WiFi shield will be already usable without wiring anything. Surely that might be naive somehow, but hey I'm still a noob ;)

Can you guys tell me or simply point out a tutorial where it tells me what wiring I have to do to at least get pass this "WiFi shield not present" check?

Then I just realized that I do not have the "real" Arduino WiFi Shield and therefore the origin WiFi lib won't work for me according to this thread: http://forum.arduino.cc/index.php?topic=371362.0

Sadly I did not received any documenation on how to get this thing to work now. I found A LOT of threads about the "WiFi shield not present" error but none of them solved my specific problem with the shields I bought.


texts: So i am using adafruit io and esp-now on an esp32 to recieve voice commands from the internet and sensor values from another esp32. Independently, they both work quite fast but together the esp-now recieving speed slows down greatly with more packets lost. Any reason for that?


texts:
I am trying to split an incoming string into 2 integer values since I have to control 2 dc motors with it. The processor is node MCU and I get following error:-

Com Port Reading:-

WiFi connected
Received: "84+62"
"84+62"

Soft WDT reset

>>>stack>>>

ctx: cont
sp: 3ffffd90 end: 3fffffc0 offset: 01b0
3fffff40:  2b343822 00223236 3ffee70c 40204148
3fffff50:  3ffe85ee 3ffee6d8 3ffee70c 402043c5
3fffff60:  3ffe85dc 3ffee70c 3ffee6d8 402043c5
3fffff70:  3ffe85f0 3ffee69c 00000000 00000001
3fffff80:  00000000 40200038 3ffefca4 0000000f
3fffff90:  00000007 00000000 00000001 402048f9
3fffffa0:  3fffdad0 00000000 3ffee744 40204984
3fffffb0:  feefeffe feefeffe 3ffe851c 401009a5
<<<stack<<<

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

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

Code:-

if (msg.length() > 0) {
        Serial.print("Received: "); Serial.println(msg);
        char charBuf[50];
        msg.toCharArray(charBuf, 50);
        Serial.println(charBuf);

        char left[3] = {};
        char right[3] = {};
        int n = 0;

        while (charBuf != 0) {
          for (int i = 0; i < strlen(charBuf); i ++) {
            if (charBuf[i] != '+') {
              left[n] += charBuf[i];
              n++;
            }
            else {
              n = 0;
              break;
            }
            right[n] += charBuf[i];
            n++;
          }
        }
        Serial.println("Left Motor: "); Serial.print(left);
        Serial.println("Right Motor: "); Serial.print(right);

    }

My desired result is following:-

Left Motor: 84
Right Motor: 62

So what changes I need to make?


texts: Arduino Yun receives UDP packets but prints them with gibberish

texts:
Arduino Yun is set to receive UDP packets. It receives those data with some gibberish.
How is all set up: Arduino Yun (acts as a server) is connected through Ethernet to a PC which is (through WiFi) connected to the router. Another PC (acts as client), is also connected to the router (through Wifi).
Client uses netcat to connect to Arduino Yun. I write something and press enter. The packets are received by the Arduino Yun with some gibberish. For example, I write "test" and press enter, but this is what I receive on the Arduino Yun:

Sometimes gibberish characters are different, but always exist. This is what Wireshark monitors when I send the "test" packet (with netcat) to my Arduino Yun:

It shows that indeed I send only "test", so the gibberish is created on the Arduino side, I suppose.
This is my sketch (not the entire code, but the important part):
void loop() {
  int udp_received = Udp.parsePacket();
  if (udp_received) {
    char udp_buffer[16];
    udp_buffer[15] = '\0';
    Udp.read(udp_buffer, 15);
    Serial.println(udp_buffer);
  }
}

I use BridgeUdp.h
Any insights appreciated.


texts: What is the proper way to send data through http using sim908?

texts:
Preamble:

I have a sim908 shield and I'm trying to send some data periodically to a server using AT commands.
For every command, I wait for the response to check if everything is working.
Actually the sketch works but, often, I noticed errors during http request.

State of the art:

Here it is the sequence of AT commands (not the entire code) into the loop:

1) Check the Network Registration and, if necessary, wait

AT+CREG?

2) Set params for GPRS connection (no user or password required)

AT+SAPBR=3,1,"Contype","GPRS"
AT+SAPBR=3,1,"APN","web.omnitel.it"

3) Get current bearer

AT+SAPBR=2,1

4) If bearer == 0,0,0,0 (not assigned) get a new bearer

AT+SAPBR=1,1

5) Init HTTP

AT+HTTPINIT

6) Set CID and URL

AT+HTTPPARA="CID",1
AT+HTTPPARA="URL","www.someurl.com/service.php?p1=1&p2=2"

7) Execute the HTTP command (POST)

AT+HTTPACTION=1

8) Close HTTP connection

AT+HTTPTERM

Question:

Why HTTP init (step 5) or HTTP posting (step 7) often fails? What is wrong in this procedure? I'm missing something? There is a way to make the procedure more stable?

Thank you in advance :)

Important update:

If occurs an error during sending data via HTTP, is a great idea to renew the bearer (step 4)

Answers to the comments:

a) Shield has an antenna and it works. If I try to disconnect the antenna, code still  search the network (step 1) untill I reconnect the antenna.

b) Some times I have this error initializing HTTP (step 5):

  AT+HTTPINIT

  +CME ERROR: 3

Some times I have only "OK" as response posting data (step 7) instead of:

  +HTTPACTION:1,200,xxx

Or this response:

  +HTTPACTION:1,600,0

c) I have error at step 4 (AT+SAPBR=1,1) only if I execute the command when I have yet a bearer. The error in this case is:

  AT+SAPBR=1,1

  +CME ERROR: 3

For this reason I do a check (step 3)


texts: Python Arduino Serial Communication Speed

texts:
Background : Im controlling serial manipulator using Arduino Uno with Servo Shield. Servo work at 20 ms, so i would like to send command atleast every 2.5ms. Command sent from PC.

I send 8 bytes of data from my python code on PC at 250k Baudrate. If i send it every 25 ms, my robot could respond and everything works fine. But if i send every 2.5 ms, my system wont work.

Here my arduino code,

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
int x,temp;

int sudutT0(long int p)
{
  int u = 3600+((405*p)/180);
  return u;
}

void setup() {
  Serial.begin(250000);
  Serial.println("Joint 2 Test!");
  pwm.begin();
  pwm.setPWMFreq(50);

  Wire.setClock(1000);
  for (uint8_t pin=0; pin<16; pin++)
  {
  pwm.setPWM(pin, sudutT0(90),4095);
  }
  pwm.setPWM(3, sudutT0(150), 4095);
}

void loop() {
    if(Serial.available() == 8){
      if(Serial.read() == 0xF5)
      {
        //Joint 1
      temp = Serial.read();
      x = sudutT0(temp);
      pwm.setPWM(0,x,4095);
      // Joint 2 Servo
      temp = Serial.read();
      x = sudutT0(temp);
      pwm.setPWM(1,x,4095);
      x = sudutT0(180-temp); //810 - theta
      pwm.setPWM(2,x,4095);
      //Joint 3 - 6, Gripper
      for(uint8_t u = 3; u<8; u++)
      {
        temp = Serial.read();
        x = sudutT0(temp);
        pwm.setPWM(u,x,4095);
      }
      //delay(100);
      }
    }
}

Is there anything that i miss, that make my system could not respond if i send signal every 2.5 ms?


texts:
I'd like to use my Teensy 3.1 to send MIDI Show Control messages using USB MIDI in order to control an ETC Nomad system. These are different from standard NoteOn, NoteOff, ProgramChange, etc. commands, but as far as I can tell they are not supported by the standard library.

Is there any way I can send these messages directly (using lower level commands), as seen here, or does anyone know of a library that supports this? Google has, unusually, not been much help.


texts: Best way to power an Arduino using the Vin pin

texts:
I have a powerbank rated 5v. The battery is actually 3.6v, powering the built-in SMPS to give out 5v. I have stripped one end of the USB cable coming from the power bank, powering a motor driver and the Arduino in parallel. The positive end of the power bank, which is 5v, is going into the Arduino and the motor driver IC's Vcc.

I heard that 5v is not enough to drive the Arduino from the Vin pin. And there is only one power out from the powerbank, so directly connecting the Arduino through the USB would leave nothing to drive the motor driver IC.

A USB splitter would be the obvious solution, but is there anything else I can do? The power source has to be mobile. Can I power the Arduino through the Vin with those 9v batteries commonly used in electronics hobby projects?


texts: I'm getting watchdog timer resets in NodeMCU. How can I permanently disable or stop that?

texts:
I'm using NodeMCU for my project. At first it works fine, but after some days it is resetting frequently because of the watchdog timer. I have used the Esp.wdtfeed() method also. But it is not working. Can you please tell me what the problem exactly with or any solution? Here is my code:

void setup(void) {
  ESP.wdtDisable();
  ESP.wdtEnable(WDTO_8S);
  Serial.begin(9600);
  int n = WiFi.scanNetworks();
  Serial.println("");
  if (n == 0)
    Serial.println("no networks found");
  else {
    for(int i=0;i<n;i++) {
      if(WiFi.SSID(i)==ssid1) {
        WiFi.begin(ssid1,password1);
        ssid=ssid1;
      } else if(WiFi.SSID(i)==ssid2) {
        WiFi.begin(ssid2,password2);
        ssid=ssid2;
      } else if(WiFi.SSID(i)==ssid3) {
        WiFi.begin(ssid3,password3);
        ssid=ssid3;
      }
    }
  }
  display.init();
  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_16);
  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.drawStringMaxWidth(15,15, 128,"Display started");
  display.display();
  // Wait for connection
  display.clear();
  int j=0;
  while(j<10) {
    display.drawStringMaxWidth(15,15, 128,"connected to");
    display.drawStringMaxWidth(15,32, 128,ssid);
    display.display();
    display.clear();
    delay(1000);
    j++;
  }
  display.drawStringMaxWidth(15,32, 128,"");
  display.display();
  Serial.print("Connected to ");
  display.clear();
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  if (mdns.begin("esp8266WebForm", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.print("Connect to http://esp8266WebForm.local or http://");
  Serial.println(WiFi.localIP());
  server.on("/", getvalues);
  pinMode(buzzPin,OUTPUT);
  pinMode(but,INPUT);
}

void loop(void) {
  ESP.wdtFeed();
  if((WiFi.status()== WL_DISCONNECTED)||(WiFi.status()==WL_CONNECTION_LOST)) {
    display.drawStringMaxWidth(15,15, 128,"disconnected");
    display.display();
    int n = WiFi.scanNetworks();
    Serial.println("");
    if (n == 0)
      Serial.println("no networks found");
    else {
      for(int i=0;i<n;i++) {
        if(WiFi.SSID(i)==ssid1) {
          WiFi.begin(ssid1,password1);
          ssid=ssid1;
        } else if(WiFi.SSID(i)==ssid2) {
          WiFi.begin(ssid2,password2);
          ssid=ssid2;
        } else if(WiFi.SSID(i)==ssid3) {
          WiFi.begin(ssid3,password3);
          ssid=ssid3;
        }
      }
      int j=0;
      display.clear();
      while(j<10) {
        display.drawStringMaxWidth(15,15, 128,"connected to");
        display.drawStringMaxWidth(15,32, 128,ssid);
        display.display();
        display.clear();
        delay(1000);
        j++;
      }
      display.clear();
      display.drawStringMaxWidth(15,32, 128,"");
      display.display();
    }
  }
  getvalues();
  delay(20000);
}


texts: when 3 components on Arduino nano work together, one of them doesn't work

texts:
When I was doing a desktop fan project, I'm trying to put a servo motor, a 5v motor with potentiometer and DHT-11 on it
at first, the servo motor and DHT 11 works, but the 5v motor with potentiometer doesn't.
I thought it may be the problem with the power supplies. by the way, I'm using the direct power supplies from my laptop USB cable
then I just annotated all the code for DHT11 to let it stop running.
Then, it starting reporting an error with my myservo.attach(11);
which was
exit status 1
'myservo' does not name a type

I just get crazy about this.
I don't want these credits on electronics and robotics now.
/*Arduino nano                                      works
    DHT11-TEMP                                        works
    servomotor for oscillating           works
    fan motor and speed control     wrong
    */

/*#include "DHT.h"                                                       //DHT11 <Variable and library settings>
#define DHTPIN 10
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE); */

#include <Servo.h>                                                  // oscillating <library settings>
Servo myservo;
int pos = 0;

int pwmPin = 12; //pin 12, power to motor                 //fan motor and speed control <library settings>
int pot = A1; // input from variable resistance
int c1 = 0;   // recording in variable c1
int c2 = 0;   // recording in variable c2

  /*void setup() {
  Serial.begin(9600);                                                    //DHT11< setup>
  Serial.println(F(" DHT-11 STARTING!"));
  dht.begin();                       */

  myservo.attach(11);                                             /*oscillating< setup>*/

  pinMode(pwmPin, OUTPUT);                                /*fan motor and speed control <setup>*/
  pinMode(pot, INPUT);
}
void loop() {
  /*
  delay(1000);                                                                            //DHT11< loop>
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
}
  float hif = dht.computeHeatIndex(f, h);
  float hic = dht.computeHeatIndex(t, h, false);
  Serial.print(F(" Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("C "));
  Serial.print(f);
  Serial.print(F("F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("C "));
  Serial.print(hif);
  Serial.println(F("F"));
*/

for(pos = 0; pos <= 180; pos += 1)                            /*oscillating< loop>*/
{
    myservo.write(pos);
    delay(30);
 }
  for(pos = 180; pos>=0; pos-=1)
  {
    myservo.write(pos);
    delay(30);
  }

   {
  c2= analogRead(pot);                                                                  /*fan motor and speed control<loop>*/
  c1= 1024-c2;         // subtracts c2 from 1000 ans saves the result in c1
  digitalWrite(pwmPin, HIGH);
  delayMicroseconds(c1);
  digitalWrite(pwmPin, LOW);
  delayMicroseconds(c2);
   }
}


texts: avrdude.conf: programmer type must be written as "id_type"?

texts:
I'm trying to compile & run using ino.

At the ino upload step I get the following error:

avrdude: error at /usr/share/arduino/hardware/tools/avrdude.conf:332: programmer type must be written as "id_type"

Relevant section of avrdude.conf:

programmer
  id    = "wiring";
  desc  = "Wiring";
  type  = wiring;   # line 332
;

I've seen various posts around the internet that suggest I just delete the config & refresh it, but I'd like to find the correct syntax and actually understand & fix the issue.


texts: SIM900 module connects then disconnects from carrier soon after


texts: Shift register with relay board behaving erratically

texts: I have a nodemcu connected to a shift register(https://www.amazon.de/gp/product/B07CHBYR7Z) to control an 8 channel relay board (https://www.amazon.de/Elegoo-Relaismodul-Optokoppler-Arduino-Raspberry/dp/B01M61VVGV). The realy board is connected to various pumps. The setup itself works quite well normally. However after some switching cycles or when I manually bridge the relay to activate a pump the shift register suddenly either doesnt react at all. Switches on everything or is off by one. I read that it might be possible that I have flow back from the relay coil so I added the diode over the gnd and vcc pin of the relay board. However that didnt help either. Can anybody tell me what I am doing wrong? I hope the schematic is legible.


texts:
So, I was working on a project where I needed to get a random object from a stack, so to make sure my design was correct, I made a dummy program that does nothing but fill a stack with data, then print it out.

why in the world is nothing coming out of the stack but -1s??

Here's the stack.h file.

http://pastebin.com/vjhNLpNu


texts: Communication between Arduino Uno and Mega

texts:
I am working on a project which uses a set of sensors (HC-SR04). These sensors use pins 2 to 13 of the Arduino Uno. Here you can find the board:

.

I also want to add an MP3 shield (VS1053B) to it and it fills all the pins on Arduino. So I decided to add an Arduino Mega and add the sensors to it and use the Arduino Uno and MP3 shield. The problem is with connecting these two Arduinos. As I said the MP3 shield fills A4 and A5 pins too, so I can not use them to communicate with the Mega. What other options do I have?


texts: What is the equivalent of this old SPI code using the current SPI library?

texts:
I see some old library code that initializes SPI this way:

    SPI.begin();
    SPI.setClockDivider(2);

It does not use beginTransaction/endTransaction blocks, and setClockDivider is now deprecated. The current way to use SPI is to use transaction blocks where you pass the settings in.

What is the equivalent to this code using transaction blocks? Also, since the other settings (max speed, data order, data mode) aren't specified in the above code, there must be defaults. What are these defaults?


texts: Can I use two sensors with different baud rate without problems on arduino?

texts:
One sensor has a baud rate of 115200, the other 9600. I think this will create problems in the serial because I can only choose one baud rate.

What do you think?
The first sensor is the pulse sensor, while the other is the gsr sensor by grove.
Link: http://pulsesensor.com/
Link 2: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor


texts: LED GPS Speedometer Not Registoring Speed Above 0

texts:
I'm trying to make a speedometer that will change colors depending on the speed on which I am traveling.

If the speed is decreasing at any time or below 5 mph LEDs be red.

And if the speed is above 5 mph or increasing speed the LEDs will be a different color.

I am using an Adafruit 24 NeoPixel ring for LED's and a u-blox NEO-6 GPS module.

And the GPS is sometimes not registering the speed or any other GPS values and not switching colors when speed is at certain values or when it is increasing or decreasing. It tends to stay only one color no matter the speed. Also the GPS is not registering speeds above zero when I ride my bike or in a moving car.

I added a picture of the values I am getting, it seems to be connecting to satellites and getting correct GPS coordinates but as soon as I as I take it to real world test, the speed inst changing and LEDs are not changing. I also included a picture of the Arduino configuration I am using.

I am a very new to coding so any help would be very grateful.

(if anyone could help with the accelerating and decelerating code to that would be absolutely amazing!!!!)

#include "TinyGPS++.h"
#include "SoftwareSerial.h"
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define LED_PIN  6
#define LED_COUNT 24
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_RGB + NEO_KHZ800);
SoftwareSerial serial_connection(10,11);
int speedM;
TinyGPSPlus gps;

void setup() {
  #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
#endif
  strip.begin();
  strip.show();
  strip.begin();
  Serial.begin(9600);
  serial_connection.begin(9600);
  Serial.println("Project Red Stop");
}
void loop() {
speedM = gps.speed.mph();
//int val = speedM;
 while(serial_connection.available())//While there are characters to come from the GPS
  {
    gps.encode(serial_connection.read());//This feeds the serial NMEA data into the library one char at a time
  }
  if(speedM < 5)
  //   if(speedM < 5 & val--)
  {
    Serial.println("Speed MPH:");
    Serial.println(gps.speed.mph());
    Serial.println("Satellite Count:");
    Serial.println(gps.satellites.value());
    Serial.println("Latitude:");
    Serial.println(gps.location.lat(), 6);
    Serial.println("Longitude:");
    Serial.println(gps.location.lng(), 6);
    colorWipe(strip.Color(0,100,0), 100);
   // strip.setPixelColor(0, strip.Color(0,100,0));                   // gps works faster with this:
    strip.show();
    delay(10);
  }
  else if(speedM > 5)
  //   else if(speedM > 5 & val++)
  {
    Serial.println("Speed MPH:");
    Serial.println(gps.speed.mph());
    Serial.println("Satellite Count:");
    Serial.println(gps.satellites.value());
    Serial.println("Latitude:");
    Serial.println(gps.location.lat(), 6);
    Serial.println("Longitude:");
    Serial.println(gps.location.lng(), 6);
    colorWipe(strip.Color(0,100,100), 100);
    strip.show();
    delay(10);
  }
}
void colorWipe(uint32_t color, int quick) {
  for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
    strip.setPixelColor(i, color);         //  Set pixel's color (in RAM)
    strip.show();                          //  Update strip to match
    delay(0);                           //  Pause for a moment
  }
}


texts:
Given the following enums

enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
enum class CrossingZoneState: uint8_t {
    CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
    CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
};

Where RELAY_OFF = HIGH, HIGH is #define HIGH 0x1 which I assume is a C++/Arduino constant? because I didn't define it. And RELAY_ON = LOW, LOW is 0x0

in the following function I get the error that follows.

CrossingZoneState CheckEntrySensor(uint8_t esp) {
    //esp, short for entry sensor pin
    if (digitalRead(esp) == HIGH)
    {
        state = CrossingZoneState::CROSSINGZONE_CLEAR;
        return state;
    }
    else if (digitalRead(esp) == LOW)
    {
        state = CrossingZoneState::CROSSINGZONE_OCCUPIED;
        return state;
    }
    // if the digital read errs, return the current state so it re-runs
    return state;
};

boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState relayState)    {

    int testInt = 0;
    if (relayState == RelayState::RELAY_OFF)
    {
        testInt = 1;
    }
    digitalWrite(relayNumber, relayState);
    if (digitalRead(relayNumber) == testInt) {
        return true;
    };
    return false;
};

I tried having RelayState be an enum class as well but was getting similar type errors. Here is the error from VS2015 with the code shown above.

  Compiling debug version of 'ModelRRXingStateMachine' for 'Arduino/Genuino Uno'
  ModelRRXingStateMachine.ino:11:55: error: 'RelayState' has not been declared
  :boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState relayState)
  ModelRRXingStateMachine.ino:2:1: error: 'CrossingZoneState' does not name a type
  :CrossingZoneState CheckEntrySensor(byte esp)
  Error compiling project sources

I'm not a professional programmer and am new to C++, usually writing in C# or VB.Net so I'm not sure what the compiler is looking for here, both enums are declared and one is declared with a type. Also, the VS code editor is showing no errors, the errors shown above show up in the error window when I try to build.


texts: Number of digits setting for serial printing the sensor output value

texts:
I am getting fan motor rpm as 3200. But if I get the data as 50, I should get the value like 0050. How can I do this?

I can do it like checking the value for single digit(0-9), double digit (10-99), and triple digit (100-999) and four digit(1000-9999). I need to fix digit size and send it through serial. Is there any other way for this?


texts: Getting more current through an LED array

texts:
I have an Arduino Uno controlling an array of 24 LEDs (datasheet).  I understand these LEDs are ultraviolet and have a forward current of 0.5A.  My power source (12V 2A) is wired to a switch which is then wired to the LED array and Arduino.  I should probably use a 12V 4A power source but was worried if too much current would go to the Arduino.  As per my attached diagram, the Arduino and LED array are in parallel.  I would like to get more current through my LEDs to increase their brightness.  What would be the best way to do this?

Updated: I tried adding a 100 Ohm resistor (where R11 is located) but the Arduino wasn't drawing enough power to turn on my LCD.  And then I tried a 1 Ohm resistor instead but the resistor burned out.  Unfortunately, I threw out the resistor and don't have a picture of it.  I believe the correct value should be ~47 Ohm so I have added that resistance as R11.  However, I haven't tested it yet as I want to make sure it's correct.  (12V - 6V) = 130mA * R >>> R = 46.15 Ohm.  I used a voltage drop of 6V so that at least 5V is still going into the Arduino (12V - 6V = 6V which is greater than 5V).  I measured the current through a multimeter to be 130mA.


texts: How do you use an Arduino to control a 4 - 20 mA transmitter?

texts:
I am using an Arduino Mega to control the speed of an AC pump. This can be done by connecting to the variable frequency drive. Here is a link of the relevant datasheet, pages 66 and 67 relate to what I am doing.

http://www.parker.com/Literature/SSD%20Drives/AC%20Drives/AC650/HA464828U003.pdf

From what I have read and been told already, I should be able to control this using a 4 - 20 mA loop, which is fed into AIN2, as long as I connect the 0V terminal as well?

My question is what is the best way to make a current loop transmitter using an Arduino Mega.

So far the options I have are:

Create a circuit out of discrete components, this would then be controlled using the Megas PWM
Use an IC circuit, I was looking at the AD694JNZ
Use an add on board, I was looking at this one: http://uk.rs-online.com/web/p/products/8828929/?grossPrice=Y&cm_mmc=UK-PLA--google--PLA_UK_EN_Semiconductors-_-Semiconductor_Development_Kits&mkwid=sm9dTYvCc_dc|pcrid|88057061283|pkw||pmt||prd|8828929&gclid=CjwKEAjwk6K8BRDM3aCSkdCtzSQSJAA3Vf38mNs9lZrg2A1AjrVpS3SCubT0AbAr7L8OImUZbfCPzRoCIXjw_wcB

I have a budget for my project so cost is not an issue, however I am running out of time. What would be the easiest method to implement and how?

I have been thinking of using options 2 or 3, however my issues are that this is my first Arduino project. I understand what PWM is but I don't know how I would go about implementing it. I also can't find any tutorials online that demonstrate how to program the MIKROE board using an Arduino.

Thank you in advance for any help :)


texts: Running in loop or once according to a slide switch position

texts:
I have a question.

I made a system which includes a servo, a stepper and a wiper motor :)
All these parts has one job to do and I can code it. But, I want to make 2 modes in this system Single Operation, Loop operation.

for example position 1-single operation, 2-loop operation.
I can code the loop operation thanks to arduino syntax :)

But I cannot code single one. I can read switch state detection.  I want to do exactly same things, but only one time when slide switch on the position.

The code is really long and it includes Turkish defines. If you need to see the code, let me know.


texts: Arduino Leonardo as keyboard installs driver

texts:
I want to do some security awareness training within the company I work for. And I want to demonstrate the BadUSB attacks by having some arduino's act as a keyboard and open a webpage, and scatter these USB's around my workplace.

However, whenever I plug it in a new machine it installs it's Arduino drivers, which takes a long while. This sadly kills the use I have for it.

Is there a way to have the arduino act as a keyboard without the need of installing new drivers?

The Arduino I use is the Arduino Leonardo

I'm new to arduino's and frankly I don't have a solid grasp on how drivers work, so if I said something dumb that's probably why :P.


texts: Porting SH1106 Oled Driver - 128 x 64 / 128 x 32 Screen is garbled but partially responsive

texts:
I'm porting the SH1106 driver to netmf and have found several libraries that more or less accomplish the same thing. A few were much easier to understand and had less abstraction so I followed those.

I've tried the U8glib with my arduino and it works just fine. The ported display driver yields these results:

inverted:

What you're looking at is the screen right after the initialization and attempting to draw a filled circle. You can see the bottom of the circle at the top of the screen. Somehow the origin or page is shifted, but I don't fully understand what's going on. I can send the invert display command and that works as well and turn the display on and off. My initialization code is this:

public void init()
{
    resetPin.Write(true);
    Thread.Sleep(1); // VDD (3.3V) goes high at start,
    resetPin.Write(false); // bring reset low
    Thread.Sleep(10); // wait 10ms
    resetPin.Write(true); // bring out of reset

    dcPin.Write(DisplayCommand);

    SendCommandB(0xAE);    /*display off*/

    SendCommandB(0x02);    /*set lower column address*/
    SendCommandB(0x10);    /*set higher column address*/

    SendCommandB(0x41);//0x40);    /*set display start line*/
    SendCommandB(0xB0);    /*set page address*/
    SendCommandB(0x81);    /*contract control*/
    SendCommandB(0x80);//contrast);    /*128*/
    SendCommandB(0xA1);    /*set segment remap*/
    SendCommandB(0xA6);//invertSetting);    /*normal / reverse*/
    SendCommandB(0xA8);    /*multiplex ratio*/
    SendCommandB(0x3F);    /*duty = 1/32*/
    SendCommandB(0xAD);    /*set charge pump enable*/
    SendCommandB(0x8B);     /*external VCC   */
    SendCommandB(0x30);    // | Vpp);    /*0X30---0X33  set VPP   9V liangdu!!!!*/
    SendCommandB(0xC8);    /*Com scan direction*/
    SendCommandB(0xD3);    /*set display offset*/
    SendCommandB(0x00);   /*   0x20  */
    SendCommandB(0xD5);    /*set osc division*/
    SendCommandB(0x80);
    SendCommandB(0xD9);    /*set pre-charge period*/
    SendCommandB(0x1F);    /*0x22*/
    SendCommandB(0xDA);    /*set COM pins*/
    SendCommandB(0x12);
    SendCommandB(0xDB);    /*set vcomh*/
    SendCommandB(0x40);
    SendCommandB(0xAF);    /*display ON*/

    // Switch to 'data' mode
    dcPin.Write(Data);
    this.ClearScreen();
    this.Refresh();

}

I have two methods to "refreshing"

public virtual void Refresh()
        {
            Spi.Write(displayBuffer);
        }

    /// <summary>
    /// Send buffer to display
    /// </summary>

public void Display()
        {
            //set column address
            dcPin.Write(DisplayCommand);
            SendCommandB(0x21);
            SendCommandB(0);
            SendCommandB((byte)(Width - 1));

            //set page address
            SendCommandB(0x22);
            SendCommandB(0);
            SendCommandB((byte)(_pages - 1));
            dcPin.Write(Data);

            //Spi.Write(displayBuffer);

            for (ushort i = 0; i < displayBuffer.Length; i = (ushort)(i + 16))
            {
                //Spi.Write(displayBuffer);
                SendArray(displayBuffer, i, (ushort)(i + 16));
            }
        }

At this point I'm a little lost. My hunch is something to do with paging and or display RAM. I'm looking for some insight here on how to fix this as I know there's a lot of experience here with these displays. Thanks!


texts: Project wont compile when I place functions below function calls

texts:
I use VSCode, not the Arduino IDE. I saw and tried to use a lot of code snippets which are provided for Arduino projects...

So when I copy/paste these examples into my VSCode and try to compile it fails. (I won't believe that people offer non-working examples.)

When I place the functions above the function calls it compiles.

Is this normal behavior or do I have to add some settings to get this working as provided?

Fails in VSCode (works in Arduino IDE):

#include "Arduino.h"
void setup() {
}
int zero = 0;

void loop() {
  zero = myfunction();
}

int myfunction(){
  return 0;
}

Works in VSCode (Works in Arduino IDE):

#include "Arduino.h"

void setup() {
}
int zero = 0;

int myfunction(){
  return 0;
}

void loop() {
  zero = myfunction();
}


texts: Might be a stupid question (not too experienced), but when I upload two different pieces of code intended for two different devices connected to the arduino, does it overwrite the first upload and if so what can I do to over come this. Im trying to use an NFC reader and fingerprint scanner but when i upload the second code to the board it just seems to overwrite the previous.


texts: WeMos D1 ESP-Wroom-02 Mother Board ESP8266 - where is reset pin for deep-sleep

texts:
This item was bought for battery use with deep sleep purposes. For doing so in ESP8266 reset pin must be connected to Gnd pin in order to wake up. This board lacks a reset on- board pin.
Since spec states it has a such capabilities - I wonder if someone has succeeded with putting it to sleep ( and wake it back on ).
PS - I know that on-chip gpio16 can be soldered to on-chip gnd - I'm hoping there is a more elegant, not soldering invloved, solution.
Guy


texts: How to dim background LEDs on TFT display with ILI9341

texts:
I have bought a 2.5" TFT shield online, which is equipped with the ILI9341 controller. I need to dim the intensity of the background LEDs to match ambient light.
This particular shield does not provide a pin to control the intensity of the LEDs with PWM via a separate input, so I need to dim the background LEDs of this display via software.
The zip file with the libraries can be downloaded here.
Does one of you know how can issue a command to the TFT display to dim the background LEDs?
Thanks in advance!
UPDATE 1:
I wrote a new function to set the display's brightness by controlling the background LEDs, but something is missing as I can seem to be writing correctly to the display. So I'm trying to get the display to answer to a known command first, like 0x28 (Display Off).
The new function is defined in Adafruit_TFTLCD.cpp:
// Set display brightness (background LED's)
void Adafruit_TFTLCD::setDisplayBrightness(uint8_t x) {
  // Try with 0x28 (Display Off) to see if display reacts
  writeRegister8(0x28, 0);
  return;
}

The function prototype is defined in Adafruit_TFTLCD.h
// New functions
void setDisplayBrightness(uint8_t x);

Then I call the function in my main loop. To make sure, I first write some rectangles on screen, wait 5 seconds, then fill the screen with blue, call the new function and enter an endless loop so no other commands can interfere:
  tft.fillScreen(BLUE);
  tft.setDisplayBrightness(10); // Which really is command 0x28 to test

Any clues what I might be missing?
Thanks!
UPDATE 2:
I got so far as to have the ILI9341 react to some commands, but not all the time, and not to all commands. I suspect there is something in the way you issue the commands that I'm missing( timing?, sequence?, other?)
Here is what I have found out so far:
I can get the display to react to the Display Off command (0x28), but only when I issue it in the begin(..) function. So, the original code in Adafruit_TFTLCD.cpp is like this:
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
delay(500);

If I change it to the following the display reacts by remaining white:
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
writeRegister8(ILI9341_DISPLAYOFF, 0); // Display off is declared as 0x28
delay(500);

So, I have a reaction to command 28h.
Then I tried function 0x51 like this in the begin(...) function:
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
delay(500);
writeRegister8(0x51, 0x80); // Test command 0x51 - background intensity
delay(500);

To no effect :-(
I even added command 0xBE (background PWM frequency) to see if it had any effect, but nothing :-(
void Adafruit_TFTLCD::begin(uint16_t id) {
  ...
  writeRegister8(ILI9341_DISPLAYON, 0);
  writeRegister8(0xbe, 0x80);
  delay(500);
  writeRegister8(0x51, 0x0);
  delay(500);

Also if I issue the 0x28 command:
writeRegister8(ILI9341_DISPLAYOFF, 0)

elsewhere in Adafruit_TFTLCD (e.g. in FillScreen, Fill Rect etc, it doesn't work either).
Any ideas? They would be highly appreciated!


texts: Arduino eeprom_put sketch writes data in two locations?

texts:
Using precisely this code - the eeprom_put example in the Arduino IDE, and am seeing some strange results...

The sketch does write correctly to eeAddress = 0, and the corresponding eeprom_get sketch does return the data.

Please note that I've initialized the entire EEPROM with 'FF's before any test...

The weird part is this sketch writes exactly the same data starting at Address = 2048. The loop is not running; I see no jump to offset 2048... I gotta be missing something!

I'm dumping EEPROM using avrdude, and viewing results in an external hex editor.

How is this stuff stored? Apart from not being able to directly view a float - OK, I get it - should the other data be simply viewable in hex?

My own experiments in writing hex bytes directly also work, but also write in two locations.

Small update to this: Precisely the same behavior seen with a RobotDyn Mega. Both the 'clone' Mega and the RobotDyn report: Device signature = 0x1e9801 (probably m2560)

#include <EEPROM.h>

struct MyObject {
  float field1;
  byte field2;
  char name[10];
};

void setup() {

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

  float f = 123.456f;  //Variable to store in EEPROM.
  int eeAddress = 0;   //Location we want the data to be put.

  //One simple call, with the address first and the object second.
  EEPROM.put(eeAddress, f);

  Serial.println("Written float data type!");

  /** Put is designed for use with custom structures also. **/

  //Data to store.
  MyObject customVar = {
    3.14f,
    65,
    "Working!"
  };

  eeAddress += sizeof(float); //Move address to the next byte after float 'f'.

  EEPROM.put(eeAddress, customVar);
  Serial.print("Written custom data type! \n\nView the example sketch eeprom_get to see how you can retrieve the values!");
}

void loop() {
  /* Empty loop */
}


texts: Code doesn't seem to work when trying to program 2 sensors

texts:
Can anyone help me with this issue

I'm trying to program two FSR sensors through typing this code but I've realized that one is working instead of two.

The logic behind the code is that if you were to squeeze both sensors at the same time it will print out an output on the serial monitor acknowledging that both sensors have been squeezed. I have got only one to work by using this code.

The first sensor is connected to the A0 pin on the arduino and the second sensor is connected to the A1 pin

This is the code that I've written

/* FSR simple testing sketch.

 Connect one end of FSR to power, the other end to Analog 0.
 Then connect one end of a 10K resistor from Analog 0 to ground
 For more information see www.ladyada.net/learn/sensors/fsr.html */

int fsrPin = 0;
int fsr2Pin = 1;   // the FSR and 10K pulldown are connected to a1
int fsrReading ;
int fsr2Reading;   // the analog reading from the FSR resistor divider

void setup(void) {
    // We'll send debugging information via the Serial monitor
    Serial.begin(9600);
}

void loop(void) {
    fsrReading = analogRead(fsrPin);
    fsr2Reading = analogRead(fsr2Pin);

    Serial.print("Analog reading = ");
    Serial.print(fsrReading);
    Serial.print("\t");
    Serial.print(fsr2Reading);

    // We'll have a few threshholds, qualitatively determined
    if (fsrReading < 10) {
        Serial.println(" - Nothing");
    } else if (fsrReading < 200) {
        Serial.println(" - Light");
    } else if (fsrReading < 500) {
        Serial.println(" - Lightness");
    } else if (fsrReading < 800) {
        Serial.println(" - Medium");
    } else if (fsr2Reading < 1100) {
        Serial.println(" - No-Pressure");
    } else if (fsr2Reading < 1400) {
        Serial.println(" - Light-touch");
    } else if (fsr2Reading < 1700) {
        Serial.println(" - Light-squeeze");
    } else if (fsr2Reading < 2000) {
        Serial.println(" - Medium-squeeze");
    } else {
        Serial.println(" - Big-squeeze");
    }
    delay(1000);
}

So could anyone tell how to edit this code correctly in order to get two sensors to work?

The one connected to the A0 pin is working but not the other


texts: Transmitting Electrodes Signal to Breadboard Wireless

texts:
I have recently made a DIY EEG from schematics and instructions I found online. I wanted to take the electrodes signal and transmit it wirelessly to the breadboard. According to the picture, the 2 electrodes wire (used for amplifying signals) would be attached to pin 2 and 3 on the AD620AN component, and the third electrodes would be attached to the ground of the breadboard. However, is there a way to transmit the information wirelessly to the AD620AN? I wanted the EEG to be wireless so that it is more practical to wear when performing activities, rather than having wires everywhere. The picture will show the final output of the breadboard going to a soundcard but mine is actually going to the analog input of the Arduino.
Thank you.


texts: Trying to interface E18-D80NK sensor but the output is always one - what to do?

texts:
I'm trying to use a E18-D80NK but the output is always 1
Referring to the above link. I am facing the same problem. But unfortunately there is no solution in the given link. My code goes as follows:
#define SENSOR 2 // define pint 2 for sensor
void setup() {
  Serial.begin(9600);// setup Serial Monitor to display information
  pinMode(SENSOR, INPUT_PULLUP);// define pin as Input  sensor
}

void loop() {

  int L =digitalRead(SENSOR);// read the sensor

      if(L == 0){
    Serial.println(" Obstacle detected");

     }else{

     Serial.println("  === All clear");

     }
  delay(500);

}

Wiring:
Brown = 5V
Black = INPUT
Blue = Gnd

This is always giving me '=== All clear' as output. Also, would like to mention that, I bought a new sensor recently. Now i doubt is it a defective piece.
Could you please help.


texts: Start I2C communication at an external event

texts:
I'm working on a Arduino Uno and a ADC ADS1115. Devices communicate by I2C where Arduino is the master.

I would like to use the ADC to the maximum of his possibility.

So i configure the ADC to set a pin when a conversion finish and use this pin as an external interrupt.
But i can't read the data because I2C interrupt can't work in a external interrupt handler.
I think to use a timer to have a fixed sampling rate too, but it's the same issue.

There is my code below, and if you have any idea of how i can doing my goal let's share it ;)

#include <QueueArray.h>
#include <ADS1115_Vibratec.h>

  Adafruit_ADS1115 ads;

  QueueArray <uint16_t> fifo;

  int i=0;

void setup() {

 Wire.begin();

 Serial.begin(115200);

 ads.Config( ADS1115_REG_CONFIG_OS_NOEFFECT,
          ADS1115_REG_CONFIG_MUX_DIFF_0_1,
          ADS1115_REG_CONFIG_PGA_6_144V,
          ADS1115_REG_CONFIG_MODE_CONTIN,
          ADS1115_REG_CONFIG_DR_860SPS,
          ADS1115_REG_CONFIG_CMODE_TRAD,
          ADS1115_REG_CONFIG_CPOL_ACTVLOW,
          ADS1115_REG_CONFIG_CLAT_NONLAT,
          ADS1115_REG_CONFIG_CQUE_1CONV);

 ads.Set_ConvReady_function();

 attachInterrupt(0,interrupt,RISING); //INT0 -> pin 2, fonction interrupt,    front montant

  }

  void loop() {

   while (!fifo.isEmpty ())
   {
      Serial.write(fifo.dequeue());
      Serial.println();

   }

  }
  void interrupt()
  {
    fifo.enqueue(ads.ReadConvert());
  }


texts:
I'm trying to cut my esp8266 range down to about a meter to save power.  I know that I can adjust output power but I don't know enough to understand what a given setting will actually yield.

I can set zero to kill it or 20.5 to set max range, but what setting is appropriate for a meter or so?  Is there a rule of thumb?


texts: Measuring car speed between two points: What sensor to use and how to cover the distance?

texts:
PROBLEM
Cars regularly exceed the speed limit in our street
SOLUTION
Measure each car's speed and clearly display the speed to the driver
EXECUTION

Measure the time the car takes to cover a set distance (e.g. 25 meters) to calculate the speed
For this I'd set up two sensors and calculate the difference between the timestamps recorded between the car passing the first and second sensors -> then convert into km/h
Display the result on an LED screen

CHALLENGES & QUESTIONS
A. What sensors should I use here? Photoresistor with laser diode, digital or analog IR sensor, ...
B. How can I best cover the distance between the sensors and connect them to the Arduino? Long wire, wireless, connect two Arduinos, ...
Thanks!


texts: How do I run a loop for a specific amount of time?

texts:
I currently have a for loop that loops 300 times and then moves on.

Instead, I'd like that loop to run for a specific number of minutes, instead.

Here's the current loop, for reference.

for(int i = 1; i<300; i++){
  if (kill() == true){ break; }

  strip.setPixelColor(1, strip.Color(random(100,255),random(100,255),random(100,255)));
  strip.show();

  tone(TONE, notes[random(0,3)]);
  delay(100);
}

Also, I have an RTC that's used elsewhere in the app, so real actual time is available for use if it makes sense to do that...though I'd love to know of a way to do it without an RTC module for future projects.


texts: Ramping up and down arduino motor due to ultrasonic sensor input

texts:
Im working on an arduino robot that needs to follower a leader robot infront of it. The leader robot can accelerate, decelerate , and stop and my robot needs to be able to follow the leader without crashing into it.

I have my two sensors working however Im having a harder time integrating the motors to ramp up or down. Currently only one wheel turns on at a time for the right and left commands.
How can I appropriatly ramp up or down the wheel speed.

int SpRMotor = 5;  //speed Right Motor
int MotorA1 = 7; //Right Motor = +
int MotorA2 = 6; //Right Motor = -
int MotorB1 = 8; //Left Motor = -
int MotorB2 = 9; //Left Motor = +
int SpLMotor = 10;  //speed Left Motor

int TriggerPIN1 = 3;//right
int EchoPIN1 = 2;
int TriggerPIN2 = 12;//left
int EchoPIN2 = 11;

void setup(){
  pinMode(TriggerPIN1,OUTPUT);
  pinMode(EchoPIN1,INPUT);
  pinMode(TriggerPIN2,OUTPUT);
  pinMode(EchoPIN2,INPUT);

  pinMode(MotorB1, OUTPUT);
  pinMode(MotorB2, OUTPUT);
  pinMode(MotorA1, OUTPUT);
  pinMode(MotorA2, OUTPUT);
  pinMode(SpLMotor, OUTPUT);
  pinMode(SpRMotor, OUTPUT);

  analogWrite(SpRMotor, 170);
  analogWrite(SpLMotor, 170);
  Serial.begin(9600);
  }
void loop(){

  int limit;
  int sampledata1, sampledata2;
  sampledata1 = distance(TriggerPIN1, EchoPIN1);
  Serial.print("distance1: ");
  Serial.print(sampledata1);
  delay(100);
  sampledata2 = distance(TriggerPIN2, EchoPIN2);
  Serial.print(" distance2: ");
  Serial.println(sampledata2);
  delay(100);
  limit = 10;
  if((15> sampledata1 >= limit)&&(15> sampledata2 >= limit))
  {
    Serial.print("True");
    forward();
    delay(100);
  }
     if (sampledata2  >= 15 )
    {turnRight();}
  if (sampledata1  >= 15 )
    {turnLeft();}
  if ((limit > sampledata1)&&(limit> sampledata2 ))
  {
    Stop();
  }

}

void forward(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, HIGH);
digitalWrite(MotorB1, HIGH);
digitalWrite(MotorB2, LOW);
}

void turnRight(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, LOW);
digitalWrite(MotorB1, HIGH);
digitalWrite(MotorB2, LOW);
}

void turnLeft(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, HIGH);
digitalWrite(MotorB1, LOW);
digitalWrite(MotorB2, LOW);
}

void Stop(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, LOW);
digitalWrite(MotorB1, LOW);
digitalWrite(MotorB2, LOW);
}
int distance(int trig, int echo)
{ digitalWrite(trig,LOW);
  delayMicroseconds(2);
  digitalWrite(trig,HIGH);
  delayMicroseconds(10);
  digitalWrite(trig,LOW);
  long timedelay = pulseIn(echo,HIGH);
  int distance = 0.0343 * (timedelay/2);

  return distance;
}


texts: How do I use a 3 legged phototransistor?

texts:
I have searched the Internet and found the following circuit to use with my phototransistor but it is not working, I can say so because all analog input i get is 1023 even if i have covered it totally, I have include the phototransistor and the diagram can anyone tell why is it not working!
I used this webpage to check my sensor and it works-I used this page

I have used 10kohm resistor.

This is my phototransistor


texts: Combining code for multiple sensors in one program

texts:
I need to operate 2 different sensors (gas and temp) simultaneously.
I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together. My background in coding is basic and I'm not the one who wrote these codes.

Here are the sketches:

Thermistor code:

void setup() {
  //This function gets called when the Arduino starts
  Serial.begin(9600);
  //This code sets up the Serial port at 9600 baud rate
}

void loop() {
  //This function loops while the arduino is powered
  int val; //Create an integer variable
  val=analogRead(0);
  //Read the analog port 0 and store the value in val
  Serial.println(val);
  //Print the value to the serial port
  delay(1000);
  //Wait one second before we do it again
}

This is the gas detector code:

/* GAS Sensor MQ-2
This sensor detects flammable gasses
the board has four pins
connect AO to Arduino pin A0
connect DO to Arduino pin 2
connect Gnd to Arduino Gnd
connect Vcc to Arduino 5 volts
*/

int sensorPin = A0;
// select the input pin for the potentiometer
int DOPin = 2;
// select the pin for the LED
int sensorValue = 0;
// variable to store the value coming from the sensor
int ledPin =13;

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(DOPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  Serial.print("Analog Output = ");
  Serial.println(sensorValue);
  // turn the ledPin on if triggered
  if (digitalRead(DOPin) ==HIGH) {
    digitalWrite(ledPin, LOW);
    Serial.println("Digital Output = OFF");
  } else {
    digitalWrite(ledPin, HIGH);
    Serial.println("Digital Output = ON");
  }
  delay(1000);
}


texts:
I am working on an Arduino project, where I am transmitting GPS data between two Arduinos. This code can transmit the raw GPS data:

int a = Serial1.available();
if(a){
    uint8_t hej[a];
    for(int i=0; i<a; i++){
        hej[i] = Serial1.read();
    }

    rf95.send(hej, a);
}

I need to be able to identify the device that's transmitting the data. This can be in form of an integer value. I have tried to add a value to the array, but that messes up the data when I receive it.
Is there a simple way to add an ID to the data I am transmitting?


texts: Though an emulator is quite useful for debugging code that has no side effects, most real-world applications include some circuitry besides the Arduino. If a microcontroller on an Arduino had a JTAG interface, it would be pretty straight-forward, but what if it's e.g. an Arduino Uno?


texts: How can I make this button toggle the position of a servo?

texts:
I am trying to make something so when I press the button it sets the position of the servo to 50 and then when I press it again, it sets it to 150. The button is momentary not a toggle switch. This is what I have come up with so far. I would also like to account for button bounce. Hope someone can help. Thanks in advance!

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

// variables will change:
int pos = 0; // variable to store the servo position
int buttonState = 0; // variable for reading the pushbutton status
int button_mode = 1; // Variable for the button's current state.
// button_mode = 1 when the button is up, and 0 when the button is pressed.
// This variable is 'static' and persists because it is declared outside a function.

void setup() {
  myservo.attach(8); // attaches the servo on pin 9 to the servo object
  Serial.begin(9600); // Initialize the Serial port at 9600 baud.
  pinMode(9,INPUT); // Set Digital pin 9 to an input so it can monitor the button.
}

void loop() {
  buttonState = digitalRead(9);
  if ((digitalRead(9) == LOW) && (button_mode == 1)) {
    // Check Digital pin 9 to see if it's pressed.
    pos = 150; //set servo position variable to 150
    myservo.write(pos); //set servo postion to 'pos'
    delay(1000); // wait 1 second
    button_mode = 0; // Button was up before, but is pressed now. Set the button to pressed
    Serial.println("Button has been pressed."); // and report that to the serial monitor.
  } else if ((digitalRead(9) == HIGH) && (button_mode == 0)) {
    pos = 50;
    myservo.write(pos);
    delay(1000);
    button_mode = 1; // Button was down before, but is released now. Set the button to
    Serial.println("Button has been released"); // released and report that to the serial monitor.
  }
  delay(100); //small delay to account for button bounce
}


texts: Why does this method return an unprintable character, how do I convert it to display correctly?

texts:
Page 14 says that the method should return the value 'h17'

typedef struct  {
  uint8_t data;
  uint8_t timestamp;
  unsigned char crc;
} tData;

int main(void)
{
  unsigned char* tempData = "snap";

    for(;;)
    {
      tData payload;
      payload.crc = crc8(tempData,sizeof(tempData));
      UDR0 = payload.crc;
    }

    return 0;
}


texts:
I use my Arduino with Adafruit PCA9685 servo controller. To set PWM signals I use the provided library: https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library

It allows easily set PMM signal and works good. But how can I "unset" PWM signal for a certain pin?

If a PWM siganl is active, the servo stucks on the current position and can't be moved by hand, but only by setting other pulse length. So I need to move servo and then "free" it.


texts: Use normal TFT Shield with SD as a Nextion Display

texts: I have a normal Elegoo TFT 2.8" display shield that also had an SD reader. I am trying to use it as a Nextion display. I want to do this because the Nextion tool allows you to make very nice looking sophisticated graphics and I wanted to do the same. Is there any possibility? Maybe some interpreter library?


texts: Arduino LED matrix and 2D array, data seems to be corrupting

texts:
Duplicate of this question

I'm trying to drive an 8x8 LED matrix with an arduino nano, but I can't get the LEDs to display what I tell it to.

I'm using this LED Matrix

Here's my code:

int row1 = 2;
int row2 = 3;
int row3 = 4;
int row4 = 5;
int row5 = 6;
int row6 = 7;
int row7 = 8;
int row8 = 9;

int col1 = 10;
int col2 = 11;
int col3 = 12;
int col4 = 18;
int col5 = 14;
int col6 = 15;
int col7 = 16;
int col8 = 17;

void setup() {
  int i;
  for(i = 2; i <= 18; i++) {
    pinMode(i,OUTPUT);
  }
  for(i = 2; i <= 9; i++) {
    digitalWrite(i, HIGH);
  }
}

void loop() {

  int display [8][8] = {
  {1,0,0,0,0,0,0,0},
  {0,1,0,0,0,0,0,0},
  {0,0,1,0,0,0,0,0},
  {0,0,0,1,0,0,0,0},
  {0,0,0,0,1,0,0,0},
  {0,0,0,0,0,1,0,0},
  {0,0,0,0,0,0,1,0},
  {0,0,0,0,0,0,0,1}
  };

  updateScreen(display);
}

void updateScreen(int screen[8][8]) {

  Serial.begin(9600);
  int i;
  for (i = row1; i <= row8; i++) {
    Serial.println(i-1);
    digitalWrite(i, LOW);
      digitalWrite(col8, screen[i-2][0]);
      Serial.print(screen[i-2][0]); Serial.print("|");
      digitalWrite(col7, screen[i-2][1]);
      Serial.print(screen[i-2][1]); Serial.print("|");
      digitalWrite(col6, screen[i-2][2]);
      Serial.print(screen[i-2][2]); Serial.print("|");
      digitalWrite(col5, screen[i-2][3]);
      Serial.print(screen[i-2][3]); Serial.print("|");
      digitalWrite(col4, screen[i-2][4]);
      Serial.print(screen[i-2][4]); Serial.print("|");
      digitalWrite(col3, screen[i-2][5]);
      Serial.print(screen[i-2][5]); Serial.print("|");
      digitalWrite(col2, screen[i-2][6]);
      Serial.print(screen[i-2][6]); Serial.print("|");
      digitalWrite(col1, screen[i-2][7]);
      Serial.println(screen[i-2][7]);
      delay(1);
      blank();
    digitalWrite(i, HIGH);
  }

}

void blank() {
  digitalWrite(col1, LOW);
  digitalWrite(col2, LOW);
  digitalWrite(col3, LOW);
  digitalWrite(col4, LOW);
  digitalWrite(col5, LOW);
  digitalWrite(col6, LOW);
  digitalWrite(col7, LOW);
  digitalWrite(col8, LOW);
}

And here is the output:

1
1|0|0|0|0|0|0|0
2
0|1|0|0|0|0|0|0
3
0|0|1|0|0|0|0|0
4
0|0|0|1|0|0|0|0
5
0|0|0|0|1|0|0¾j
6
0|0|0|0|0|1|0|0
7
0|0|0|0|0|0|1|0
8
0|0|0|0|0|0|0|1

So I can tell that the error (probably) isn't my wiring, because those array values are clearly wrong, I have no idea where the ¾j is coming from.


texts:
I'm looking to make a DIY version of Dan Conrad's Spectrabloom. I've got an Arduinio Uno, a piece of code that uses PWM to randomly fade three 1w LEDs (one red, one blue and one green) and a PicoBuck LED driver.
Question is - do I have to have two power supplies? One to power the PicoBuck and one to power the Arduino or can I have them all running off one supply? If the latter - can anyone give me pointers on the way to hook everything up?


texts:
I have found this project (https://create.arduino.cc/projecthub/richardosgood/clone-infrared-signals-with-arduino-3a3cb2?f=1) about cloning a remote control.
I set up the Arduino and managed to copy the ON command of my LG remote control, the problem is that when I try to play the signal it doesn't work.
I think that it could be a frequency error but I wasn't able to find anywhere the correct frequency for my tv (model 32ls5600). Does anyone know how to fix this problem ? I'm currently sending the signal at 38khz. Thanks everybody!


texts: How do I upload the sensor data from arduino into a database?

texts:
I have just connected a Libelium shield to connect many sensors to Arduino UNO, that measure water ph level, temperature,...etc. I really couldn't figure out how do I upload the sensor data into a database(MySQL). I have the code for database connectivity, but still couldn't figure out how(Querying) to upload the sensor data into the database.

The main problem here is how do I make the arduino recognize the sensor data to upload it into database or send to to another Arduino or Raspberry pi through XBee.

Code for database connectivity:

void sendData(){

          Serial.println("Connecting...");
          if (my_conn.mysql_connect(server_addr, 3306, user, password)){
            delay(500);
            Serial.println("Starting SQL!");
            Serial.println(INSERT_SQL);
            my_conn.cmd_query(INSERT_SQL);
            Serial.println("Query Success!");
            my_conn.disconnect();
            Serial.println("\n");
          }
          else {
            Serial.println("Connection failed!");
          }
}


texts:
I am working on a project that involves moving various servos and lights and I need a good UI to work with the device. I've previously used Blynk, which worked very well but I didn't like some of the limits it has. My current code works with Blynk and I'd like to change it to a web server so it can work on any device without an app or internet connection.

Right now my esp configures itself as an access point and I can navigate to its IP address to get to my "hello world file" but after that I'm stuck. What really stumps me is getting the input from the interface that I make in HTML, I could fairly easily make an arrangement of buttons, sliders, and fields, that fits my need but how do I get the value of these as a variable in my arduino code?

I've seen some examples of code that are very simple essentially a couple buttons redirect to different web pages on the server and it takes these commands to assign a variable, but that seems kind of poor form, is there a better way, or how do I make that work with a complex interface with many buttons and switches.

I've heard of Jquery and Ajax but not familiar on how to make this work with Arduino code.


texts: Detecting the light source location using multiple photoresistors

texts:
I am not an expert yet, so please forgive any possibly wrong terminology that I may have used.

I am planning to place 6 light sensors in 1 meter (or maybe more) distance from one another, like this (sorry about the bad schematic, I am not an expert, but I hope it makes sense):

simulate this circuit – Schematic created using CircuitLab

I am going to place them in a relatively dark room. My goal is, when I am pointing a flash light towards them to be able to tell which sensor is measuring the highest values (where the light is coming from), and for how long (in milliseconds).

I know how to do the connections and measure values. My questions are two:

Which is the most efficient way to detect which of the 4 sensors is recording the higher values? I am assuming I have to compare the values that they are recording. However, I think that if in each loop I sort the captured values, the process might become heavy. I guess I could minimise the comparisons, since for example if LDR1's value is higher than LDR2 and LDR3, I can assume that the light source is cannot be pointing towards LDR6 for example. However, I am thinking that maybe there could be an even more efficient way to detect that (not necessarily in software).
Since the room will not be completely dark, the analog pins will record some values even when I am not pointing the flash light towards them. Is there a way to filter that out? I have come across calibration (https://www.arduino.cc/en/tutorial/calibration), but I am not sure whether this is the optimal solution. Please take into account that the light source might not be very strong (but its light will definitely be brighter than the room light).


texts: Output 20x20 Image to Arduino serial monitor

texts:
I am working on an Arduino project where I need to display a black and white (no gray) image to the serial monitor. It doesn't need to be high resolution, so something like 20x20 would work. I will be using this several times a second to make video of a sort, but it doesn't need to be a very high fps (4 or 5 would work). Currently I am just using unicode blocks and printing them (at a baud rate of 500,000) to the serial monitor, but it ends up having a very bad screen tear sort of effect. Is there any way to do this better, or at the very least make the serial monitor print everything at once instead of each character individually?

Thanks!


texts: Questions Concerning Arduino Compatible Boards

texts:
I've seen an Arduino-compatible board called Bluno from DFRobot. I'm curious if a shield, specifically the DFRobot motor shield can be connected to the Bluno.

Can anyone confirm if it can be connected with a shield?


texts:
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
#include <SoftwareSerial.h>

char Mob[20]="+923319020922";
String stringGPS = "";
String stringGPS1 = "";
char c=0;
int t=0,i;
int buzzer = 9;
int buttonState = 0;

SoftwareSerial mySerial(10, 11); // RX, TX

//const int buttonPin1 =9 ;
int buttonState1 = 0;
int helmetstate=0;
const int relay=8;
char inByte=0;

void setup()
{
  lcd.begin(20, 4);
  lcd.setCursor(0, 0);
  pinMode(relay, OUTPUT);
  pinMode(buzzer, OUTPUT);
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  digitalWrite(relay, LOW);
  delay(15000);
  lcd.print("Config modem....");

  Config();

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Smart helmet      ");
}

void loop()
{
  if(Serial2.available())
  {
    inByte = Serial2.read();
    //Serial.write(inByte);
    if(inByte=='A'||inByte=='B'||inByte=='C'){
    inByte=0;
    SMS(Mob);

    while(Serial2.available()>0)
    {
      i = Serial2.read();
    }
  }

  if(inByte=='D')
  {
    digitalWrite(relay, LOW);
    inByte=0;
  }

  if(inByte=='E')
  {
    digitalWrite(relay, HIGH);
    inByte=0;
  }
  else
  {
  }
}

 //buttonState = digitalRead(buttonPin);
 // if (buttonState == LOW) {
 //Serial.print("ok");
 //lcd.clear();
 // lcd.setCursor(0, 0);
 //lcd.print("Sending msg       ");
 // lcd.setCursor(0, 0);
 //lcd.print("Smart helmet      ");
 // checkGPS();
 // SMS(Mob);

 //helmet();
 checkGPS();
 lcd.setCursor(0, 1);
 lcd.print(stringGPS1);
 //Serial.println(stringGPS1);
}

/*
void helmet()
{
  buttonState1 = digitalRead(buttonPin1);
  if (buttonState1 == HIGH)
  {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("SWITCH ON  .......    ");
    digitalWrite(relay, HIGH);
  }
  else
  {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("SWITCH OFF .......    ");
    digitalWrite(relay, LOW);
  }
}
*/

void checkGPS()
{
  // Serial.print("check gps");
  // while (Serial.available())
  // {
  if (Serial.available()>0)
  {
   // c = Serial.read();
   // stringGPS  = c;
   //Serial.print(c);
   while (c != 'R')
   {
     c = Serial.read();
     // Serial.print(c);
   }
    // if (c== 'R')
    // {
    //   Serial.print(c );
         while(t!=41)
         {
           if (Serial.available())
           {
             c = Serial.read();
             stringGPS += c;
             t++;
             //Serial.print(stringGPS );
          }
  }
  stringGPS1= stringGPS.substring(15, 41);
  // Serial.println(stringGPS1);
  t=0;
  c=0;
  stringGPS = "";
    // }
  }
  }

void SMS(char Mob[20])
{
   digitalWrite(buzzer, HIGH);
   lcd.setCursor(0, 0);
   lcd.print("Sending msg       ");
   Serial1.print("AT+CMGS=\"");     // send the SMS number
   Serial1.print(Mob);/// Send mobile number
   Serial1.print("\"\r");
   delay(4000);
   Serial1.print(stringGPS1);// send the SMS Data
   Serial1.print("\r");
   delay(2000);
   Serial1.write(0x1A);  ///Ctrl+Z
   delay(1000);
   Serial1.write(0x0A);  ///Carrige return
   delay(1000);
   Serial1.write(0x0D);    ///line feed
   delay(1000);
   stringGPS1 = "";
   lcd.setCursor(0, 0);
   lcd.print("Smart helmet      ");
   digitalWrite(buzzer, LOW);
}

void Config()/////configuration for sim900
{
  delay(4000);
  Serial1.print("ATE0\r"); ////Disable Echo
  delay(4000);
  Serial1.print("AT\r"); ///checking echo
  delay(4000);
  Serial1.print("AT+CMGF=1\r");///msg format
  delay(4000);
}

when i run this code it give me error that serial1 was not decleared in the scope


texts: very lightweight low power microcontroller with memory?

texts:
I have build a couple of projects using arduino.  For a new project I want to log skin surface temperature vs. time (just perhaps a few times per day) and possibly other easy to obtain info such as voltage.

I need to make everything as small and lightweight as possible (since it would be measuring skin temperature on a small mammal), i.e. below 5g, lighter if possible, ideally 3g, including the battery, so that it doesn't upset the 50-100g animal too much.

I read it might be possible to change the arduino pro mini to use less current by getting rid of the voltage regulator? but perhaps it is more sensible to change completely and learn to program another type of microcontroller which someone could recommend? It would need to be possible to operate it directly from a lightweight coin cell or similar lightweight battery. (I'm also not sure how to find a lightweight 3.3V battery for the arduino pro mini, I guess they exist but I can only find 3V batteries so far). If it has onboard memory to save temperature every few hours which could be downloaded later that would be ideal (I would also be interested if anyone has recommendations for memory). I know it's possible to buy an "Ibutton" but if I have time I would like to make my own so that I can add other sensors and obtain more information.


texts: How to Home a stepper and make it move 45 degree after that

texts:
I am trying to let a stepper find home (via microswitch) after power up. After that make it move 45 degrees (or the equivalent in steps) and wait for 3 seconds. Below is the code i found/adapted.

The setup part kind of works, but does not run smoothly.

The stepper1() part does not work at all (only jerking movements).

I would also like the motor to be disable when it waits which in my understanding should be achieved by digitalWrite(M2en,HIGH);but when I place this at the beginning and end (LOW, HIGH) of stepper1() it never worked. Any ideas would be great.

#include "AccelStepper.h"

int M2dirpin = 4;  //Motor Y direction pin
int M2steppin = 5; //Motor Y step pin
int M2en=12;  //Motor Y enable pin
#define home_switch 9 // Pin 9 connected to Home Switch (MicroSwitch)

// AccelStepper Setup
AccelStepper stepperX(1, 5, 4);   // (1,2,3) = (Dedicated Board, STEP, DIR)
// Stepper Travel Variables
long initial_homing = -1; // Used to Home Stepper at startup

void setup() {

  pinMode(home_switch, INPUT_PULLUP);
  pinMode(M2dirpin,OUTPUT);
  pinMode(M2steppin,OUTPUT);
  pinMode(M2en,OUTPUT);
  digitalWrite(M2en,LOW);
  Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
  stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper

  // Start Homing procedure of Stepper Motor at startup
  Serial.print("Stepper is Homing . . . . . . . . . . . ");

  while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
    stepperX.moveTo(initial_homing);  // Set the position to move to
    initial_homing--;  // Decrease by 1 for next move if needed
    stepperX.run();  // Start moving the stepper
    delay(20);
  }

  stepperX.setCurrentPosition(0);  // Set the current position as zero for now
  stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper
  initial_homing = 1;

  while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
    stepperX.moveTo(initial_homing);
    stepperX.run();
    initial_homing++;
    delay(20);
  }

  stepperX.setCurrentPosition(0);
  Serial.println("Homing Completed");
  Serial.println("");

 // Move 10 steps forward from the limit switch (to get out of the switch)
  while (stepperX.currentPosition() != 10)
  {
    stepperX.setSpeed(10);
    stepperX.run();

}
}
void loop()
{
//stepper1();
}

void stepper1()
{
  stepperX.move(22.5);
  stepperX.run();
  delay(3000);
}


texts: Problem in interfacing esp8266 with Arduino ide for simple blink program

texts:
Arduino: 1.8.13 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Serial, None, Only Sketch, 115200"

In file included from c:\programdata\matlab\supportpackages\r2018b\3p.instrset\arduinoide.instrset\idepkgs\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2\algorithm:60:0,

                 from C:\ProgramData\MATLAB\SupportPackages\R2018b\3P.instrset\arduinoide.instrset\idepkgs\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266/Arduino.h:238,

                 from sketch\Blink.ino.cpp:1:

c:\programdata\matlab\supportpackages\r2018b\3p.instrset\arduinoide.instrset\idepkgs\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2\utility:68:28: fatal error: bits/c++config.h: No such file or directory

 #include <bits/c++config.h>

                            ^

compilation terminated.

exit status 1

Error compiling for board NodeMCU 1.0 (ESP-12E Module).

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


texts: Do we need to burn bootloader in new Atmega328p before uploading the arduino code

texts: I have an arduino code which is working fine. Now I am planning to make a PCB out of it. But I do not want to use the complete Arduino board. I just want to use the Atmega328p microcontroller. So my plan is to connect the USBasp programmer to the new Atmega328p and upload the code. So before this code, do I need to upload the bootloader or uploading the code first will run fine.


texts: Serial Monitor shows a continuous "word salad" without a loop

texts:
I have written a little program which should (at the end) host a little website. This is just my setup. But for some reason, it writes "srl?" endlessly onto the serial monitor. I just connected the ESP8266-01 to my Arduino UNO, using 115200 baud with the nodeMCU board. Using different boards results in an error telling me I should use nodeMCU.
As I have written in the title, I do not understand how it can produce an endless output without a loop with Serial.print/write in it.
#include <ESP8266WiFi.h>

const char* NAME = "x"; //ssid
const char* PWRT = "x"; //password

WiFiServer server(80);

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

  Serial.printf("connect with %s \n", NAME);
  WiFi.begin(NAME, PWRT);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
  }

  server.begin();
  Serial.printf("webserver open, access with %s\n", WiFi.localIP().toString().c_str());

}

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

}


texts:
How do I transfer a series of byte[256]-buffers to a server with an ENC28J60 Ethernet adapter? I get blocks of uint8_t from an Arducam camera module and I'd like to transfer them to a host. Does somebody have an idea how to solve that? I asked a previous question regarding that topic but now new issues arrived.

This is how the array is filled:

uint8_t temp = 0, temp_last = 0;
byte buf[256];
length = myCAM.read_fifo_length();
while (length--) {
  temp_last = temp;
  temp =  SPI.transfer(0x00);
  if ((temp == 0xD9) && (temp_last == 0xFF)) {
    buf[i++] = temp;
    is_header = false;
    i = 0;
  }
  if (is_header == true) {
    //Write image data to buffer if not full
    if (i < 256)
      buf[i++] = temp;
    else {
      i = 0;
      buf[i++] = temp;
    }
  }
}


texts: How to use pyserial to write two separate message?

texts:
I'm using pyserial to communicate with my arduino. I set up the connection and everything works fine. Now I have these two writing commands:
pyserial.write("conn".encode())
pyserial.write("mod1".encode())

On my arduino:
while (!Serial.available());
String s = Serial.readString();
if (s=="conn") do...;
if (s=="mod1") do...;

The problem is that none of the if statements are true because s becomes "connmod1", because the messages are sent almost at the same time I guess. I know I could use some delimiter to split the string, but I would like to know what the convenient solution might be?


texts: What is the best data type to be used through i2C

texts:
i'm trying to send multiple commands to multiple slaves controlling motors. Slave Controller(Arduino Nano) will receive the command, and returns the current position of the motors to the Master(Arduino Mega).

What data type would be best to use in this scenario. I am considering, string or byte data type.


texts: Trouble using a TSSP77038 with an Arduino

texts:
I have a Vishay TSSP77038 IR receiver that I would like to read the output of. It is connected as shown in the picture - Vs to 5V, GND to GND and the output to a pin on the Arduino.

My problem is that the reading is constantly low (it is active low so says it is receiving a IR signal), even when i completely cover the sensor or I am in a dark room. Can someone please tell help? Thanks a lot in advance :)


texts: ESP Web Server calling javascript function

texts:
Is there a way to call javascript functions from ESP?
I don't want to call ajax requests every few seconds. I want to update my values only when they change.

Can it by done? Thanx.


texts: Use an ethernet shield and RFID rc522 together on a mega?

texts: I am using an Arduino Mega and I would like to connect a rc52 RFID reader and a network shield.  My problem is that both are set to use the same set of pins: 50 - 53.  Can I redefine the pins used so that I can use both at the same time?