Thursday, July 2, 2015

Wordpress with MySQL: Error establishing a database connection

The Problem

I ran into the following problem today when I was setting up a fresh local wordpress install on my Mac.


"Error establishing a database connection
This either means that the username and password information in your wp-config.php file..."
Fortunately, the fix was pretty simple!

The Fix

First, check if MySQL is running:
In terminal, I typed
mysqladmin version

If the server is running, the above command should return something like:

So the server is running, and I'm 100% sure I have the right username and password. So, what's the problem?
On a whim, I found the fix:
In /<wordpress folder>/wp-config.php, change the line
define('DB_HOST', 'localhost');
to
define('DB_HOST', '127.0.0.1');

That fixed the problem! :)

Friday, April 17, 2015

We can see the stars because Poynting vector is non zero

Do you ever look up at the night sky, and think "wow, these stars/planets are so far away from us, yet I can still observe them! How is that possible?!"

Chances are, you probably haven't.

Still, it is intriguing to think that we can potentially, given infinite time, observe a star/emitting body at the very end of the universe. This is all thanks to the non-zero Poynting vector in the equation for electromagnetic (EM) radiation.

I decided to write this blog post after my EM theory prof said "We can see stars because Poynting vector is non zero." I won't include any complicated theory or equations because 1) It's final exam season and I shouldn't even be writing this blog post and 2) you only need to know the basic concept.

What is a Poynting vector?
I assume you know what electric and magnetic fields are. (Electric fields are present when dealing with charged particles (like electrons), and magnetic fields when dealing with MOVING charged particles) Combine these fields, and you get an 'electromagnetic (EM) field'. These fields have a sense of direction about them, and depending on what you do with the field, you can get energy out of them. Poynting vector represents the directional rate of energy transfer of an EM field.

What is EM radiation?
Charges that are accelerating have EM fields that can transport energy "irreversibly out to infinity", and this is what we call "radiation." Given a charged particle that is accelerating in space, you can calculate the total power passing through its surface by integrating the Poynting vector. Clearly, this is non-zero if the Poynting vector is non-zero. But then, the EM 'news' travels at the speed of light, which means the energy left our charged particle at an earlier time. Have I lost you yet?

Think of it as pulling one end of a long slinky quickly. The other end of the slinky starts moving only after a certain amount of time. Now imagine that the slinky is 'energy', and you're moving it at the speed of light. (This might be an unfair analogy, since slinky expands while there is no sense of physical 'expansion' for energy)

Nonetheless, you measure the time at which the energy left the source (t0), and then measure another time point (t') when the energy crosses you at some other point in space, a distance 'r' away from the source. This means t' = t0 + r/c, where c is the speed of light. The power that is 'radiated' is essentially the amount of energy detected as r --> infinity. Obviously, since speed of light is constant, the further you move away from the source, the longer radiated energy will take to reach you -- but no matter how far away you are, it WILL reach you (even when there is a giant star between you and the source, thanks to gravitational lensing).

And this is precisely why we see stars!

UBC Course Review: EECE 360

Course: EECE 360
Topic: Systems and Control
Term: 2015W
Professor: Dr. Z. Jane Wang

Pre-reqs: EECE 202 or EECE 253 (Circuit Analysis II)

This was one of the core courses for engineering physics at UBC that I found most enjoyable and directly applicable. We got to learn about feedback system design, state-space analysis, root-locus method and frequency domain controller design. Course notes (ppt slide sets) were very useful in the beginning but lacked information for later chapters (especially for phase lead/lag design). Class attendance was decent (>50%), and most lectures consisted of ~20% theory explanations and 80% solving example problems. There were 5 major homework sets, due bi-weekly. Each took about 3 to 5 hours to complete, except for the "MATLAB assignment" which took about 8+ hours.

Overall, I would give the course 4.5 bode plots out of 5.

----
Disclaimer: These course reviews reflect my own personal views, which may differ from those of everyone else :o

Wednesday, March 25, 2015

Thoughts on Grad School (from Professors and Current Grad Students)

Today, I attended an interesting info session on grad school. There were talks from professors of physics and engineering, as well as from a current grad student.

I went in thinking that grad school wasn't really my thing, and came out reassured of that. :p Nonetheless, here is a list of recurrent topics during the session.

  • Things you need for grad school

    • GPA: If you are aiming for big name universities, you want a 88%+ overall average. Some students with 80% or above are considered, but only if they participated in extracurricular activities or they received high marks in the related field.
      • Comment: Given the insane workload (7 to 10 courses per term) of my program, this is quite hard to achieve (compared to 3 to 4 courses per term for other faculties). If you're in the same situation, read below, regarding reference letters.
    • Reference letters: Stellar, academic reference letters from possibly your undergrad research supervisor are the best, according to the grad committee member at the info session. If you haven't done undergrad research, a STRONG reference letter from a professor you frequently visit might work as well (with extra emphasis on strong!).
    • ! If your grades aren't as good, but you participated in various clubs, ask your referee to take that into consideration!
      • Comment: When asking your referees, give them at least two weeks to write, and always ask them if you could give them something to work with, such as a small blurb about what your previous experiences with your referee, or other important things you want mentioned in the letter. Remember, you won't be able to read the reference letter, so you want to give your referee as much information as you could that can help!
    • GRE, for American universities: You absolutely need to ACE the general GRE test, according to the director of my program. He has gotten 99th percentile on all subjects of his general GRE, but 60th percentile on the physics GRE, yet he still got into Stanford for masters in theoretical physics.

  • Pros and Cons of grad school

    • Pros:
      • You get paid to take courses and do your research
        • Never go to a grad school that requires you to pay!
      • You can take courses that you really enjoy
      • You have TIME to actually learn the material
        • In my current undergrad, it's honestly overwhelming to juggle 7 courses and thoroughly learn the materials.
    • Cons:
      • You don't get paid too much.
        • "You get to live just above the poverty line, enjoy Kraft Dinner, and share a basement suite with fun people"
      • You are pigeon-holing yourself in terms of knowledge
        • The professors had split opinions on this one. A physics professor gave many example cases where a student with a phD in one field got jobs in a completely different field, but with some overlap in terms of applied skills. Still, it seems true when they say you become the world-leader in that particular field, insofar as to add new knowledge to that field. This would indeed require a great deal of pigeon-holing..

  • Consider these points before applying for a grad school

    • If you are going to grad school so you can make more money, STOP
      • There is no guarantee that you will land a faculty job, or a job after your phD. Currently, there is an overflow of phD grads looking for placement. Faculty jobs are only possible for the top of the top students, and a "typical firm won't hire a phD student for a task that could be done by an undergrad". 
    • Don't go to grad school just because other people are going.
      • Make your own decisions! Consider everything, and do a LOT of research beforehand.
    • Don't be afraid to apply beyond the 'top universities'
      • Top universities might not necessarily be world-leading in your particular field of interest!


To give my two cents, grad school is indeed for people interested in becoming experts in their fields of interest. You should be willing to dedicate at least half a decade into it (after the 4 to 5 years of gruelling undergrad). Needless to say, if you are dedicated and work hard enough, you can definitely kick-ass, and you totally deserve that 'Dr.' prefix!


Thursday, December 18, 2014

Real Time Controls with ATMEGA1284 using Interrupts

Few months ago, I had to create a real-time signal generator using a microcontroller unit (MCU) that would control the trajectory of a multi-kilowatt laser. As the process involved is for large-scale laser welding, it was requested that the system be highly reliable.
I was given an ATMEGA1284P with an external 16MHz quartz. (To see how to set up the external clock, click here)
The signal being generated was between 5-30Hz (which is quite slow), so I tried using time-based Sleep() instructions. This resulted in a terribly incorrect frequency.

The solution was to use interruptsInterrupts are used everywhere. In software, they can be used to handle errors that pop up during program execution. In electronics, a button press can generate an interrupt, leading to a function execution.

In our case, the interrupt is generated from the MCU itself. 
In short, the quartz --which is a crystal oscillator-- 'ticks' (hopefully) at a constant frequency. The MCU is able to count these ticks. At every certain number of ticks (which you assign), the MCU can call a function called an Interrupt Service Routine (ISR).

The benefit of this method is that as long as the quartz is reliable, the MCU will reliably run the ISR at every few instances in time.
The biggest drawback -- and something to watch out for -- is that the ISR must be very concise (a loop of any kind is a big no-no).

Example Problem

Say we want to generate a sine signal to an analog-out pin at a certain frequency.

We can use interrupts to output a certain value of the sine wave at a given time. Unfortunately, depending on the MCU (and true for ATMEGA1284P), calculating sin() within the ISR takes a long time -- long enough to cause delays in the signal. Since sine is a periodic function, it is much better to pre-compute the values with a given temporal resolution and call them from an array during the ISR. 


Initialization

First, we need to declare a few variables.

#define RESOLUTION 250

volatile unsigned int counterMaxValue;
const int clkspeed = 16000000; 
const int prescaler = 64;
volatile int frequency = 5; // Default freq. is 5Hz

// for pre-computed sine table.
int table_index = 0;  
double sin_table[RESOLUTION];
float increment;

const int outportB = 2; // PortB
const int outportC = 1; // PortC

counterMaxValue is the number of 'ticks' of the quartz at which the ISR should be called.
clkspeed is the frequency of our quartz, in Hz.
prescaler is the number at which to divide the number of 'ticks,' and it allows us to use a certain range of frequencies. Read more about prescaler here.

The Interrupt

Now, we must configure the hardware. We are using Timer 1 of the 1284P, in the Clear Timer on Compare (CTC) mode. When I was first learning about CTC, I used this resource.
void initInterrupt() {
  // INTERRUPT SET UP
  cli();//stop interrupts

  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B

  /* 
   CTC mode activation:
   The counter value (TCNT1) is incremented from 0 to the value specified in OCR1A. 
   Once it hits that value, the interrupt is generated, and the interrupt service routine (ISR) is called.
   The below setting for TCCR1B enables this to happen. See the datasheet for more details.
   */
  TCCR1B |= (1 << WGM12)|(1 << CS11)|(1 << CS10); 

  // set compare match register for freq * n increments
  counterMaxValue = (unsigned int) (clkspeed/(frequeny*n*prescaler) - 1);
  OCR1A = counterMaxValue;//eg:(16*10^6)/(2000*64)-1 (must be <256 for 8 bit counter.); 124 for 2kHz

  //initialize counter value to 0
  TCNT1  = 0; 
  
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

  //enable interrupts
  sei();
}

After this function is run, the interrupts will begin. But first, we must set up a pre-computed sine table; and above all, we must define the ISR.

The setup()

void setup()
{
  ...

  // Pre-compute sine table
  increment = 6.283185/(RESOLUTION-1);
  for (int index = 0; index < RESOLUTION; index++)
  {
    sin_table[index] = sin(x);
    x = x + increment;
  }

  initInterrupt();
}

The ISR


I was using Wiring to program the MCU, and there was an error when I tried to use any of the timers. The problem was solved by commenting out the definition set out by wiring.
// Had to comment out line 77-86 of ...\wiring-0100\wiring-0100\cores\AVR8Bit\WHardwareTimer.cpp
// in order to 're-define' TIMER1_COMPA_vect
ISR(TIMER1_COMPA_vect) {
  // NO LOOPS / WAITING / DELAYS IN THE ISR!!
   
  // Traverse through the table. This is much faster than computing sine every time! :)
  // Equivalent to: 
  // y = sin(x)*amplitude+1638+offset; // Based at 5V, up to 4V peak to peak; offset +/- 1V. 2047 - 409 = 1638; 5V - 1V to account for offset
  // x = x + increment;
  if (table_index > RESOLUTION-1) // loop back to beginning
  {  
    table_index = 0;
  }
  y = sin_table[table_index]*amplitude+1638+offset;
  table_index++;
  output = word(y);
  portWrite(outportB, int (lowByte(output)));
  portWrite(outportC, int (highByte(output))); 
}

Just a quick note on outputting the signal: I am using a 12-bit digital to analog converter (DAC). Two ports on the MCU are used, each outputting half of the word.
The DAC I used allowed two modes of output: unipolar (0V to 10V), or bipolar (-5V to 5V). I used the latter, which means that when I send (1111 1111 1111)2 to the DAC, the output value will be (+Vref)*(2047/2048).
In short, output value of '409' from the MCU corresponds to 1V output from the DAC.

Now everything is ready! An empty loop() suffices to run this on the MCU.

The loop()

void loop(){}

After uploading the program to your 1284P, it should start sending out sine signals in digital form to the DAC, which it can then transform to the analog signal.

Conclusion

Establishing accurate real time controls on a microcontroller requires us to use timer-based interrupts. There are many benefits to this method, including parallelization of tasks for the MCU.

In other words, the MCU can do other things, such as polling for user input in the main loop(), while ISR takes care of the timing-based tasks. This would not be possible using the sleep() function, which simply waits for a certain amount of time until moving on to the next instruction.

Lastly, the most important thing to consider when using timer-based interrupts is to keep the ISR as simple and short as possible!

Monday, December 15, 2014

[Solidworks] Tube Routing without Solidworks Premium


Without a doubt, Solidworks Routing package within the premium version of SW can be quite useful when creating electrical connections, pipes, or tubes. Unfortunately, a lot of us have to make-do without such handy tools. In this tutorial, I will cover how to create flexible tubings with just a few loft tools. The example model I am using is a minimal working example (MWE) so please excuse the crude design.

Problem

- Route a flexible tube between two connections that updates with the varying position of the end connections.
A flexible tube must be connected between the two highlighted profiles.

Solution


1. First, create a cross-sectional sketch of the tube. Save the part.

Cross-sectional sketch of the tube
2. Create a new assembly, and import the assembly with the original parts. This will enable the tube route to be automatically updated. (Do not import by parts!)
3. Import the sketch, and mate it to one end of the connection. Make sure it is fully defined.
Mate the sketch to one end of the tube connection.

4. Go into “Edit Component” mode for the tube, and click on any of the planes.


5. CTRL+DRAG the plane to create a new plane.


Define the plane to be coincident to the other end of the tube connection.


6. Make a sketch on this new plane of the tube cross section. Exit sketch.

7. While still in Edit Component mode, go to Features -> Lofted Boss/Base.
8. First we have to create the outer wall. So, designate the outer closed loop as the end geometries.
It will create the shortest-path connection, which ends up looking quite strange!



9. This can be easily fixed by clicking on Start/End Constraints, and setting them to be “Normal To Profile.” The orthogonal distance to profile can be edited here as well, but remember these values because we will need it soon.


10. We have to now cut out the inside of the tube. To do this, first make the sketches in loft visible. (Click on the + sign beside Loft, right click on the sketches and click “Show”)

11. Go to Features -> Lofted Cut. Now click on the inner closed loops.
Set the same Start/End Constraints as before (do you remember those numbers? :O)

Now your tube is done!

You can open the original assembly without the tube, change the positions, and the assembly with the tube should update on its own.


Ta-da!

Saturday, December 13, 2014

Budapest for 1.5 days




If I could describe Budapest using two words, it would be 'grey' and 'mysterious.' The weather wasn't so great during the 1.5 days; it was raining, cloudy and foggy -- definitely not the best time to take photographs. Still, they turned out alright after some post-processing. :)

My travel buddy this time was Alvin, and despite our super uncomfortable wet shoes, we tried to make the best of the trip. Alvin's friend, Albert from Canada met up with us and showed us around despite his busy study schedule for med school finals.

The Chain Bridge
The city is divided into two parts by the river Danube; Buda on the west bank and Pest on the east.
Hungarian Parliament Building


Walking around the city, I noticed a lot of Roman-esque buildings. It turns out, Romans declared this city the capital of Pannonia Inferior.

At the centre of Chain Bridge, overlooking the Statue of Liberty on the left and Pest on the right.