texts: How to apply a programme to all values in a list simultaneously

texts:
I'm attempting to turn on a set of LED's one at a time and then switch them all off at the same time, I am stuck however on turning them off at the same time.

That is my code:

int ledpins[] = {2,3,4,5,6,7,8,9}; //creates a list of the pins in use

void setup() {
  for (int i = 0; i < 8; i++){
    pinMode(ledpins[i], OUTPUT);  // iterates over the list led pins from the 0 pin to the pins before the eigth
  }
}

void loop() {
  for (int i = 0; i < 8; i++){
    digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
  }

  delay(100); //when all on will wait 100 ms
  digitalWrite(ledpins[0,7], LOW); //turns off all the leds at once
  delay(100);
}

The annotations are for my own understanding.
I just need help turning all the LED's off at once which I dont know the command for.


texts: How to find out whether an arduino can control a servo motor

texts:
I have a servo motor with following specs
Torque - 1.08Nm
Max rpm - 3000
Current rating - 7.8 amp
Max voltage - 56V DC

Please tell me how to calculate whether an arduino board - uno rev 3 can control the servo motor? If not, how to find out how many such boards are required?


texts: Bluetooth sending values from two joysticks

texts:
Is there any good way of sending values from two joysticks from arduino A to arduino B? I tried sending using if statements, so if the Y- or X-axis' value changed then it would send that, but the servo motor on Arduino B went a little bit crazy.

Here's what I've done so far:

//Master Code
void loop()
{
      yVal = analogRead(yAxis);   // read the value of the Right Joystick (value between 0 and 1023)
      yMap = map(yVal, 0, 1023, 0, 255);
      xVal = analogRead(xAxis);     // read the value of the left Joystick (value between 0 and 1023)
      xMap = map(xVal, 0, 1023, 0, 110);

  if(Serial.available() && !(xVal > 505 && xVal < 510)){
      Serial.print('X');
      delay(10);
      Serial.write(xMap);
      }
  if(Serial.available() && !(yVal > 500 && yVal < 520)){
      Serial.print('Y');
      delay(10);
      Serial.write(yMap);

    }
    delay(10);
}

And the Slave code:

//Slave code
void loop(){
  while(Serial.available())
  {
    c = Serial.read();
    delay(5);
    val = Serial.read();
    if(c == 'X'){
        digitalWrite(13, LOW);
        myServo.write(val);
    }else if(c == 'Y'){
        digitalWrite(13, HIGH);
    }
    }

}

Edit: I was thinking that maybe I should do something like a start and stop bit for X and Y?

Edit2: I wrote an if statement in Arduino B because it was reading the value -1, I don't know why, but after the if statement the servo motor hasn't been going crazy and the program works now. I still would like to know if I can do this in a better way. Thanks in advance!


texts: HC-12 modules stopped receiving, cannot understand why

texts:
I've created a simple transmitter with an HC-12 and an Arduino Nano (clone), where I send the values of DHT11 and LM35 sensors to a receiver unit made only of a Wemos D1 and another HC-12.

Setup is really simple and worked fine for a couple of days (transmitter in the cellar 2 floors down, receiver in my living room, it was POSTing data to my own server correctly), then I unplugged the receiver and modified the transmitter to add a JSON library; when I plugged them back again the receiver is not getting anything anymore.
Transmitter seems to be working fine, at least it prints the number of bytes written in the Serial Monitor.

I tried:

reverting back to the working version (no JSON), but still the same
tested each of the HC12 modules with a simple test code and AT commands, they all responds and are all set to factory configuration, like it was before actually (AT+DEFAULT)
made another receiver with an Arduino Uno and a lcd screen - a setup that I was successfully using before changing to the Wemos. Strangely, now this setup doesn't work too...
Switched the modules and what I got? The transmitter still transmits, the receiver doesn't receive, nothing changed.

Tried sending a simple string "Test", still no results.

Relevant code:

Transmitter:

#include <ArduinoJson.h>
#include <DHT_U.h>            // just Adafruit Library
#include <DHT.h>
#include <SoftwareSerial.h>
#define DHTTYPE DHT11   // DHT 11
SoftwareSerial HC12(10, 11); // HC-12 TX Pin, HC-12 RX Pin
int DHTPIN = 4;
int LMPIN = 5;
DHT dht(DHTPIN, DHTTYPE);
StaticJsonDocument<80> doc;

void setup() {
  analogReference(INTERNAL);
  Serial.begin(9600);             // Serial port to computer
  HC12.begin(9600);               // Serial port to HC12
  dht.begin();
}

void loop() {
  delay(5000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  int reading = analogRead(LMPIN);
  float lmt = reading/9.31;
  doc["dht_h"] = h;
  doc["dht_t"] = t;
  doc["ds_t"] = lmt;
  char result[50];
  serializeJson(doc, result);
  Serial.println(result);
  int written = HC12.print(result);
  Serial.println(written);    // it's 39 chars
}

Receiver (all wifi sections are removed):

#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#define STASSID "....."
#define STAPSK  "....."
SoftwareSerial HC12(D13, D15); // HC-12 TX Pin, HC-12 RX Pin

const char* ssid     = STASSID;
const char* password = STAPSK;
const char* host = "...........";
const uint16_t port = 3000;

void setup() {
  Serial.begin(9600);
  HC12.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

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

void loop() {

  String content = HC12.readString();
  Serial.println(content);
  if(content.length()) {
    // This will send a string to the server
    Serial.println("sending data to server");
    if (client.connected()) {
      //....
    }
  }
  delay(1000);
}

I'm pretty stumped by the fact that it stopped working, and that both the HC-12 modules seem to be working fine (at least they respond to all the AT commands).
I even tried purging arduino from the system and reinstalling (I now have the very latest IDE release) but nothing....

Am I missing something obvious? (I've a weak electronic background, I'm a web developer by trade).
Is there a way to check if data is actually sent?
How can I debug these modules?


texts:
I have a code which make some calculations using sensor values and provide two comma separated values.

float x;// initialization
float y;// initialization
//some calculations here using sensor values
Serial.print(x);Serial.print(",");Serial.print(y);

but the issue is due to some unstable situations of the sensor readings, I don't receive sensor data in same time intervals (overall delay is 1 second). I send these values to my Android device through a Bluetooth connection. At that stage, android device cannot separate two values due to lack of smoothness of the Serial.print(). Is there any way to make it smooth (like saving to a buffer before serial print or something) ?


texts: What type of hardware could make a ball tilt or roll?

texts:
I wanted to know what type of component or module I could use to make a hollow ball move.  I have these hollow plastic balls (think empty easter eggs) that I was going to put a nano in and a sound detector and was just hoping to just get it to move.  I prefer a sort of a tilt left and right effect, but if it just rolls randomly that would work as well.

I was thinking just a simple vibration, but it doesn't really shift the ball at all, so I'm at a loss without building something quite complex with magnets or something.  Perhaps a motor stuck to the side?


texts:
I'm trying to receive MIDI messages on a Leonardo. To do that I used the circuit in the diagram below (only the top half for receiving). The only thing I did differently was using an 1N4148 diode instead of the 1N914. I connected GND to pin GND, 5V to pin 5V and RX to pin 0 (RX), and I used code below to see whether I do get any inputs or not. (I first started with some more complex code but it seems this is the minimal thing I can do.) As a MIDI source I used an Arturia Keystep which I tested on a midi instrument.

Unfortunately I don't get any input, and I don't know why. What I tried so far:

Verified the polarity of all cables, and made sure all connections work.
Swapped the Leonardo with a different one (both new).
Swapped out the 6N137 optocoupler with another one (both new).
Addded above the if-statement a Serial.println("test"); which then resulted in an endless avalanche of "test" in the serial monitor - just to check if the USB connection works.
Measured the voltage between pin 5 and 8 on the 6N137 and it is indeed 5V.

Is there anything obvious I'm doing wrong? What things do you suggest doing to try to find the bug? (I do have a multimeter but no oscilloscope.)

 (from this answer).

byte b;
void setup() {
  Serial.begin(9600); //USB
  Serial1.begin(31250); //MIDI
}

void loop() {
  if (Serial1.available() > 0) {
    b = Serial1.read();
    Serial.println((int)b);
  }
}


texts:
I searched for ov2640 with Arduino examples but only I could get the examples of Arducam. So I'm trying this example with OV2640 camera. As ov7670 and ov2640 have similar pinouts. But I'm not getting the image(output)(But I got the output while using OV7670 camera). I don't know why I'm not getting the output. Someone please let me know where do I go wrong(Reference image attached) and please let me know any other example you may know.
Thank you,
Roshan


texts: Using a analog multiplexer to use 9 serial input sensors?

texts:
I have 9 sensors, they will send a datastring to my Arduino through Tx/Rx (every 3½ seconds, pre-programmed). The only problem is that there's only one Tx/Rx port on an Arduino Uno. Is it possible to use an analog multiplexer to "make" more Serial ports? Because the sensors send something every 3½ seconds, there's no need to be fast.

EDIT: It's a Temperature and Relative Humidity Sensor


texts: How to program a Arduino Nano(Bricked) with a working arduino nano

texts: I corrupted my bootloader on one arduino, luckily I had a spare lying around. Please help as there is not a single tutorial to help my exact state


texts: Modify On board 4 pin switch to work with Arduino

texts:
I have a HDMI Switch module which switches Input signals. It has a 4 pin push button to switch inputs. ( - )

I want to modify the button in order to control it with an Arduino. (push via Arduino command) What should i do in order to achieve this ?

I am newbie in Arduino so please excuse my mistakes.

Thanks


texts: Elegoo "Uno R3" not being recognized in any computer anymore

texts: I used to be able to use my Elegoo Uno R3, just fine. It worked with my computer no problem. Except I used the USB cable on a power bank and now the Uno isn't being recognized on any computer. I tried uninstalling and re-installing the IDE and drivers. But nothing works. I don't even get the serial 2.0 USB in the device manager. the Uno itself works. The orange and green lights stay on continuously when plugged in and It's still outputting the code I put in it before it stopped connecting to my computer. Any help to be able to fix my Uno. The button on the UNO doesn't seem to do anything either.


texts:
I have a kit of 37 sensors as described here:

http://www.instructables.com/id/Arduino-37-in-1-Sensors-Kit-Explained/?ALLSTEPS
https://tkkrlab.nl/wiki/Arduino_37_sensors

I want to create a simple circuit:

if the light is detected - flash LED
if there is no light - do nothing

Among 37 sensors I don't seem to find anything related to light / brightness / lumens...

Can you please advise me which sensor to get?

Shall I get a photocell  (Light Dependent Resistor) as described here: https://learn.adafruit.com/adafruit-arduino-lesson-9-sensing-light/parts ?


texts:
I was doing some research about this subject and I only have more questions than answers.

I want a little IMU sensor (I don't know which hardware I should get) that sends data wirelessly to my Arduino.

The sender part (IMU + sender + battery) should be small (tennis ball size is fine) and the receiving part should be an Arduino.

What should I buy? How can I achieve this? I was looking at a lot of ideas: Xbees, bluetooth, radio receivers, Arduino Nano, etc.

My focus is on the Arduino code, I just need that the IMU sends data at least at a ratio of 10ms.

As a plus I would love to have more than one Wireless IMU sensor connected to my Arduino.


texts:
Question given in the title. I'm trying to dynamically allocate the size of an array on runtime on an arduino pro micro. I've tried realloc, malloc and the c++ variant delete and new without success. This is my current test code:

int* test = 0;

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

void loop() {
  Serial.println("test");
  if(test != 0){ //c++ delete and new attempt
    delete [] test;
  }
  test = new int[2];
  //test = (int*) realloc(test, 2 * sizeof(int)); //realloc attempt
  //test = (int*) malloc(2*sizeof(int));          //malloc attempt
  test[0] = 1;
  test[1] = 2;
  int answer = test[0] + test[1];
  Serial.println(" " + answer);
  Serial.print(" " + test[0]);
  Serial.println(" " + test[1]);
  Serial.println("test");
  delay(100000000000);
}

All of my attempts result in either some garbage in the serial or in most cases:

test

test

Does anyone know what I'm doing wrong?


texts: about receiving float on Atmega32 from matlab

texts:
I want to receive a float on Atmega32 from matlab. I display the output on an lcd, but i receive 0.000, can any one help me? Please ...

matlab code

s=serial('COM1','BaudRate',9600);
fopen(s)
fwrite(s,170,'uint8');//header frame
fwrite(s,1.2,'float');//the data to be sent

ATmega32 code

union {
  signed long l;
  float f;
} data;

int main(void)
{
  DDRA=0xff;//for LCD
  DDRB=0xff;//for LCD
  data.l;
  char value[8];
  usart_init();
  Lcd8_Init();

  while(1)
  {
    if(uart_receive()==0xAA)
    {
      //header,0xAA=170
      Lcd8_Set_Cursor(0,0);
      Lcd8_Write_String("Float");
      _delay_ms(100);

      data.l=(long)uart_receive();
      data.l=(long)(data.l||(uart_receive()<<8));
      data.l=(long)(data.l||(uart_receive()<<16));
      data.l=(long)(data.l||(uart_receive()<<24));

      dtostrf(data.f,8,3,value);//convert float to string

      Lcd8_Clear();
      Lcd8_Set_Cursor(0,0);
      for(int i=0;i<8;i++) Lcd8_Write_Char(value[i]);
   }

}}


texts: Fade In/Fade Out with multiple LED strips

texts:
I want to make a strip led application(Fade In/Fade Out).Each strip has 48 pixels.One of the strips should be red and the other should be blue.Using the for loop, I managed to fade in-fade out a small number of strips (eg 10).But when I fade in / fade out all of the 48 leds, the code behaves as if there is a "delay".I guess that's because there's a lot of data in the for loop.Is there a way to do fade in / fade out without using a for loop?

#include "FastLED.h"
#define NUM_LEDS_PER_STRIP 48
CRGB redLeds[NUM_LEDS_PER_STRIP];
CRGB blueLeds[NUM_LEDS_PER_STRIP];
void setup() {
FastLED.addLeds<NEOPIXEL, 6>(redLeds, NUM_LEDS_PER_STRIP);
FastLED.addLeds<NEOPIXEL, 7>(blueLeds, NUM_LEDS_PER_STRIP);
FastLED.setBrightness(0);
}

void loop() {
//fade in
for(int i=0;i<256;i=i+5) {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(i);
redLeds[j] = CRGB(255,0,0);
blueLeds[j] = CRGB(0,0,255);
FastLED.show();
}}
//fade out
for(int i=255;i>=0;i=i-5) {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(i);
redLeds[j] = CRGB(255,0,0);
blueLeds[j] = CRGB(0,0,255);
FastLED.show();
}}
}


texts: Is there an Arduino simulator that runs on Mac OS X?

texts: I need to simulate my Arduino project with other circuit components before implementing the project. Is there a decent simulator that runs on Mac platform?


texts: Arduino-controlled current limiter for lathe

texts:
I'm building a lathe that will be powered by a 3-phase 750w AC motor (4 pole, max unloaded RPM of 1400 RPM). I want to be able to control the RPM using a potentiometer attached to an Arduino mega which I can figure out how to do.

Under load, I'm guessing the motor is going to want to draw more current across each of the phases, the cabling can take the extra current draw but I don't want to damage the motor.

Could I use AnalogueRead (using current transducers) to tell the Arduino to increase the resistance with a servo-potentiometer setup or cut the power momentarily (using transistors on each phase) if the current rose above a certain level? If so, is there any code that would be good to steal/adapt?

Thanks all!


texts: I need to measure voltage between 0-10 volts using my Arduino Due.  I have an ADS7805p chip, which I believe will work, but am not sure how to wire it on my breadboard.  I'm used to just using the chip on the arduino, but that only goes 0-5 volts and I can't loose the resolution by converting.  Can someone, please, point me to or instruct me on how to wire something like this to my arduino?


texts:
Where would I find information on how to configure the Arduino Zero's timers?

Because this...

  // Timer stuff
  // Set up the generic clock (GCLK4) used to clock timers
  REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                    GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                     GCLK_GENCTRL_GENEN |         // Enable GCLK4
                     GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                     GCLK_GENCTRL_ID(4);          // Select GCLK4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  // Feed GCLK4 to TC4 and TC5
  REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                     GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                     GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_TC4_COUNT16_CC0 = 150;                      // Set the TC4 CC0 register as the TOP value in match frequency mode
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

  //NVIC_DisableIRQ(TC4_IRQn);
  //NVIC_ClearPendingIRQ(TC4_IRQn);
  NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
  NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

  REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
  REG_TC4_INTENSET = TC_INTENSET_OVF;             // Enable TC4 interrupts
  // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

  REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV256 |   // Set prescaler to 1024, 48MHz/1024 = 46.875kHz
                   TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                   TC_CTRLA_ENABLE;               // Enable TC4
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

Is completely indecipherable and highly error prone.


texts: Using serial.available to return number of bytes

texts:
My code:

char data;
int numOfBytes;
void setup() {
    Serial.begin(9600);
}
void loop()
{
    if (Serial.available() > 0)
    {
        int numOfBytes = Serial.available();
        Serial.print("numOfBytes: ");
        Serial.println(numOfBytes);

        data=Serial.read();
        Serial.print("data: ");
        Serial.print(data);
        Serial.print("\n-----------\n");

        delay(500);
    }
}

I expected that this code returns 5 and then 4,3,2,1.
But it returned: 1,4,3,2,1

Why?


texts: 8266 get uint8_t PROGMEM array from uploaded file

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

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

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

Thanks in advance.


texts: Which NANO is replica and which is Original one? What is the difference

texts:
I'm newbie to Arduino and I recently bought two Nano, but they are different with each other.

(I just burned the usb diode so I made it straight with red cable)
The right one in fist picture has a little cyan color in it but the left one is dark blue.


texts:
I have a Razor IMU, which communicates through a USB to Serial Converter with a USB Host Shield mounted on an Arduino Mega 2560.

Even though serial communication can be achieved directly through the Arduino pins, I'm using a Host shield to keep the pins free for other devices. I found the Host Shield Library, which had specific examples for XBOX and PS3 controllers, Bluetooth devices, keyboards and mice etc., but I can't figure out a way to send/receive data to the IMU connected to the shield.

I'm kind of a noob, so be kind. :)

Thanks!


texts: Arduino Blink two LEDs without Delay(amount of repetitions)

texts:
Arduino community.  I have had experience with Arduino for 3 years now and have finally come to the conclusion to get rid of the delay function entirely.

Below is the code to blink two LEDs a complete 10 times.  The problem is that the setup() doesn't repeat like a loop(), which means it doesn't last a long enough to find a time difference between PreviousMillis and CurrentMillis because it runs once; thus, defeating the idea of blinking a LED in the setup().  But, I have researched ways to imitate the loop() with while loops; I have used Adafruit's method to spice things up(Constructors and classes!),
https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview.

But I need a little help because it doesn't work, instead, it blinks forever(Mission half-complete =)).

Notice how I have used while loops in the Update(), which is located within the Flasher Class, to mimic a loop() until the condition becomes true.

The problem is, I don't know why this code doesn't work and what to do from here.

The ultimate goal is to blink the LEDs at pin 12 and pin 13 a total of 10 Times, instead of repeatedly blinking for an eternity.  I am using an Arduino Uno R3 and a Serial baud rate of 115200.

Ignore what I did in the loop().  It's the same function as the setup() code, instead, the led blinks an eternity (unfortunately), when a value of "1" is typed.

    class Flasher{
    // Class Member Variables
    // These are initialized at startup
    int ledPin;      // the number of the LED pin
    long OnTime;     // milliseconds of on-time
    long OffTime;    // milliseconds of off-time

    // These maintain the current state
    int ledState;                 // ledState used to set the LED
    unsigned long previousMillis;   // will store last time LED was updated
    unsigned long currentMillis = 0;

  public: Flasher (int pin, long on, long off)
{            // Constructor - creates a Flasher
    // and initializes the member variables and state

      ledPin = pin;
      pinMode(ledPin, OUTPUT);

      OnTime = on;
      OffTime = off;

      ledState = LOW;
      previousMillis = 0;
    }

    void Update(int a){
      // check to see if it's time to change the state of the LED
      for (int i = 0; i < a; i++) {
        while ((currentMillis - previousMillis <= OnTime) || ((currentMillis - previousMillis <= OffTime))) {
          currentMillis = millis();

          if ((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
          {
            ledState = LOW;  // Turn it off
            previousMillis = currentMillis;  // Remember the time
            digitalWrite(ledPin, ledState);  // Update the actual LED
          }
          else if ((ledState == LOW) && (currentMillis - previousMillis >=OffTime))
          {
            ledState = HIGH;  // turn it on
            previousMillis = currentMillis;   // Remember the time
            digitalWrite(ledPin, ledState);   // Update the actual LED
          }
        }
      }
    }
};

Flasher led1(12, 100, 400);
Flasher led2(13, 350, 350);

void setup(){

  Serial.begin(115200);
  led1.Update(10);

}

void loop(){

   /* if (Serial.available()) {
      String str = Serial.readString();

      if (str.substring(0, 1).equals("1")) {
        led1.Update(10);

      }
  }*/
}


texts: Can you use an input pin instead of ground in Arduino circuitry?

texts: Beginner here: Would the circuit in the picture work or do input pins not absorb the energy as ground does? I know setting the pin as an input makes the direct 5V connection safe but maybe I'm mistaken. I'm trying to understand the nature of how these connections are made. Thank you in advance!


texts: I'm looking for a way to emulate addressable LED strip using LED diodes in a custom arrangement

texts:
What I want to achieve is, I want to use my own LED pin diodes, customly place them into my sculpture and animate them. This is as I understand quite straightforward. The problem is the amount of wiring . I would want them to connect one another in series with addresses, rather then each led needing a direct data from the controller on a separate cable.
I know that addressable LEDs use a single data line through the all lights, eliminating the need to connect each led physically to the controller to get data. Is there any way to build a similar system with a bus-like structure, I believe it is possible. And if so, how? What would I need? I guess I need individual small chips for each LED, but I don't know if that's the case or even if it is how so.
I consider myself quite a newbie in electronics-arduino or LEDs, however I'm actively looking into it and researching.


texts:
I am making a keypad and when I try to save the buttons that were pushed they reset back to zero.

int tmp = 1;
int digit = 1;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int code = 0;

void setup() {
  Serial.begin(9600);
  pinMode(7, INPUT);
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, INPUT);
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  if (digit > 4) {
    digit = 1;
  }
  for (int i = 2; i <= 7; i++) {
    int tmp = digitalRead(i);
    if (tmp == HIGH) {
      if (digit == 1) {
        int a = i - 1;
      }
      if (digit == 2) {
        int b = i - 1;
      }
      if (digit == 3) {
        int c = i - 1;
      }
      if (digit == 4) {
        int d = i - 1;
        Serial.print(a);
        Serial.print(b);
        Serial.print(c);
        Serial.print(d);
        digitalWrite(8, HIGH);
      }
      digitalWrite(9, HIGH);
      delay(100);
      digitalWrite(9, LOW);
      delay(100);
      Serial.print(i);
      digit++;
    }
  }
}


texts: Rewrite part of the example code from Adafruit FONA

texts:
Recently, I bought the FONA 800 shield from Adafruit. I have got it running with the examples and it plays very nicely.

I want to use the part of the example code which handles a call in my own sketch. The example code waits for a number to call which should be entered in the serial. I want to do the exact same thing, just with the phone number supplied from a variable in Arduino.

I have two possibilities: To supply the whole number when the call should be performed and to build up let's say an array every time a number is entered.

The code for performing a call:

// call a phone!
    char number[30];
    flushSerial();
    Serial.print(F("Call #"));
    readline(number, 30);
    Serial.println();
    Serial.print(F("Calling ")); Serial.println(number);
    if (!fona.callPhone(number)) {
      Serial.println(F("Failed"));
    } else {
      Serial.println(F("Sent!"));
    }

The flushSerial function:

void flushSerial() {
  while (Serial.available())
  Serial.read();
}

And the readline function:

uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) {
uint16_t buffidx = 0;
boolean timeoutvalid = true;
if (timeout == 0) timeoutvalid = false;

while (true) {
  if (buffidx > maxbuff) {
    //Serial.println(F("SPACE"));
    break;
  }

while (Serial.available()) {
  char c =  Serial.read();

  //Serial.print(c, HEX); Serial.print("#"); Serial.println(c);

  if (c == '\r') continue;
  if (c == 0xA) {
    if (buffidx == 0)   // the first 0x0A is ignored
      continue;

    timeout = 0;         // the second 0x0A is the end of the line
    timeoutvalid = true;
    break;
  }
  buff[buffidx] = c;
  buffidx++;
}

if (timeoutvalid && timeout == 0) {
  //Serial.println(F("TIMEOUT"));
  break;
}
  delay(1);
}
  buff[buffidx] = 0;  // null term
  return buffidx;
}

It is the readline function which should be edited. Right now it retrieves the number entered from serial.

I am kind of a newbie myself so I am not that familiar with data types and so on.

Thank you very much for any answers.

EDIT:
The function without readline:

if (!fona.callPhone("12345678")) {
        Serial.println(F("Failed calling"));
      } else {
        Serial.println(F("Calling ..."));
      }


texts: SSD1306 / U8glib display fonts and commands

texts: I cannot seem to find any reference for the SSD 1306 or U8glib display font library or any command reference, like all the options for display() etc. For my fonts I been going into the utility folder and scrolling through notepad for the U8glib library but its very croweded with numbers and code. is there any reference for both libraries online that is user friendly?


texts: How do I grab data from my Arduino device using a Python program?

texts:
We are currently creating a system which can log student attendance using RFIDs. Currently, we have the RFID Scanner set up (MFRC522 reader and Arduino UNO microcontroller). The database for the student's info and time-logging is also already set up. We are; however, having problems with accessing the data the Arduino is sending. We want the Arduino device to send us the Tag IDs via a USB Connection and have set it up to send the relevant data through the Serial Port. However, we cannot access this data using a Python program with this code.

import serial

x = 1
while(x == 1 ):
    ser = serial.Serial("COM3", baudrate = 9600, timeout = 0)
    if(ser.is_open):
       print("Serial Port in Use")
    else:
       print("Card ID: " + ser.read)

We are attempting to read from Port COM3 (the SP the Arduino uses). If the serial port is in use, the program outputs the "Serial Port in Use" (for testing purposes only, to be removed in final code) and if not, it will output the Card ID. However, through this, we run into the problem of being unable to use the same serial port with the Arduino (we are running on Windows). We tried using a serial port splitter but replacing the "COM3" with the name of the virtual port does not work.

We would prefer not to use Processing and would be open to simply avoiding the use of a serial port completely.


texts: I have master in electronics and IT. I know various microcontrollers programming in c. I want to volunteer myself to learn for arduino Projects especially for low Level Drivers etc. Can somebody suggest me Websites or way ?


texts:
Build my own 'Artnet to WS2812b Neopixel' boxes for lighting in a club. Working fine. I have 20 stripes with 50 pxls each. One ESP8266(NodeMCU) is feeding 6 stripes, so it gets 2 DMX universes via Artnet. Depending on the FPS(~20-40FPS) i'm sending, thats about 200-300kbp/s constant bitrate for each of the ESPs.
Every 4-8h one of my boxes freezes randomly. No pinging possible anymore. The other boxes continue working as usual. Only chance of resetting is to disconnect the power.
First, i thought the ESP gets to hot (installed at the clubs ceeling and the power supply is also in such a box) or the humidity is to high, but it must be a software problem (tested it in the oven, dont laugh ;)).
So why isn't the watchdog resetting? I am not able to provoke any of those freezes at home (only waiting)

The code is pretty straight forward:

test the leds
connect to wifi (if no wifi, go to 1)

Loop:

check UDP packets for Artnetdata
update the WS2812 with the fastled-lib

any ideas?

#define FASTLED_ESP8266_NODEMCU_PIN_ORDER
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

#include <FastLED.h>

// ARTNET CODES
#define ARTNET_DATA 0x50
#define ARTNET_POLL 0x20
#define ARTNET_POLL_REPLY 0x21
#define ARTNET_PORT 6454
#define ARTNET_HEADER 17

WiFiUDP udp;

#define NUM_LEDS 50

CRGB leds[NUM_LEDS];
CRGB leds2[NUM_LEDS];
CRGB leds3[NUM_LEDS];
CRGB leds4[NUM_LEDS];
CRGB leds5[NUM_LEDS];
CRGB leds6[NUM_LEDS];

unsigned long previousMillis = 0;
int offset=0;

uint8_t uniData[514];
uint8_t maxuni=0;
uint16_t uniSize;
uint8_t hData[ARTNET_HEADER + 1];

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

IPAddress local_ip(192, 168, 0, 111);
IPAddress gateway_ip(192, 168, 0, 1);
IPAddress subnet_ip(255, 255, 255, 0);

void setup() {
  WiFi.begin(ssid, password);
  WiFi.config(local_ip, gateway_ip, subnet_ip);

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

delay(2000); // sanity delay
FastLED.addLeds<WS2812, 1, GRB>(leds, NUM_LEDS);
FastLED.addLeds<WS2812, 2, GRB>(leds2, NUM_LEDS);
FastLED.addLeds<WS2812, 3, GRB>(leds3, NUM_LEDS);
FastLED.addLeds<WS2812, 4, GRB>(leds4, NUM_LEDS);
FastLED.addLeds<WS2812, 5, GRB>(leds5, NUM_LEDS);
FastLED.addLeds<WS2812, 6, GRB>(leds6, NUM_LEDS);
initTest();

  }

  udp.begin(ARTNET_PORT); // Open ArtNet port
}

void loop() {

  if (udp.parsePacket()) {
    udp.read(hData, ARTNET_HEADER+1);
    if ( hData[0] == 'A' && hData[1] == 'r') { //checking first two letters, if its Artnet data
      if ( hData[8] == 0x00 && hData[9] == ARTNET_DATA) {
      uniSize = (hData[16] << 8) + (hData[17]);
      udp.read(uniData, uniSize);

      if(hData[14]>maxuni){maxuni=hData[14];}

     switch(hData[14]+1-maxuni){

      case 0: //for each DMX universe updating the pixels
         for (int j=50; j--;){
            leds[j].setRGB(uniData[j*3+offset],uniData[j*3+1+offset],uniData[j*3+2+offset]);
          leds2[j].setRGB(uniData[j*3+150+offset],uniData[j*3+151+offset],uniData[j*3+152+offset]);
          leds3[j].setRGB(uniData[j*3+300+offset],uniData[j*3+301+offset],uniData[j*3+302+offset]);
         }
         break;

      case 1:
         for (int j=50; j--;){
           leds4[j].setRGB(uniData[j*3+offset],uniData[j*3+1+offset],uniData[j*3+2+offset]);
          leds5[j].setRGB(uniData[j*3+150+offset],uniData[j*3+151+offset],uniData[j*3+152+offset]);
          leds6[j].setRGB(uniData[j*3+300+offset],uniData[j*3+301+offset],uniData[j*3+302+offset]);
         }
         break;
     }
}
}
}

FastLED.show();
}

void initTest()
{
//only at Startup checking the LEDs, so nothing special here....}


texts: Simple reading and writing on Floppy Disk

texts:
I am trying to interface a 3.5" floppy drive (read and write data onto floppy disc). Since I need to write just few bit long number on it (16 is more than enough) I am thinking I could write it track-wise (each track is one bit), which gives me teoretically 80 bit long number, so I could write 4 times 16 bit long number for some redundancy.

I found this code, which solves reading data out. For writing I found this page which says, that writing should be similar easy process.

I attached code I am running here. Reading seems to work, but writing not. The interesting part of code is:

void writeData(byte data){
  Serial.println("Writing");
  digitalWrite(writeEnablePin, LOW); //starting spining a motor
  digitalWrite(motorEnableBPin, LOW); //enabling motorEnable
  stepAllTheWayOut(); //moving head to the edge of drive
  for(unsigned i = 0; i<10; i++){ //repeating 10 times
    for(unsigned index = 0; index<=8; index++){ //repeating 8 times (there are 80 tracks)
      digitalWrite(writeDataPin,bitRead(data,index)); //setting data pin
      Serial.print(bitRead(data,index)); //printing out what is being written
      delay(500); //spinning for a while to write all over the track
      digitalWrite(writeEnablePin, HIGH); //stepping not working when writeEnablePin is LOW
      stepIn();
      digitalWrite(writeEnablePin, LOW);
    }
    Serial.println("");
  }
  digitalWrite(motorEnableBPin, HIGH);
  digitalWrite(writeEnablePin, HIGH);
}

The output is:

Setup done.
Writing
010101010
010101010
010101010
010101010
010101010
010101010
010101010
010101010
010101010
010101010
Reading
111001000
101010001
110111001
001000101
001011001
111111101
110101101
111110011
111111001
101111110

The output is not what should be written. (the bits are changed every time i run the code)

Any idea what am I doing wrong when writing?


texts: Arduino LilyPad and nRF8001 module wiring

texts:
I am trying to wire up a nRF8001 BLE module with the LilyPad board, as the title says.

The problem is that if I wire them up I am not more able to see the nRF8001 module during the scan phase with the nRF UART 2.0 app ( https://play.google.com/store/apps/details?id=com.nordicsemi.nrfUARTv2&hl=it for Android). INstead, if I wire the nRF8001 up with the Arduino Uno rev3 I can correctly exchanging messages from the serial monior to the app and viceversa.

Since the LilyPad is quite equals the the Arduino in terms of processor and pinout, I am wondering what I am doing wrong.

The wirings is the following:

LilyPad   <--->   nRF8001
  +                 Vin
  -                 GND
pin #2              RDY
pin #9              RST
pin #10             REQ
pin #11             MOSI
pin #12             MISO
pin #13             SCK

Does anyone have any suggestion? Thanks in advance!

Filippo


texts: How to download files from a user/password protected web server (user:passw@ip:port)

texts:
I need to do a GET request in the form: user:passw@ip:port/streaming/channels/1/picture  to capture a still frame from an Ip camera.
Is there a way to do this with the ESP8266HTTPClient.h library?

The samples show a GET request as: http.begin(host,port,url);
What I need to do is get the user:passw@ put in before the host:url


texts:
I've done a Wifi radio with a headless Raspberry Pi in the past (connecting a radio MP3 stream available on internet directly on boot, without any user input), and now I'm wondering: would it be possible to do the same with an Arduino, battery-powered?

Please correct me if I'm wrong but it seems that all these features are available:

battery-powered: this is definitely possible with a few AAs
audio output (easily possible with a DAC I think?)
Wifi (possible with a shield, right?)
Internet access to http://198.51.100.0/myradio.mp3 stream
real-ime MP3 stream decoding (Is an Atmega enough for this?)

Does this mean that a Wifi radio based on Arduino is possible?


texts: automated parking system (sir sensor+ stepper motor)

texts:
my project about automated system I am using stepper motor to open and close the gate

I want my code be like when the gate opened it stays 5 seconds

then check the sensor, if there is a motion the gate should not close and stay open, when there is no motion the gate should close

if the gate is closing and there is a motion, motion should interrupt closing the gate and reopening the gate

I am using Arduino uno

the code is :

#include <RH_ASK.h>//include radioHead ASK library
#include <SPI.h> // include dependant SPI libray
#include <Stepper.h> // Include the Arduino Stepper.h library:
// Define number of steps per rotation:

RH_ASK rf_driver; // create ASK object
int ledon = 13;
int ledoff = 5;
int sensor = 3;

const int stepsPerRevolution = 2048;// Define number of steps per rotation:

// Wiring:
// Pin 8 to IN1 on the ULN2003 driver
// Pin 9 to IN2 on the ULN2003 driver
// Pin 10 to IN3 on the ULN2003 driver
// Pin 11 to IN4 on the ULN2003 driver
// Create stepper object called 'myStepper', note the pin order:
Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {

  rf_driver.init(); //initialize ASK object

  // Begin Serial communication at a baud rate of 9600:
  Serial.begin(9600);

  // Set the speed to 5 rpm:
  myStepper.setSpeed(5);
  pinMode(ledon, OUTPUT);
  pinMode(ledoff, OUTPUT);

}

void loop() {

  //set buffer to size of expected message
  //uint8_t buf[8];
  // uint8_t buflen =sizeof(buf);

  //check if recevied packet is correct size
  //  if (rf_driver.recv(buf,&buflen))
  //{
  // int i;
  // message received with valid checksum
  // Serial.print("id: ");
  // Serial.println((char*)buf);
  // String userid =(char*)buf;
  // Serial.println(userid);

  // }

  //delay(5000);

  // uint8_t buf2[8];
  // uint8_t buflen2 = sizeof(buf2);

  // if (rf_driver.recv(buf,&buflen))

  // {

  //  int i;
  // message received with valid checksum
  // Serial.print("password: ");
  // Serial.println((char*)buf);
  // String password = (char*)buf;
  //  Serial.println(password);

  // }
  // delay(5000);

  String pass = "1234";
  String id = "A00036757";

  if (pass == "1234" ) {
    Serial.print("car exists");
    digitalWrite(ledon, HIGH);
    delay(300);
    myStepper.step(stepsPerRevolution / 3); //clockwise -OPEN GATE
    delay(10000);

    //if(digitalRead(sensor) == HIGH){
    delay(500);
  }

  if (digitalRead(sensor) == LOW) {

    digitalWrite(ledon, LOW);
    delay(300);

    digitalWrite(ledoff, HIGH);
    delay(300);
    myStepper.step(-stepsPerRevolution / 3); // CLOSE AFTER 5s COUNTERCLOCKWISE -  close gate
    digitalWrite(ledoff, LOW);
  }
  else {
    Serial.print("NO CAR");
  }


texts: Minimal ATmega328p Ethernet Configuration

texts: What would be minimal schematic for ATMega328P in order to have communication over ethernet? So I'm not asking about attaching existing shields to existing Arduino board, but just for bare minimum of ATMega328P and ethernet on one board, so basically like minimal version of Arduino Yun.


texts:
I want to control a kettle. It has 4 buttons and a digital disply of the temp. I would like the buttons and disply to remain functional. I just want to make the buttons remoteky pressabke. The buttons are at 5v. There is an almost bread‐board like set of little sockets where they connect to the higher voltage part of the kettle. (Where I see the kettle's built in relay, that powers the buttons and displsy.)k

If I have a 2nd set of wires to my arduino feed into these sockets would there be an issue with the signal from arduino going to the buttons?

Also, I think I might need a relay if I later adapt this for spark/particle core because it is 3.3v is there such a relay?


texts:
I'm using TMRpcm library for playing .wav files from my SD card. Everything works fine, but if I include Wire.h library the files aren't playing at all (there's no sound). I have only added this line of code above my program:

#include <Wire.h>
//code after

I suppose that this is because of the timer and interruption because TMRpcm documentation mentions that:

  May interfere with other libraries that rely on interrupts. The isPlaying() disable() or noInterrupts()
   functions can be used to prevent parallel code execution.

I've tried to use those functions but maybe I do something wrong. Can somebody help me? How can I use those libraries at once?

UPDATE:
Here's my before code:

tmrpcm.play("neMode.wav");
delay(2000);

and after:

noInterrupts();
tmrpcm.play("neMode.wav");
delay(2000);
interrupts();

It doesn't change anything. I hear no sound at all.


texts: How to combine two different sensor sketches to one complete sketch?

texts:
How to combine two different sensor sketches to one complete sketch for a complete circuit that attaches to one Arduino Uno?

Sharp Dust Sensor

int measurePin = A0; // Connect dust sensor to Arduino A0 pin
int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2

int samplingTime = 280;
int deltaTime = 40;
int sleepTime = 9680;

float voMeasured = 0;
float calcVoltage = 0;
float dustDensity = 0;

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

void loop(){
  digitalWrite(ledPower,LOW); // power on the LED
  delayMicroseconds(samplingTime);

  voMeasured = analogRead(measurePin); // read the dust value

  delayMicroseconds(deltaTime);
  digitalWrite(ledPower,HIGH); // turn the LED off
  delayMicroseconds(sleepTime);

  // 0 - 5V mapped to 0 - 1023 integer values
  // recover voltage
  calcVoltage = voMeasured * (5.0 / 1024.0);
  dustDensity = 0.17 * calcVoltage - 0.1;

  Serial.print("Raw Signal Value (0-1023): ");
  Serial.print(voMeasured);

  Serial.print(" - Voltage: ");
  Serial.print(calcVoltage);

  Serial.print(" - Dust Density: ");
  Serial.println(dustDensity); // unit: mg/m3

  delay(1000);
}

MQ-135 Sensor

int airquality = A2;
void setup()
{
  Serial.begin(9600);

}
void loop()
{

  int sensorValue = analogRead(A2);
  Serial.print("Air Quality = ");
  Serial.print(sensorValue);

  Serial.print("*PPM");
  Serial.println();
  delay(1000);

}


texts: Pulldown resistors and multiple switches

texts:
Maybe this is a question for Electronics SE but I’m not a member there yet so hopefully someone will have an answer here.

I did an experiment with having some push-to-make buttons connected to my Uno. I copied the circuit from the aduino.cc website and all worked exactly as expected. Here is my schematic of the circuit as I have it now:

The pins are both held LOW by the Pulldown resistor until the switch is closed, when they go HIGH.
All well and good. But I’ve just been looking at the circuit and something puzzles me. I can see a direct connection from Switch 1 to Pin 2 VIA the resistors and the Ground connection – and vice versa, S2 to P1. See my pathway in Red here:

Now, to be clear, this is NOT happening – but I just want to understand why not. Is it just that the 2 resistors in combination provide enough resistance to stop the opposite pin from going HIGH? In which case, this Pulldown resistor is actually serving 2 completely different functions in the circuit…?


texts: Arduino in Eclipse IDE: How to add SPI library (core library already added)?

texts:
I want to use eclipse for arduino programming, so I followed the guides to set up a static project for the arduino core library. Then I added the library file (.a) and the .h and .cpp files to my new project in the settings.
So far, so good.
But now I am trying to add the SPI library to my project without success (I only have the .h and .cpp files, no .a)!

My sample code

#include <Arduino.h>
#include <SPI.h>

int main(void) {
    init();
    pinMode(13, OUTPUT);
    for (;;) {
        digitalWrite(13,1);
        SPI.setBitOrder(0);
    }
}

The pinMode and digitalWrite parts work, but with the SPI method I get an error:

05:33:26 **** Build of configuration Debug for project ArduinoTestProject ****
make all
Building file: ../main.cpp
Invoking: AVR C++ Compiler
avr-g++ -I/home/fabio/Workspace/arduinoLIB/SPI -I/home/fabio/Workspace/arduinoCORE -Wall -g2 -gstabs -Os -ffunction-sections -fdata-sections -fno-exceptions -mmcu=atmega328p -DF_CPU=16000000UL -MMD -MP -MF"main.d" -MT"main.d" -c -o "main.o" "../main.cpp"
Finished building: ../main.cpp

Building target: ArduinoTestProject.elf
Invoking: AVR C++ Linker
avr-gcc -s -Os -o"ArduinoTestProject.elf"  ./main.o   -l"arduinoUNO" -l"m" -lm -Wl,-Map,ArduinoTestProject.map,--cref -mrelax -Wl,--gc-sections -L/home/fabio/Workspace/arduinoCORE/lib -mmcu=atmega328p; avr-nm -C -n "ArduinoTestProject.elf" >ArduinoTestProject.symbol
./main.o: In function `main':
../main.cpp:38: undefined reference to `SPIClass::setBitOrder(unsigned char)'
collect2: error: ld returned 1 exit status
avr-nm: 'ArduinoTestProject.elf': No such file
make: *** [ArduinoTestProject.elf] Error 1

05:33:26 Build Finished (took 72ms)

Does anyone see the problem?


texts: Is the johnny-five library and javascipt good for Arduino projects?

texts:
I am new to Arduino. I just have my Arduino UNO kit and started to do some small projects with node.js and the Johnny-five library.

My question is why there not many content about javascript+Arduino in web, and the last news on Johnny-five website dated last year.

  Is js development still relevant for Arduino?


texts:
I am trying to make an ultrasonic distance meter using Arduino. For this I added the ultrasonic library. But on compiling it shows this error "ultrasonic.h
not available". Please tell me how to add this .h file.


texts:
I'm newbie with Arduino and need to do a short task: read data from SPI (sent by another microcontroller) and send to WiFi (by ESP32-WROOM-32).

I can't understand how to initialize and read data from SPI. I'm using VSPI. I need to use VSPI class? Or a SPI class?

Any idea will help me a lot.

Thanks


texts: Is there a way to make a function take an exact number of clock cycles?

texts: Is it possible to use something like a compiler directive to pad a function with do nothing instructions so that as you add lines of code or take them away it always executes in the same amount of time?  I know there is the blink without delay style of writing a loop, but I want something a little more exact.


texts: I'm new to Arduino and my first project is an RFID reader. since I need a lot of known tags list , i have a problem with not enough memory. for that reason I want to convert strings like :  "426d9244", "1265dd39"... to a long int. I know it's been asked but as a new programer I find it hard to understand. an example would be very appreciated also.


texts:
I noticed that OneButton library does not work with pins A6 and A7 (with A1 and A2 it works good) on my Arduino Nano. Is it because A6 and A7 are Analog only? There is possibility to make them work properly?

sketch example is here https://github.com/mathertel/OneButton/blob/master/examples/TwoButtons/TwoButtons.ino


texts: Serial communication between python and arduino

texts:
I am working on object tracking robot. I am using python and OpenCV to detect the object and send the proper data to the arduino that controls two servo motors.
The data which should be sent to the arduino are servo motors angles ranging between 0-180. I am using sample codes to understand how python and arduino communicate using serial bus.When I send a single digit, the arduino receives it and work as intended, but when I send more than one digit nothing happens.
This is the arduino code:

#include <Servo.h>
int data;
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0;    // variable to store the servo position

void setup() {
  Serial.begin(9600); //initialize serial COM at 9600 baudrate
  pinMode(LED_BUILTIN, OUTPUT); //make the LED pin (13) as output
  digitalWrite (LED_BUILTIN, LOW);
  myservo.attach(9);
  Serial.println("Hi!, I am Arduino");
}

void loop() {
while (Serial.available()){
 //to receive more than one character
 char buffer[] = {' ',' ',' ',' ',' ',' ',' '}; // Receive up to 7 bytes
 while (!Serial.available()); // Wait for characters
 Serial.readBytesUntil('n', buffer, 7);
 data = atoi(buffer);

}
myservo.write(data);
}

And here is the python code:

import serial
import time  # Required to use delay functions

arduinoSerialData = serial.Serial('com14', 9600)  # Create Serial port
object called arduinoSerialData
time.sleep(2)  # wait for 2 secounds for the communication to get
established

print arduinoSerialData.readline()  # read the serial data and print it as
line
print ("Enter 1 to turn ON LED and 0 to turn OFF LED")

while 1:  # Do this forever

    var = raw_input()  # get input from user
    print "you entered", var  # print the intput for confirmation

    arduinoSerialData.write(var)


texts: Can a KCPI-3101 be replaced with an Arduino?

texts:
I'm planning to use a KPCI-3101 Keithley with a computer to creat a DAS with a sensor to show the data on computer

can i replace the Card and computer with an Arduino?


texts: Else Statement Never Functions As Expected

texts:
I've been working on a rather simple Arduino-breadboard project, that is supposed to imitate a traffic light intersection. There are two sets of lights, one called the North-South lights, and then the East-West lights (quite similar to the traffic lights your would see at an intersection on the road). The goal is to get the traffic lights to turn their correct colors at the correct times; however, one of my yellow lights is not turning on at all, and the breadboard LEDs I'm using completely skip over the yellow light in question and go straight to the red-green configuratin that is supposed to happen after.
Here is the code I have:
void setup() {

  pinMode(2, OUTPUT); //R-ns
  pinMode(3, OUTPUT); //Y-ns
  pinMode(4, OUTPUT); //G-ns
  pinMode(5, OUTPUT); //R-ew
  pinMode(6, OUTPUT); //Y-ew
  pinMode(7, OUTPUT); //G-ew

}

void loop() {

  for(int count = 0; count<16; count++) {

    if (count<7) {
      digitalWrite(2, HIGH);
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      digitalWrite(7, HIGH);
      }

     else if (count==7) {
      digitalWrite(2, HIGH);
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      digitalWrite(7, LOW);
      }

     else if (7<count<15) {
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      digitalWrite(7, LOW);
      }

     else {
      digitalWrite(2, LOW);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      digitalWrite(7, LOW);
      }

    delay(1000);
    }

}

As you can see, the North-South traffic light is supposed to turn on at the 16th second, except I don't see it happen on the physical LED. I don't understand why this is happening; can anyone explain what is happening?


texts: Blinking cursor on Arduino is inconsistent and misses inputs

texts:
I am trying to write a part of a program that prints time and allows the user to move a cursor across it. I have the following code, but there are a few issues with it.

#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
#include <Time.h>
#include <TimeLib.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16,2);
  setTime(12,30,15,0,0,0);
}
int col = 0;

void loop() {
  uint8_t buttons = lcd.readButtons(); //create readable buttons
  char time_out[16];
  lcd.setCursor(0,0);
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());
  lcd.print(time_out);
  lcd.setCursor(col,0);
  lcd.blink();
  delay(100);
  if (buttons) {
    lcd.clear();
    if (buttons & BUTTON_RIGHT) {
      col += 1;
    }
    if (buttons & BUTTON_LEFT) {
      col -= 1;
    }
  } //buttons
}

If you upload this to your board, you can tell that the blinking is highly irregular, not at all aesthetically pleasing.

You'll also notice that sometimes, when pressing left/right, the input isn't registered.

I suspect this has to do something with the delay() function used, which pauses the entire program.

I looked into the following method, but this does not work when needing to print something in a loop (as the time library requires).

Any idea how I could make this work better (regular blinking times and no miss of user input)?

Thanks a lot!


texts: How to power board plus module with one battery pack

texts: I'm someone who's very new to robotics and the physical side of computers (software guy) so apologies if this is a stupid question. I'm purchasing an Arduino Nano 33 IoT that I'll be using in conjunction with an Adafruit FONA 3G Cellular Breakout (https://www.adafruit.com/product/2687). I'd like to be able to power the entire unit off of one battery pack but my problem is that both the Arduino and the Adafruit 3G unit have separate power inputs. Adafruit's website says that a Lipoly battery is required to run the unit. Is there any way to "pass through" or "split" power between the two units? This way I was thinking I could run everything off of one external battery pack. Optimally I don't have to use a Lipoly battery and I could use a large external battery pack connected to jumpers or a barrel jack.


texts:
I have a transistor tester with 16x2 LCD running a plug-in at328 with an 8Mhz xtal. I would like to use this hardware for another purpose.

My first idea was to replace the crystal with a 16Mhz one, write a program on my Uno and swap the AT328.

Is this the only way? I also have an USB adapter. Reading/saving the code now on it is of secondary interest.


texts:
I have a problem. I don’t know how to combine this two codes & the diagram. My project is about automatic water storage door that using water sensor & rain sensor. The rain sensor will function when rain while the water sensor will control the open/close door. The door will open when it rain but it will remain close when the volume in the water storage is full.the volume of water in tank was controlled by flood sensor(water sensor). Here is the code for two sensor.
rain sensor
const int senmin = 0;
const int senmax = 1024;
int led = 13;
int sensory = A0;
int i;
void setup() {
Serial.begin (9600);
pinMode(led, OUTPUT);
}
void loop() {
int sensor = analogRead(sensory);
int range = map(sensor, senmin, senmax, 0, 3);
switch (range)
{
case 0:
Serial.println("raining");
digitalWrite(led, HIGH);
  break;

case 1:
  Serial.println("not raining");
  digitalWrite(led,LOW);

}
delay(500);
}
water sensor
const int waterSens = A0; //define water sensor
const int led = 9;//define led to pin 9
int waterVal; //define the water sensor value
void setup() {
pinMode(led, OUTPUT); //set led as an output
pinMode(waterSens, INPUT);//set water sensor as an input
Serial.begin(9600);  //start the serial port at 9600 bauds
}
void loop() {
waterVal = analogRead(waterSens); //read the water sensor
Serial.println(waterVal); //print the value of the water sensor to the serial monitor
if (waterVal <= 0){
digitalWrite(led, HIGH);//if the water sensor senses water turn the led on
}
else{
digitalWrite(led, LOW);//if it doesn't sense anything turn the led off
}
}


texts:
I recently created a state machine for my latest Arduino project. It is a simple LED control, but it has many different modes and functions. I created a template for my state machine so I can use it in the future, but I am looking to take it to the next level. Here is a copy of the current template for reference:

/*Setup Variables here*/
int nextState;
int currState;

/*Fill enum with all case names*/
enum cases{

  init;
  idle;
  case1;
  case2;
  leave;

};

/*Begin Program*/
void setup(){
  Serial.begin(9600);
  currState = init;
}

void loop(){
  switch(currState){

    case init:
      /*Prepare program here*/
      nextState = idle;
      break;

    case idle:
      if (input1){
        nextState = case1;
      }else if (input2){
        nextState = case2;
      }else{
        nextState = idle;
      }

    case case1:
      //Code for case1 here
      break;

    case case2:
      //Code for case2 here
      break;

  }

  currState = nextState;
}

I am trying to make a Queued State Machine (QSM). This means that instead of a single variable nextState, I can add several states to be executed. Is the best way to do this an array? I have not found much in my research about how to add and remove elements easily, so if this is the best way, could you point me towards a good tutorial on these types of array functions?

Thanks in advanced for all the help!


texts: What difference between readString and while loop read

texts:
From Arduino code, I have a question for SoftwareSerial Class

First: when I use more example for Esp8266 those functions use while loop to read response string from Esp when we send AT_Command to ESP.

getResponse(const uint32_t  wait) {
    String tmpData = "";
    long int time = millis();
    while ((time + wait) > millis()) {
        while (esp8266->available() > 0) {
            char c = esp8266->read();
            if (c == '\0') continue;
            tmpData += c;
        }
    }
    tmpData.trim();
    return tmpData;
}

I know that SoftwareSerial Class have a public method is readString() then I'm tried to use that and it return same result returned by while loop read:

getResponse(const uint32_t  wait) {
    String tmpData = "";
    tmpData = esp8266->readString();
    return tmpData;
}

Thanks for any. I'm working on improving my Eng.
Regards


texts: Digispark Attiny85 draws more power for digital input than expected

texts:
I'm trying to figure out why my attiny85 (on a digistump developer board) draws around 3mA at 3V when setting up a pin as INPUT and connecting it straight to ground. The current is measured with a multimeter between said pin and ground (thus only the current sunk by that pin is measured). I would assume that without a pullup resistor it would consume a lot less but it seems, regardless if I configure the button as INPUT or INPUT_PULLUP the current is the same.

Sketch:

void setup() {
  pinMode(3, INPUT);
  //According to datasheet pin needs to be low to disable internal pullup
  digitalWrite(3, LOW);
}

void loop() {
  digitalRead(3);
  delay(100);
}

I would like to design a circuit that can detect a normally closed switch being opened, but the idle power consumption is way to high at the moment. I was planing on using a very high external pullup but it seems I can't disable the internal one...


texts: Getting Accurate Velocity Readings From IMU

texts:
Hi I am currently using a BNO055 for a design project. This sensor outputs a linear acceleration vector corresponding to three (xyz) directions. I am trying to "integrate" the acceleration to get a speed the object it is mounted to is traveling.
I noticed early on that in my speed graph there is large amounts of drift.
I was looking for any guidance someone might have for tuning out the drift some way or filtering options I could use for acceleration data to reduce the drift


texts:
I tried to run this code on my Arduino Uno clone (which has no function so far and is a shortend version of my programm):

String rules [16][5] ={
   {"B0 B5", "", "", "cs S0", "", },
   [...]
};

void setup() {
  Serial.begin(9600);
  String foo = "bar";
  Serial.println(foo);
}

void loop() {
}

I left the rules array out, but it is quite big. It isn't used yet, but it contains rules how to react on certain situations (which should be used later).

As the Arduino IDE gives the following after complilig:

Sketch uses 4316 bytes (13%) of program storage space. Maximum is 32256 bytes.
Global variables use 1174 bytes (57%) of dynamic memory, leaving 874 bytes for local variables. Maximum is 2048 bytes.

When I run this sketch there is nothing on the serial monitor. If it works, there should appear bar, but it does not. The Arduino sends only a linebreak over the serial, but no text.

When I remove some characters from that array so that there are about 900 bytes the script works and prints bar to the serial monitor.

So, aren't 874 bytes not enough to store a three-character string? Why does it need 900 bytes to store such a short string?


texts: Is there any problem in running Arduino logic to 12V LEDs?

texts:
I want to run a strip of 300 12V LEDs (Adafruit Neopixels with WS2811), with my Arduino. Is it safe to connect a follows, or is there some "separation" between voltage levels needed?

5V voltage/out and ground (from converter 1) to Arduino Voltage-in and ground.
12V voltage-out (from converter 2) to LED strip voltage-in.
12V ground (from converter 2) to Arduino ground and LED strip ground.
Arduino data pin to LED strip data pin.


texts:
I'm making a project and I'm using multiple 1 digit 7 segment displays. I haven't plugged them all on my arduino because currently I'm just testing. The problem is on the I/O ports. Obviously I need to use shift registers and since it's my first time ever using them I need to know more about them. After googling, I found that the specific model I bought outputs 8 pins and you can stack up to 8 in series. So lets do the math. 8 shift register x 8 pins each SR = 64 new pins It seems cool but assuming I'm using 28 displays let's do the math again.
28 displays, each display has 8 pins (8 for segments and 2 as common cathode)
28 x 8 = 224 required pins.
Is is possible to expand the I/O pins by 224 pins? How many shift registers can I stack together? Also which is better, the single digit display or the 4 digit display?


texts: Choosing wireless tech for lowest possible lag

texts:
I am drafting a pub quiz project, where the Referee gives a signal and multiple players push their buttons. The first to push wins the right to give an answer.

I want all buttons (referee's + X players) to be wireless. Since the best quiz players can click a button within 10ms of the signal, it is very important that there is a very, very little variance in ping between different buttons. I cannot have players shouting "my button is laggy!" On the other hand, I don't want to use more expensive/complex tech than needed.

SO, what would be the optimal wireless tech to use? Please share your experience from similar projects (or just theoretical knowledge :) Here's what I researched so far (correct me if I'm wrong):

Bluetooth 4 LE (as in RFduino)
Pros: 3-6ms latency (advertised), low energy
Cons: cost, not more than 7 buttons to the device
Wi-fi
Pros: 2ms latency (I justed pinged my wi-fi router), dozens of buttons if need be
Cons: cost, power-hungry
RF data tranceiver
Pros: dunno, cost seems to be a bit smaller
Cons: multiple buttons at the same frequency will probably create a lot of noise
Simplest "Radio remote"
Pros: zero lag since it's all electromechanical, no data
Cons: multiple buttons at the same frequency won't work

So, did I miss anything? I appreciate any guidance.


texts: Problems running Arduino project off a 9V battery

texts:
I have been working on an Arduin Uno Rev2 project for a while now. I have been developing using my MacBook, downloading code through the USB jack running it, monitoring the serial output on my MacBook, etc.

The Arduino is being powered from my MacBook through the USB jack which is also carrying the serial output back to the MacBook.

But now I want to make this project portable. IE: instead of powering it off a wire from my Macbook, I want to power it off a battery. So I followed these instructions #4 and connected up a 9V battery to the VIN pin.

At first it seemed to work. But very soon started noticing great instability. There are many serious problems I need to solve working off this battery:

As soon as I connect up the battery, I loose the Serial Monitor connection (even though the USB cable is still connected). So I can no longer see what's going on inside the Arduino for debugging purposes. Why? How can I continue to see the Serial Monitor? Is there a way to see the serial output from somewhere other than the USB jack?
I can tell by the lights on the board and by the behavior of the outputs that the software is malfunctioning. But I can't tell exactly why (because of #1). Why would changing the power source cause this?
I know that the VIN pin needs 7-12 volts. The battery I plugged in is a new 9V battery. But what happens as it wears down? Does it still push 9 volts? Or does the voltage drop? Can I tell my Arduino to stop functioning if the voltage drops below acceptable levels? Because ceasing altogether is better than malfunctioning.
I have read that I need to ensure that the current from the battery remains around 500mA. But how can I measure that in hardware/software? This ties back into question #3.


texts:
I have used the pubsubclient library for Arduino for communicating with an MQTT broker in the past, however the library works only with Ethernet connecction. I need to use GSM in my application and am using the SIM900 at the moment. However, I cannot seem to find any library for MQTT communication using an Arduino as MQTT client and SIM900 as gateway. I found this to be surprising as there must surely be many instances where one would want to upload data from Arduino to a MQTT broker in a mobile scenario where cellular network is the only option (in place of Ethernet). So my questions are:

Is it possible to use the Arduino as MQTT client and SIM900 as gateway for communicating with an MQTT broker? Are there any libraries for the same?
What is the current standard way (gateway / communication protocol) of uploading some sensor data from Arduino to an internet server in a mobile scenario (i.e., where Ethernet is not an option)?


texts: First time set up- permission denied to usb port- ubuntu 14.04

texts:
I just plugged my arduino in and the light is on, but the blink test failed to upload. here is my error:

Arduino: 1.6.7 (Linux), Board: "Arduino/Genuino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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


texts: How to use ATtiny pins that are usually 'reserved' for chip programming?

texts:
How to program an ATtiny45 to use the pins 1, 5, 6, 7 (i.e. PB5, PB0, PB1, PB2) as input or output?

pinMode(5, OUTPUT);
pinMode(0, OUTPUT);
pinMode(1, INPUT);
pinMode(2, INPUT);
digitalWrite(5, HIGH);
...

These pins are usually used to program the ATtiny itself, so how to avoid a conflict?

Of course, I could just avoid these 4 pins, but then as there are also pins for VCC and GND, there would be only 2 pins left: PB3, PB4!

Question: how to use the pins as input/output that are usually used for ATtiny programming?

Linked question:

Should I connect pins 1, 5, 6, 7 of the ATtiny to the programmer
Or should I connect pins 1, 5, 6, 7, as well as 8 and 4 (VCC and GND) of the ATtiny to the programmer?

If the second bullet is correct, when connecting VCC and GND, won't it make the ATtiny run the previously uploaded code?


texts: No change in acs 712 readings after connection to load

texts:
I would like to measure the amount of power used by a 3w bulb. I am using a 9v battery to power the bulb and an acs712 current sensor to get current usage. However, i get no change in values after i connect the load and it light up.
Is my current sensor faulty or? I'm confused.


texts: Can't upload code to Arduino board on Mac

texts:
I'm using a MacBook Pro with 10.13.6, an Official Arduino Uno Board and Arduino 1.8.13 IDE.
I'm having troubles uploading code to the Arduino Board.
I have 5 ports available:

dev/cu.-AvnetaSPPPort
dev/cu.Bluetooth-Incoming-Port
dev/cu.SRS-BTX300-DataInteract
dev/cu.RS-XB41-BluetoothSeria-1
dev/cu.UEMEGABOOM-LWACP-2

I'm not sure if any oh these ports is the correct one but I've already tried all of them and I keep getting errors like: "avrdude: ser_open(): can't open device "/dev/cu.-AvneraSPPPort": Resource busy"
Some weeks ago I was trying Arduino on the same computer and all went good but right now I can't get it to work, however I don't remember wich port was selected.
In the IDE the board I have selected is "Arduino Uno" and as Programmer option I have "AVRISP mkll".
Does anyone know how to solve this?


texts:
I currently have an Uno (which operates at 5v), and I'm looking at buying a Due (which only operates at 3.3v). I'd like to make them communicate via Serial or SPI or similar, but presumably connecting them directly isn't an option (I guess the Due's pins would get damaged).

Is there any way to make the connection safe? Or is there an alternative form of communication I could safely use between them instead?


texts:
I'm building a simple outdoor temp and humidity sensor with an esp32 I've aquired but I need a platform that I can submit the Json to so that then my laptop can make an http request to get the Json string from the platform and parse it.

Anybody know a free platform like this


texts: Can I monitor data of variables while simulating Arduino on Proteus?

texts:
I simulate Arduino UNO on proteus 8 Pro. I use Arduino software for writing a program.

Is it possible to trace or know the data that are stored in valuables while running the code on Proteus?

I would like to know how the code is running step by step so that I can find logical errors.

Thank you,


texts: Help with code. Fade in LEDs from off (shift register)

texts:
I used this tutorial here and decided it to overcomplicate the pattern. For further learning. My code in theory should start the LEDs at a low brightness and fade them in using this code. My expected output is as follows.

All 8 LEDs start out as off.
Fade in slowly.
LEDs turn of one by one from left to right.
LEDs turn on one by one right to left.
Fade out.
Repeat.

This is the loop that fades the LEDs in.
for (byte b = 1; b < 255; b++) {
  setBrightnessUp(b); //sets the brightness up function
  delay(20);
}

This is the function:
void setBrightnessUp(byte brightness) {// 0 to 255
  analogWrite(outputEnablePin, brightness);
}

However at this time it appears to be getting into my loop but not increasing the brightness at all. When the code first runs, the LEDs are on but at a minimum brightness. The rest of the code including the fade out at the end works fine.
Fade out functions:
for (byte b = 255; b > 0; b--) {
  setBrightness(b); //sets the brightness function
  delay(20);
}

void setBrightness(byte brightness) { // 0 to 255
  analogWrite(outputEnablePin, 255 - brightness);
}

Here is the complete code. Excuse the over commenting it helps me learn:
//sets pin out for control pins on shift register

int latchPin = 5;
int clockPin = 6;
int dataPin = 4;
int outputEnablePin = 3; //enables a PWM pin output

//uses byte (8bit binary variable)
byte leds = 0;

void setup() {
  // sets the pins to output mode
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode (outputEnablePin, OUTPUT);
}

void loop() {
  //attempted to make led fade in from 0
  leds = 0; // set led to no output ready for dimming effect
  updateShiftRegister(); //calls the function used for output
  delay(1000); //troubleshooting delay
  for (byte b = 1; b < 255; b++) {
    setBrightnessUp(b); //calls the brightnessup function
    delay(20);
  }
  leds = 255; //Sets the byte variable to 255 or 11111111
  updateShiftRegister(); //calls the function used for output
  delay(500); //waits 1/2 second

  //sets a variable i at 8 and runs while i is more than 1
  //minus 1 each loop
  for (int i = 8; i > -1 ; i--) {
    //Bitclear acts on a byte like its an array
    //it sets the bit at position i to 0 (or off)
    // the left most bit is 7 the right most 0
    bitClear(leds, i);
    updateShiftRegister(); //calls the display function
    delay(250); // waits
  }
  //sets a veriable i at 0 and runs while is less than 8
  //plus 1 each loop
  for (int i = 0; i < 8 ; i++) {
    //same as bitclear but turns on the bit at position i
    bitSet(leds, i);
    updateShiftRegister(); //calls the display function
    delay(250); //waits
  }
  //After the 2 other for loops are finished this will then fade
  //the LEDs out
  //sets the bite to 255 (11111111), while its more that 0
  //and minus 1 each loop
  for (byte b = 255; b > 0; b--) {
    setBrightness(b); //calls the brightness function
    delay(20);
  }
}

// this function outputs the data to the shifter
void updateShiftRegister() {
  digitalWrite(latchPin, LOW);//sets the latch pin to low(off)
  shiftOut(dataPin, clockPin, LSBFIRST, leds);
  // the first 2 functions set the data and clock pins needed
  //to receive data. The LSBFIRST tells it to start at the right
  //most bit (MSBFIRST is oposite). LEDs is our binary array (byte)
  // EG 0000000 would print no lights. It shifts this into the
  //shiftregister at 1 bit at a time from one end or the other
  //(determined by LSBFIRST or MSBFIRST)
  digitalWrite(latchPin, HIGH);  // sets the latch pin to high
  //the low to high state change triggers the output
}

//brightness down slowly
void setBrightness(byte brightness) { // 0 to 255
  analogWrite(outputEnablePin, 255 - brightness);
}

//supposed to fade the brightness up
void setBrightnessUp(byte brightness) { // 0 to 255
  analogWrite(outputEnablePin, brightness);
}

Board layout


texts: Reading Digital Pins and Outputing on entire Ports

texts:
I'm very new to coding so please don't grill me.

I'm working on a scientific project where I am using a NI-DAQ to digitally trigger mosfets to trigger 300us - 3ms pulses on two high powered LED arrays. My intention is to use the Arduino UNO to basically relay one digital output into many. It remains important to use the NI-DAQ as the pulses are dependent on video cues and other outputs, otherwise the pulses would be purely produced by the Arduino.

I have decided to the port Port reg output to accomplish this as it would appear to have the greatest temporal precision but I’m having a very difficult time getting a single pin to trigger a port. I would greatly appreciate some help.

My code currently looks as such:

int inpin = 2; //input specified as pin 2
int x = 0; // variable to store the read value

void setup() {
pinMode(inpin, INPUT); //sets digital pin 13 as input
DDRD=B11111111; //pin 8-13 is in output mode
DDRC=B11111111; //pin A0-5 designated output
}

void loop() {
x = digitalRead(inpin); //read the input pin
if (inpin = HIGH) PORTB=B11111111; // if digital input is high, all Bport high
if (inpin = HIGH) PORTC=B11111111; // if digital input is high, all Cport is high
if (inpin != HIGH) PORTB=B00000000; // if digital input is low, all Bport is low
if (inpin != HIGH) PORTC=B00000000; // if digital input is low, all Cport is low

}

At the moment it seems the board it reading the input but is not relaying the outputs correctly with the PORTB continuously off and PORTC continuously on. Any help would be great!


texts: Unable to send data from Processing to Arduino through ports

texts:
I'm just beginning to use Processing along side with Arduino and need help linking the two. Just to get started, I just wanted to send a single character (eventually strings) to the Arduino and have the Arduino light up a matrix if the Arduino receives the data.

Here's my code for the Arduino (I'm using an Arduino Uno):

#include <Adafruit_GFX.h>   // Core graphics library
#include <RGBmatrixPanel.h> // Hardware-specific library

// Set up the matrix
#define CLK 8
#define LAT A3
#define OE  9
#define A   A0
#define B   A1
#define C   A2
RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, false);

int incomingByte = 0;   // for incoming serial data

void setup() {

  Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
  matrix.begin();
}

void loop() {
    if(Serial.available() > 0) {
    incomingByte = Serial.read();

    // Print a white "Done!" to the matrix
    matrix.setCursor(1, 0);
    matrix.setTextSize(0);
    matrix.setTextColor(matrix.Color333(7, 7, 7));
    matrix.print("Done!");

  }
}

And here's the code for Processing:

// Example by Tom Igoe

import processing.serial.*;

// The serial port:
Serial myPort;

// List all the available serial ports:
println(Serial.list());

// Open the port you are using at the rate you want:
myPort = new Serial(this, Serial.list()[1], 9600);

// Send a capital "A" out the serial port
myPort.write(65);

I run the processing sketch and then upload the code to the Arduino, but get nothing. The Arduino is using COM3 and I believe the Processing sketch is too, but that may be where I'm messing up.

If I open up the serial monitor and send some data to the Arduino that way, then the LED lights up fine, but only when I do it through that.

Any help would be appreciated. Thanks!


texts:
I have been working on an arduino program, which has gotten rather large. I am close to hitting the 32k limit on Flash for my ATmega328p. I would like lower my program size by saving some of my many string literals into EEPROM.

All of the example programs on the EEPROM page suggest loading them in at runtime, in which case they would take up flash memory anyways! What I am wondering, is if there is a way to write to EEPROM from my PC, THEN load the arduino program which will access those values. Do I need some external hardware to do this?

Thanks for your help!

-sam


texts: How do you change the state of an image on a TFT display when the associated pin changes state?

texts:
I just recently resolved my problem on getting images to load on to my TFT display via the SD card. Thanks to UTFT_SdRaw!!! it's by far the easiest to use. For a novice like me, its been a real feat. Now translating the code, I am trying to turn on and off the image when the pin state changes:

Example:
When pin A2 on my MEGA goes high (+5vdc) I want my SD to spool up and load an image so here is my code snipit:

****myFiles.load(20, 55, 130, 130, "Power Medium.raw");****

So now when the pin state changes back to low (0vdc), how do I remove the image without clearing the entire screen? The image seems to stay frozen instead of disappearing when the pin voltage falls away.

Any ideas? I am stumped. Thanks in advance for any comments and suggestions that may help me over the hump.


texts: Need some help in coding a "timer" in an if else statement

texts:
I want to code something like a "timer" (don't know what to call it) in an if else statement in my arduino uno.

Basically I have 2 buttons. If the button1 is pressed and button2 is also pressed in a certain amount of time (let's say 3 seconds), the code will execute. If button1 is pressed but button2 is not pressed within 3 seconds then it will loop back up. How do I go about writing this code?

I've included a flowchart to make my question clearer.

Thanks all :)

if(digitalRead(button1) == LOW)       // this is where I need help
{
  if(digitalRead(selectbutton) == LOW)
  {
    for(x=1; x<=30; x++)
    {
      digitalWrite(dir, HIGH);
      delayMicroseconds(10);
      time_now = millis();
      digitalWrite(led, HIGH);
      while(millis() < time_now + 50)
      {
      }

      time_now = millis();
      digitalWrite(led, LOW);
      while(millis() < time_now + 50)
      {
      }
    }
    x=0;
  }
}

else if(digitalRead(button2) == LOW)    //same here >_<
{
  if(digitalRead(selectbutton) == LOW)
  {
    for(x=1; x<=10; x++)
    {
      digitalWrite(dir, LOW);
      delayMicroseconds(10);
      time_now = millis();
      digitalWrite(led, HIGH);
      while(millis() < time_now + 150)
      {
      }

      time_now = millis();
      digitalWrite(led, LOW);
      while(millis() < time_now + 150)
      {
      }
    }
    x=0;
  }
}

}


texts:
for my rc robot I want to use ir to send/receive the value from a jostick.

Is it possible ? I can't use any other radio chip like nrf24l01.


texts: How to burn bootloader and upload sketches on custom arduino?

texts: Ive turned a project I breadboarded with arduino and other modules into one pcb on EAGLE. The pcb includes the ATMEGA328p smt version that doesn't have the bootloader installed. My question is then what module or components can I use to burn the bootloader onto the atmega and upload programs to it together?


texts: How can I programming detect that a Bulb/LED is ON/OFF or a circuit is working as expected using Arduino?

texts: I've created a circuit to turn on bulb using GSM module and Arduino. I want a mechanism(or programming) to know whether the bulb is on or off or fused. I've tried taking the input from the pins. But it only tells whether the pin is on or off but not the circuit as a whole.


texts: What happens if I power the Arduino with both the USB and external power voltage simultaneously?

texts:
I am a new Arduino user. I am not sure whether I can connect both USB and external supply through power adaptor to Arduino simultaneously. Would this burn the controller?

Basically, I want to automatically shut down the computer after saving all open documents before my UPS battery goes out whenever I am not there to manually shut it down. I am trying to notify the computer about the power failures of main supply - AC 220V 50 Hz (notification/signal sent when power goes out) via USB using Arduino. I am thinking that this can be done by using the external voltage power supply pin. Whenever power goes out in the mains, the external voltage power supply pin will drop to 0 V from 7 V. The value of the voltage can be read using software ( I am unclear about this: Can it be done? If yes, how?). The Arduino will still be powered up as it is connected to USB of computer and thereby communicates to the computer about the power failure.


texts: Delay in displaying data received from UART when used with PCINT on PIN0

texts:
I have been trying to find a solution for UART receive interrupt for my UNO board and I came across a possible solution in : PCInt

I did a small editing in the following portion of the code to make it work for UART.(code works like a loop-back test)

void RXint(void) {
char k;
if(Serial.available()>0)
{
k=Serial.read();
Serial.print(k);
}}
void setup()
{
Serial.begin(9600);
PCattachInterrupt(0, RXint, FALLING);
}
void loop()
{}

The code works pretty well with one big drawback.
The character displayed is having one char delay, what i mean is that for the following input

  qwerty

output is

  qwert

That means if I enter the 5th char,the output will be 4th one.
When the first input is given, it doesn't show output till the second input is entered.

Can someone help me out with this

(This is only a test code, the interrupt part is to be used in a larger code where the loop() carries out different tasks and interrupt is to be raised when data is received via UART)  .


texts: About controlling led using push button using ATmega328p

texts:
I am using an ATMega328P and I want to illuminate an LED connected to PORTB according to an input (with pull up resistor) from PORTD.  In the same program, I generate phase-correct PWM and take output from pin PD6.
The problem is when I comment the function (PWM_out), the LED illuminates correctly.  But, when this function is not commented, the LED flashes (on-off) repeatedly and I do not want this.

#ifndef F_CPU
#define F_CPU 16000000UL
#endif

#include <avr/io.h>
#include <util/delay.h>

void phase_pwm(void)
{
  TCCR0A=(1<<WGM00)|(1<<COM0A1)|(1<<COM0B1);
  TCCR0B=(1<<CS01);
}

void PWM_out(uint8_t duty_cycle)
{
  OCR0A=((duty_cycle*256)/100);
}

int main(void)
{
  DDRD=0xf0;
  DDRB=0xff;

  phase_pwm(50);
  PWM_out();

  while(1)
  {
    if(PIND==0x04)
    {
      PORTB=0x02;
    }
    else
    {
      PORTB=0x00;
    }
  }
}


texts:
I'm new to Arduino, but I have this idea for a Smart Bag I would like to build.

I need the Arduino to be able to detect my moving by mobile and follow me.

What would be the best way to achieve that?


texts: Setting an array pointer to null on declaration

texts:
How can I set an array pointer to null?

I have a pointer to a 3 int array that I am trying to set to null.

  int (*EXCLUSIVE_COLOR)[3];

Per this link I was trying to set it to null upon initialization.
However this does not assign a null value to it. It assigns three 'random' integers to the array elements:

  {128, 447, 451}

How can I make it point to a null or empty value?


texts:
I have a potentiometer attached to one analog port of arduino (assume A0)
I'm reading the value of that using input_voltage = analogRead (A0); which is a value between 0-1023.
So I want to map this value to frequency from 1Hz to 20Hz. Then I want to fade my LED using this frequency.
Tried to doing this map using int frequency = map (input_voltage, 0, 1023, 1, 20);
But how can i apply this frequency to LED?
I mean PWM has a constant frequency (about 500Hz). How should I apply frequencies from 1 to 20 to this LED in order to fade it?


texts:
I am new to the world of electronics so please forgive me if I ask stupid questions.
I would like to ask if there is a difference between Bluetooth Modules that state: "for Arduino" as well as those that don't.
If they are different, does it mean that they have different programs to program each of them or does it mean that some configurations need to be done so that the Bluetooth Module will be compatible with Arduino Boards?


texts:
In this Question how does the code Processing work?
Which programming language is it written in? How to run it?


texts: Can I use the same Data Registry for both input and output pins?

texts:
This is for a class in which we are not allowed to use the Arduino Library (Not my choice or preference). I know to use DDRB for the B pins. This is the code that I have so far:

//Global pointers
unsigned char *portDDRB = (unsigned char *) 0x24;
unsigned char *portDataB = (unsigned char *) 0x25;
unsigned char *portPinB = (unsigned char *) 0x23;

void setup () {
  //For the led output I know that I would do this
  *portDDRB |= 0x80;
}

void loop () {
   //And here the code would be like this to light up the light:
   if (condition to turn on light) {
     *portDataB |= 0x80;
   }
   // To Turn off the LED:
   if (condition to turn off the light) {
     *portDataB &= 0x7F
   }
}

I would like for the light to turn on when the input of PB4 is HIGH (from a button press). I just am not sure on what to put in the condition statements or the setup functions.

When I set the DDRB to 0x80, is that just making the PB7 an output and the rest as input?

I am using the Arduino Mega ATmega2560 btw.

From the comments I have this:

//Global pointers
unsigned char *portDDRB = (unsigned char *) 0x24;
unsigned char *portDataB = (unsigned char *) 0x25;
unsigned char *portPinB = (unsigned char *) 0x23;

void setup () {
  //For the led output I know that I would do this
  *portDDRB |= 0x80;
}

void loop () {
   //And here the code would be like this to light up the light:
   if (portPinB & 0x10) {
     *portDataB |= 0x80;
   }
   // To Turn off the LED:
   else {
     *portDataB &= 0x7F
   }
}


texts: Can i burn an Arduino sketch .hex directly using USBASP?

texts: I am unable to upload sketches to my Arduino Uno board using the upload option in the IDE. I have done quite a few tests to find the reason but everything seems to be working fine when tested separately. I found that I can program the ATMega328 board when placed on a breadboard using an USBASP progammer and avrdude. So will it work if I burn the .hex generated in Arduino IDE using avrdude and USBASP by placing the ATMega on a breadboard? I would then want to replace the IC on the UNO board back for my application. Thanks for your time and help in advance.


texts:
I am working with STPM10 energy metering chip (evaluation board) and I want to read the data from 8 internal registers of the chip each containing 32 bits.

The datasheet of the STPM10 chip suggested to have a simplex synchronous SPI where the MOSI of the Arduino is not connected to any pin on the energy chip. Instead they provided a timing diagram to switch from reading and writing on the energy chip.

After the t5, datasheet stated that we should apply 32 serial clocks per data record and up to 8 data records can be read this way. My problem is how to apply 32 serial clocks to the chip.  Is the Serial clock on the Arduino SPI automatically activated after SPI.begin() ? If not, how can I start the serial clock? By the way, this is the code I've written:

#include <SPI.h>

SPISettings settingA(32000000, LSBFIRST, SPI_MODE0);
const byte SYN = 8;
void setup() {
  Serial.begin(9600);
  pinMode(SYN,OUTPUT);
 /*Initializes the SPI bus by setting SCK, MOSI and SS to outputs
  Pulling SCK, and MOSI low, and SS high */
  SPI.begin();
  SPI.beginTransaction(settingA);

  }

void loop() {
  //0----->t1
  digitalWrite(SS,HIGH);
  digitalWrite(SYN,HIGH);
  delay(500);
  //t1----->t2
  digitalWrite(SYN,LOW);
  delayMicroseconds(1000);
  //t2----->t3
  digitalWrite(SYN,HIGH);
   delayMicroseconds(0.035);
  //t3----->t4
  digitalWrite(SS, LOW);
  delayMicroseconds(0.035);
  //t4----->t5
  digitalWrite(SYN, LOW);
  delayMicroseconds(0.035);
  //t5---->t6
  digitalWrite(SYN, HIGH);
  delayMicroseconds(0.035);

  byte d1 = SPI.transfer(0x00);
  byte d2 = SPI.transfer(0x00);
  byte d3 = SPI.transfer(0x00);
  byte d4 = SPI.transfer(0x00);
  byte d5 = SPI.transfer(0x00);
  byte d6 = SPI.transfer(0x00);
  byte d7 = SPI.transfer(0x00);
  byte d8 = SPI.transfer(0x00);
  byte d9 = SPI.transfer(0x00);
  byte d10 = SPI.transfer(0x00);
  byte d11 = SPI.transfer(0x00);
  byte d12 = SPI.transfer(0x00);
  byte d13 = SPI.transfer(0x00);
  byte d14 = SPI.transfer(0x00);
  byte d15 = SPI.transfer(0x00);
  byte d16 = SPI.transfer(0x00);
  byte d17 = SPI.transfer(0x00);
  byte d18 = SPI.transfer(0x00);
  byte d19 = SPI.transfer(0x00);
  byte d20 = SPI.transfer(0x00);
  byte d21 = SPI.transfer(0x00);
  byte d22 = SPI.transfer(0x00);
  byte d23 = SPI.transfer(0x00);
  byte d24 = SPI.transfer(0x00);
  byte d25 = SPI.transfer(0x00);
  byte d26 = SPI.transfer(0x00);
  byte d27 = SPI.transfer(0x00);
  byte d28 = SPI.transfer(0x00);
  byte d29 = SPI.transfer(0x00);
  byte d30 = SPI.transfer(0x00);
  byte d31 = SPI.transfer(0x00);
  byte d32 = SPI.transfer(0x00);

  digitalWrite(SS,HIGH);
  digitalWrite(SYN,HIGH);
  delay(499);

  Serial.println(String(d4,BIN) + " " + String(d3,BIN) + " " +  String(d2,BIN) + " " +  String(d1,DEC));
  Serial.println(String(d8,BIN) + " " + String(d7,BIN) + " " +  String(d6,BIN) + " " +  String(d5,BIN));
  Serial.println(String(d12,BIN) + " " + String(d11,BIN) + " " +  String(d10,BIN) + " " +  String(d9,BIN));
  Serial.println(String(d16,BIN) + " " + String(d15,BIN) + " " +  String(d14,BIN) + " " +  String(d13,BIN));
  Serial.println(String(d20,BIN) + " " + String(d19,BIN) + " " +  String(d18,BIN) + " " +  String(d17,BIN));
  Serial.println(String(d24,BIN) + " " + String(d23,BIN) + " " +  String(d22,BIN) + " " +  String(d21,BIN));
  Serial.println(String(d28,BIN) + " " + String(d27,BIN) + " " +  String(d26,BIN) + " " +  String(d25,BIN));
  Serial.println(String(d32,BIN) + " " + String(d31,BIN) + " " +  String(d30,BIN) + " " +  String(d29,BIN));
  Serial.println(" ");


texts:
In my circuit I have a relay that will turn on some light bulbs this is my circuit:

The switch over the 5V is in fact my Arduino. A HIGH will turn on the relay and a LOW will turn it off.

This is working fine, but because of security measures I need to add a mechanical switch to be able to turn on and off whenever needed. This is the circuit I'm using for this configuration:

This circuit also works fine, the lamp is turned on and off by changing either switches but the Arduino loses track of the status of the lamp. The only thing it knows is if the relay is on or off.

Is there a simple way to tell when the lamp is on?


texts: Trigger external interrupt on Arduino Uno R3 with an LED and a button

texts:
I want to cause the external interrupt on digital pin 2 (PD2 on ATmega328). I have chosen any logic change mode. Here is my code:

void setup()
{
    DDRD &= ~( 1 << DDD2 );//PD2 on input mode
    EICRA |= ( 1 << ISC00 );//any logic change
    PORTD |= ( 1 << PORTD2 );//pull-up enable
    EIMSK |= ( 1 << INT0 );//turns on INT0

    DDRD |= ( 1 << DDD5 );//PD5 on output mode
    PORTD |= ( 1 << PORTD5 );//turn on PD5

    SREG |= ( 1 << 7 );//global interrupts enabled
}

void loop()
{

}

ISR( INT0_vect )
{
    if( ( PIND & ( 1 << PIND5 ) ) > 0 )//if turned on
    {
         PORTD &= ~( 1 << PORTD5 );//turn off led
    }
    //and vice-versa
    else
    {
         PORTD |= ( 1 << PORTD5 );
    }
}

Here is how I connect things.

NOTE: I did not find an ordinary button which just connects two contacts ( which I actually use ). Here if I understand correctly the button in the picture connects left pair and right pair of contacts so everything is connected when pushed and disconnects them from each other when released.

The problem is when I push the button no interrupt occurs. What am I doing wrong?


texts: How to manage two alarms with one interrupt?

texts:
I have a datalogger using the RTC DS3231 as an interrupt generator. I am able to have the interrupts work but here is my problem. I would like to take 2 separate measures from 2 different sensors (one for humidity, temperature and the other for accelerations), one every 30 min et one every hour, the thing is that because I use the same pin (only one pin from the DS3231) for both of these alarms I cannot use a simple counter in my interrupt function otherwise one measure will not be taken when both of the alarms will trigger...

For example I just did a quick test with one alarm each min when seconds are 00 and an other alarm each minute when seconds are 20. The problem as I said is that I cannot increment counters for each since I use the same interrupt function (because of the single pin).
Here is my loop function and interrupt handling function :

void loop() {
  delay(1000);
  sleepNow();
  if (alarm == true){
    handleAlarm(); // reset the possibility to trigger alarm
    if (counter_dtphl == COUNT_DTPHL){
      take_measure_DTPHL();
      counter_dtphl = 0;
    }
    else if (counter_accel == COUNT_ACCEL){
      take_measure_ACCEL();
      counter_accel = 0;
    }
  }
}

void wakeUpNow() {
  Serial.println("In wake up now");
  delay(100);
  alarm = true;
  //Serial.println(counter);
  sleep_disable();//Disable sleep mode
  byte sec = get_date(SEC);
  Serial.println(sec);
  if (sec == 0){
  counter_dtphl +=1;
  }
  else if (sec == 30){
  counter_accel +=1;
  }
  detachInterrupt(digitalPinToInterrupt(interruptPin)); //Removes the interrupt from pin 2;
}

void handleAlarm() {
  alarm = false;
  rtcObject.LatchAlarmsTriggeredFlags();
}

COUNT_ACCEL and COUNT_DTPHL are constant having the value of minutes corresponding to the trigger for the measure.

Has anybody an idea how to manage this situation ?
For the acceleration I need to save the data for a period of 30 sec. One solution I tried is to increment the counter according to the time in second that corresponds each minute but I cannot put it in the wakeUpNow function since only fast processing should be done there (it is the function executed by the interrupt).

Thank you for your time !


texts: How to detect whether connected to computer

texts: I built a keypad that can adjust volume, play, pause, skip tracks, and control the arrow and num keys. It has some backlighting under the keys. I'd like to turn this off when the computer is off. Additionally, whenever the computer is restarted the device must be unplugged and plugged back in or the operating system will not register keypresses. Is there a way I can tell if the computer is on or if the device is connected?


texts: I have been assigned a university project to make sound/audio responsive LED using assembly language. I have already made a C++ code in arduino which uses Fastled library. How do I write a working code for this project in assembly (not restricted  to arduino IDE, but preferable). I've already tried converting my code to assembly using an online converter, but it is useless.