texts: Access method from main sketch inside class

texts:
I am lost at this one. In Java, I would do it this way:

Inside the main sketch, I would instantiate the object from the class:

do = new DoClass(this);

I would also include a method inside the main sketch:

public void doSomething(){}

Then, inside the DoClass, I would have the following constructor:

    public class DoClass{
       Sketch sketch;
       public DoClass(Sketch skt){
          this.sketch = stk;
       }
 }

Then, at some point, I would call, from DoClass:

stk.doSomething():

which should be the same as calling:

doSomething();

from the main sketch. Any ideas how to achieve that? If yes, could you please show an example of how to achive the above example in Arduino?


texts: How can I call the variable **Servo::write** in Arduino for my 360 servo?

texts:
I'm trying to control a Servo with a push button and to help me watching if it is working I am using a LED but I'm not sure if I'm doing it well the Servo::write so I need you to tell me what am I doing wrong that my Servo::write function its not working but the LED does the function. Here is the code I am using:

#include <Servo.h>

Servo myservo;

const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 13;       // the pin that the LED is attached to
const int serPin = 9;

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
myservo.attach(serPin);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}

void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);

// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
  // if the current state is HIGH then the button
  // wend from off to on:
  buttonPushCounter++;
  Serial.println("on");
  Serial.print("number of button pushes:  ");
  Serial.println(buttonPushCounter);
} else {
  // if the current state is LOW then the button
  // wend from on to off:
  Serial.println("off");
}
 // Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;

Servo::write(myservo);

// turns on the LED every four button pushes by
// checking the modulo of the button push counter.
// the modulo function gives you the remainder of
// the division of two numbers:
if (buttonPushCounter % 2 == 0) {
 digitalWrite(ledPin, HIGH);
 myservo.write(serPin < 180);
} else {
 digitalWrite(ledPin, LOW);
 myservo.write(serPin > 0);
}

}


texts: Getting issues while using SoftwareSerial

texts:
I am trying to read string send from esp8266 esp01 to Arduino mega. When I use normal Rx and Tx ports, it works properly but when i am initializing new serial port using SoftwareSerial then nothing is being shown on the serial monitor.

Please help me as i have been stuck and trying to solve this for weeks now.
Below are the code for esp8266 and Arduino mega

    Code for ARDUINO MEGA

#include<SoftwareSerial.h>

SoftwareSerial myS(4,5);

String data="true";

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
myS.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(myS.available()){
  data=myS.readString();
  }
  Serial.println(data);
  //Serial.write(data);
  delay(2000);
}

    Code for ESP8266

void setup() {
  Serial.begin(9600);     // Initialize the Serial interface with baud rate of 9600
}

// the loop function runs over and over again forever
void loop() {
  if(Serial.available()>0)    //Checks is there any data in buffer
  {
    Serial.print("We got:");
    Serial.print(char(Serial.read()));  //Read serial data byte and send back to serial monitor
  }
  else
  {
    Serial.println("Hello World..."); //Print Hello word every one second
    delay(1000);                      // Wait for a second
  }
}

Moreover, i have tried read() as well instead of readString(), but it does not work either. I have also tried switching Rx and TX pins meaning connecting Rx->Tx, Tx->Rx and vice versa i.e. Rx->Rx and Tx->Tx, but it does not work in any of the case.
Any help or suggestion will be appreciated.
Thanks


texts: Passing functions while creating a library

texts:
I'm trying to create a library to bind a major part of common code ( starting Wifi, initiate MQTT, OTA and more ).

while using same code in a non library sketch, which works as expected, I find a common error message while trying to pass such :

void rse::startWDT(){
  wdt.attach(1, feedTheDog); // Start WatchDog
}

while

void rse::feedTheDog() {
  wdtResetCounter++;
  if (wdtResetCounter >= wdtMaxRetries) {
    sendReset("WatchDog woof");
  }
}

yields an error message:

error: no matching function for call to 'Ticker::attach(int, <unresolved overloaded function type>)'
   wdt.attach(1, feedTheDog); // Start WatchDog
                           ^

Same error was while trying to pass callback to :

mqttClient.setCallback(callback);

Again - when running this code in a Non library sktech I get no error.

Guy

EDIT1: Solved ( thanks to comments )- using std::bin

1) for a function without arguments:

wdt.attach(1, std::bind(&myIOT::feedTheDog, this)); // Start WatchDog

2) for a function with 3 argumunets:

mqttClient.setCallback(std::bind(&myIOT::callback, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));


texts: If I connect a battery to the vin pin on the arduino, will the 5V pin be activated?

texts: My wording might be a bit confusing, if I plug an 8 volt battery into Vin, will the arduino be powered and will the 5V pins work?


texts:
I’m using ESP8266 with Arduino code. Each device posts a ‘state’ and an ‘avail’ messages for a specific topic.

I wish to be able to read those retained messages and not only right after connecting and subscribe to MQTT broker.

EDIT 1  - Clarifications

I'm using Raspberry Pi Zero W as a MQTT Broker ( Local ).
When device boots, it changes its state from offline to online, but a different process checks periodically if state is offline or online for current device and others on the network.
it is not same as when subscribing to a retained topic, that you get the state at that specific time.
Storing chage of state in a variable, is one way to do it, but is there a different way ?


texts: HTTP get request using Arduino Uno and ESP8266

texts:
I have an Arduino Uno and an ESP8266 and I want to send a HTTP get request to google.com and print the response.
Please help me thanks.


texts: Control Servo motor via Python GUI (PyQt) component "QDial"

texts:
I want to control a servomotor via a Python Gui (PyQt) component "QDial". Hopefully the servomotor should rotate "simultaneously" with the Dial in GUI.

Below is the related code:
Arduino
void loop(){

   // while(!Serial){} //
   if(Serial.available()>0){
       posOrder = Serial.readString(); // get Angle-Value from Serial

       // write to Serial Monitor
        Serial.print("Set Servo Position to: ");
        Serial.println(posOrder);

        int angle = posOrder.toInt();
        myservo.write(angle);
        Serial.flush();

        delay(30);
    }
}

Qdial
## ....some code...

   self.dial.valueChanged.connect(self.writeToSerial)

## ...

def writeToSerial(self):
    # create serial connection
    self.ser = serial.Serial(self.portPath, timeout=None, baudrate=self.baudRate)

    self.posAngle = self.dial.value()  # get value
    self.ser.write(str(self.posAngle).encode()) # write to Serial

Problem
When I click on the tick of the Dial, it works pretty well. After click, the function dial.valueChanged.connect(self.writeToSerial) will call the function writeToSerial(), which has enough time to write dial value to the Serial. The serial monitor shows:
Set Servo Position to: 65
Set Servo Position to: 30
Set Servo Position to: 170

But when I rotate the dial by holding the left mouse button, the function dial.valueChanged.connect(self.writeToSerial) will be called in each small step. It means, the function writeToSerial() will be crazy frequntly called and the serial.write() function can't write data in time. The serial monitor shows something like:
Set Servo Position to: 65666770717273747677
Set Servo Position to: 99100104108109114116119122126128130131133
Set Servo Position to: 1411421431441451461481501521541561

I can als use self.dial.sliderReleased.connect(self.writeToSerial) to make it triggered only once the left mouse button is released. But in this way, the servo motor can't rotation with dial "simultaneously"
Question
How to solve this Problem? to let the servo motor rotate "simultaneously" with dial


texts: XBEE WiFi S6B RSSI for Smartphone localization

texts:
I am building an early prototype, proof of concept, network monitoring tool.  A big part of it uses localization of a Smartphone.  It seems that the best way to do this is using RSSI from multiple points.  I plan to do this using several Arduino Fios with Xbee WiFi (S6B) cards.

My current setup has a network running from my smartphone (it is running DHCP) with a laptop monitoring all the traffic on the network.

What I need is for my Fio Xbees to dump the RSSI of the "access point" (Smartphone) onto the network so my laptop can pull the data.

Thus, to/from is not important as far as the packet is concerned, I just need the data dropped on the "wire" for my laptop to later parse, which is good because Serial.print* sends out a broadcast to 255.255.255.255:fffff.

I can make my devices broadcast any integer, but when I go into AT mode nothing aside from the initial DHCP handshake gets put on the wire.  Any ideas?

void setup() {
  Serial.begin(9600);
  Serial.flush();
  delay(1000);//enter AT mode start
  Serial.print("+");//AT
  Serial.print("+");//AT
  Serial.print("+");//AT
  Serial.flush();
  delay(1000);//enter AT mode finish
  while(Serial.available()>0){
    Serial.write(Serial.read());
  }

}

void loop(){
  Serial.println("ATDB");

  while(Serial.available()>0){
    Serial.write(Serial.read());
  }
  delay(750);//3/4 a sec
}

Note, Serial.println("ATDB"); should cause the xbee to drop the RSSI on the wire; see
XBee_WiFi_AT_Commands.pdf
at digi.com.

The three "+"s at the start are how you move the device into AT mode; see
Digi_International_90002124_G.pdf at mouser.com.

Once again what I am trying to do is get the collected RSSI information dropped onto a wifi connection from multiple xbee WiFi S6B equipped Fios.


texts:
I've used the following code to light 8 yellow leds sequentially but it only runs as it's supposed to be on Proteus. However in my breadboard the 8 leds keeps blinking all together, the resistors used are 220 ohms. Also when i'm trying to change the value of the variable "leds" to be for example 0x0F, it doesn't light, I've read in the Arduino shiftout tutorial that 0.1F capacitor on the latch pin will even the flickers so now I'm really confused.

int latchPin = 8;
int clockPin = 12;
int dataPin = 11;

byte leds = 0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{
  leds = 0;
  updateShiftRegister();
  delay(500);
  for (int i = 0; i < 8; i++)
  {
    bitSet(leds, i);
    updateShiftRegister();
    delay(100);
  }
}

void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);

}


texts: I am looking into putting sound files onto an Arduino Nano without a microSD card

texts:
I figured out how to install the sound onto the card from this site
https://github.com/charliegerard/dev-notes/blob/master/arduino/wavFilesWithoutSdCard.md
It says I need to use pin 11 on the Uno but would pin 11 on the nano work or not? I am getting these boards.
https://www.amazon.com/gp/product/B0713XK923/ref=ox_sc_act_title_3?smid=A2WWHQ25ENKVJ1&psc=1
Also, does anyone have good speaker suggestions, I'm going with these right now(https://www.amazon.com/CQRobot-JST-PH2-0-Interface-Electronic-Projects/dp/B0738NLFTG/ref=sr_1_6?dchild=1&keywords=speakers+arduino%5D%5C&qid=1607285501&sr=8-6)
I'm not sure if I'm giving enough information so just tell me if I need to provide you with more information.


texts: I am making an easy game but something in my code is wrong

texts:
I am making a game where you need to push the button when the LED lights up but it is not registering the push at the right time. I need to push the button when LED is about to go off.

My code:

randNumber = random(2);

if(randNumber == 0){
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
}

if (btnAddFirst.pressed() && randNumber == 0){
  Serial.println("You did it");
}
else {
  Serial.println("u failed");
}


texts:
I need to emulate a component that measures an input mechanically and varies resistance from 0 to infinity (a more detailed set of specs list it at 20-1,000ohms, though I'll have to actually check its true values myself once I have physical access to it).

My aim is to replace this troublesome mechanical component with a current (read as available and serviceable) component, and convert the signal from the new component into an emulated signal (varying resistance) from the old component.

I am not certain as to the resolution required (how big the steps can be), though it may be able to handle 50ohm 'leaps', just judging by the range of mechanical movement and my past experience with replacing similar mechanical systems with ready-made kits for conversions.  I'd like to smooth the curve a whole lot more than 50ohm leaps though.

I have barely an idea where to begin on this.  I thought maybe a resistor ladder and a set of transistors triggered by the arduino to connect into the different points in the line, though I suspect there has to be a better way to achieve a much better result (and I don't think I have enough outputs for that anyway).

Is there a digital component that can vary its resistance using a PWM signal or maybe an analog signal from an arduino?

FYI, I greatly appreciate your input.

EDIT

The controller provides a constant voltage to the component, and the controller then looks at the ground (the voltage over a static resistor) I presume. It is an actual load.

I may be able to provide a variable voltage to the controller on its ground pin, though I have never seen that done on them before. I think that may be the trick, though the controller may(??) dislike it? I can try that.. The next best thing (only 2nd because it requires more components) would be the digital pot.

Anyone ever forged a return signal on a circuit thats supposed to supply its own constant voltage to a resistor type sensor?


texts:
My Arduino Nano v3.0 (made by Gravitech US) is behaving in an unexpected manner. Whenever I try to upload a simple Blink program on the board it always give error which is shown below.

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x01
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x01
...

I have another Nano (a Clone) and an Arduino UNO, both of which work perfectly using the same USB cable and PC.

History: When I used this Nano (original) for the first time, it was having some issue related to the FTDI chip. The FTDI USB was locking up on power up. I referred an answer from Arduino Nano 3.0: FTDI USB locks up on power up.  I shorted the pin no. 26 (TEST) and 25 (AGND) on the FTDI chip, and then I was able to use it. I uploaded the Blink program and tested it, which was working fine.

Now, at present (three years later), when I try to upload even a simple Blink example sketch on it, it never succeeds, and gives me the above mentioned error.

I also tried holding the reset button and releasing it when it shows

  Uploading...

Another Issue: Sometimes when I just check the continuity on my Arduino Nano just to confirm whether the hardware is okay or not, it gives me unexpected results. On checking, the Pins RST and GND get shorted sometimes. And sometimes even VCC, RST and GND get shorted. I also checked the small reset switch on board, and it is working fine.

I contacted Gravitech, but they aren't responding.

What can be the issue with my arduino Nano? I haven't used it yet in any of my project. Just the Blink program that I uploaded 3 years ago on it, was the last time I saw it working.

Any help would be greatly appreciated.


texts:
I think many people know about the staircase lights, which will get triggered by 2 PIR-sensors (1x upstairs and 1x downstairs).

Here is my code - which works well.  It's not cleaned up - as i don't know how i can simplify it. I think there'll be a much nicer way of getting the same output. :)

#include "FastLED.h"
#define NUM_LEDS 300
CRGB leds[NUM_LEDS];
#define PIN 3
int sensorUP = 5;
int sensorDOWN = 7;
int state = LOW;
int valUP = 0;
int valDOWN = 0;

void setup()
{
  FastLED.addLeds<WS2811, PIN, GRB>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness(20);
  pinMode(2, INPUT_PULLUP); // internal pull-up resistor
  pinMode(sensorUP, INPUT);
  pinMode(sensorDOWN, INPUT);
  Serial.begin(9600);
}

void loop() {
  valUP = digitalRead(sensorUP);
  valDOWN = digitalRead(sensorDOWN);

  if (valUP == HIGH) {
    colorWipeUP(0x55, 0xFF, 0x00, 2);
    delay(600);
    colorWipeUP(0x00, 0x00, 0x00, 2);
    delay(100);
  }
  if (valDOWN == HIGH) {
    colorWipeDOWN(0x55, 0xFF, 0x00, 2);
    delay(6000);
    colorWipeDOWN(0x00, 0x00, 0x00, 2);
    delay(100);
  }
}

void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 0; i < NUM_LEDS; i++) {
    setPixel(i, red, green, blue);
   FastLED.show();
    delay(SpeedDelay);
  }
}
void colorWipeDOWN(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 299; i < NUM_LEDS; i--) {
    setPixel(i, red, green, blue);
    FastLED.show();
    delay(SpeedDelay);
  }
}

void setPixel(int Pixel, byte red, byte green, byte blue) {
  leds[Pixel].r = red;
  leds[Pixel].g = green;
  leds[Pixel].b = blue;
}

void setAll(byte red, byte green, byte blue) {
  for (int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
  }
  FastLED.show();
}

At the moment the LEDs just go on and after a delay off again (one-by-one).

QUESTION: I wish for a little smoother effect by fading them on and off.
So i reached the actual output by using different snippets and trying to understand. What i don't understand atm is how to add fading.


texts:
I’m trying to use a LDR to monitor the light levels and if the LDR is covered and the button is pressed, the LED should switch on. I’m in the process of adding debouching but every time I run the code, the it goes in the if (val > 421) part the led is on, but the button hasn’t been pressed and the code stops.

I’m suspecting it may be a logic issue with the states. I’m using the millis function for the debouncing so the code should ignore the first 200ms of when the button is pressed. I just help in regard to the debouncing so when the LDR is covered and the switch is pressed , the LED should turn on.

The code is shown below:

const int buttonPin = 8;
const int ldrPin = 0;
const int LEDPin = 13;

boolean buttonState = 0;
boolean NEWbuttonState = 0;
boolean LEDState = 0;
int bounce_time = 200;
unsigned long my_time;

boolean on;

int val = 0;

void showValue(float myval)
{
  Serial.print(myval);
  Serial.print(" lightstatus ");
  Serial.println(LEDState);
}

void setup()
{
  pinMode(buttonPin, INPUT);
  pinMode(LEDPin, INPUT_PULLUP);
  on = false;
  analogReference(DEFAULT);
  pinMode(ldrPin, INPUT);
  Serial.begin(9600);
  my_time = millis();
}

void loop()
{

  val = analogRead(ldrPin);

  NEWbuttonState = digitalRead(buttonPin);

  if ((millis() - my_time) > bounce_time)
  {
    digitalWrite(LEDPin, LOW);

    if (buttonState != NEWbuttonState)
    {
      buttonState = NEWbuttonState;

      //if button is pressed
      if (NEWbuttonState == 1 && LEDState == 0)
      {
        buttonState = NEWbuttonState;

        if (val > 421)
        {
          my_time = millis();

          digitalWrite(LEDPin, 1);
          LEDState = 1;
          showValue(val);
          Serial.print("button press");
        }

        if (val < 420)
        {
          my_time = millis();

          digitalWrite(LEDPin, 0);
          LEDState = 0;
          showValue(val);
        }
        buttonState = 1;
      }
      else
      {
        if (NEWbuttonState == 0)
        {
          buttonState = 0;

        }
      }
    }
  }
}


texts:
I have not used the Arduino in over 2 years and have forgotten a bunch of stuff I was wondering if someone could help me out. I have two analog sensors both the same connected to the appropriate analog pins. I am getting a read on the serial monitor and when i test the sensors the values are changing so i know the circuit is correct and everything is in the right place. I just have an issue with my code.

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue1 = analogRead(A0);

  // print out the value you read:
  Serial.println(sensorValue1);
   //Serial.print("val1 = " );
  Serial.print(sensorValue1);
  Serial.print(" ");

  delay(1000);        // delay in between reads for stability

   // read the input on analog pin 1:
  int sensorValue2 = analogRead(A1);

  // print out the value you read:
  Serial.println(sensorValue2);
  //Serial.print("val2 = " );
  Serial.print(sensorValue2);
  Serial.print(" ");
  delay(1000);        // delay in between reads for stability

 }

once i view this in the serial monitor it is not organized and the sensorvalue1 is skipping over to the next line. I would appreciate the help.

There are two sensors so there should be two values but in the picture the values are all messed up i would ideally like it to give me a two seperate values one for each sensor

val1= sensorvalue1
val2= sensorvalue2


texts: How to send keystroke with shift modifier?

texts:
This is a bit of a newbie question, but here it goes anyway. So basically I want to send a keystroke using the DigiKeyboard library, but with shift held down. I looked through the code and saw this comment in scancode-ascii-table.h:

//Format: most signifficant bit indicates if scan code should be sent with shift modifier
remaining 7 bits are to be used as scan code number.

I dont really understand where to specify this, whether it's when you call the sendKeyStroke function, or somewhere in the code. Help appreciated.


texts: arduino suddenly shows “avrdude: ser_open(): can't open device ”\\.\COM3" after last upload

texts:
I am using arduino uno to make a sound detector. I uploaded a program, found error in the code that it returns unintended numbers unreasonably big. I also think I used wrong code for the module, but it was connected in the way that can work properly with the proper code.

The code I uploaded was:

const int ledPin =13;
const int middleValue = 512;
const int numberOfSamples =128;

int sample;
long signal;
long averageReading;

long runningAverage = 0;
const int averagedOver = 16;

const int threshold=400;

void setup(){
    pinMode(ledPin, OUTPUT)
    Serial.begin(9600)
}

void loop(){
    long sumOfSquares = 0;
    for (int i=0; i<numberOfSamples; i++){
        sample = analogRead(0);
        signal = (sample - middleValue);
        signal *= signal;
        sumOfSquares += signal;
    }
    averageReading = sumOfSquares/numberOfSamples;
    runningAverage=(((averagedOver -1 )*runningAverage)+averageReading)/averagedOver;

    if(runningAverage>threshold){
        digitalWrite(ledPin, HIGH);
    }else{
        digitalWrite(ledPin, LOW);
    }
    Serial.println(runningAverage);
}

When the arduino suddenly stopped sending serial numbers, I pressed reset button and uploaded the default code:

void setup() {
}

void loop() {
}

but now it shows that it cannot connect to COM3 (arduino) and cant find the device, When I can see arduino uno successfully connected to PC using device manager (windows 8.1). The led light of arduino also turns on when I connect it to power source or usb.

it shows "port not found" when I click to see the serial output

Did I just fry Arduino? How should I fix this?

Also, i checked the led pin 13 blinking three times when i plug in the usb. I just cant upload anything


texts:
When does the ISR mapped to SPI_STC_vect (SPI transmission complete) get fired? Does it fire after a byte has been received (eight clock cycles) of when the slave select changes back to high to deselect the slave?
Or: does "transmission" mean the transmission of a byte or the whole bunch of bytes that belong to the command sequence?


texts:
I'm new both to this forum and to Arduino. My robot is comprised of Arduino Uno with Arduino Motor Shield, 12V DC gear motor, and two limit switches. The robot supposed to move endlessly on rails between the two walls back-and-forth. I have it all wired up and am able to switch the directions of the motor's rotation by pushing the limit switches. However, I also want to have a pause between switching of directions:

... Robot moving forward ...

If front limit switch is pushed
Stop motor
Pause 2 seconds
Run motor CCW

... Robot moving backwards ...

If rear limit switch is pushed
Stop motor
Pause 2 seconds
Run motor CW

... Robot moving forward ...

Simple delay(2000) doesn't work as the limit switch remains pushed against the wall. I've been trying out millis() approach but the fact that limit switch remains pushed (HIGH) I can never produce a difference in time needed to trigger an action. I learned about State Machine but not sure if and how this could help my case?

Can anyone please help me in implementing a two second pause between the switching of the motor's direction?

Below is the code that momentarily switches the motor's direction when robot reaches the wall and limit switch is pushed.

int switchFront_State = 0;
int switchRear_State = 0;

const int ledYellow = 6;
const int ledGreen = 5;

const int switchFront = 4;
const int switchRear = 2;

const int motorDirection = 12;
const int motorBreak = 9;
const int motorPWM = 3;

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

  pinMode(switchFront, INPUT_PULLUP); // Front switch
  pinMode(switchRear, INPUT_PULLUP); // Rear switch

  pinMode(ledYellow, OUTPUT);
  pinMode(ledGreen, OUTPUT);

  // Setup Channel A
  pinMode(motorDirection, OUTPUT); // Motor direction pin
  pinMode(motorBreak, OUTPUT); // Motor break pin
  pinMode(motorPWM, OUTPUT); // Motor PWM pin
}

void runMotorBackward(){ // Motor moving backward
  digitalWrite(motorDirection, LOW);
  digitalWrite(motorBreak, LOW);
  digitalWrite(motorPWM, 128);
}

void motorStop(){ // Stop motor
  digitalWrite(motorBreak, HIGH);
  digitalWrite(motorPWM, 0);
}

void runMotorForward(){ // Motor moving forward
  digitalWrite(motorDirection, HIGH);
  digitalWrite(motorBreak, LOW);
  digitalWrite(motorPWM, 128);
}

void loop(){
  switchFront_State = digitalRead (switchFront);
  switchRear_State = digitalRead (switchRear);

  if (switchFront_State == HIGH){ // If front switch is pressed
    digitalWrite(ledYellow, HIGH); // Yellow LED
    motorStop();
    runMotorBackward();
    } else {
    digitalWrite(ledYellow, LOW);
  }

  if (switchRear_State == HIGH){ // If rear switch is pressed
    digitalWrite(ledGreen, HIGH); // Green LED
    motorStop();
    runMotorForward();
  } else {
    digitalWrite(ledGreen, LOW);
  }
}


texts: How to vary the frequency of a PWM sinewave with arduino uno?

texts:
I'm generating a sine wave using a table, a PWM pin and an RC filter on the output. I would like to be able to control the frequency of the sine wave, how can I do that easily?

By the way, which is the maximum frequency achievable and why? As far as my understanding goes, the limit is given by the time arduino needs in order to run the loop() function.

This is the code I am using on arduino UNO. Please point it out if this is a horrible way to generate a sine wave with arduino, and if it is, feel free to provide a better solution.

const int8_t SIN1024_DATA [] = {... data table values (1024 values) ...};
int i = 0;
void setup()
{
  pinMode(9, OUTPUT);
}

void loop()
{
  digitalWrite(9, SIN1024_DATA[i]);
  i++;
  if(i == 1024){i = 0;}
}


texts: How can I alter my program to read PWM signals from Arduino Mega?

texts:
I am new to programming and Arduinos but I've decided to give a go for a project. I'm after a code that will read PWM signals from a RC receiver (Specifically aileron and throttle) and output this as 4 PWM signals to drive two H Bridges (Right motor forward/reverse and left motor forward/reverse).

This is my code that isn't working.

unsigned long timer[3];
byte last_channel[2];
int throttle;
int aileron;

void setup() {
pinMode(8, OUTPUT);//Right motor fowards
pinMode(9, OUTPUT);//Right motor reverse
pinMode(10, OUTPUT);//left motor fowards
pinMode(11, OUTPUT);//left motor reverse

PCICR |= (1 << PCIE0);  //This enables pin change intterupt enabler

PCMSK0 |= (1 << PCINT0); // This tells the mask register
which pins will cause an intterupt (Pin 2)

PCMSK0 |= (1 << PCINT1); // (Pin 3)

Serial.begin(9600); //Sets the data rate in bits per second
}

void loop() {

}
ISR(PCINT0_vect) {

timer[0] = micros(); // registers intterupt time

//Throttle_Channel----------------------------------------------------------

if(last_channel[0] == 0 && PINB & B00000001 ) { // This checks if pin has
changed from low to high

last_channel[0] = 1;

timer[1] = timer[0];
}

else if(last_channel[0] == 1 && !(PINB & B00000001)){

last_channel[0] = 0;

throttle = timer[0] - timer[1]; //calculates the change in time and sets to

input[0]
//--------------------------------------------------------------------------
}
//Aileron_Channel-----------------------------------------------------------

if(last_channel[1] == 0 && PINB & B00000010 ) { // This checks if pin has

changed from low to high

last_channel[1] = 1;

timer[2] = timer[0];
}

else if(last_channel[0] == 1 && !(PINB & B00000010)){ //This checks if pin  has

changed from high to low

last_channel[1] = 0;

aileron = timer[0] - timer[2]; //calculates the change in time and sets to i

input[0]
//--------------------------------------------------------------------------
}

//Calculations to put output in correct form--------------------------------
int throttle_pwm = (throttle - 1500) / 1000;

int aileron_pwm = (aileron - 1500) / 1000;

int v = (0.5 - abs(aileron_pwm)) * (throttle_pwm / 0.5) + throttle_pwm;

int w = (0.5 - abs(throttle_pwm)) * (aileron_pwm / 0.5) + aileron_pwm;

int lm = v + (w/2) * 255;

int rm = v - (w/2) * 255;
//--------------------------------------------------------------------------

if (lm > 0 && rm > 0){

analogWrite(8,rm);

analogWrite(9,0);

analogWrite(10,lm);

analogWrite(11,0);
}

else if (lm > 0 && rm <= 0){

analogWrite(8,0);

analogWrite(9,abs(rm));

analogWrite(10,lm);

analogWrite(11,0);
}

else if (lm <= 0 && rm > 0){

analogWrite(8,rm);

analogWrite(9,0);

analogWrite(10,0);

analogWrite(11,abs(lm));

}

else if (lm <= 0 && rm <= 0){

analogWrite(8,0);

analogWrite(9,abs(rm));

analogWrite(10,0);

analogWrite(11,abs(lm));

//--------------------------------------------------------------------------
}
}

It compiles fine but I've tried measure PWM at the four output and it doesn't work. If anyone could offer advice or guidance it would be greatly appreciated.


texts: Teensy 4.1 serial communication with 7N2 (7 databits no parity 2 stopbits)

texts:
I have ported a project from arduino Due to a teensy 4.1
In the project I read data from a sensor which speaks serial at 7 databits, no parity and 2 stopbits (no configurable).
Now it seems that teensy does not support this dataformat.
Could I read my sensor in a way using teensy 4.1? I could maybe use softwareserial but the format does not seem to be configurable.


texts: How to find the deferenced value of a transmit Port Register?

texts:
So I am working with the SoftwareSerial library. I'm looking at the write function and I see a *reg value being manipulate. I want to find the value of *reg so I traced the value by stepping into each function call.so here we go.

*reg = _transmitPortRegister
_transmitPortRegister = portOutputRegister(port) //I'm working with pin 1 in register D

Continuing...

#define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) )

const uint16_t PROGMEM port_to_output_PGM[] = {
    NOT_A_PORT,
    NOT_A_PORT,
    (uint16_t) &PORTB,
    (uint16_t) &PORTC,
    (uint16_t) &PORTD,
};

My first question is what is the point of (uint16_t) &PORTD? I am assuming that's just the value of PORTD's register because it is being anded with an empty 16 bit int.

Continuing on,

#define PORTB _SFR_IO8(0x05)
#define PORTC _SFR_IO8(0x08)
#define PORTD _SFR_IO8(0x0B)

#define _SFR_IO8(io_addr) _MMIO_BYTE((io_addr) + __SFR_OFFSET)
#define __SFR_OFFSET 0x20

#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

Now, I followed it all the way here. But how do I find out what actually is the deferenced value? Since this is all IDE, i'm not sure how to GDB this either.

LASTLY, the write function takes in a parameter b, which is a byte. Now in the write function, this is the code to write.

// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);
  b >>= 1;
}

In that block of code, I am not quite sure why they are doing b & 1. Are they just anding the whole byte with 1? If so, then why comment it as "choose byte"
and inside the if-else blocks, they're just oring *reg with reg_mask. How does that translate to sending a one?

Sorry for any confusion, i am glad to clarify any confusing parts of this question. Please let me know.


texts: Is digitalWrite(pinnumber,LOW) different from ground pin

texts:
I am using Tinkercad simulator, but an unusual thing happened. When I connect one wire of dc motor to pin 9 with digitalWrite(9,HIGH) and other wire to ground, the motor runs with rpm of 5555.

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

void loop()
{
  digitalWrite(9, 1);
}

But instead if I connect the other wire to pin 13(say) and set digitalWrite(13,LOW) the motor runs at an rpm of 3846.

void setup()
{
  pinMode(9, OUTPUT);
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(9, 1);
  digitalWrite(13,0);
}

Can anyone explain this?


texts:
I have an SPI slave connected to Due. I send the SPI slave into sleep mode. During sleep, I need to pull all pins low, including MOSI. What's the best way to pull the SPI-4 pin low on a Due?

Here's a similar question but it's about an AVR chip and the answer obviously doesn't apply to SAM3X8 which is an ARM.


texts: Serial Port Issues Elegoo Mac OX High Sierra

texts:
Edit:
Unfortunately the question that has been linked to my question does not answer my question. I have followed its instructions but it is a slightly different issue. Any help on my question would be hugely appreciated:

Apologies but I am very new and trying to learn how to use the Arduino. I bought a starter kit from Elegoo the included an Arduino Uno (I think it is a knock off and no the real thing?). I Have been trying to get the code to upload on to it and keep getting the following errors:

  Sketch uses 2282 bytes (7%) of program storage space. Maximum is 32256 bytes. Global variables use 212 bytes (10%) of dynamic memory,
  leaving 1836 bytes for local variables. Maximum is 2048 bytes.
  avrdude: stk500_recv(): programmer is not responding avrdude:
  stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

So I know that that my iMac is recognising the Arduino but I am still not able to upload any code to it. I have spent hours trying work around solutions I have found on the internet or Elegoo have sent me.

I have three questions. Firstly if I just buy a real Arduino from Arduino (I had not realised I was being sent an imitation) will this solve my problems?

Secondly, if not can anyone recommend a work around that I would be able to implement? I am reasonably computer literate but not to the level of diving into the Terminal and inputting lots of code!

Thirdly, I am really struggling being a beginner with the instructions given by Elegoo, they are very badly translated and confusing. Can anyone recommend a way to learn the basics and complete some basic projects for a beginner. I am happy to pay for the tutorials if needed.


texts:
I have an
Adafruit MicroSD card breakout board and an Adafruit Feather HUZZAH with ESP8266 WiFi
I wired that up according to this link's last picture.
The code I am using:

#include <SPI.h>
#include <SD.h>
...
const int chipSelect = 15;
...
Serial.print("Initializing SD card...");
pinMode(SS, OUTPUT);

if (!SD.begin(chipSelect)) {
     Serial.println("initialization failed!");
     return;
 }
Serial.println("initialization done.");
...

I always get the message "initialization failed", I also tried to format my SD card to be sure to have fat32 file system on it, but had no success with that.
What can I do to debug this error further?

TIA


texts: while(1) loop blocks program to enter interrupt

texts:
I want to build a program in C that enables / disables a passive matrix display. But my problem occurs before I can even implement one function of this display.

I have a simple switch connected to Port C pin 24, which is configured as INPUT with a pull-up resistor and debouncing input filter. When I toggle the switch the code enters an interrupt and toggles the "display" on or of depending on the state of the switch.

Everything works fine until I introduce a simple while(1) loop, which should handle everything I want to do. But every time I write the function called run, which only contains one while(1) loop and a single dummy operation __asm__("nop"), the while loop prevents the code from entering the interrupt.

This is my code:

void display_init(void) {
    sysclk_init();
    delay_init(sysclk_get_cpu_hz());
    pmc_set_writeprotect(false);
    pmc_enable_periph_clk(ID_PIOC);
    NVIC_EnableIRQ(PIOC_IRQn);
    REG_PIOC_PER = SWITCH;
    REG_PIOC_ODR = SWITCH;
    REG_PIOC_OWDR = SWITCH;
    REG_PIOC_PUER = SWITCH;
    REG_PIOC_IFER = SWITCH;
    REG_PIOC_DIFSR = SWITCH;
    REG_PIOC_LSR = SWITCH;
    REG_PIOC_REHLSR = SWITCH;

    //Clear input change register to avoid immediate interrupt
    REG_PIOC_ISR;
    REG_PIOC_IER = SWITCH;
    run();
}

void run() {
    while(1) {
        __asm__("nop"); //Dummy operation for debugging
    }
}

void PIOC_Handler(void) {
    REG_PIOC_ISR;
    if(REG_PIOC_PDSR & PIO_PC24) {
        __asm__("nop"); //Breakpoint
    } else {
        __asm__("nop"); //Breakpoint
    }
}

As far as I know, an interrupt stops everything executed at the current time and starts working on the interrupt code. My question is now: Why is the interrupt not stopping the while loop?

Before I recognized this problem, I had a simple condition in the while loop that checks whether 1 or 0 to equals 1 when I set this state to 0, so the condition was 1 == 0 which should equal false. The loop did not stop and continued to run even if the condition for this loop was false... Is it possible that while loops do not like to be used in parallel with interrupts?

EDIT:

void main(void) {
    board_init();
    display_init();
}

I don't have an Arduino setup() function because I'm using Atmel Studio to ensure working at low Level, to avoid unnecessary code and to keep memory usage as low as possible.


texts: CPU information on Arduino Serial Monitor

texts:
how to show the

CPU temperature,
CPU usage (percentage) and
the memory usage(percentage)

in Arduino Serial Monitor.


texts:
Still don't understand about char concatenation.

void setup() {

  testCounter(3);

}

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

char testCounter(int countx){
  char a[10];
  strcpy(a, "COUNTER: ");
  strcat(a, printDigits(countx));
  return a;
}

char printDigits(int digits){
  char a[3];
  if(digits < 10) {
    strcpy(a, "0");
    sprintf(a,"%d",digits);
  } else {
    sprintf(a,"%d",digits);
  }
  return a;
}

Error:  invalid conversion from 'char' to 'const char' [-fpermissive]* in testCounter line:

strcat(a, printDigits(countx));

Don't understand this part of error.

printDigits function return char, so... strcat should be work. But why still error?

Please help...


texts: Arduino UNO and TB67H303HG Ic driver: Wiring question

texts:
I would like to control the TB67H303HG (a full bridge driver IC for DC motor
adopting MOS in output transistor) with my Arduino UNO.
This is its datasheet.

I was thinking to connect:

PIN 3 INPUT to Arduino Digital Output 13 and set it to LOW to use the direct PWM mode
PIN 5 Vref to 24VDC
PIN 6 Vcc to 24VDC
PIN 7 STBY to Arduino pin 8
PIN 8 IN1 to Arduino Pin 12
PIN 9 IN2 to Arduino Pin 11
PIN 16 OUT1A and 12 OUT1B in parallel to the Motor
PIN 14 OUT2A and 10 OUT2B in parallel to the Motor
PIN 13 and 17 to GND
PIN 20 Vcc to 24VDC
PIN 22 PWM to Arduino PWM 10

I do not know if I'm wrong, but I think I should use IN1 and IN2 to select the motor spin rotation and the Pin 12 PWM to change the velocity by setting the Arduino pin 10 with the PWM output from 0 to 255. Is it correct?

Can you tell me if the wiring is correct?
Thank you a lot!


texts: Touching a capacitive button, non-mechanically

texts:
This is not about using a capacitive button to control an Arduino; it is the opposite. I would like to "touch" a capacitive button on another conventional device. There could be a way like actually moving a finger-like stick and touch the button, but that is too much work. Can't it be done non-mechanically?
According to this page ( https://scienceline.org/2012/01/okay-but-how-do-touch-screens-actually-work/ ), "Instead, they work with anything that holds an electrical charge – including human skin.". Then, can I emulate "touching" the button by sending some small electrical current?
If so, what module/parts do I need to send such small current?


texts: HC-SRO4 always returns zero no matter what I do?

texts:
Wondering if it's the sensor or the code?  can anyone help?

I've used the code here

/*
HC-SR04 Ultrasonic Sensor with LCD dispaly

HC-SR04 Ultrasonic Sensor
  VCC to Arduino 5V
  GND to Arduino GND
  Echo to Arduino pin 12
  Trig to Arduino pin 13

LCD Display (I used JHD162A)
  VSS to Arduino GND
  VCC to Arduino 5V
  VEE to Arduino GND
  RS to Arduino pin 11
  R/W to Arduino pin 10
  E to Arduino pin 9
  DB4 to Arduino pin 2
  DB5 to Arduino pin 3
  DB6 to Arduino pin 4
  DB7 to Arduino pin 5
  LED+ to Arduino 5V
  LED- to Arduino GND

Modified by Ahmed Djebali (June 1, 2015).
*/
#include <LiquidCrystal.h> //Load Liquid Crystal Library
LiquidCrystal LCD(11,10,9,2,3,4,5);  //Create Liquid Crystal Object called LCD

#define trigPin 13 //Sensor Echo pin connected to Arduino pin 13
#define echoPin 12 //Sensor Trip pin connected to Arduino pin 12

//Simple program just for testing the HC-SR04 Ultrasonic Sensor with LCD dispaly
//URL:

void setup()
{
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  LCD.begin(16,2); //Tell Arduino to start your 16 column 2 row LCD
  LCD.setCursor(0,0);  //Set LCD cursor to upper left corner, column 0, row 0
  LCD.print("Target Distance:");  //Print Message on First Row
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;

  LCD.setCursor(0,1);  //Set cursor to first column of second row
  LCD.print("                "); //Print blanks to clear the row
  LCD.setCursor(0,1);   //Set Cursor again to first column of second row
  LCD.print(distance); //Print measured distance
  LCD.print(" cm");  //Print your units.
  delay(250); //pause to let things settle
}


texts: Split serial monitor output to only save part of the output


texts:
I would like to estimate the effective (minimum) endurance of the EEPROM of the Arduino in terms of single-byte writes.

The datasheet of the ATmega used on many Arduino boards says (page 20):

  The ATmega48A/PA/88A/PA/168A/PA/328/P contains 256/512/512/1Kbytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles.

Consider the ATmega328P with 1 kB of EEPROM. As I can write single bytes, if I loop through the EEPROM, writing every byte position the same number of times, that would make 1024 * 100,000 writes (assuming the nominal endurance).

But as far as I know not single bytes are erased before a write, but pages / cells. On page 285 / table 28.12 of the datasheet, the page size is specified to be 4 bytes. Does that mean the specified minimum endurance amounts to 1024 * 100,000 / 4 single-byte writes?


texts: How to send and receive data from serial using analog pins?

texts:
I have L293D shield connected to my arduino UNO and it fills nearly all the digital pins including TX(1) and RX(0) pins.
I know this function, but as far as I know, it works for digital pins.

SoftwareSerial NAME(Rx,Tx);

How can I set 2 analog pins as Tx and Rx? I will use them for HC-06.


texts: Elegant solution for refreshing TFT display content?

texts:
I'm currently drawing black boxes over old content before displaying constantly refreshing content on my display, so for instance to display temperature:

if (sensorTemp != nowTemp){
    nowTemp = sensorTemp;
    tft.fillRect(0,52,88,21,ILI9341_BLACK);
    return nowTemp;
}

If I don't do this the display will just overlay content until it becomes a white blob.

However, this solution leaves me with a black flickering on the display and I can't control exactly what is refreshed where. So for instance when I want to display the current time or date it has to refresh the date all the time, even though nothing changed.

void loop() {
  tft.setTextSize(2);
  tft.setCursor(0,0);
  tft.print(rtc.getDateStr());
  tft.fillRect(144,0,199,15,ILI9341_BLACK); //Black box drawn over 'old' time data
  tft.setCursor(144,0);
  tft.print(rtc.getTimeStr());  //Draw new time
  tft.setCursor(0,52);
  tft.print(tempCall());  //call function to check on temperature and draw new data if necessary
}

Is there a more elegant solution to this problem?


texts:
I would like to control a 5V relay with Wemos D1 R1 module through webserver. I'm using the following modules:

Tongling 5vdc Relay
Wemos D1 R1

I'm using the following schematic:

and here is the code I'm using:

#include <ESP8266WiFi.h>

const char* ssid = "Myssidname";
const char* password = "Myssidpass";

int ledPin = D3;
WiFiServer server(80);

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

 pinMode(ledPin, OUTPUT);
 digitalWrite(ledPin, LOW);

 // Connect to WiFi network
 Serial.println();
 Serial.println();
 Serial.print("Connecting to ");
 Serial.println(ssid);

 WiFi.begin(ssid, password);

 while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
 }
 Serial.println("");
 Serial.println("WiFi connected");

 // Start the server
 server.begin();
 Serial.println("Server started");

 // Print the IP address
 Serial.print("Use this URL : ");
 Serial.print("http://");
 Serial.print(WiFi.localIP());
 Serial.println("/");

}

void loop() {
 // Check if a client has connected
 WiFiClient client = server.available();
 if (!client) {
   return;
 }

 // Wait until the client sends some data
 Serial.println("new client");
 while(!client.available()){
   delay(1);
 }

 // Read the first line of the request
 String request = client.readStringUntil('\r');
 Serial.println(request);
 client.flush();

 // Match the request

 int value = LOW;
 if (request.indexOf("/LED=ON") != -1) {
   digitalWrite(ledPin, HIGH);
   value = HIGH;
 }
 if (request.indexOf("/LED=OFF") != -1){
   digitalWrite(ledPin, LOW);
   value = LOW;
 }

 // Return the response
 client.println("HTTP/1.1 200 OK");
 client.println("Content-Type: text/html");
 client.println(""); //  do not forget this one
 client.println("<!DOCTYPE HTML>");
 client.println("");

 client.print("Led pin is now: ");

 if(value == HIGH) {
   client.print("On");
 } else {
   client.print("Off");
 }
 client.println("

");
 client.println("Click here Turn relay ON
");
 client.println("Click here Turn relay OFF
");
 client.println("");

 delay(1);
 Serial.println("Client disconnected");
 Serial.println("");

}

After uploading the code successfully and watching the monitor, the light gets turned on and I get the following message:
16:02:20.400 -> WiFi connected
16:02:20.425 -> Server started
16:02:20.479 -> Use this URL : http://192.168.100.7/
16:02:41.680 -> new client
16:02:41.680 -> GET / HTTP/1.1
16:02:41.680 -> Client disconnected

However, when I turn on or off the relay using the browser, nothing happens:
19:38:56.010 -> new client
19:38:56.010 -> GET /LED=ON HTTP/1.1
19:38:56.010 -> Client disconnected
19:38:57.016 -> new client
19:38:57.016 -> GET /LED=OFF HTTP/1.1
19:38:57.063 -> Client disconnected

However nothing happens to the light and relay doesn't click.
a few more notes:

I tried in upload the code with relay at high to disconnect the circuit but light is still on
Wemos Network name appears in my network list
It doesn't not respond to AT Commands


texts:
My issue is that I can't rotate the motors continuously. If I press any button, motor.step will be executed and then it stops, even though I didn't release the button.
This is my project so far.
Code:

#include <AFMotor.h>

//define steppers
AF_Stepper motor1(48, 1);
AF_Stepper motor2(48, 2);

char data;

void setup()
{

  motor1.setSpeed(200);  // 10 rpm
  motor2.setSpeed(200);  // 10 rpm
  Serial.begin(9600);
}

void loop()
{
  Serial.println(data);
  if (Serial.available())
  {
    data = Serial.read();
    if (data == 'A')
    {
      motor1.step(200, FORWARD, DOUBLE);
    }
    if (data == 'B')
    {
      motor1.step(200, BACKWARD, DOUBLE);
    }
    if (data == 'C')
    {
      motor2.step(200, FORWARD, SINGLE);
    }
    if (data == 'D')
    {
      motor2.step(200, BACKWARD, SINGLE);
    }
    if (data == 'E')
    {
    delay(50);
    }
  }
}

App Inventor blocks:


texts: Can we use Arduino mini in eagle to create new custom modal

texts:
I want to learn pcb design in Eagle/Fritzing. So i was thinking of using existing amazing Arduino mini/nano in eagle and create a custom pcb which has all arduino capability and plus some components like 7 segment/Bluetooth radio etc.

Can we do that? Is is allowed or arduino design is not open to be modified?


texts: Example with dynamic array works with uint8_t, why not with uint16_t?

texts:
I tried the following example that uses uint8_t.

Is using malloc() and free() a really bad idea on Arduino?

When I replaced it with uint16_t it stops running after five loops. Any ideas?

Leo


texts: Error trying to compile an example from newly added Arduino menu library

texts:
I added the ArduinoMenu library https://github.com/neu-rah/ArduinoMenu and when I try to compile one of the examples, I get following error.

  Using library LiquidCrystal at version 1.0.5 in folder: C:\Program Files (x86)\Arduino\libraries\LiquidCrystal exit status 1 Error compiling for board Arduino/Genuino Mega or Mega 2560.

How can I fix this?


texts:
I am currently hooking up my arduino to an adafruit mini thermal printer. When a button is pressed, some code is executed which then sends some information to the thermal printer.

Everything works fine except the thermal printer print is very weak and can barely be seen as soon as the printer needs to print more than 3-5 chars. Any ideas why? Both, the arduino and the thermal printer are hooked up to 9V batteries.

Here is the code

#include "Adafruit_Thermal.h"

// Here's the new syntax when using SoftwareSerial (e.g. Arduino Uno) ----
// If using hardware serial instead, comment out or remove these lines:

#include "SoftwareSerial.h"
#define TX_PIN 6 // Arduino transmit  YELLOW WIRE  labeled RX on printer
#define RX_PIN 5 // Arduino receive   GREEN WIRE   labeled TX on printer

SoftwareSerial mySerial(RX_PIN, TX_PIN); // Declare SoftwareSerial obj first
Adafruit_Thermal printer(&mySerial);     // Pass addr to printer constructor

int buttonIn = 8;
int val = 0;

void setup() {
  pinMode(7, OUTPUT);
  digitalWrite(7, LOW);

  pinMode(buttonIn, INPUT);

   mySerial.begin(19200);  // Initialize SoftwareSerial
   //Serial.begin(19200); // Use this instead if using hardware serial
   printer.begin();        // Init printer (same regardless of serial type)
}

void loop() {
  // put your main code here, to run repeatedly:
     val = digitalRead(buttonIn);
     if(val == HIGH)
     {
        printer.println("test");
        printer.sleep();      // Tell printer to sleep
        delay(3000L);         // Sleep for 3 seconds
        printer.wake();       // MUST wake() before printing again, even if reset
        printer.setDefault();

     }
}

Did I set up anything false? Is the power supply not enough?
The adafruit was sent with a selftest from the seller where everything seemed to be fine.

Left, seller test, second from left, my selftest, third and fourth from left are example printer and charset tests.

And here you can see how everything is wired together.

Thank you very much!


texts: Arduino Uno R3 cannot detect GPRS Shield SIM900

texts:
I am new to Arduino which I got only this week for my project which sends sms from my windows     application.
I have Arduino Uno R3 and GPRS Shield (Simcom) Sim900  (S2-1040S-Z0912)
I am currently following this guide > https://educ8s.tv/arduino-gsm-shield/
As of the moment I have problem connecting the Sim900 to Arduino (I think Arduino cannot detect Sim900). The Arduino is working properly as my PC detected it. Also I confirm that the SIM900 is working properly as I can call the Sim inside and it is ringing (also the led on the device is blinking almost every 3 secs or so)
I found this, but I'm planning to use USB powered only as I only need the SMS feature so I am stacking the SIM900 on top of the Arduino.
How to communicate the Arduino board with SIM900?
I am using this library http://www.tinyosshop.com/datasheet/GSM_GPRS_GPS_Shield_GSMSHIELD.rar
and below is the sketch:
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "sms.h"
SMSGSM sms;

int numdata;
boolean started=false;
char smsbuffer[160];
char n[20];

char sms_position;
char phone_number[20];
char sms_text[100];
int i;

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

    if (gsm.begin(9600))
    {
        Serial.println("\nstatus=READY");
        started=true;
    }
    else
        Serial.println("\nstatus=IDLE");

    if(started)
    {
        if (sms.SendSMS("214", "?15001"))
        {
          Serial.println("\nSMS sent OK.");
        }
        else
        {
          Serial.println("\nError sending SMS.");
        }
    }
};

void loop()
{
    if(started)
    {
        sms_position=sms.IsSMSPresent(SMS_UNREAD);
        if (sms_position)
        {
            Serial.print("SMS postion:");
            Serial.println(sms_position,DEC);
            sms.GetSMS(sms_position, phone_number, sms_text, 100);
            Serial.println(phone_number);
            Serial.println(sms_text);
        }
        delay(2000);
    }
};

and here is the output
Trying to force the baud-rate to 9600

1200
2400
4800
9600
19200
38400
57600
115200
ERROR: SIM900 doesn't answer. Check power and serial pins in GSM.cpp

status=IDLE

What I have tried so far:
I tried the sketch with SoftwareSerial mySerial(7, 8); and SoftwareSerial mySerial(9, 10) which i found on other tutorials but didn't work.
I tried modifying GSM.cpp and modify the value of _GSM_TXPIN_  and _GSM_RXPIN_  to 7, 8 and 9, 10 but didn't work.
Found that the pin on my Arduino is RX=0 and TX=1, and SIM900 is TX=0 and RX=1, tried the SoftwareSerial code above but with 0, 1 and GSM.cpp with 0, 1 but still not working.
I am currently still trying every other sketch i find on the internet but nothing works.
EDIT:
This is the link for the module i bought
https://www.lazada.com.ph/products/sim900-gsm-shield-i267689740-s379728457.html?mp=1
I cant find the link for the datasheet of this specific module so I will try to include the picture of the module


texts:
My question is simple. Does Arduino set the digitalwrite() the moment it is called or at the end of the while loop. E.G.

int ledPin = 13;
void setup()
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{for(int i=0; i<10; i++){
if(i%2==0){
  digitalWrite(ledPin, HIGH);
  delay(1000);}else{
  digitalWrite(ledPin, LOW);
  delay(1000);      }
}


texts:
I am building a small wireless controlled robot using the Arduino and the raspberry pi. It works by the user wirelessly connecting through to the raspberry Pi (using vnc or some other form wirelessly) and using the user inputs to send a command to the Arduino which controls the motorised wheels. SO for example if the user presses the up button, a 'W" command is sent from the Raspberry Pi to the Arduino which then reads it and pushes the wheels forward.

I was looking to use one of the new Arduino-Raspberry Pi bridges to connect the two to make it easier to use, but I am not too familiar on how they work. Had a few question such as:

1) How exactly do they work (connection wise)?

2) is it possible to write one python code in the raspberry pi that when run can load the specific ino code into arduino?

3) which bridge would be the most suited for my project? (eg: Arduberry, alamode, gertduino, etc?)

Sorry really new to the raspberry pi and need to find a solution soon so any help would be awesome.

Cheers


texts: Arduino SD Card open file modes append / overwrite

texts:
Running Arduine IDE SD DataLogger Example, my data gets appended to a txt file.

File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
  dataFile.println(dataString);
  dataFile.close();
}

Is there an explicit option to open the file in overwrite / append modes?


texts: How do send sketch updates to devices without the editor?

texts:
I'd like to update the sketch of a device that a friend out of state is testing. I could have them install the full editor and send the source code but I'd rather not require them to do something so technical.

Is there a way to compile the firmware binary and push that out to a device over the COM port more directly?


texts:
I want to use an MFRC522 module as explained in this video.

But is it possible to get around with Arduino and use a TTL to USB converter to connect RC522 directly to my PC running Ubuntu?

Using the RC222's UART interface, should I rewrite Arduino libraries from scratch for PC or is there a way to easily port the libraries?


texts: Finding Relatively Accurate Velocity Using an IMU

texts:
I am currently working on a project where I am trying to accurately find velocity in a handheld device using an IMU for about 30 seconds.
I have been having major issues doing this because of large amounts of drift from poor calculations due to inaccurate sensor readings.
I have tried tuning offsets for my sensor and using other sensor fusion libraries to find my linear acceleration.
At this point I don't know if I am doing something wrong, going about the process wrong, or if my sensors are just to inaccurate to accomplish this.
I am hoping if anyone may have recommendations on how to accomplish this from the ground up. I currently have two 9DOF IMUS listed below. The first one I tried to use the predefined linear acceleration function to find velocity in ndof mode, using bosch calibration steps. The second i spent hours tuning the offsets on to get linear acceleration and it came out much worse than the first sensor. For the second I can include code but I used the madgwick from the Adafruit_AHRS library for the sensor fusion for sake of time.
Any help is appreciated.

https://www.adafruit.com/product/4646 (BNo055 first board)
https://www.adafruit.com/product/3463 (FXOS8700 + FXAS21002 second board)


texts: how does an 8-bit AVR do 10-bit analog read?

texts:
I am building a pH meter and having a real close look into the analog components, and reading the Arduino documentation for analogRead().
https://www.arduino.cc/en/Reference/AnalogRead

I see it says the Arduino, in my case an 8-bit AVR ATmega328 Arduino Uno,
yields a resolution between readings of: 5 volts / 1024 units or, .0049.

My question is whether that is accurate, or even possible. How can an 8-bit MCU provide a 10-bit analog read? how does that work?

Shouldn't the analog read be 2^8 or 256?


texts: How to use millis() in my code instead of delay()?

texts:
I'm having issues trying to convert my code to non-blocking.
I was able to do so in some parts, but the rest aren't the same.
When I try to replace delay with an if statement like the spinning and sensors debounce it doesn't work at the right time, because the variable I subtract from cur_ms is not updated.
What I'm trying to do is to always switch_dir() and update_code(), and when second_btn.released() I want the other two functions to keep running but also to run a sequence of actions (those with the delay) without blocking.
I would love to get your help.
Thanks in advance :)
void loop()
{
    uint32_t cur_ms = millis();

    if (cur_ms - spin_ms >= SPINNING_MS) {
        switch_dir();
        spin_ms = cur_ms;
    }

    if (cur_ms - read_ms >= SENSORS_DEBOUNCE_MS) {
        update_code(get_sensors_state());
        read_ms = cur_ms;
    }

    if (second_btn.released()) {
        ball_servo.write(BALL_SERVO_MAX);   // drop the ball
        digitalWrite(BLOWER_PIN, LOW);  // blower on
        delay(BALL_DOOR_MS);
        ball_servo.write(BALL_SERVO_MIN);   // close ball door
        delay(BLOWER_MS);
        digitalWrite(BLOWER_PIN, HIGH); // blower off
    }
}


texts: I am trying to setup 20 input switches that can be pressed with hand. I am trying to get the output based on the pattern in which the input switches are pressed with the hand. Based on the pressure and the area of the hand pressing the input switches, there can be multiple switches that can be pressed to display the output pattern at the same time. How can I use Arduino Uno inputs to support these multiple pin reads at the same time?


texts: ESP8266-01S Stopped responding after second launch

texts:
Here's the code:

#include <SoftwareSerial.h>
#define RX 6
#define TX 5

String AP = "...";
String PASS = "...";

SoftwareSerial esp8266(RX,TX);

void setup() {
  Serial.begin(9600);
  Serial.println("Setup started");

  esp8266.begin(115200); // Change this to the factory baudrate used by ESP8266
  delay(1000);

  Serial.println("Setting BAUDRATE to 9600");
  esp8266.println("AT+IPR=9600");
  esp8266.begin(9600);
  delay(500);
  Serial.println("Setup finished");

  reset();
  connectWifi();
}

//reset the esp8266 module
void reset() {
  Serial.println("Resetting...");
  esp8266.println("AT+RST");
  delay(3000);

  if (esp8266.find("OK"))
    Serial.println("Module Reset");
  else
    Serial.println("Module Reset Failed!!!");
}

//connect to your wifi network
void connectWifi() {
  Serial.println("Connecting to Wifi...");
  String cmd = String("AT+CWJAP=\"") + AP + "\",\"" + PASS + "\"";
  esp8266.println(cmd);
  delay(4000);
  Serial.println("Checking Wifi...");
  int ctr=0;
  while(!(esp8266.find("OK"))) {
    if(esp8266.find("ERROR")) {
      Serial.println("Cannot connect to wifi...");
      break;
    }
    delay(50);
    ++ctr;
    if(ctr>10){
      Serial.println("Cannot connect to wifi...");
      break;
    }
  }
  Serial.println("ConnectWifi finished");
}

The ESP8266-01S wires are as follows:

GND to arduino ground
3v3 to arduino 3v3
RX to arduino pin 5
TX to arduino pin 6
EN to arduino 3v3

The thing worked for one time, and when I re-compiled and sent it again without any changes or even button presses, it stopped working. Furthermore, if I connect ESP module directly through arduino rx and tx and connect arduino reset to ground, I still don't get anything. The led on the esp is blinking during data transfers, but everything else doesn't change and I get no response at all.


texts: Controlling a NC connection from two sources?

texts:
I'm trying to control a garage door opener. The button that lets you open the door from the inside is a NC connection (press the button and it goes to "open" and makes the motor run).

I want to keep that AND add another source (an Arduino w/ an RF module) that taps in to this.

Is there some sort of splitter I'd add to the garage door button wires to do this?


texts: src folder in sketch structure and include library from subfolder

texts:
My Arduino/PlatformIO libraries folder

libraries
└── cleaner_robot
    └── TB6612_Dual
        ├── tb6612_dual.h
        └── tb6612_dual.cpp

I used this code to innclude it:

#include <TB6612_Dual/tb6612_dual.h>

But the compilation has errors like "undefinded variables, undefinded reference,...etc"

This is my sketch folder

Cleaner_Robot
└── src
    └── TB6612_Dual
        ├── tb6612_dual.cpp
        └── tb6612_dual.h

If i use this code, all is ok

#include "src/libs/TB6612_Dual/tb6612_dual.h"

So the question is how to include if header file is in a sub folder of a folder in libraries folder of Arduino/PlatformIO ?, i has searched for many things, but cant help.
I also read about src folder allowed in Arduino, but where can find an official announcement/manual for this structure ?, cant find much about this

Thanks  :)


texts: Optimizing Arduino File Selection from SD card

texts:
the following code will display the files on an SD card in an Arduino and allow the user to open a file of their choosing. Here's the code with a walkthrough of what it does.

In the Init state, I call the libraries needed to run the code

// Example use of lfnOpenNext and open by index.
#include<SPI.h>
#include "SdFat.h"
#include "FreeStack.h"

// SD card chip select pin.
const uint8_t SD_CS_PIN = 10;

SdFat sd;
SdFile dirFile;
SdFile file;

// Number of files found.
uint16_t numberOfFiles = 0;

This is the area of the real problem, calling  SdFile parIndex[50]; Takes a large amount of dynamic memory. For number of files on an SD card, this is a pretty small number, so I need to get at something better

// Position of file's directory entry.
uint16_t dirIndex[50];
SdFile parIndex[50];
//------------------------------------------------------------------------------

In the Setup phase, we make sure the SD card is plugged in and, if it is, we call the function to give the files on the SD card.

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

  // Initialize at the highest speed supported by the board that is
  // not over 50 MHz. Try a lower speed if SPI errors occur.
  if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50)))
  {
    sd.initErrorHalt();
  }
  if (dirFile.open("/", O_READ))
  {
  printDirectory(dirFile, 0);
  }
}

The printDirectory function (This is the part most open to edits, if there's any way to improve performance here, please let me know as well).

void printDirectory (SdFile CFile, int numTabs)
{
  SdFile file;
  while (file.openNext(&CFile, O_READ))
  {
  if (file.isHidden()||false)
    {
      //file hidden, skip
    }
    else
    {
      for (uint8_t i = 0; i < numTabs; i++)
      {
        //create tabs for spacing
        Serial.print('\t');
      }
      if (file.isSubDir())
      {
        SdFile SubDirFile;
        printDirectory(SubDirFile, numTabs+1);
      }
      else
      {
        // Save dirIndex of file in directory.
        dirIndex[numberOfFiles] = file.dirIndex();
        parIndex[numberOfFiles] = CFile;
        // Print the file number and name.
        Serial.print(numberOfFiles);
        Serial.write(' ');
        file.printName(&Serial);
        Serial.println();
        numberOfFiles++;
      }
    }
  file.close();
  }
}

This is the user interface portion, it was largely slapped together as a proof of concept for the above code. As it's written, the code only accepts index values 0-9, but my actual program could call any index value.

void loop() {
  int c;

  // Read any existing Serial data.
  do {
    delay(10);
  } while (Serial.available() && Serial.read() >= 0);
  Serial.print(F("\r\nEnter File Number: "));

  while (!Serial.available()) {
    SysCall::yield();
  }
  c = Serial.read();
  uint8_t i = c - '0';
  if (!isdigit(c) || i >= numberOfFiles) {
    Serial.println(F("Invald number"));
    return;
  }

After making sure that the input value exists, it calls up the arrays that contain the parent's directory SdFile object and the index of the desired file.

  Serial.println(i);
  if (!file.open(&parIndex[i], dirIndex[i], O_READ)) {
    sd.errorHalt(F("open"));
  }
  Serial.println();

  char last = 0;

  // Copy up to 500 characters to Serial.
  for (int k = 0; k < 500 && (c = file.read()) > 0; k++)  {
    Serial.write(last = (char)c);
  }
  // Add new line if missing from last line.
  if (last != '\n') {
    Serial.println();
  }
  file.close();
  Serial.flush();
  delay(100);
}

The main issue I have is that SdFile parIndex[50]; uses 22% of my dynamic memory vs the rest of the program using 12%. How can I rewrite my code to not require keeping the SDFile objects in dynamic memory?

For anyone unfamiliar, documentation for the SdFat library can be downloaded from that link.

Edit:
In terms of use: The SD files are .csv files that store speed and time parameters for running a motor test. Each test lasts for a few minutes to hours.


texts:
I have modified the code for Flappy Duino to give me a score at the end of the game. Here is the code:

#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h>

Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);

#include "Sprite.h"
#include "Chym.h"
#include "Bar.h"

Chym player;
Bar bar; Bar bar2;
int gameScore = 0;
int highScore = 0;
int KNOCK_PIN = 2;
int LED_PIN = 8;

boolean clicked = false;

void loop(){}

void resetGame() {
  player.respawn();
  bar.setPos(0, 20);
  bar2.setPos(50, 30);
  gameScore = 0;
}

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

  display.begin();
  display.setContrast(50);
  display.clearDisplay();
  display.display();

  digitalWrite(LED_PIN, HIGH);

  pinMode(KNOCK_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);

  resetGame();

  while(1) {
    getInput();
    player.update();
    bar.update(); bar2.update();
    drawLCD();
  }
}

void getInput() {
  int knock = digitalRead(KNOCK_PIN);
  if (knock == 0) { // push down
    clicked = true;
    gameScore = gameScore + 1;
    Serial.println(gameScore);
  }
  else {
    clicked = false;
  }
}

void drawLCD() {
  display.clearDisplay();

  if (!player.isDead()) {
    int ht1 = bar.hitTest(player.getX(), player.getY());
    int ht2 = bar2.hitTest(player.getX(), player.getY());
    int die = ht1 + ht2;
    if (die == 1) {
        // game over
        player.die();
    }

    if (clicked) {
      player.flyUp();
    }
    else {
      player.cancelJump();
    }
    player.render();

    bar.render(); bar2.render();
  }
  else {
    if (gameScore >> highScore) {
      highScore = gameScore;
    }
    display.setCursor(0, 0);
    display.setTextSize(1);
    display.print("ur Score- ");
    display.println(gameScore);
    display.print("HI Score- ");
    display.println(highScore);
    if (clicked) {
      resetGame();
    }
  }

  display.display();
}

The first time the game runs thru the gameScore is greater than highScore so gameScore and highScore print as the same. However every other time the function is called up the highScore doesn't change even when the following statement is true:

if (gameScore >> highScore) {
          highScore = gameScore;
        }

What am I doing wrong?


texts: DFRobot GSM / GPS shield with UNO init error

texts:
Apologies, but I have little experience of Arduino etc. Has the "Sim808 init error" been resolved anywhere please? I have tried every example I can find including the ones on these StackExchange pages without success. I started with the GPS test code from:
https://wiki.dfrobot.com/SIM808_GPS_GPRS_GSM_Shield_SKU__TEL0097
Parancey, Marcello, Pooya and Arslan and others have suggested mods to this code so I have tried all of them I think - none working.
Then I watched this video:
https://www.youtube.com/watch?v=fN8fwX3KmsM
which appears to show the code below or similar:
/*
### Get GPS data
1. This example is used to test SIM808 GPS/GPRS/GSM Shield's reading GPS data.
2. Open the SIM808_GetGPS example or copy these code to your project
3. Download and dial the function switch to Arduino
4. open serial helper
4. Place it outside, waiting for a few minutes and then it will send GPS data to serial

create on 2016/09/23, version: 1.0
by jason

*/
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

//#define PIN_TX    10
//#define PIN_RX    11
//SoftwareSerial mySerial(PIN_TX,PIN_RX);
//DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

DFRobot_SIM808 sim808(&Serial);

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

  //******** Initialize sim808 module *************
  //while(!sim808.init()) {
  while(!sim808.checkPowerUp()) {
      delay(1000);
      Serial.print("Sim808 init error\r\n");
  }

  //************* Turn on the GPS power************
  if( sim808.attachGPS())
      Serial.println("Open the GPS power success");
  else
      Serial.println("Open the GPS power failure");

}

void loop() {
   //************** Get GPS data *******************
   if (sim808.getGPS()) {
    Serial.print(sim808.GPSdata.year);
    Serial.print("/");
    Serial.print(sim808.GPSdata.month);
    Serial.print("/");
    Serial.print(sim808.GPSdata.day);
    Serial.print(" ");
    Serial.print(sim808.GPSdata.hour);
    Serial.print(":");
    Serial.print(sim808.GPSdata.minute);
    Serial.print(":");
    Serial.print(sim808.GPSdata.second);
    Serial.print(":");
    Serial.println(sim808.GPSdata.centisecond);

    Serial.print("latitude :");
    Serial.println(sim808.GPSdata.lat,6);

    sim808.latitudeConverToDMS();
    Serial.print("latitude :");
    Serial.print(sim808.latDMS.degrees);
    Serial.print("\^");
    Serial.print(sim808.latDMS.minutes);
    Serial.print("\'");
    Serial.print(sim808.latDMS.seconeds,6);
    Serial.println("\"");
    Serial.print("longitude :");
    Serial.println(sim808.GPSdata.lon,6);
    sim808.LongitudeConverToDMS();
    Serial.print("longitude :");
    Serial.print(sim808.longDMS.degrees);
    Serial.print("\^");
    Serial.print(sim808.longDMS.minutes);
    Serial.print("\'");
    Serial.print(sim808.longDMS.seconeds,6);
    Serial.println("\"");

    Serial.print("speed_kph :");
    Serial.println(sim808.GPSdata.speed_kph);
    Serial.print("heading :");
    Serial.println(sim808.GPSdata.heading);

    //************* Turn off the GPS power ************
    sim808.detachGPS();
  }

}

I have mounted the DFRobot shield on a UNO and powered through the barrel connector with a 2_amp 5V stabilised power supply. The DFRobot shield shows a red LED power light and pressing reset flashes the blue LED next to it, but nothing else does anything - the serial monitor just repeats "Sim808 init error". In the video the blue "net" LED flashes even before the SIM card is inserted, but my card does not flash. Do I return the board to Farnell and ask for my money back?
Any help greatly appreciated!


texts:
I am using Arduino Leonardo and Ardumoto to drive 2 12v motors running at 1.3 amps each.

I purchased a rechargeable battery of 12V with 5AH

I first started by plugging in the battery to the Arduino via the barrel jack. Arduino then sparks and is fried.

I read somewhere that I wasn't supposed to hook it up to the Arduino and to hook it up to the VIN ports in the Ardumoto. I purchased a new Arduino and plugged in the Positive and negative from the battery to the ports and now the Ardumoto board fried (copper lining on board burnt off).

I'm reading online and from what I've gathered, the Ardumoto can handle a max of 18 volts and a maximum of 2 amps per each output. I'm obviously missing something and would not like to fry my boards next time.

Please assist?


texts:
I want to use a 5 inch 800x480 TFT display (touch not needed) with an Arduino (mega, uno or due). I'm thinking of buying this display: link (buydisplay.com). How can I connect this ?

I have also seen some pricier screens with serial i2c connection., but I don't understand the difference between this and using a shield?

Do anyone have any advice for displays to order and/or shields for Arduino ? Preferably a solution that I can reproduce by my self later for mass-production by doing be own circuit board.

Thanks in advance!


texts: Why won't Wifi Shield detect any networks? Even really close

texts:
I just purchased an Adafruit Wifi Shield CC3300 and strapped it onto my Arduino Uno board.

I'm running this basic sketch that I found to test the functionality of the Wifi Shield: http://arduino.cc/en/Guide/ArduinoWiFiShield#toc1

Of course in my home I have Wifi, so I expected this sketch to show my Wifi name. However it doesn't. Instead I get this output on my serial monitor:

Init...
** Scan Networks **
Initializing Wifi...
MAC: 0:0:0:0:0:0
Scanning available networks...
** Scan Networks **
number of available networks:0
Scanning available networks...
** Scan Networks **
number of available networks:0

It just keeps going forever detecting zero networks.
I even took the Arduino and stood 3 feet away from my Wifi router. Still nothing.
I even tried making my cell phone a Wifi hotspot and holding it right next to the Arduino. Still nothing. And why does it say the MAC Address 0:0:0:0:0:0?

Can anyone suggest a fix?
FYI, here is a photo of what my setup looks like:


texts:
I'm new to using the SN74HC595 shift register, and trying to follow this tutorial: https://www.arduino.cc/en/tutorial/ShiftOut based on this configuration:

When my arduino Uno R3 is plugged in by USB to my Windows-7 x64 PC, it works (in general etc.), but right when I attach pin 16 or pin 10 of the 74HC595  to the 5V pin on the Uno, as it says to do, the entire arduino shuts off and the computer no longer recognizes it, until I disconnect the jumper wire from pin 16 or 13, from the 5v pin on the Uno, then it starts up again
Also just tested, and the same thing happens when I try to connect any of the 74HC595  pins to the 5v Uno pin (after pin 8 of the 74HC595  is connected to the Uno's GND), the whole Uno shuts off and disconnects from the computer
Am I missing something here?


texts: How to bootload a atmega328-pu using arduino uno?

texts:
I have some Atmega328-Pu micro-controllers without boot-loader program. Now I need to burn boot-loader to them all. I have two arduino uno boards having Atmega328 P-Pu micro-controllers on board. I used this circuit  from this page Installing an arduino boot-loader
It does not work. The boot-loader is not uploaded. Can you please help me out? If you need any more informations please ask. I have been struggling with this kind of boot-loading techniques for more than a week. I am using arduino IDE 1.0.1 and the board is Arduino uno R3


texts: Sleep and Wake Arduino according to LDR interrupt

texts:
I have to sleep the system in the night and have to wake the system in day time. I am using LDR to get input. LDR input is connected to interrupt pin 0 of Arduino Uno.

Here is my code.

#include <avr/sleep.h>
int led =13;
int triggerPin = 2;

void wakeUpNow()
{

}

void setup()
{
pinMode(triggerPin, INPUT);
pinMode(led, OUTPUT);
attachInterrupt(0, sleepNow, LOW);
}

void loop()
{
digitalWrite(led, HIGH);;
delay(1000);
digitalWrite(led, LOW);
}

void sleepNow()
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
attachInterrupt(0,wakeUpNow, RISING);
sleep_mode();
sleep_disable();
detachInterrupt(0);
}

Cannot we attach two function in a interrupt?

Edited
The following code works perfectly. I want to replace the conditional check with interrupt.

#include <avr/sleep.h>
int led =13;
int wakePin = 2;

void wakeUpNow()
{
delay(100);
}

void setup()
{
pinMode(wakePin, INPUT);
pinMode(led, OUTPUT);
//attachInterrupt(0, sleepNow, LOW);
}

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

if(digitalRead(wakePin)==LOW)
  sleepNow();

}

void sleepNow()
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
attachInterrupt(0,wakeUpNow, RISING); function
sleep_mode();
sleep_disable();
detachInterrupt(0);
}

I want to replace `

if(digitalRead(wakePin)==LOW)
  sleepNow()

with`

attachInterrupt(0, sleepNow, LOW);

Please let me know how I can do that.

Thank you.


texts: Using multiple RTC libraries in one program

texts: There are multiple RTC libraries available, can I load several RTC libraries into my code and then use the functions I like from each one?  Will there be some conflict if for example I include DS1307.h   and RTCLib.h and other RTCXXXX.h libraries as well?


texts:
I have an Arduino Pro Micro mimicking as a HID, connected to a PC.

The PC BIOS is configured to wake from keyboard events - it is switched on by hitting a key on the regular keyboard. This is a wanted feature and should stay.

Unfortunately, it also wakes when the Arduino sends HID events, which is understandable and pretty obvious, but to be avoided.

Is there something in the USB protocoll, or even in the Arduino HID libraries, that lets me tell the chip to either not wake up the host (unlikely, I guess); or so that I can detect when the PC has shut down, so I can tell the Arduino to go sleeping as well until the PC wakes up again?

EDIT: I am using the "HID-project" USB library (HID 2.4.3) from https://github.com/NicoHood/HID.


texts: Can I read from a memory card with three pins?

texts:
I have a project where I have three pins to use and I just realized it would be better to use a memory card than replacing the code each time.

I'm building a Arduino with a push button. Press the button and it sends keystrokes to the connected computer with login details.
The login details need to change every three months so having that on a memory card will be easier.

So since I use a digispark Attiny 85 with a total of 6 pins (where two is used to send the keystrokes).
I have one to the push button, and three pins left.

Is there any card reader that can work with three pins? I only need to read if that makes a difference.
The ones I find use four pins (+ vcc and gnd).

Pretty much any memory card type is ok.


texts: I recently bought a Raspberry Pi Pico to play with, and am attempting to upload my first program to it the Arduino way, as my own operating system rather than a c++ program over an existing operating system (meaning to replace the built-in Raspberry Pi Pico operating system which runs MicroPython, not in the sense of running Linux, Windows, Mac, or any derivative or fork). I have not found any record of people hacking it like that - is it possible? If so, how would I go about it? Sorry if this is in the wrong Stack Exchange.


texts: How to use ESP8266 Pin D3 / GPIO 0 and D8 / GPIO 15 properly

texts:
I am using WeMos D1 Mini Pro to control multiple relays. I found out that during start up the relay connected to pin D3 and D8 would switch between on and off a couple times in a very short interval. I found out that the two pins are related to boot loader configuration.

Question is: Is there any way to prevent the relay from "blinking"? Is there a way to disable the relay output until boot loader finish it's stuff? Because this behavior only occur once every boot up.


texts: Turn on relay for amount of time by continuous input

texts:
I have a project having two input status

first the input is not continuous the output buzzer relay will be on for 10 seconds and then turned off or it can be off directly by push button

the second state if the input is continuous the output buzzer relay will be on for 10 seconds and then turned off or it can be off directly by push button

I made this code but it does not work can anyone suggest an edit without using millis() because it will crash after 49 days and without using delay function.
Note that the device will work 24 hours / 365 days.
const int input1 = 19;
const int input2 = 36;
const int relay1 = 10;
const int relay2 = 21;
const int reset = 40;
const int buzzerreset = 45;
const int buzzerrelay = 46;

int buttonState1 = 0;    //for input1
int buttonState2 = 0;    //for input2
int buttonState3 = 0;    //for pushbutton
int buttonState4 = 0;    //for buzzer reset
int b4 = 0;              //for buzzer reset

void setup() {
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(buzzerrelay, OUTPUT);
  pinMode(input1, INPUT);
  pinMode(input2, INPUT);
  pinMode(reset, INPUT);
  pinMode(buzzerreset, INPUT);

  digitalWrite(relay1, LOW);
  digitalWrite(relay2, LOW);
  digitalWrite(buzzerrelay, LOW);
}

void loop() {
  buttonState1 = digitalRead(input1);
  if (buttonState1 == HIGH) {
    digitalWrite(relay1, HIGH);
    digitalWrite(buzzerrelay, HIGH);
    //delay(10000);
    //digitalWrite(buzzer, LOW);
  }

  buttonState3 = digitalRead(reset);
  if (buttonState3 == HIGH) {
    digitalWrite(relay1, LOW);
    //digitalWrite(buzzer, LOW);
  } else {
    buttonState4 = digitalRead(buzzerreset);

    if ((buttonState4 == HIGH || buttonState1 == HIGH) && b4 == LOW) {
      digitalWrite(buzzerrelay, LOW);
    }
    // while (digitalRead(input1) == HIGH);
    // digitalWrite(buzzerrelay, LOW);

    (buttonState2 = digitalRead(input2));
    if (buttonState2 == HIGH) {
      digitalWrite(relay2, HIGH);
      digitalWrite(buzzerrelay, HIGH);
      //delay(10000);
      //digitalWrite(buzzer, LOW);
    }

    buttonState3 = digitalRead(reset);
    if (buttonState3 == HIGH) {
      digitalWrite(relay2, LOW);
      //digitalWrite(buzzer, LOW);
    } else {
      buttonState4 = digitalRead(buzzerreset);
      if (buttonState4 == HIGH) {
        digitalWrite(buzzerrelay, LOW);
      }
      //while (digitalRead(input2) == HIGH);
      //digitalWrite(buzzerrelay, LOW);
    }
  }
}


texts: How to read voltage value from arduino to esp32

texts:
I am learning Arduino(uno)-ESP32 basics for a hobby project. In Arduino sketch, it's writing some random value(mimicking a sensor) to Arduino analog pin 9.

const int analogInPin = A0;  // NOT CONNECTED
const int outPin = 9;        // DIGITAL OUT. [ESP32 INPUT]

// SETUP()
randomSeed(analogRead(analogInPin));

// LOOP()
sensorValue = random(0, 1024);
// 0 - 5v WHEN MEASURED
// MAP VALUE OR JUST WRITE 'sensorValue'
outputValue = map(sensorValue, 0, 1023, 0, 255);
analogWrite(outPin, outputValue);

In ESP32 sketch, I'm trying to read this value

int adc_value = 0; // EXPECTS A VALUE B/W 0 - 4095

//SETUP()
pinMode(26,INPUT);

//LOOP()
adc_value = analogRead(26);
Serial.println(adc_value);// OUTPUT 2 VALUES; 0 AND 4095
// MAP_VALUE = (adc_value * 5 ) / (4095);

The output is only 2 values, 0 and 4095. Is it due to ESP 3.3V and Arduino 0-5v output range or some other mistakes?


texts: I want to build an arduino-based RC Tank, which should be controlled with a notebook or smartphone (Android). Bluetooth would be an easy solution, but the range is a bit short for a RC Vehicle, so I want to controll it via WIFI. I found a ton of examples and tutorials on how to do that but all of them reqire a router which both the arduino and the Smartphone are connected to. Any idea on how to directly control an Arduino with an smartphone via WIFI?


texts: Arduino as ISP with serial monitor for ATmega328

texts:
I have an ATmeg328 TQFP on a board (in system). I use an Arduino Uno as an ISP to programm the chip. However, i would like to use Serial Communication with the chip through the Arduino board.

Is this possible?
If yes, how can i realize this?

EDIT: i have the tx and RX pins not available. The chip is on a board. With through arduino board, I mean that I would like to use the miso mosi sck pins to do this.


texts:
It's a basic one: I have two values from two different analogRead pins:

int val1;
int val2;

For example, val1 = 10 and val2 = 10. How could I put these two values into a variable val3 = val1 + val2 that will give the answer 1010, instead 20 ?


texts: Send one bit out per clock pulse received using direct port manipulation?

texts:
I want to send one bit of a byte out per 'rising edge' received to an Arduino digital input. I am addressing the outputs using direct port manipulation (to achieve maximum speed), and I would like to do the same for input.

So I'm calling a function called bitBang in my main loop, sending the ready line high before moving into the function:

//Send control
PORTB |= _BV(PORTB2);
bitBang(controlByte);
PORTB &= ~_BV(PORTB2);

What I would like to do upon entering the function is listen for a rising edge to appear on the digital input port using the direct port syntax and iterate through the byte setting the data line high or low depending on the bit's value.

How can I achieve this in the most efficient way possible?


texts: JSN-SR04T-2.0 with NodeMCU not starts after reset or reconnect usb power

texts:
I have bought a NodeMCU (1.0) and a JSN-SR04T waterproof ultrasonic sensor compatible with HC-SR04.

If I upload my program to NodeMCU it works but sometimes it measures a wrong distance - it is an another question, but it may connect to this question.

If I press the reset button my application not starts or if it is unplugged and plugged in to usb power it not starts.

If I unplug the ultrasonic sensor 3.3V and ground it starts.

It starts with the following code:

const int trigPin = D4;
const int echoPin = D3;

void flashLed() {
  digitalWrite(LED_BUILTIN, LOW);
  delay(400);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(100);
}

void setup() {

  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

  flashLed();
  Serial.begin(115200);
  flashLed();
  delay(10);

  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    digitalWrite(LED_BUILTIN, HIGH);
    delay(1000);
    digitalWrite(LED_BUILTIN, LOW);
    delay(1000);
  }
  Serial.println("");
  Serial.println("WiFi connected");

  server.begin();

  Serial.println("Web server running. Waiting for the ESP IP...");
  delay(10000);

  Serial.println(WiFi.localIP());

  digitalWrite(LED_BUILTIN, HIGH);

}

I have uploaded the full source code to github project:

https://github.com/kisdaniel/nodemcu-wif-http-HC-SR04/blob/master/HomeDashboardUltrasonicHttp.ino

Why it not starts?

UPDATE:

I have make a minimal version of code to reproduce the problem:

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

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

Wiring:

Node MCU 3.3V -  Vcc (ultrasonic sensor)
Node MCU GND  -  GND (ultrasonic sensor)
Node MCU D4   -  Trigger (ultrasonic sensor)
Node MCU D3   -  Echo (ultrasonic sensor)


texts: Arduino RS485 communication protocol - minimising overheads and best practice

texts:
I'm building a single master multiple slave RS485 network for remote sensors on test equipment. I have the hardware built and working, and I can do a Serial.print on the master and have the slaves display the values received on their attached OLED screens. The goal is for the master to cycle through the slave addresses one by one and request data, then wait for the slave to respond (or timeout and register as a fail on the master's GUI).

The issue I have is that to work out if a packet is intended for a slave device I have to parse the entire packet, wait for start and end packets, and check the address. This means every device has to capture and check every packet on the network for its own address byte. If I compare on the fly I can exit the serial loop as soon as I know which device the packet is intended for, but the next received packet will just re-open the serial loop part way through transmission.

Other than disabling the RS485 transceiver between packets, is there an elegant way to solve this issue without massive overheads?

My hardware uses Arduino Nanos (master is currently an Uno but will be a piece of National Instruments hardware) and MAX13487 transceivers.

Thanks!


texts:
I'm using the most recent Arduino IDE to upload a sketch to an Arduino Uno, and the upload seems to succeed, but the final verification step fails with the error:

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: reading input file ".build_ano/uno/firmware.hex"
avrdude: writing flash (30908 bytes):

Writing | ################################################## | 100% 5.01s

avrdude: 30908 bytes of flash written
avrdude: verifying flash memory against .build_ano/uno/firmware.hex:
avrdude: load data flash data from input file .build_ano/uno/firmware.hex:
avrdude: input file .build_ano/uno/firmware.hex contains 30908 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 3.96s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x7800
         0xff != 0xfe
avrdude: verification error; content mismatch

avrdude: safemode: Fuses OK (H:00, E:00, L:00)

avrdude done.  Thank you.

I've re-ran the upload several times, and tried different USB cables, but I get the exact same verification error each time. Does this mean the upload effectively failed (presumably because the flash memory has gone bad), and that my sketch is not running on the Arduino? Is there any way I can fix this?

I tried uploading to a different Arduino Uno, and I received the exact same error.


texts:
I created a class inside the sketch file(not in another file) and init it as object before setup() and loop() as a global object, after I change some parameters inside the object in setup() , I found in loop() the parameters in the global object remain unchanged.
Here is the pseudocode code to describe my question:

//all of the code below are in the same ino file.
class Animal{
public:
  bool alive = false;
  Animal (bool liveStatus){
    alive = liveStatus;
  }
}

Animal dog(false);
Animal cat(false);
Animal lion(false);
Animal animalArray(dog,cat,lion);

void setup(){

  for (int i=0;i<3;i++){
    Animal current_animal = animalArray[i];
    current_animal.alive = true;
  }
  //here when I print each animal's alive flag is 'true'
}

void loop(){
  for (int i=0;i<3;i++){
         // here the alive flag of each animal is still false  , they should be all true!!
  }

}

It looks like after I quit setup() somehow every change of the global object inside the setup are all gone .

Thanks for helping me ..


texts:
For few days, I am trying to figure out, why my sensors do not work on external power. I bought NodeMCU along with couple different sensors etc. I was happily working with them, connecting them one by one to the 3.3v pin in the NodeMCU board, programming each of them. Everything was working as expected. After I have finished, I decided it's time to use them all at once, but I knew, that for that to work, I need to provide them with enough power, as USB probably won't be enough (plus, when I'm done, I don't plan to use USB to power the system anyway). I have a module that converts 230v AC into 5v DC, and then I am stepping it down to 3.3v in order to power the sensors. After checking with multimeter, the voltages are ok, and so is the current.

My problem is, that the sensors give completely random data (most of the time they don't give any information, but once in a while they send something like 1000 times the normal value). Below you can see the schematic that I use. Can you please help me figure this out?

Edit: I would just like to add - I did try to run NodeMCU solely on the Ext. Power - the circuit looked exactly as below, I just connected positive output of 3.3v power source, to the 3.3v connector on NodeMCU. The board was working (I was able to control the onboard LED via WiFI), but the sensor did not. I then reconnected the sensor from external power, to NodeMcu 3.3v, and it (the sensor) worked... I have no idea why.

simulate this circuit – Schematic created using CircuitLab